问:
How to remove OneDrive folder using PowerShell
I'm trying to remove a user OneDrive folder using PowerShell but I'm not seeing any sucess even though I've been searching around internet so I would be really appreciated if I can get any help or suggestion.

so Just for testing purpose, I'm trying to delete my a folder in my own OneDrive called "Testing" and I wanted to delete everything in there including subfolders and files.

```<code>    Connect-SPOService -Url https://company-admin.sharepoint.com

    $OneDriveURLs = Get-SPOSite -IncludePersonalSite $true -Limit All -Filter "Url -like '-my.sharepoint.com/personal/'"

    foreach($OneDriveURL in $OneDriveURLs)

    {

    Connect-SPOService -Url https://company-admin.sharepoint.com

    Connect-PnPOnline -Url $OneDriveURLs
    Remove-PnPFolder -Name "Google Drive" -Folder "Testing"

    }
</code>```

答:
Your cmdlet format is not correct, you should follow the structure, more about it in Microsoft Docs

You would need to change <username> to the name the personal drive.

Change your format to :

```<code>$drive= https://company-admin.sharepoint.com/personal/<username>
$folder = 'testing'
Remove-PnPFolder -Name $drive -Folder $folder
</code>```

If that does not work, as an alternative you can try the following powershell module OneDrive and use:

```<code>Remove-ODItem -AccessToken $Auth.access_token -ResourceId "https://sepagogmbh-my.sharepoint.com/" -path "/Upload"
</code>```

You can read more about the module on their GitHub page.

Body:
I'm trying to remove a user OneDrive folder using PowerShell but I'm not seeing any sucess even though I've been searching around internet so I would be really appreciated if I can get any help or suggestion.

so Just for testing purpose, I'm trying to delete my a folder in my own OneDrive called "Testing" and I wanted to delete everything in there including subfolders and files.

    Connect-SPOService -Url https://company-admin.sharepoint.com

    $OneDriveURLs = Get-SPOSite -IncludePersonalSite $true -Limit All -Filter "Url -like '-my.sharepoint.com/personal/'"

    foreach($OneDriveURL in $OneDriveURLs)

    {

    Connect-SPOService -Url https://company-admin.sharepoint.com

    Connect-PnPOnline -Url $OneDriveURLs
    Remove-PnPFolder -Name "Google Drive" -Folder "Testing"

    }

Body:
Your cmdlet format is not correct, you should follow the structure, more about it in Microsoft Docs

You would need to change <username> to the name the personal drive.

Change your format to :

$drive= https://company-admin.sharepoint.com/personal/<username>
$folder = 'testing'
Remove-PnPFolder -Name $drive -Folder $folder

If that does not work, as an alternative you can try the following powershell module OneDrive and use:

Remove-ODItem -AccessToken $Auth.access_token -ResourceId "https://sepagogmbh-my.sharepoint.com/" -path "/Upload"

You can read more about the module on their GitHub page.


来源: stackexchange

问:
Dataframe reshaping for tensorflow training
I'm trying to get some data ready for training in a GAN model. This data is around 37k faces of resolution 28x28 with 3 channels each. At the moment, this data is in a Dataframe object and I would expect the shape of this data to be (37k, 28, 28, 3), but the shape turns out to be (37k,). Is there a way I can reshape this data to conform to this data to the proper shape?</p>

答: What you want to do can be implemented using the stack function.</p>

ContentLicense: CC BY-SA 4.0


问:
HTML button to NOT submit form
I have a form. Outside that form, I have a button. A simple button, like this:

```<code><button>My Button</button>
</code>```

Nevertheless, when I click it, it submits the form. Here's the code:

```<code><form id="myform">
    <label>Label
      <input />
    </label>
</form>
<button>My Button</button>
</code>```

All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.

```<code><button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>
</code>```

答:
Late in the game, but you don't need ANY JavaScript code to use a button as a button.  The default behavior is to submit the form, most people don't realize that.  The type parameter has three options: submit (default), button and reset.  The cool thing about this is if you add an event handler it will bypass submitting the form.</p>
```<code><button type="button">My Button</button>
</code>```

Title: HTML button to NOT submit form

Body:
I have a form. Outside that form, I have a button. A simple button, like this:

<button>My Button</button>

Nevertheless, when I click it, it submits the form. Here's the code:

<form id="myform">
    Label
      <input />

</form>
<button>My Button</button>

All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.

<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>

Body:
Late in the game, but you don't need ANY JavaScript code to use a button as a button.  The default behavior is to submit the form, most people don't realize that.  The type parameter has three options: submit (default), button and reset.  The cool thing about this is if you add an event handler it will bypass submitting the form.

<button type="button">My Button</button>


问:
[gulp 4]: Trying to run Gulp4 to convert SCSS to CSS
I tried to run the gulp to covert SCSS to CSS，the gulp is working wihout any error but there aren't have any css files output to the target folder, I also tried to change the output path but it still didn't work，and my code is below :

```<code>// gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass')(require('node-sass'));
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var browserSync = require('browser-sync').create();
var notify = require('gulp-notify');
var sassLint = require('gulp-sass-lint');

var styleLink = {
    sassLink: 'src/**/*.(scss|sass)',
    OutputLink: '../css'
}
var browserSyncLink = {
    root: '../',
    watchHtml: '../*.html',
    watchJS: '../*.js'
}

// notify
function showErrorNotify(error) {
  var args = Array.prototype.slice.call(arguments);
  // Show notification
  notify.logLevel(0);
  notify
    .onError({
      title: '[' + error.relativePath + '] Error',
      message: '<%= error.messageOriginal %>',
      sound: 'Pop'
    })
    .apply(this, args);

  // Keep gulp from hanging on this task
  this.emit('end');
}

// sass task
function sassTask() {
  return gulp.src(styleLink.sassLink, { sourcemaps: true })
        .pipe(sass()) // compile SCSS to CSS
        .pipe(autoprefixer())
        .pipe(gulp.dest('./', { sourcemaps: '.' }));
}

function browserSyncServer(cb) {
  browserSync.init({
    server: {
      baseDir: browserSyncLink.root
    }
  })
  cb();
}

function browserSyncLoad(cb) {
  browserSync.reload();
  cb();
}

function sassLinkTask() {
  return gulp
    .src(styleLink.sassLink)
    .pipe(
      plumber({
        errorHandler: showErrorNotify
      })
    )
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
}

function watchTask() {
  gulp.watch('../*.html', browserSyncLoad);
  gulp.watch(['src/**/*.+(scss|sass)', '../js/*.js'], gulp.series(gulp.parallel(sassTask, sassLinkTask), browserSyncLoad));
}

exports.default = gulp.series(gulp.parallel(sassTask, sassLinkTask), browserSyncServer, watchTask);
</code>```

when I ran this code i alos didn't get any error.

It seems no error..

Could anyone please help me ? Thanks.
and please excuse my poor English...

答:
In your watchTask you have this:

src/**/*.+(scss|sass)  note the + sign before the alternation.

But in your styleLink variable you have:

var styleLink = {
    sassLink: 'src/**/*.(scss|sass)',
    OutputLink: '../css'
}
```

Change to     sassLink: 'src/**/*.+(scss|sass)',

Body:
I tried to run the gulp to covert SCSS to CSS，the gulp is working wihout any error but there aren't have any css files output to the target folder, I also tried to change the output path but it still didn't work，and my code is below :

// gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass')(require('node-sass'));
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var browserSync = require('browser-sync').create();
var notify = require('gulp-notify');
var sassLint = require('gulp-sass-lint');

var styleLink = {
    sassLink: 'src/**/*.(scss|sass)',
    OutputLink: '../css'
}
var browserSyncLink = {
    root: '../',
    watchHtml: '../*.html',
    watchJS: '../*.js'
}

// notify
function showErrorNotify(error) {
  var args = Array.prototype.slice.call(arguments);
  // Show notification
  notify.logLevel(0);
  notify
    .onError({
      title: '[' + error.relativePath + '] Error',
      message: '<%= error.messageOriginal %>',
      sound: 'Pop'
    })
    .apply(this, args);

  // Keep gulp from hanging on this task
  this.emit('end');
}

// sass task
function sassTask() {
  return gulp.src(styleLink.sassLink, { sourcemaps: true })
        .pipe(sass()) // compile SCSS to CSS
        .pipe(autoprefixer())
        .pipe(gulp.dest('./', { sourcemaps: '.' }));
}

function browserSyncServer(cb) {
  browserSync.init({
    server: {
      baseDir: browserSyncLink.root
    }
  })
  cb();
}

function browserSyncLoad(cb) {
  browserSync.reload();
  cb();
}

function sassLinkTask() {
  return gulp
    .src(styleLink.sassLink)
    .pipe(
      plumber({
        errorHandler: showErrorNotify
      })
    )
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
}

function watchTask() {
  gulp.watch('../*.html', browserSyncLoad);
  gulp.watch(['src/**/*.+(scss|sass)', '../js/*.js'], gulp.series(gulp.parallel(sassTask, sassLinkTask), browserSyncLoad));
}

exports.default = gulp.series(gulp.parallel(sassTask, sassLinkTask), browserSyncServer, watchTask);

when I ran this code i alos didn't get any error.

It seems no error..

Could anyone please help me ? Thanks.
and please excuse my poor English...

Body:
In your watchTask you have this:

src/**/*.+(scss|sass)  note the + sign before the alternation.

But in your styleLink variable you have:

var styleLink = {
    sassLink: 'src/**/*.(scss|sass)',
    OutputLink: '../css'
}

Change to     sassLink: 'src/**/*.+(scss|sass)',


问:
Angular scss url(), cant resolve relative path when project is build
i have a folder filled with svg's (path: src/assets/icons).
The css function url() is implemented like this:

```<code>url("/assets/icons/CheckSmall.svg");
</code>```

It finds the svg data, when I run ng serve.
But when I build my Project, it cant find the svg data. Although it exists in the folder dist/myApp/assets/icons/CheckSmall.svg

I have read through many forums and discussions and tested a few things (One of many discussions).

For example i used different pathing "strategies":

```<code> 1. url("^assets/icons/CheckSmall.svg")
 2. url("~/assets/icons/CheckSmall.svg")
</code>```

For number (1) it seems like it is not a supported feature in Angular, thats why i dont want to use it. And for (2) it copies my Assets and puts them into the folder dist/myApp.

Is there a viable(supported or documented) alternative? Or can I somehow adjust the angular.json.

答:
Try using the following syntax:

background-image: url('../../assets/icons/<file-name>')
```

Where the route is relative to the css file

If you're setting non-default baseHref or deployUrl flags as part of the build that can also affect it

Try using that approach in styles.scss or in the relevant component, without the scss variable. The relative path won't be correct when the scss variable is used in different folders

Body:
i have a folder filled with svg's (path: src/assets/icons).
The css function url() is implemented like this:

url("/assets/icons/CheckSmall.svg");

It finds the svg data, when I run ng serve.
But when I build my Project, it cant find the svg data. Although it exists in the folder dist/myApp/assets/icons/CheckSmall.svg

I have read through many forums and discussions and tested a few things (One of many discussions).

For example i used different pathing "strategies":

 1. url("^assets/icons/CheckSmall.svg")
 2. url("~/assets/icons/CheckSmall.svg")

For number (1) it seems like it is not a supported feature in Angular, thats why i dont want to use it. And for (2) it copies my Assets and puts them into the folder dist/myApp.

Is there a viable(supported or documented) alternative? Or can I somehow adjust the angular.json.

Body:
Try using the following syntax:

background-image: url('../../assets/icons/<file-name>')

Where the route is relative to the css file

If you're setting non-default baseHref or deployUrl flags as part of the build that can also affect it

Try using that approach in styles.scss or in the relevant component, without the scss variable. The relative path won't be correct when the scss variable is used in different folders


问:
{'error': 'RESTEASY003650: No resource method found for PUT, return 405 with Allow header'} when updating user data in Keycloak
I am trying to update user info in keycloak by sending put request. Get request is working fine I am getting all the users but Whenever I tried to send put request to update the user data I get this error "{'error': 'RESTEASY003650: No resource method found for PUT, return 405 with Allow header'}" while searching for the solution I find somewhere that I should add 'HTTP_X_HTTP_METHOD_OVERRIDE' in headers I also tried this but still, I am facing same error, how can I fix it.

code:

```<code>def update_user(user_id, user_data):
    import requests
    headers = dict()
    headers['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT'
    headers['content_type'] = 'application/json'
    data = {
        "grant_type": "password",
        "username": "admin",
        "password": os.getenv("KEYCLOAK_ADMIN_KEY"),
        "client_id": "admin-cli"
    }
    token = _request("POST", f"{server_internal_url}realms/master/protocol/openid-connect/token", None, data=data).json()["access_token"]
    # token = admin_token()
    headers["Authorization"] = f"Bearer {token}"
    headers["Host"] = kc_host
    # here = _request("PUT", admin_url+f"/users"+"/".format(user_id=user_id), token, data=json.dumps(user_data)).json()

    response = requests.put(admin_url+f"/users"+"/".format(user_id=user_id), headers=headers, data=data, verify=VERIFY)

    print(response.json())
</code>```

server_internal_url = "https://keycloak:8443/auth/"

admin_url = "https://keycloak:8443/auth/admin/realms/{realm_name}"

答:
It looks like you request has wrong URL:

```<code>response = requests.put(admin_url+f"/users"+"/".format(user_id=user_id), headers=headers, data=data, verify=VERIFY)
</code>```

I guess it should be:

```<code>response = requests.put(admin_url+"/users/"+user_id, headers=headers, data=data, verify=VERIFY)
</code>```

Body:
I am trying to update user info in keycloak by sending put request. Get request is working fine I am getting all the users but Whenever I tried to send put request to update the user data I get this error "{'error': 'RESTEASY003650: No resource method found for PUT, return 405 with Allow header'}" while searching for the solution I find somewhere that I should add 'HTTP_X_HTTP_METHOD_OVERRIDE' in headers I also tried this but still, I am facing same error, how can I fix it.

code:

def update_user(user_id, user_data):
    import requests
    headers = dict()
    headers['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT'
    headers['content_type'] = 'application/json'
    data = {
        "grant_type": "password",
        "username": "admin",
        "password": os.getenv("KEYCLOAK_ADMIN_KEY"),
        "client_id": "admin-cli"
    }
    token = _request("POST", f"{server_internal_url}realms/master/protocol/openid-connect/token", None, data=data).json()["access_token"]
    # token = admin_token()
    headers["Authorization"] = f"Bearer {token}"
    headers["Host"] = kc_host
    # here = _request("PUT", admin_url+f"/users"+"/".format(user_id=user_id), token, data=json.dumps(user_data)).json()

    response = requests.put(admin_url+f"/users"+"/".format(user_id=user_id), headers=headers, data=data, verify=VERIFY)

    print(response.json())

server_internal_url = "https://keycloak:8443/auth/"

admin_url = "https://keycloak:8443/auth/admin/realms/{realm_name}"

Body:
It looks like you request has wrong URL:

response = requests.put(admin_url+f"/users"+"/".format(user_id=user_id), headers=headers, data=data, verify=VERIFY)

I guess it should be:

response = requests.put(admin_url+"/users/"+user_id, headers=headers, data=data, verify=VERIFY)


问:
Customizing CSS classes in ASP.NET
I am working on an application where the user will be allowed to change the font color of header titles.

The header titles use a value from cssClass (the cssClass uses font-size, font-color, font-weight & font-family).

Is there a way that I can allow a custom font-color in the css file itself?

One option would be to eliminate font-color from the cssClass, and use Font-Color in the .aspx page.

答: Use a label control between the <h1> tags and use System.Drawing.Color to apply the color.</p>

ContentLicense: CC BY-SA 3.0

Title: Customizing CSS classes in ASP.NET


问:
CSS not applying to html code within {% block bodycontent %}
I'm currently building a website and am having trouble getting the css to apply to parts of my html code. I have a base.html which I want displayed on every page, and I'm using {% block bodycontent %} in different documents to give the different pages specific features. However, I'm finding that the css stylesheet doesn't seem to apply to the code within the block, and is only applying to base.html. I'm using the flask framework, and am not sure if this may be the problem - when I run the html file locally without flask, the styling seems to be working, but of course the page is incomplete, because it is not interacting with the base.

This is my base:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Welcome</title>
</head>
<body>

  <div class="header">
    <nav>
      <a href="/">Welcome</a>
        <ul class="nav_links">
          <li> <a href="about_us">About us</a></li>
          <li> <a href="mission_statement">mission statement</a></li>
          <li> <a href="login">Login</a></li>
          <li> <a href="contact"><img src="../static/imag/contact.png" alt="Contact" class="contact"></a></li>
        </ul>
      </nav>
  </div>

{% block bodycontent %}
{% endblock bodycontent %}

</body>
</html>
</code>```

This is my about_us.html:

```<code>{% extends "base.html" %}
{% block bodycontent %}
<link rel="stylesheet" href="../static/css/about_us.css">

  <div>
    <h1>Welcome!</h1>
    <h2>About us</h2>
    <p>insert paragraph about us</p>
  </div>

{% endblock bodycontent %}
</code>```

and finally, this is an excerpt of the css which is aplying only to the base.html - in this case, the .header and nav are applying, but the div etc. aren't.:

```<code>.header{
  overflow: visible;
  background-color: White;
  position: sticky;
  padding: 0;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

nav{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

div{
  color: DimGray;
  font-family: Helvetica;
}

div h1{
  position: absolute;
  top: 17%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div h2{
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div p{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  font-size: 20px;
  text-align: center;
  line-height: 2em;
}
</code>```

I hope this contains all the information needed to answer the question. Sorry this is so long, I'm new to stack overflow and hope someone can help. Thank you in advance!

答:
In base.html add  <link rel="stylesheet" href="path/to/css/file"> in the head of your html.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="path/to/css/file"> <!-- Here -->
  <title>Welcome</title>
</head>
<body>

  <div class="header">
    <nav>
      <a href="/">Welcome</a>
        <ul class="nav_links">
          <li> <a href="about_us">About us</a></li>
          <li> <a href="mission_statement">mission statement</a></li>
          <li> <a href="login">Login</a></li>
          <li> <a href="contact"><img src="../static/imag/contact.png" alt="Contact" class="contact"></a></li>
        </ul>
      </nav>
  </div>

{% block bodycontent %}
{% endblock bodycontent %}

</body>
</html>
</code>```

Body:
I'm currently building a website and am having trouble getting the css to apply to parts of my html code. I have a base.html which I want displayed on every page, and I'm using {% block bodycontent %} in different documents to give the different pages specific features. However, I'm finding that the css stylesheet doesn't seem to apply to the code within the block, and is only applying to base.html. I'm using the flask framework, and am not sure if this may be the problem - when I run the html file locally without flask, the styling seems to be working, but of course the page is incomplete, because it is not interacting with the base.

This is my base:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Welcome</title>

      Welcome

 About us

 mission statement

 Login

{% block bodycontent %}
{% endblock bodycontent %}

This is my about_us.html:

{% extends "base.html" %}
{% block bodycontent %}
<link rel="stylesheet" href="../static/css/about_us.css">

Welcome!

About us

insert paragraph about us

{% endblock bodycontent %}

and finally, this is an excerpt of the css which is aplying only to the base.html - in this case, the .header and nav are applying, but the div etc. aren't.:

.header{
  overflow: visible;
  background-color: White;
  position: sticky;
  padding: 0;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

nav{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

div{
  color: DimGray;
  font-family: Helvetica;
}

div h1{
  position: absolute;
  top: 17%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div h2{
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div p{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  font-size: 20px;
  text-align: center;
  line-height: 2em;
}

I hope this contains all the information needed to answer the question. Sorry this is so long, I'm new to stack overflow and hope someone can help. Thank you in advance!

Body:
In base.html add  <link rel="stylesheet" href="path/to/css/file"> in the head of your html.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="path/to/css/file"> <!-- Here -->
  <title>Welcome</title>
</head>
<body>

  <div class="header">
    <nav>
      <a href="/">Welcome</a>
        <ul class="nav_links">
          <li> <a href="about_us">About us</a></li>
          <li> <a href="mission_statement">mission statement</a></li>
          <li> <a href="login">Login</a></li>
          <li> <a href="contact"><img src="../static/imag/contact.png" alt="Contact" class="contact"></a></li>
        </ul>
      </nav>
  </div>

{% block bodycontent %}
{% endblock bodycontent %}

</body>
</html>


问:
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>```

答:
Try to catch the exact exception the error is client exception of 404 status code try to catch it directly and catch its response. Also I have never heard of function $e->getResponseBody() it should be $e->getResponse() as given in guzzle docs. You can take more reference from this answer

```<code>public function callback(Request $request)
  {
    // Validate state
    // ...

    // Initialize the OAuth client
      try {
        // Make the token request
        // ...
        // Define user details and manager details
        // ...

      }
      catch(\GuzzleHttp\Exception\ClientException $e){
            if($e->hasResponse()){
               if ($e->getResponse()->getStatusCode() == '404'){
                    $avatar = null;
                    return redirect('/')
                      ->with('error', 'Error requesting access token')
                      ->with('errorDetail', json_encode($e->getResponse()));
               }
            }
      }
      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>```

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'));
  }

Body:
Try to catch the exact exception the error is client exception of 404 status code try to catch it directly and catch its response. Also I have never heard of function $e->getResponseBody() it should be $e->getResponse() as given in guzzle docs. You can take more reference from this answer

public function callback(Request $request)
  {
    // Validate state
    // ...

    // Initialize the OAuth client
      try {
        // Make the token request
        // ...
        // Define user details and manager details
        // ...

      }
      catch(\GuzzleHttp\Exception\ClientException $e){
            if($e->hasResponse()){
               if ($e->getResponse()->getStatusCode() == '404'){
                    $avatar = null;
                    return redirect('/')
                      ->with('error', 'Error requesting access token')
                      ->with('errorDetail', json_encode($e->getResponse()));
               }
            }
      }
      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'));
  }


问:
what's the recommended way to copy non-compiled rust assets to target
What is the recommended way to copy non-compiled rust application assets such as HTML and image files to the build target directory.

In particular, is placing a build.rs script in the project root and manually coding those actions truly the recommended method?

答:
There are macros, std::include_bytes!(file_path) and std::include_str!(file_path), for incorporating the contents of files into the compiled binary. (However, the documentation is not explicit about the incorporation part though).

There are a number of additional standard macros.


问:
How to correctly stop overflowing and maintain the responsiveness
I have made a sticky header using flexbox then using a grid for the body. But applying height to grid items makes the page overflow which I don't want. I have figured I can solve this overflowing by calc(100vh - the height of header) but eventually the height of the header will change if I change the resolution to that of mobile making the new height useless.

The other solution I can think of is by explicitly adding a height to the header but I think that is not the right solution to my problem
https://codepen.io/iwantroca-the-flexboxer/pen/ZEayyqp

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html {
  font-size: 17px;
  font-family: poppins;
}

body {
  min-height: 100vh;
}

header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgb(139, 48, 48);
  color: white;
}

header>h2 {
  font-style: italic;
  font-weight: lighter;
  margin-left: 3em;
}

.app_logo {
  font-size: 2.3em;
  margin-right: 10px;
  color: rgba(187, 190, 136, 0.774);
}

/* MAIN */

main {
  display: grid;
  grid-template-columns: 1fr 4fr;
}

#projects_bar {
  background: red;
  height: 100vh;
}

#tasks_bar {
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Todo-App</title>
</head>

<body>
  <header>
    <i class="fa-solid fa-check-double app_logo"></i>
    <h1>Todo App</h1>
    <h2>Get things done</h2>
  </header>
  <main>
    <nav id="projects_bar">
      <h2>Projects</h2>
    </nav>
    <div id="tasks_bar">
      <h2>Tasks</h2>
    </div>
  </main>
</body>

</html></code>```

答:
With your current structure why not just make header 10vh and main 90vh. This means that #projects_bar and #tasks_bar will also be 90vh also because 100vh (what you previously had) will cause overflow on the y-axis.

You can also add overflow-y: hidden; on the body to make it not scroll when switching device types.

Edit ~ mentioned in comments, same result without setting a height to the header. Remove all heights, and set height on body to 100vh. min-height: 100vh; is not the same as height: 100vh; so you need to establish that first. Then you can just set height: 100%; to main, and it will fill the remaining viewport.

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html {
  font-size: 17px;
  font-family: poppins;
}

body {
  height: 100vh;
  min-height: 100vh;
  overflow-y: hidden;
}

header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgb(139, 48, 48);
  color: white;
}

header>h2 {
  font-style: italic;
  font-weight: lighter;
  margin-left: 3em;
}

.app_logo {
  font-size: 2.3em;
  margin-right: 10px;
  color: rgba(187, 190, 136, 0.774);
}

/* MAIN */

main {
  display: grid;
  grid-template-columns: 1fr 4fr;
  height: 100%;
}

#projects_bar {
  background: red;
}

#tasks_bar {
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Todo-App</title>
</head>

<body>
  <header>
    <i class="fa-solid fa-check-double app_logo"></i>
    <h1>Todo App</h1>
    <h2>Get things done</h2>
  </header>
  <main>
    <nav id="projects_bar">
      <h2>Projects</h2>
    </nav>
    <div id="tasks_bar">
      <h2>Tasks</h2>
    </div>
  </main>
</body>

</html></code>```

Body:
I have made a sticky header using flexbox then using a grid for the body. But applying height to grid items makes the page overflow which I don't want. I have figured I can solve this overflowing by calc(100vh - the height of header) but eventually the height of the header will change if I change the resolution to that of mobile making the new height useless.

The other solution I can think of is by explicitly adding a height to the header but I think that is not the right solution to my problem
https://codepen.io/iwantroca-the-flexboxer/pen/ZEayyqp

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html {
  font-size: 17px;
  font-family: poppins;
}

body {
  min-height: 100vh;
}

header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgb(139, 48, 48);
  color: white;
}

header>h2 {
  font-style: italic;
  font-weight: lighter;
  margin-left: 3em;
}

.app_logo {
  font-size: 2.3em;
  margin-right: 10px;
  color: rgba(187, 190, 136, 0.774);
}

/* MAIN */

main {
  display: grid;
  grid-template-columns: 1fr 4fr;
}

#projects_bar {
  background: red;
  height: 100vh;
}

#tasks_bar {
  background: yellow;
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Todo-App</title>

Todo App

Get things done

Projects

Tasks

Body:
With your current structure why not just make header 10vh and main 90vh. This means that #projects_bar and #tasks_bar will also be 90vh also because 100vh (what you previously had) will cause overflow on the y-axis.

You can also add overflow-y: hidden; on the body to make it not scroll when switching device types.

Edit ~ mentioned in comments, same result without setting a height to the header. Remove all heights, and set height on body to 100vh. min-height: 100vh; is not the same as height: 100vh; so you need to establish that first. Then you can just set height: 100%; to main, and it will fill the remaining viewport.

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html {
  font-size: 17px;
  font-family: poppins;
}

body {
  height: 100vh;
  min-height: 100vh;
  overflow-y: hidden;
}

header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgb(139, 48, 48);
  color: white;
}

header>h2 {
  font-style: italic;
  font-weight: lighter;
  margin-left: 3em;
}

.app_logo {
  font-size: 2.3em;
  margin-right: 10px;
  color: rgba(187, 190, 136, 0.774);
}

/* MAIN */

main {
  display: grid;
  grid-template-columns: 1fr 4fr;
  height: 100%;
}

#projects_bar {
  background: red;
}

#tasks_bar {
  background: yellow;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Todo-App</title>
</head>

<body>
  <header>
    <i class="fa-solid fa-check-double app_logo"></i>
    <h1>Todo App</h1>
    <h2>Get things done</h2>
  </header>
  <main>
    <nav id="projects_bar">
      <h2>Projects</h2>
    </nav>
    <div id="tasks_bar">
      <h2>Tasks</h2>
    </div>
  </main>
</body>

</html>


问:
Pipeline hangs after starting Azurite

I used the following yml content. Used Azurite 3.15 and 3.9. But no luck. Then I tried as separate jobs. Still unable to pass the integration test.

```<code> stages:
    - stage: Publish
      displayName: 'Build and Publish Artifacts'
      jobs:
      - job: 'NGKMediaManagementAPI'
        steps:
        - task: NodeTool@0
          inputs:
             versionSpec: 13.x
        - script : npm install -g azurite@3.9.0
        - script : mkdir azurite
        - script : azurite
</code>```

答:
Solved the hanging issue and Passed the Init tests(based on Azurite) in pipeline.
use the following command in your yml file.
Most importantly start /B azurite will remove the hanging issue !!!

```<code> - task: NodeTool@0
      inputs:
         versionSpec: 13.x
    - script : npm install -g azurite
      displayName: Install Azurite
    - script : start /B azurite
      displayName: Start azurite
</code>```

below is success the pipeline

Title: Pipeline hangs after starting Azurite

Body:
I used the following yml content. Used Azurite 3.15 and 3.9. But no luck. Then I tried as separate jobs. Still unable to pass the integration test.

 stages:
    - stage: Publish
      displayName: 'Build and Publish Artifacts'
      jobs:
      - job: 'NGKMediaManagementAPI'
        steps:
        - task: NodeTool@0
          inputs:
             versionSpec: 13.x
        - script : npm install -g azurite@3.9.0
        - script : mkdir azurite
        - script : azurite

Body:
Solved the hanging issue and Passed the Init tests(based on Azurite) in pipeline.
use the following command in your yml file.
Most importantly start /B azurite will remove the hanging issue !!!

 - task: NodeTool@0
      inputs:
         versionSpec: 13.x
    - script : npm install -g azurite
      displayName: Install Azurite
    - script : start /B azurite
      displayName: Start azurite

below is success the pipeline


问:
Redirecting to subpage with id
I've had two routes:

```<code><Route path="/client/:id/members" component={Members} />
<Route path="/client/:id/members/:mid" component={MemberProfile} />
</code>```

why when I'm trigger:

```<code>window.location.href = `/client/${id}/members/${mid}`;
</code>```

then my url is changed to correct form like in the route path but not redirect me to MemberProfile component?

Thanks for any help!

答:
Given:

```<code><Route path="/client/:id/members" component={Members} />
<Route path="/client/:id/members/:mid" component={MemberProfile} />
</code>```

It seems like you are rendering these routes into a Switch component. Remember that the Switch component renders the first child <Route> or <Redirect> that matches the location. This means that route path order and specificity matters.

Order your routes by decreasing specificity. "/client/:id/members/:mid" is more specific than "/client/:id/members" and should render higher in the Switch.

```<code><Switch>
  ...
  <Route path="/client/:id/members/:mid" component={MemberProfile} />
  <Route path="/client/:id/members" component={Members} />
  ...
</Switch>
</code>```

Additional note

You may want to avoid using window.location.href to redirect as this reloads the entire page, and thus, your app. Use a Redirect component to render a declarative navigation, or use history.replace(`/client/${id}/members/${mid}`); to issue an imperative redirect.

Title: Redirecting to subpage with id

Body:
I've had two routes:

<Route path="/client/:id/members" component={Members} />
<Route path="/client/:id/members/:mid" component={MemberProfile} />

why when I'm trigger:

window.location.href = `/client/${id}/members/${mid}`;

then my url is changed to correct form like in the route path but not redirect me to MemberProfile component?

Thanks for any help!

Body:
Given:

<Route path="/client/:id/members" component={Members} />
<Route path="/client/:id/members/:mid" component={MemberProfile} />

It seems like you are rendering these routes into a Switch component. Remember that the Switch component renders the first child <Route> or <Redirect> that matches the location. This means that route path order and specificity matters.

Order your routes by decreasing specificity. "/client/:id/members/:mid" is more specific than "/client/:id/members" and should render higher in the Switch.

<Switch>
  ...
  <Route path="/client/:id/members/:mid" component={MemberProfile} />
  <Route path="/client/:id/members" component={Members} />
  ...
</Switch>

Additional note

You may want to avoid using window.location.href to redirect as this reloads the entire page, and thus, your app. Use a Redirect component to render a declarative navigation, or use history.replace(`/client/${id}/members/${mid}`); to issue an imperative redirect.


问:
How to undo ALTER TABLE using sqlplus (Oracle 10g Express)?
```<code>rollback;
</code>```

doesn't seem to undo alter table changes.

Background:

I'm generating some .sql scripts (based on parsed Hibernate scripts) which are trashing my tables. Importing the full database for testing takes up to 30 minutes (also slowing my machine) and as much as I enjoy taking breaks, i'd prefer to just undo everything with a command such as rollback and try again.

btw this is Oracle 10g Express Edition Release 10.2.0.1.0

Is this even possible?

答:
With the express edition, I'm not sure this is possible.  You cannot rollback a DDL operation like ALTER TABLE because DDL is implicitly committed.

Oracle does have the option to create restore points that you can then flashback the entire database to a point in time relatively quickly.  That will undo the effects of all committed transactions (DML and DDL) between the creation of the restore point and the point where you issued the flashback command.  Here is an example of creating and flashing back to a restore point and here's another that does the flashback for the entire database.  I'm just not sure that this functionality is available in the express edition.

Body:
rollback;

doesn't seem to undo alter table changes.

Background:

I'm generating some .sql scripts (based on parsed Hibernate scripts) which are trashing my tables. Importing the full database for testing takes up to 30 minutes (also slowing my machine) and as much as I enjoy taking breaks, i'd prefer to just undo everything with a command such as rollback and try again.

btw this is Oracle 10g Express Edition Release 10.2.0.1.0

Is this even possible?


问:
A global struct pointer is used, but it does not take input. In C
The input lines are marked beside.
Here,
*ptr is a global struct pointer.
In the main function, the get_data() function is called but it does not take any input rather the program terminates.

```<code>    #include<stdio.h>
    #include<stdlib.h>

    struct detail
    {
        int present, absent, credit, left_weeks;
    };

    struct detail *ptr;             // global

    void get_data()
    {
        printf("\nYou have opted for Entering the data \n");
        printf("\nEnter the number of presents - ");
        scanf("%d",&ptr->present);                                       // First input

        printf("\nEnter the number of absents - ");
        scanf("%d",&ptr->absent);                                        // Second input

        printf("\nEnter the subject credit - ");
        scanf("%d",&ptr->credit);                                        // Third input

        printf("\nEnter the number of weeks left - ");
        scanf("%d",&ptr->left_weeks);                                    // Fourth input
    }

    int main()
    {
        get_data();
    }
</code>```

I have checked in visual studio code and also an online compiler.
Could anyone help.

答:
already answered but I want to elaborate.

```<code>struct detail *ptr;
</code>```

creates a pointer whose job is to point at an instance of detail. but you have not told it which one to point at (Imagine you had several instances of details in you program). In fact you dont have any instances of detail yet.

So you have to create an instance of detail

On the stack and set ptr to point at it

```<code> int main (..){
   ...
   struct detail d;
   ptr = &d;
</code>```

On the heap

```<code> int main (..){
   ...
   struct detail *d = malloc(sizeof(struct detail));
   ptr = d;  // d is a pointer already here
</code>```

Or static global

```<code>  struct detail d;
  ....
  int main(..){

    ....
    ptr = &d;
</code>```

Body:
The input lines are marked beside.
Here,
*ptr is a global struct pointer.
In the main function, the get_data() function is called but it does not take any input rather the program terminates.

    #include<stdio.h>
    #include<stdlib.h>

    struct detail
    {
        int present, absent, credit, left_weeks;
    };

    struct detail *ptr;             // global

    void get_data()
    {
        printf("\nYou have opted for Entering the data \n");
        printf("\nEnter the number of presents - ");
        scanf("%d",&ptr->present);                                       // First input

        printf("\nEnter the number of absents - ");
        scanf("%d",&ptr->absent);                                        // Second input

        printf("\nEnter the subject credit - ");
        scanf("%d",&ptr->credit);                                        // Third input

        printf("\nEnter the number of weeks left - ");
        scanf("%d",&ptr->left_weeks);                                    // Fourth input
    }

    int main()
    {
        get_data();
    }

I have checked in visual studio code and also an online compiler.
Could anyone help.

Body:
already answered but I want to elaborate.

struct detail *ptr;

creates a pointer whose job is to point at an instance of detail. but you have not told it which one to point at (Imagine you had several instances of details in you program). In fact you dont have any instances of detail yet.

So you have to create an instance of detail

On the stack and set ptr to point at it

 int main (..){
   ...
   struct detail d;
   ptr = &d;

On the heap

 int main (..){
   ...
   struct detail *d = malloc(sizeof(struct detail));
   ptr = d;  // d is a pointer already here

Or static global

  struct detail d;
  ....
  int main(..){

    ....
    ptr = &d;


答:
```<code>library(tidyverse)

df %>%
  group_by(ID) %>%
  pivot_longer(-ID) %>%
  filter(value>0) %>%
  summarise(TRA = str_c('{', toString(name), '}'))

# A tibble: 4 x 2
     ID TRA
  <int> <chr>
1     1 {P2, P3}
2     2 {P1, P2, p265}
3     3 {P3, p265}
4  1000 {P1, P3}
</code>```

Data:

```<code>df <- structure(list(ID = c(1L, 2L, 3L, 1000L), P1 = c(0L, 1L, 0L,
1L), P2 = c(1L, 1L, 0L, 0L), P3 = c(1L, 0L, 1L, 1L), p265 = c(0L,
1L, 1L, 0L)), row.names = c(NA, -4L), class = "data.frame")
</code>```

Title: convert data to transaction in Rstudio

Body:
I have a data as follows and I want to convert it to transaction format at Rstudio.Please guide me

ID    P1 P2 P3 ....... p265                 ID     TRA
1     0  1  1  .......  0                   1      {P2,p3,....}
2     1  1  0  .......  1                   2      {P1,P2,...,P265}
3     0  0  1  .......  1                   3      {p3,...,p265}
.     .  .  .           .                   .      .
.     .  .  .           .                   .      .
.     .  .  .           .                   .      .
1000  1  0  1  .......  0                   1000   {p1,p3,...}

Body:
library(tidyverse)

df %>%
  group_by(ID) %>%
  pivot_longer(-ID) %>%
  filter(value>0) %>%
  summarise(TRA = str_c('{', toString(name), '}'))

# A tibble: 4 x 2
     ID TRA
  <int> <chr>
1     1 {P2, P3}
2     2 {P1, P2, p265}
3     3 {P3, p265}
4  1000 {P1, P3}

Data:

df <- structure(list(ID = c(1L, 2L, 3L, 1000L), P1 = c(0L, 1L, 0L,
1L), P2 = c(1L, 1L, 0L, 0L), P3 = c(1L, 0L, 1L, 1L), p265 = c(0L,
1L, 1L, 0L)), row.names = c(NA, -4L), class = "data.frame")


问:
Kivy error, [CRITICAL] [Text ] unable to find any valuable text provider (python 3.6.1) (windows 10)
I have been trying to use Kivy (1.10.0) in pycharm, when it came to testing the install with:

```<code>from kivy.app import App
from kivy.uix.button import Button

class TutorialApp(App):

    def build(self):
        return Button(text='Hello Kivy')

if __name__ == '__main__':
    TutorialApp().run()
</code>```

this was also tried with 'Label' in place of 'Button'

I got this when ran in pycharm both times:

```<code>[INFO   ] [Logger      ] Record log in C:\Users\Denise\.kivy\logs\kivy_17-08-12_56.txt
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Text        ] Unable to find any valuable Text provider.
sdl2 - ImportError: DLL load failed: The specified module could not be found.
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\text\text_sdl2.py", line 12, in <module>
    from kivy.core.text._text_sdl2 import (_SurfaceContainer, _get_extents,

pil - ModuleNotFoundError: No module named 'PIL'
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\text\text_pil.py", line 7, in <module>
    from PIL import Image, ImageFont, ImageDraw

[CRITICAL] [App         ] Unable to get a Text provider, abort.
</code>```

The same error occurred in python 3.6.1 shell when typing the following:

```<code>from kivy.uix.button import Button
</code>```

or

```<code>from kivy.uix.button import Lable
</code>```

Please help, how do I get Kivy to run?

答:
The way I solved this error is by creating a virtual environment and running the program on the virtual environment</p>
```<code>(kivy_venv) C:\Users\musers\PycharmProjects\kivy-projects>python main.py
</code>```

Body:
I have been trying to use Kivy (1.10.0) in pycharm, when it came to testing the install with:

from kivy.app import App
from kivy.uix.button import Button

class TutorialApp(App):

    def build(self):
        return Button(text='Hello Kivy')

if __name__ == '__main__':
    TutorialApp().run()

this was also tried with 'Label' in place of 'Button'

I got this when ran in pycharm both times:

[INFO   ] [Logger      ] Record log in C:\Users\Denise\.kivy\logs\kivy_17-08-12_56.txt
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Text        ] Unable to find any valuable Text provider.
sdl2 - ImportError: DLL load failed: The specified module could not be found.
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\text\text_sdl2.py", line 12, in <module>
    from kivy.core.text._text_sdl2 import (_SurfaceContainer, _get_extents,

pil - ModuleNotFoundError: No module named 'PIL'
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\Denise\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\text\text_pil.py", line 7, in <module>
    from PIL import Image, ImageFont, ImageDraw

[CRITICAL] [App         ] Unable to get a Text provider, abort.

The same error occurred in python 3.6.1 shell when typing the following:

from kivy.uix.button import Button

or

from kivy.uix.button import Lable

Please help, how do I get Kivy to run?

Body:
The way I solved this error is by creating a virtual environment and running the program on the virtual environment

(kivy_venv) C:\Users\musers\PycharmProjects\kivy-projects>python main.py


问:
Opsgenie - Create Alert API doesn't set responders tag
I'm having issues with the Opsgenie's API integration and creating alerts.

In their docs, they state that you can set the responders field to a user or team, but upon creating the alert I can't see this field set properly.

E.g.
When sending a create alert/POST request to their alerts endpoint https://api.eu.opsgenie.com/v2/alerts, with this payload

```<code>{
    "message": "Alert Sample",
    "responders": [
        {
            "type": "user",
            "name": "some-user"
        }
    ],
    "priority": "P5"
}
</code>```

an alert will be created indeed, but the given responders field will be set to the user/team who owns the API integration (the team for which the API integration was created for). Meaning, the responders field will always be set to the same value as the owner field, e.g.
owner=team-name, responders=team-name.

What am I missing? Is there any way you an set the responders field to a value different from the owner?

Is this a bug in their API integration or do I just have have a wrong expectation what these fields represent?

答:
I don't know whether the order of "name" and "type" is relevant here, but in following sample they first set "name" and then "type": https://community.atlassian.com/t5/Opsgenie-questions/Re-Re-Cannot-use-Responder-or-Tags-in-API-to-Create-an/qaq-p/1312154/comment-id/412#M412

Another consideration: as you already said, in a team-level API integration the responder is automatically the team who owns the integration. Maybe this is not supposed to be overridden.
Did you also try to set the responder in a global API integration? (those are available only in Standard or Enterprise plan and have to be implemented by the OpsGenie-Owner)

Body:
I'm having issues with the Opsgenie's API integration and creating alerts.

In their docs, they state that you can set the responders field to a user or team, but upon creating the alert I can't see this field set properly.

E.g.
When sending a create alert/POST request to their alerts endpoint https://api.eu.opsgenie.com/v2/alerts, with this payload

{
    "message": "Alert Sample",
    "responders": [
        {
            "type": "user",
            "name": "some-user"
        }
    ],
    "priority": "P5"
}

an alert will be created indeed, but the given responders field will be set to the user/team who owns the API integration (the team for which the API integration was created for). Meaning, the responders field will always be set to the same value as the owner field, e.g.
owner=team-name, responders=team-name.

What am I missing? Is there any way you an set the responders field to a value different from the owner?

Is this a bug in their API integration or do I just have have a wrong expectation what these fields represent?


问:
HLS stream is not working with react-native-video
I am trying to embed live stream using react-native-video packages, but HLS link is not working, please help

答: Thank you for contacting AWS support. May I know what error did you see? And yes, can you playback the stream on other players?</p>


问:
'git diff' between a remote and local repository
I am trying to diff my local file with a GitHub repository before I submit a pull request, so I can see what will show up. Is there an accurate way of doing this?

I assume GitHub's compare tool manipulates Git's diff.

答:
Important to remember:
Git diff will show you diferences between two commited branchs ( remote or local).

Step 1) - Commit local

So the first step to do is make sure you have commited your local repository. You can run git status to see if there is any file left.

If you need to add a file run a git add {filename} or to add all files git add .. Then you can run a  git commit -m "message" to commit you local files.

Step 2) - Fetch your branch from remote

You can fetch your remote using  git fetch origin master. If you see a message like below, you are good to go.

```<code>branch            master     -> FETCH_HEAD
</code>```

Note that origin is the repository and master is the branch within
that repository.

Step 3 Check differences

Now you can either git diff --summary FETCH_HEAD or  git diff origin/master master --summary too see your changes.

Body:
Important to remember:
Git diff will show you diferences between two commited branchs ( remote or local).

Step 1) - Commit local

So the first step to do is make sure you have commited your local repository. You can run git status to see if there is any file left.

If you need to add a file run a git add {filename} or to add all files git add .. Then you can run a  git commit -m "message" to commit you local files.

Step 2) - Fetch your branch from remote

You can fetch your remote using  git fetch origin master. If you see a message like below, you are good to go.

branch            master     -> FETCH_HEAD

Note that origin is the repository and master is the branch within
that repository.

Step 3 Check differences

Now you can either git diff --summary FETCH_HEAD or  git diff origin/master master --summary too see your changes.


问:
POST REST Call from C#
Trying to do POST rest call to my endpoint, but I want to pass empty body and access token. How can I do that ?

My code is :

```<code>using (var client = new HttpClient())
{
  var endPoint = new Uri("my EndPoint");
  var emptyBody = {}; // Getting an error here, not sure if it is right
  var newPostJson = JsonConvert.SerializeObject(emptyBody);
  var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
  var result = client.PostAsync(endPoint, payload).Result.Content.ReadAsStringAsync().Result;
}
</code>```

Can you tell how Can I pass access token and empty body and do you recommend any other change ? It is my first REST CALL.

答:
you pass access token and empty body like this:</p>
```<code>using (var httpClient = new HttpClient())
{
  try
  {
  var request = new HttpRequestMessage(HttpMethod.Post, url);
  request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); // add access token
  string jsonContent=""; // this is an empty json you send it as a body
  request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

  var response = await httpClient.SendAsync(request);
  var content = await response.Content.ReadAsStringAsync();

  }catch(Exception ex){
  }
}
</code>```

Title: POST REST Call from C#

Body:
Trying to do POST rest call to my endpoint, but I want to pass empty body and access token. How can I do that ?

My code is :

using (var client = new HttpClient())
{
  var endPoint = new Uri("my EndPoint");
  var emptyBody = {}; // Getting an error here, not sure if it is right
  var newPostJson = JsonConvert.SerializeObject(emptyBody);
  var payload = new StringContent(newPostJson, Encoding.UTF8, "application/json");
  var result = client.PostAsync(endPoint, payload).Result.Content.ReadAsStringAsync().Result;
}

Can you tell how Can I pass access token and empty body and do you recommend any other change ? It is my first REST CALL.

Body:
you pass access token and empty body like this:

using (var httpClient = new HttpClient())
{
  try
  {
  var request = new HttpRequestMessage(HttpMethod.Post, url);
  request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); // add access token
  string jsonContent=""; // this is an empty json you send it as a body
  request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

  var response = await httpClient.SendAsync(request);
  var content = await response.Content.ReadAsStringAsync();

  }catch(Exception ex){
  }
}


问:
Express route works fine, until it calls separate function, crashes server
The first GET request, (/not-work), calls a separate function, database(), with some code to connect to a database and return data. This successfully runs the database() function and that function returns data, but const result, does not get that data properly returned. Instead an unfufilled database connection object is returned. The second request however, (/works), runs nearly the exact same code as, just within the GET route itself. This works perfectly. I cannot for the life of me understand why.

const http = require('http');
const express = require('express');
const app = express();
const sql = require('mssql')
const sqlConfig = {
    user: 'login',
    password: 'pass',
    database: 'database',
    server: '123.456.789.012'
}

const database = () => {
    return sql.connect(sqlConfig,
        (err) => {
            if (err) console.log(err);
            try {
                return new sql.Request()
                    .execute('dbo.SQLProcedure', (err, recordset) => {
                        if (err) console.log(err)
                        return recordset;
                    });
            }
            catch (err) {
                console.log(err)
            }
        });
}

app.get('/not-work', (req, res) => {
    const result = database();
    console.log(result);
    res.send(result);
});

app.get('/works', (req, res) => {
    sql.connect(sqlConfig,
        (err) => {
            if (err) console.log(err);
            try {
                new sql.Request()
                    .execute('dbo.SQLProcedure', (err, recordset) => {
                        if (err) console.log(err)
                        res.send(recordset);
                    });
            }
            catch (err) {
                console.log(err)
                res.send(err);
            }
        });
});

http.createServer(app).listen(888, () => {
    console.log('Server listening 888');
});```

答:
you must use async function and Promise</p>
```<code>const database = async () => {
  return new Promise( (resolve, reject) => {
    sql.connect(sqlConfig,
      (err) => {
        if (err) console.log(err); // or reject(err)
        try {
          new sql.Request()
            .execute('dbo.SQLProcedure', (err, recordset) => {
              if (err) console.log(err) // or reject(err)
              return resolve(recordset);
            });
        } catch (err) {
          console.log(err) // or reject(err)
        }
      });
  })
}

</code>```
```<code>app.get('/not-work', async (req, res) => {
    const result = await database();
    console.log(result);
    res.send(result);
});
</code>```

Body:
you must use async function and Promise

const database = async () => {
  return new Promise( (resolve, reject) => {
    sql.connect(sqlConfig,
      (err) => {
        if (err) console.log(err); // or reject(err)
        try {
          new sql.Request()
            .execute('dbo.SQLProcedure', (err, recordset) => {
              if (err) console.log(err) // or reject(err)
              return resolve(recordset);
            });
        } catch (err) {
          console.log(err) // or reject(err)
        }
      });
  })
}

app.get('/not-work', async (req, res) => {
    const result = await database();
    console.log(result);
    res.send(result);
});


问:
Trying to get text with properties from html data
I'm trying to get text from HTML with it's properties (bold, underlined, italic, superscript etc.) but I am struggling with nested ones (like  Lorem  Ipsum , in this case Lorem should be bold and Ipsum should be bold and underlined).

Example Data

 NormalBold BoldUnderlined Bold Italic

I need to use this texts in Indesign Script and I need to assign character styles for these properties. Is there any tool or technique for PHP or Javascript that I can use?

答:
Try if DOMParser is available in the environment where you're going to run your JS code.

This parses the html string and outputs a tree structure of the nodes and their texts.

const htmlString = '
 NormalBold BoldUnderlined Bold Italic
';

const htmlElement = (new DOMParser().parseFromString(htmlString, 'text/html')).firstChild.childNodes[1].firstChild;

const tree = convertDomToArray(htmlElement);

console.log(tree);

function convertDomToArray(element) {
  if (element.nodeName === '#text') {
    return element.nodeValue;
  }

  let children = [];
  for (let childElement of element.childNodes) {
    children.push(convertDomToArray(childElement));
  }

  let output = {};
  output[element.nodeName] = children;

  return output;
}```

Body:
Try if DOMParser is available in the environment where you're going to run your JS code.

This parses the html string and outputs a tree structure of the nodes and their texts.

const htmlString = '<p> Normal<b>Bold</b> <b>Bold<u>Underlined</u></b> <b><i>Bold Italic</i></b><p/>';

const htmlElement = (new DOMParser().parseFromString(htmlString, 'text/html')).firstChild.childNodes[1].firstChild;

const tree = convertDomToArray(htmlElement);

console.log(tree);

function convertDomToArray(element) {
  if (element.nodeName === '#text') {
    return element.nodeValue;
  }

  let children = [];
  for (let childElement of element.childNodes) {
    children.push(convertDomToArray(childElement));
  }

  let output = {};
  output[element.nodeName] = children;

  return output;
}


问:
functions and events in OCI
I have a scenario in where I want to run commands in instance using functions based on events in OCI(oracle cloud infrastructure).
flow :
object storage: object update/modification -> trigger event -> execute function : to run commands in specific instances using run command
Is this achievable ?
As currently I see that to execute run command service we would need oci config files(profile)

答:
To do this, you can use the OCI Java or Python SDK within the function to invoke the Run Command API.

See API details at “Using the API” in the docs. You will also need to configure the Functions resource principal to have access to the Compute instance in question. See this for details on configuring the Functions resource principal

Title: functions and events in OCI


问:
Why does Spring Security reject my Keycloak auth token with "No AuthenticationProvider found"?
I'm trying to figure out why my Spring Boot application is rejecting my Keycloak JWT bearer token with a "No AuthenticationProvider found" error message.

I have a few services running in a docker compose environment:

```<code>ui (angular) -> proxy (nginx) -> rest api (spring boot) -> auth service (keycloak)
</code>```

The angular ui pulls the correct keycloak client from the rest service, and then authenticates without issue.  I get back a JWT token, and then turn around and hand that to follow on requests to the rest api in a header Authorization: bearer [token].

In the rest API, I can see the correct bearer token come in as a header:

```<code>2022-02-11 01:01:31.411 DEBUG 13 --- [nio-8080-exec-4] o.a.coyote.http11.Http11InputBuffer      : Received [GET /api/v3/accounts HTTP/1.0
X-Real-IP: 192.168.80.1
X-Forwarded-For: 192.168.80.1
Host: rest-api.mylocal.com
Connection: close
Accept: application/json, text/plain, */*
Authorization: Bearer eyJhbGciO...
...
2022-02-11 01:01:31.421 DEBUG 13 --- [nio-8080-exec-4] o.k.adapters.PreAuthActionsHandler       : adminRequest http://rest-api.mylocal.com/api/v3/accounts
...
</code>```

So the bearer token is there, and with https://jwt.io/ I can verify it's what I would expect:

```<code>{
  "exp": 1644515847,
  ...
  "iss": "http://auth-service.mylocal.com/auth/realms/LocalTestRealm",
  ...
  "typ": "Bearer",
  "azp": "LocalTestClient",
  ...
  "allowed-origins": [
    "http://web-ui.mylocal.com"
  ],
  "realm_access": {
    "roles": [
      "offline_access",
      "default-roles-localtestrealm",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
  "scope": "openid email profile",
  ...
}
</code>```

Processing continues by the rest api - it contacts the keycloak service and pulls the well known config:

```<code>...
2022-02-11 01:01:33.321  INFO 13 --- [nio-8080-exec-4] o.keycloak.adapters.KeycloakDeployment   : Loaded URLs from http://auth-service.mylocal.com/auth/realms/LocalTestRealm/.well-known/openid-configuration
...
</code>```

Finally it looks like it successfully parses the bearer token apart, grabs the user and authenticates them:

```<code>2022-02-11 01:01:33.521 DEBUG 13 --- [nio-8080-exec-4] o.a.h.impl.conn.tsccm.ConnPoolByRoute    : Releasing connection [{}->http://auth-service.mylocal.com:80][null]
2022-02-11 01:01:33.521 DEBUG 13 --- [nio-8080-exec-4] o.a.h.impl.conn.tsccm.ConnPoolByRoute    : Pooling connection [{}->http://auth-service.mylocal.com:80][null]; keep alive indefinitely
2022-02-11 01:01:33.521 DEBUG 13 --- [nio-8080-exec-4] o.a.h.impl.conn.tsccm.ConnPoolByRoute    : Notifying no-one, there are no waiting threads
2022-02-11 01:01:33.530 DEBUG 13 --- [nio-8080-exec-4] o.k.a.rotation.JWKPublicKeyLocator       : Realm public keys successfully retrieved for client LocalTestClient. New kids: [8a7dIQFASdC8BHa0mUWwZX7RBBJSeJItdmzah0Ybpcw]
2022-02-11 01:01:33.546 DEBUG 13 --- [nio-8080-exec-4] o.k.a.BearerTokenRequestAuthenticator    : successful authorized
2022-02-11 01:01:33.550 TRACE 13 --- [nio-8080-exec-4] o.k.a.RefreshableKeycloakSecurityContext : checking whether to refresh.
2022-02-11 01:01:33.550 TRACE 13 --- [nio-8080-exec-4] org.keycloak.adapters.AdapterUtils       : useResourceRoleMappings
2022-02-11 01:01:33.550 TRACE 13 --- [nio-8080-exec-4] org.keycloak.adapters.AdapterUtils       : Setting roles:
2022-02-11 01:01:33.555 DEBUG 13 --- [nio-8080-exec-4] a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: []
2022-02-11 01:01:33.556 DEBUG 13 --- [nio-8080-exec-4] o.k.adapters.RequestAuthenticator        : User 'bf7307ca-9352-4a02-b288-0565e2b57292' invoking 'http://rest-api.mylocal.com/api/v3/accounts' on client 'LocalTestClient'
2022-02-11 01:01:33.556 DEBUG 13 --- [nio-8080-exec-4] o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
2022-02-11 01:01:33.556 DEBUG 13 --- [nio-8080-exec-4] f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED
</code>```

and then immediately after that fails with the No AuthenticationProvider found error:

```<code>2022-02-11 01:01:33.559 TRACE 13 --- [nio-8080-exec-4] f.KeycloakAuthenticationProcessingFilter : Failed to process authentication request

org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:234) ~[spring-security-core-5.5.1.jar!/:5.5.1]
</code>```

I'm at a loss how it can say Bearer AUTHENTICATED followed by Auth outcome: AUTHENTICATED followed by No AuthenticationProvider found...  I'm assuming it somehow can't convert this bearer token into a Keycloak token, even though it definitely came from my Keycloak server.

My app config:

```<code>@ComponentScan({"com.mycompany"})
@Configuration
@EnableJpaRepositories(basePackages = "com.mycompany")
@EntityScan("com.mycompany")
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class ApplicationConfiguration
        extends KeycloakWebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        super.configure(http);

        http
                .authorizeRequests()
                // These paths (comma separated) are allowed to all
                .antMatchers("/api/v3/auth/config").permitAll()
                .and()
                .authorizeRequests()
                // Everything else should be authenticated
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();
    }

    @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        // This just pulls the Keycloak config from a DB instead of the config file
        return new CustomKeycloakConfigResolver();

        // return new KeycloakSpringBootConfigResolver();
    }
}
</code>```

答:
Missing the global config to autowire in a Keycloak auth provider:</p>
```<code>    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth)
            throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider =
                keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
                new SimpleAuthorityMapper()
        );
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }
</code>```

Body:
I'm trying to figure out why my Spring Boot application is rejecting my Keycloak JWT bearer token with a "No AuthenticationProvider found" error message.

I have a few services running in a docker compose environment:

ui (angular) -> proxy (nginx) -> rest api (spring boot) -> auth service (keycloak)

The angular ui pulls the correct keycloak client from the rest service, and then authenticates without issue.  I get back a JWT token, and then turn around and hand that to follow on requests to the rest api in a header Authorization: bearer [token].

In the rest API, I can see the correct bearer token come in as a header:

2022-02-11 01:01:31.411 DEBUG 13 --- [nio-8080-exec-4] o.a.coyote.http11.Http11InputBuffer      : Received [GET /api/v3/accounts HTTP/1.0
X-Real-IP: 192.168.80.1
X-Forwarded-For: 192.168.80.1
Host: rest-api.mylocal.com
Connection: close
Accept: application/json, text/plain, */*
Authorization: Bearer eyJhbGciO...
...
2022-02-11 01:01:31.421 DEBUG 13 --- [nio-8080-exec-4] o.k.adapters.PreAuthActionsHandler       : adminRequest http://rest-api.mylocal.com/api/v3/accounts
...

So the bearer token is there, and with https://jwt.io/ I can verify it's what I would expect:

{
  "exp": 1644515847,
  ...
  "iss": "http://auth-service.mylocal.com/auth/realms/LocalTestRealm",
  ...
  "typ": "Bearer",
  "azp": "LocalTestClient",
  ...
  "allowed-origins": [
    "http://web-ui.mylocal.com"
  ],
  "realm_access": {
    "roles": [
      "offline_access",
      "default-roles-localtestrealm",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
  "scope": "openid email profile",
  ...
}

Processing continues by the rest api - it contacts the keycloak service and pulls the well known config:

...
2022-02-11 01:01:33.321  INFO 13 --- [nio-8080-exec-4] o.keycloak.adapters.KeycloakDeployment   : Loaded URLs from http://auth-service.mylocal.com/auth/realms/LocalTestRealm/.well-known/openid-configuration
...

Finally it looks like it successfully parses the bearer token apart, grabs the user and authenticates them:

2022-02-11 01:01:33.521 DEBUG 13 --- [nio-8080-exec-4] o.a.h.impl.conn.tsccm.ConnPoolByRoute    : Releasing connection [{}->http://auth-service.mylocal.com:80][null]
2022-02-11 01:01:33.521 DEBUG 13 --- [nio-8080-exec-4] o.a.h.impl.conn.tsccm.ConnPoolByRoute    : Pooling connection [{}->http://auth-service.mylocal.com:80][null]; keep alive indefinitely
2022-02-11 01:01:33.521 DEBUG 13 --- [nio-8080-exec-4] o.a.h.impl.conn.tsccm.ConnPoolByRoute    : Notifying no-one, there are no waiting threads
2022-02-11 01:01:33.530 DEBUG 13 --- [nio-8080-exec-4] o.k.a.rotation.JWKPublicKeyLocator       : Realm public keys successfully retrieved for client LocalTestClient. New kids: [8a7dIQFASdC8BHa0mUWwZX7RBBJSeJItdmzah0Ybpcw]
2022-02-11 01:01:33.546 DEBUG 13 --- [nio-8080-exec-4] o.k.a.BearerTokenRequestAuthenticator    : successful authorized
2022-02-11 01:01:33.550 TRACE 13 --- [nio-8080-exec-4] o.k.a.RefreshableKeycloakSecurityContext : checking whether to refresh.
2022-02-11 01:01:33.550 TRACE 13 --- [nio-8080-exec-4] org.keycloak.adapters.AdapterUtils       : useResourceRoleMappings
2022-02-11 01:01:33.550 TRACE 13 --- [nio-8080-exec-4] org.keycloak.adapters.AdapterUtils       : Setting roles:
2022-02-11 01:01:33.555 DEBUG 13 --- [nio-8080-exec-4] a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: []
2022-02-11 01:01:33.556 DEBUG 13 --- [nio-8080-exec-4] o.k.adapters.RequestAuthenticator        : User 'bf7307ca-9352-4a02-b288-0565e2b57292' invoking 'http://rest-api.mylocal.com/api/v3/accounts' on client 'LocalTestClient'
2022-02-11 01:01:33.556 DEBUG 13 --- [nio-8080-exec-4] o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
2022-02-11 01:01:33.556 DEBUG 13 --- [nio-8080-exec-4] f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED

and then immediately after that fails with the No AuthenticationProvider found error:

2022-02-11 01:01:33.559 TRACE 13 --- [nio-8080-exec-4] f.KeycloakAuthenticationProcessingFilter : Failed to process authentication request

org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:234) ~[spring-security-core-5.5.1.jar!/:5.5.1]

I'm at a loss how it can say Bearer AUTHENTICATED followed by Auth outcome: AUTHENTICATED followed by No AuthenticationProvider found...  I'm assuming it somehow can't convert this bearer token into a Keycloak token, even though it definitely came from my Keycloak server.

My app config:

@ComponentScan({"com.mycompany"})
@Configuration
@EnableJpaRepositories(basePackages = "com.mycompany")
@EntityScan("com.mycompany")
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class ApplicationConfiguration
        extends KeycloakWebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        super.configure(http);

        http
                .authorizeRequests()
                // These paths (comma separated) are allowed to all
                .antMatchers("/api/v3/auth/config").permitAll()
                .and()
                .authorizeRequests()
                // Everything else should be authenticated
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();
    }

    @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        // This just pulls the Keycloak config from a DB instead of the config file
        return new CustomKeycloakConfigResolver();

        // return new KeycloakSpringBootConfigResolver();
    }
}

Body:
Missing the global config to autowire in a Keycloak auth provider:

    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth)
            throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider =
                keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
                new SimpleAuthorityMapper()
        );
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }


问:
How to change the selected background color of a text pyqt5
I want to change the background color of the selection:

Someone can help me ?

答:
Using QPalette

Qt uses the QPalette as basis for drawing all its widgets; there are various roles to which colors (or, better, brushes) can be assigned, including the Highlight role used to draw the background of selected items and text.

You can get the global application palette (QApplication.palette()) or that of the widget, and set the color for each role; note that changing the palette has no direct effect on the widget, and it must be set back on the widget in order to take effect.

lineEdit = QLineEdit()
palette = lineEdit.palette()
palette.setColor(QPalette.Highlight, QColor('aqua'))
lineEdit.setPalette(palette)
```
<p>You can make this global for <em>all</em> widgets; note that this will change the highlight color for any widget that supports selections, including item views:</p>
<pre class="lang-py prettyprint-override"><code>palette = QPalette()
palette.setColor(QPalette.Highlight, QColor('aqua'))
QApplication.setPalette(palette)
</code>```

Using Qt Style Sheets

Alternatively, Qt provides a custom implementation of style sheets (based on the CSS v2.1 specification):

lineEdit.setStyleSheet('selection-background-color: aqua;')
```
<p>Similarly to the above, this can also be set globally:</p>
<pre class="lang-py prettyprint-override"><code>QApplication.instance().setStyleSheet('selection-background-color: aqua;')
</code>```

Note that it's generally discouraged to set global properties in the stylesheet of the application as much as for containers (QWidget, QFrame, etc) and complex widgets like item views; selectors should always be preferred, and this allows more control over what widgets (or widget types) will be "styled". The following sets the selection background only for QLineEdit widgets (including subclasses):

QApplication.instance().setStyleSheet('''
    QLineEdit {
        selection-background-color: aqua;
    }
''')
```
<hr />
<h2>Important notes about altering default colors</h2>
<p>The text color should also be set, as your background might be incompatible with the default colors of the system, thus making the selected text difficult (or impossible) to read. You must then find a color that has enough contrast with the background <em>and</em> also ensures good readability: for instance, a green background should not have a red text.</p>
<p>The role for the palette is <code>HighlightedText</code>:</p>
```palette.setColor(QPalette.Highlight, QColor('aqua'))
palette.setColor(QPalette.HighlightedText, QColor('darkblue'))
```
<p>The property of style sheets is <code>selection-color</code>:</p>
<pre class="lang-py prettyprint-override"><code>QApplication.instance().setStyleSheet('''
    QLineEdit {
        selection-background-color: aqua;
        selection-color: darkblue;
    }
''')
</code>```

You can use this online tool to check color combinations and see if they are good enough.

Finally, you must also always consider the default Base palette color, which is the color used as background of widgets that accept user input (text, numbers, item views, etc.), otherwise you might choose a color that will make it impossible to distinguish the selection.

Body:
Using QPalette

Qt uses the QPalette as basis for drawing all its widgets; there are various roles to which colors (or, better, brushes) can be assigned, including the Highlight role used to draw the background of selected items and text.

You can get the global application palette (QApplication.palette()) or that of the widget, and set the color for each role; note that changing the palette has no direct effect on the widget, and it must be set back on the widget in order to take effect.

lineEdit = QLineEdit()
palette = lineEdit.palette()
palette.setColor(QPalette.Highlight, QColor('aqua'))
lineEdit.setPalette(palette)

You can make this global for all widgets; note that this will change the highlight color for any widget that supports selections, including item views:

palette = QPalette()
palette.setColor(QPalette.Highlight, QColor('aqua'))
QApplication.setPalette(palette)

Using Qt Style Sheets

Alternatively, Qt provides a custom implementation of style sheets (based on the CSS v2.1 specification):

lineEdit.setStyleSheet('selection-background-color: aqua;')

Similarly to the above, this can also be set globally:

QApplication.instance().setStyleSheet('selection-background-color: aqua;')

Note that it's generally discouraged to set global properties in the stylesheet of the application as much as for containers (QWidget, QFrame, etc) and complex widgets like item views; selectors should always be preferred, and this allows more control over what widgets (or widget types) will be "styled". The following sets the selection background only for QLineEdit widgets (including subclasses):

QApplication.instance().setStyleSheet('''
    QLineEdit {
        selection-background-color: aqua;
    }
''')

Important notes about altering default colors

The text color should also be set, as your background might be incompatible with the default colors of the system, thus making the selected text difficult (or impossible) to read. You must then find a color that has enough contrast with the background and also ensures good readability: for instance, a green background should not have a red text.

The role for the palette is HighlightedText:

palette.setColor(QPalette.Highlight, QColor('aqua'))
palette.setColor(QPalette.HighlightedText, QColor('darkblue'))

The property of style sheets is selection-color:

QApplication.instance().setStyleSheet('''
    QLineEdit {
        selection-background-color: aqua;
        selection-color: darkblue;
    }
''')

You can use this online tool to check color combinations and see if they are good enough.

Finally, you must also always consider the default Base palette color, which is the color used as background of widgets that accept user input (text, numbers, item views, etc.), otherwise you might choose a color that will make it impossible to distinguish the selection.