问:
400 Bad Request using mean stack
on my application, i can register (name, email, role) and login. when i log in my account i can update my role. But when i want to save my change after the click button onSave(), i have

```<code>`400 Bad Request` `ID Unknown:null`.
</code>```

I'm on nodeJs express mongoodb and angular 14.

user.controller.js

```<code>const mongoose = require('mongoose');
const passport = require('passport');
const _ = require('lodash');
const { rest } = require('lodash');
const User = mongoose.model('User');
// updated crud code

ObjectId = require('mongoose').Types.ObjectId; //catch collection Id
// end updated crud code

module.exports.register = (req, res, next) => {
//console.log('inside register function');
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.role = req.body.role;
user.followers = req.body.followers;
user.following = req.body.following;
user.save((err, doc) => {
    if (!err)
        res.send(doc);
    else {
        if (err.code = 1100)
            res.status(422).send(['L\'adresse email existe déja.']);
            else
                return next(err);
    }

});
}

module.exports.authenticate = (req, res, next) => {
//call for passport authentication
passport.authenticate('local', (err, user, info) => {
    //error from passport middleware
    if (err) return res.status(404).json(err);
    //registered user
    else if(user) return res.status(200).json({ "token" : user.generateJwt() });
    //unknow user or wrong password
    else return res.status(401).json(info);
 })(req,res);
}

module.exports.userProfile = (req, res, next) => {
User.findOne({ _id: req._id },
    (err, user) => {
        if (!user)
        return res.status(404).json({ status: false, message: 'User record not found'});
        else
        return res.status(200).json({ status: true, user: _.pick(user,['fullName',

'email', 'role', 'friends','followers','following']) });
    })
}

module.exports.getAllUser = async (req, res) => {
const users = await User.find().select('-password');
res.status(200).json(users);
};

module.exports.userInfo = (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send('ID unknown :' + req.params.id)

User.findById(req.params.id, (err,docs) => {
if(!err) res.send(docs);
else console.log('ID unknown ; ' . err);
}) .select('-password');

};

module.exports.updateUser = async (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send('ID unknown :' + req.params.id)

try {
await User.findOneAndUpdate(
  {_id: req.params.id},
  {
    $set: {
      role : req.body.role
    },
  },
  { new: true, upsert: true, setDefaultsOnInsert: true},
)
  .then((docs) => res.send(docs))
  .catch((err) => res.status(500).send({ message: err }));

} catch (err){
return res.status(500).json({ message: err});
}
}

module.exports.deleteUser = async (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send('ID unknown :' + req.params.id)

try {
await User.remove({_id: req.params.id}).exec();
res.status(200).json({ message: "Successfully deleted. "});
 } catch (err) {
return res.status(500).json({ message: err });
}
}

module.exports.follow = async (req, res) => {
/* if (!ObjectId.isValid(req.params.id) || !ObjectId.isValid(req.params.idToFollow))
return res.status(400).send('ID unknown :' + req.params.id) */

try {
// add to the follower list
await User.findByIdAndUpdate(
  req.params.id, // id wanted to being followed
  { $addToSet: { following: req.body.idToFollow } }, // id being followed
  { new : true, upsert: true },

);
// add to following list
await User.findByIdAndUpdate(
  req.body.idToFollow,
  { $addToSet: { followers: req.params.id}},
  { new: true, upsert: true },
 )
   return res.status(201).json(docs);

  }catch (err) {
 return res.status(500).json({ message: err });
 }
};

 module.exports.unfollow = async (req, res) => {
/*  if (!ObjectId.isValid(req.params.id) || !ObjectId.isValid(req.params.idToFollow))
return res.status(400).send('ID unknown :' + req.params.id) */

try {
// add to the follower list
await User.findByIdAndUpdate(
  req.params.id, // id wanted to being followed
  { $pull: { following: req.body.idToUnFollow } }, // id being followed
  { new : true, upsert: true },

);
// add to following list
await User.findByIdAndUpdate(
  req.body.idToUnFollow,
  { $pull: { followers: req.params.id}},
  { new: true, upsert: true },
)
return res.status(201).json(docs);

}catch (err) {
return res.status(500).json({ message: err });
}
};
</code>```

index.router.js

```<code>const express = require('express');
const router = express.Router();

const ctrlUser = require('../controllers/user.controller');

const jwtHelper = require('../config/jwtHelper');

//auth
router.post('/register', ctrlUser.register,);
router.post('/authenticate',ctrlUser.authenticate);

// user display
router.get('/userProfile',jwtHelper.verifyJwtToken, ctrlUser.userProfile);
router.get('/list', ctrlUser.getAllUser);
router.get('/user/:id', ctrlUser.userInfo);
router.put("/user/:id",ctrlUser.updateUser);
router.delete("/user/:id",ctrlUser.deleteUser);

//follow
 router.patch('/user/follow/:id', ctrlUser.follow);
router.patch('/user/unfollow/:id', ctrlUser.unfollow);

module.exports = router;
</code>```

config.json

```<code>{
"development": {
    "PORT": 3000,
    "MONGODB_URI": "mongodb://localhost:27017/PangolinDB",
    "JWT_SECRET": "LSDKFLSFQL.DFQSL.FSL",
    "JWT_EXP": "10m"
},
"production": {
    "PORT": 80,
    "MONGODB_URI": "mongodb://xxxxx/DB_Name",
    "JWT_SECRET": "LSDKFLSFQL.DFQSL.FSL",
    "JWT_EXP": "2m"
}
}
</code>```

environment.ts

```<code>export const environment = {
production: false,
apiBaseUrl: 'http://localhost:3000/api'
};
</code>```

user.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse, } from '@angular/common/http';
import { User } from './user.model';
import { Observable, ObservableInput, throwError} from 'rxjs';
import { catchError, map } from 'rxjs/operators';

import { environment } from 'src/environments/environment';

@Injectable({
providedIn: 'root'
})
export class UserService {
selectedUser: User = {
id:'',
fullName: '',
email: '',
password: '',
role:'',
friends:'',
followers:'',
following:'',
};

noAuthHeader = { headers: new HttpHeaders({ 'NoAuth': 'True'}) };
errorMgmt: (err: any, caught: Observable<any>) => ObservableInput<any>;
HttpHeaders: HttpHeaders | { [header: string]: string | string[]; };

constructor(private http: HttpClient) { }

//httpMethods

//user form

//register ()
postUser(user: User){
return this.http.post( environment.apiBaseUrl+'/register',user,this.noAuthHeader);
}
//login ()
login(authCredentials: any){
  return this.http.post(environment.apiBaseUrl + '/authenticate', authCredentials,

this.noAuthHeader);
}

//user profile
//user infos
getUserProfile(){
  return this.http.get(environment.apiBaseUrl + '/userProfile');
} // need jwt in header

getOne(){
  const token = this.getToken();
  const headers = new HttpHeaders({'Authorization ':'bearer'+ token});
  return this.http.get(environment.apiBaseUrl+'/userProfile',{headers});
}

updateUser(_id: any, value: any){
  return this.http.put(environment.apiBaseUrl + `/user/${_id}`, value);

}

edit(_id: any, data: any){
  return this.http.put(environment.apiBaseUrl + `/user/${_id}`, data);

}

//get all users
getAllUsers(){
  return this.http.get(environment.apiBaseUrl + '/list');
}

//Helper Methods

setToken(token: string) {

  localStorage.setItem('token', token);
}

getToken() {
  return localStorage.getItem('token');
}

deleteToken() {
  localStorage.removeItem('token');
}

 getUserPayload(){
  var token = this.getToken();
  if (token) {
    var getUserPayload = atob(token.split('.')[1]);
    return JSON.parse(getUserPayload);
  }
  else
  return null;
}

isLoggedIn() {
  var userPayload = this.getUserPayload();
  if (userPayload)
    return userPayload.exp > Date.now() / 1000;
  else
    return false;
}

// Error
handleError(error: HttpErrorResponse) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
  // Handle client error
  errorMessage = error.error.message;
} else {
  // Handle server error
  errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(() => {
  errorMessage;
});
}

}
</code>```

edit.component.ts

```<code>import { UserService } from './../shared/user.service';
import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, Validator, Validators, SelectControlValueAccessor,

FormBuilder } from "@angular/forms";

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

export class EditComponent implements OnInit {

updateForm: FormGroup;
id:any;
role: string;

constructor(

public formBuilder: FormBuilder,
private router: Router,
private ngZone: NgZone,
private activatedRoute: ActivatedRoute,
private UserService: UserService
) {
this.id = this.activatedRoute.snapshot.paramMap.get('id');
this.UserService.getOne().subscribe(res=>{
  this.updateForm.patchValue({

    role: res['role']
  });
});
this.updateForm = this.formBuilder.group({

  role:[''],
})

}
ngOnInit(): void {}
onUpdate(): any{

this.UserService.updateUser(this.id, this.updateForm.value).subscribe(()=>{
  console.log('mise à jouer effectuée avec succès')
  this.ngZone.run(()=> this.router.navigateByUrl('/userprofile'))
},(err)=> {
  console.log(err);
});
}

 }

<div class="row justify-content-center mt-5">
<div class="col-md-4">
<form [formGroup]="updateForm" (ngSubmit)="onUpdate()">
  <h2>Edit Role</h2>
  <div class="form-group">
    <label for="role">Role</label>
    <input class="form-control" type="text" formControlName="role" id="role">
  </div>
  <div class="form-group">
    <button class="btn btn-primary btn-block"  type="submit" >Enregistrer</button>
    <button class="btn btn-info btn-block" [routerLink]="['/userprofile']"

type="submit">Retour</button>
  </div>

</form>
</div>
</div>

<p>edit works!</p>
</code>```

auth.interceptor.ts

```<code>import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from

"@angular/common/http";
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { Router } from "@angular/router";

import { UserService } from "../shared/user.service";

@Injectable()

 //recuperation de token
 export class AuthInterceptor implements HttpInterceptor {

 constructor(private userService : UserService,private router : Router){}

intercept(req: HttpRequest<any>, next: HttpHandler) {

    if (req.headers.get('noauth'))
        return next.handle(req.clone());
    else {
        const clonedreq = req.clone({
            headers: req.headers.set("Authorization", "Bearer " +

  this.userService.getToken())
        });
        return next.handle(clonedreq).pipe(
            tap(
                event => { },
                err => {
                    if (err.error.auth == false) {
                        this.router.navigateByUrl('/login');
                    }
                })
        );
    }
   }
 }
</code>```

After hours of searh i'm still blocked.

Title: 400 Bad Request using mean stack

Body:
on my application, i can register (name, email, role) and login. when i log in my account i can update my role. But when i want to save my change after the click button onSave(), i have

`400 Bad Request` `ID Unknown:null`.

I'm on nodeJs express mongoodb and angular 14.

user.controller.js

const mongoose = require('mongoose');
const passport = require('passport');
const _ = require('lodash');
const { rest } = require('lodash');
const User = mongoose.model('User');
// updated crud code

ObjectId = require('mongoose').Types.ObjectId; //catch collection Id
// end updated crud code

module.exports.register = (req, res, next) => {
//console.log('inside register function');
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.role = req.body.role;
user.followers = req.body.followers;
user.following = req.body.following;
user.save((err, doc) => {
    if (!err)
        res.send(doc);
    else {
        if (err.code = 1100)
            res.status(422).send(['L\'adresse email existe déja.']);
            else
                return next(err);
    }

});
}

module.exports.authenticate = (req, res, next) => {
//call for passport authentication
passport.authenticate('local', (err, user, info) => {
    //error from passport middleware
    if (err) return res.status(404).json(err);
    //registered user
    else if(user) return res.status(200).json({ "token" : user.generateJwt() });
    //unknow user or wrong password
    else return res.status(401).json(info);
 })(req,res);
}

module.exports.userProfile = (req, res, next) => {
User.findOne({ _id: req._id },
    (err, user) => {
        if (!user)
        return res.status(404).json({ status: false, message: 'User record not found'});
        else
        return res.status(200).json({ status: true, user: _.pick(user,['fullName',

'email', 'role', 'friends','followers','following']) });
    })
}

module.exports.getAllUser = async (req, res) => {
const users = await User.find().select('-password');
res.status(200).json(users);
};

module.exports.userInfo = (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send('ID unknown :' + req.params.id)

User.findById(req.params.id, (err,docs) => {
if(!err) res.send(docs);
else console.log('ID unknown ; ' . err);
}) .select('-password');

};

module.exports.updateUser = async (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send('ID unknown :' + req.params.id)

try {
await User.findOneAndUpdate(
  {_id: req.params.id},
  {
    $set: {
      role : req.body.role
    },
  },
  { new: true, upsert: true, setDefaultsOnInsert: true},
)
  .then((docs) => res.send(docs))
  .catch((err) => res.status(500).send({ message: err }));

} catch (err){
return res.status(500).json({ message: err});
}
}

module.exports.deleteUser = async (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send('ID unknown :' + req.params.id)

try {
await User.remove({_id: req.params.id}).exec();
res.status(200).json({ message: "Successfully deleted. "});
 } catch (err) {
return res.status(500).json({ message: err });
}
}

module.exports.follow = async (req, res) => {
/* if (!ObjectId.isValid(req.params.id) || !ObjectId.isValid(req.params.idToFollow))
return res.status(400).send('ID unknown :' + req.params.id) */

try {
// add to the follower list
await User.findByIdAndUpdate(
  req.params.id, // id wanted to being followed
  { $addToSet: { following: req.body.idToFollow } }, // id being followed
  { new : true, upsert: true },

);
// add to following list
await User.findByIdAndUpdate(
  req.body.idToFollow,
  { $addToSet: { followers: req.params.id}},
  { new: true, upsert: true },
 )
   return res.status(201).json(docs);

  }catch (err) {
 return res.status(500).json({ message: err });
 }
};

 module.exports.unfollow = async (req, res) => {
/*  if (!ObjectId.isValid(req.params.id) || !ObjectId.isValid(req.params.idToFollow))
return res.status(400).send('ID unknown :' + req.params.id) */

try {
// add to the follower list
await User.findByIdAndUpdate(
  req.params.id, // id wanted to being followed
  { $pull: { following: req.body.idToUnFollow } }, // id being followed
  { new : true, upsert: true },

);
// add to following list
await User.findByIdAndUpdate(
  req.body.idToUnFollow,
  { $pull: { followers: req.params.id}},
  { new: true, upsert: true },
)
return res.status(201).json(docs);

}catch (err) {
return res.status(500).json({ message: err });
}
};

index.router.js

const express = require('express');
const router = express.Router();

const ctrlUser = require('../controllers/user.controller');

const jwtHelper = require('../config/jwtHelper');

//auth
router.post('/register', ctrlUser.register,);
router.post('/authenticate',ctrlUser.authenticate);

// user display
router.get('/userProfile',jwtHelper.verifyJwtToken, ctrlUser.userProfile);
router.get('/list', ctrlUser.getAllUser);
router.get('/user/:id', ctrlUser.userInfo);
router.put("/user/:id",ctrlUser.updateUser);
router.delete("/user/:id",ctrlUser.deleteUser);

//follow
 router.patch('/user/follow/:id', ctrlUser.follow);
router.patch('/user/unfollow/:id', ctrlUser.unfollow);

module.exports = router;

config.json

{
"development": {
    "PORT": 3000,
    "MONGODB_URI": "mongodb://localhost:27017/PangolinDB",
    "JWT_SECRET": "LSDKFLSFQL.DFQSL.FSL",
    "JWT_EXP": "10m"
},
"production": {
    "PORT": 80,
    "MONGODB_URI": "mongodb://xxxxx/DB_Name",
    "JWT_SECRET": "LSDKFLSFQL.DFQSL.FSL",
    "JWT_EXP": "2m"
}
}

environment.ts

export const environment = {
production: false,
apiBaseUrl: 'http://localhost:3000/api'
};

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse, } from '@angular/common/http';
import { User } from './user.model';
import { Observable, ObservableInput, throwError} from 'rxjs';
import { catchError, map } from 'rxjs/operators';

import { environment } from 'src/environments/environment';

@Injectable({
providedIn: 'root'
})
export class UserService {
selectedUser: User = {
id:'',
fullName: '',
email: '',
password: '',
role:'',
friends:'',
followers:'',
following:'',
};

noAuthHeader = { headers: new HttpHeaders({ 'NoAuth': 'True'}) };
errorMgmt: (err: any, caught: Observable<any>) => ObservableInput<any>;
HttpHeaders: HttpHeaders | { [header: string]: string | string[]; };

constructor(private http: HttpClient) { }

//httpMethods

//user form

//register ()
postUser(user: User){
return this.http.post( environment.apiBaseUrl+'/register',user,this.noAuthHeader);
}
//login ()
login(authCredentials: any){
  return this.http.post(environment.apiBaseUrl + '/authenticate', authCredentials,

this.noAuthHeader);
}

//user profile
//user infos
getUserProfile(){
  return this.http.get(environment.apiBaseUrl + '/userProfile');
} // need jwt in header

getOne(){
  const token = this.getToken();
  const headers = new HttpHeaders({'Authorization ':'bearer'+ token});
  return this.http.get(environment.apiBaseUrl+'/userProfile',{headers});
}

updateUser(_id: any, value: any){
  return this.http.put(environment.apiBaseUrl + `/user/${_id}`, value);

}

edit(_id: any, data: any){
  return this.http.put(environment.apiBaseUrl + `/user/${_id}`, data);

}

//get all users
getAllUsers(){
  return this.http.get(environment.apiBaseUrl + '/list');
}

//Helper Methods

setToken(token: string) {

  localStorage.setItem('token', token);
}

getToken() {
  return localStorage.getItem('token');
}

deleteToken() {
  localStorage.removeItem('token');
}

 getUserPayload(){
  var token = this.getToken();
  if (token) {
    var getUserPayload = atob(token.split('.')[1]);
    return JSON.parse(getUserPayload);
  }
  else
  return null;
}

isLoggedIn() {
  var userPayload = this.getUserPayload();
  if (userPayload)
    return userPayload.exp > Date.now() / 1000;
  else
    return false;
}

// Error
handleError(error: HttpErrorResponse) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
  // Handle client error
  errorMessage = error.error.message;
} else {
  // Handle server error
  errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(() => {
  errorMessage;
});
}

}

edit.component.ts

import { UserService } from './../shared/user.service';
import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, Validator, Validators, SelectControlValueAccessor,

FormBuilder } from "@angular/forms";

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

export class EditComponent implements OnInit {

updateForm: FormGroup;
id:any;
role: string;

constructor(

public formBuilder: FormBuilder,
private router: Router,
private ngZone: NgZone,
private activatedRoute: ActivatedRoute,
private UserService: UserService
) {
this.id = this.activatedRoute.snapshot.paramMap.get('id');
this.UserService.getOne().subscribe(res=>{
  this.updateForm.patchValue({

    role: res['role']
  });
});
this.updateForm = this.formBuilder.group({

  role:[''],
})

}
ngOnInit(): void {}
onUpdate(): any{

this.UserService.updateUser(this.id, this.updateForm.value).subscribe(()=>{
  console.log('mise à jouer effectuée avec succès')
  this.ngZone.run(()=> this.router.navigateByUrl('/userprofile'))
},(err)=> {
  console.log(err);
});
}

 }

<form [formGroup]="updateForm" (ngSubmit)="onUpdate()">

Edit Role

    Role
    <input class="form-control" type="text" formControlName="role" id="role">

    <button class="btn btn-primary btn-block"  type="submit" >Enregistrer</button>
    <button class="btn btn-info btn-block" [routerLink]="['/userprofile']"

type="submit">Retour</button>

</form>

edit works!

auth.interceptor.ts

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from

"@angular/common/http";
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { Router } from "@angular/router";

import { UserService } from "../shared/user.service";

@Injectable()

 //recuperation de token
 export class AuthInterceptor implements HttpInterceptor {

 constructor(private userService : UserService,private router : Router){}

intercept(req: HttpRequest<any>, next: HttpHandler) {

    if (req.headers.get('noauth'))
        return next.handle(req.clone());
    else {
        const clonedreq = req.clone({
            headers: req.headers.set("Authorization", "Bearer " +

  this.userService.getToken())
        });
        return next.handle(clonedreq).pipe(
            tap(
                event => { },
                err => {
                    if (err.error.auth == false) {
                        this.router.navigateByUrl('/login');
                    }
                })
        );
    }
   }
 }

After hours of searh i'm still blocked.


来源: stackexchange

问:
Designating Order of Plot in terminal
When i run the code on terminal based on code shown below, the plot just pops up in random order.

I want the code to designate the order of plot shown on terminal.
Per say, I want "plot thir_1st" to show at the top and then go to 2nd and 3rd.

```<code>        # 기준일 30일전
        X_ago_30 = X.iloc[check_index - 30:check_index,:]
        target_ago_30 = target.iloc[check_index - 30: check_index]
        print( "기준일 전 30일 동안 가장 큰 영향을 미친 설명 변수 리스트:", selected_variables(X_ago_30,target_ago_30))

        thir_1st = selected_variables(X_ago_30,target_ago_30)[0]
        thir_2nd = selected_variables(X_ago_30,target_ago_30)[1]
        thir_3rd = selected_variables(X_ago_30,target_ago_30)[2]

        for i in range(0,col_N) :
            if itemName.index[i] == thir_1st :

                x_thir_1st =  use_data.iloc[:,i]

                fig, ax1 = plt.subplots()
                plt.title('30일 시계열 - 1st')
                ax1.plot(per, 'r', label='PER')
                ax2 = ax1.twinx()
                ax2.plot(x_thir_1st, 'b', label = itemName.index[i])
                ax1.set_ylabel('PER fwd')
                ax2.set_ylabel(itemName.index[i])
                ax1.legend(loc='upper left')
                ax2.legend(loc='upper right')
                plt.show()

            elif itemName.index[i] == thir_2nd :

                x_thir_2nd =  use_data.iloc[:,i]

                fig, ax1 = plt.subplots()
                plt.title('30일 시계열 - 2nd')
                ax1.plot(per, 'r', label='PER')
                ax2 = ax1.twinx()
                ax2.plot(x_thir_2nd, 'b', label = itemName.index[i])
                ax1.set_ylabel('PER fwd')
                ax2.set_ylabel(itemName.index[i])
                ax1.legend(loc='upper left')
                ax2.legend(loc='upper right')
                plt.show()

            elif itemName.index[i] == thir_3rd :

                x_thir_3rd =  use_data.iloc[:,i]

                fig, ax1 = plt.subplots()
                plt.title('30일 시계열 - 3rd')
                ax1.plot(per, 'r', label='PER')
                ax2 = ax1.twinx()
                ax2.plot(x_thir_3rd, 'b', label = itemName.index[i])
                ax1.set_ylabel('PER fwd')
                ax2.set_ylabel(itemName.index[i])
                ax1.legend(loc='upper left')
                ax2.legend(loc='upper right')
                plt.show()
</code>```

Not much left to try....searched on google but couldnt find.

ContentLicense: CC BY-SA 4.0

Title: Designating Order of Plot in terminal

Body:
When i run the code on terminal based on code shown below, the plot just pops up in random order.

I want the code to designate the order of plot shown on terminal.
Per say, I want "plot thir_1st" to show at the top and then go to 2nd and 3rd.

        # 기준일 30일전
        X_ago_30 = X.iloc[check_index - 30:check_index,:]
        target_ago_30 = target.iloc[check_index - 30: check_index]
        print( "기준일 전 30일 동안 가장 큰 영향을 미친 설명 변수 리스트:", selected_variables(X_ago_30,target_ago_30))

        thir_1st = selected_variables(X_ago_30,target_ago_30)[0]
        thir_2nd = selected_variables(X_ago_30,target_ago_30)[1]
        thir_3rd = selected_variables(X_ago_30,target_ago_30)[2]

        for i in range(0,col_N) :
            if itemName.index[i] == thir_1st :

                x_thir_1st =  use_data.iloc[:,i]

                fig, ax1 = plt.subplots()
                plt.title('30일 시계열 - 1st')
                ax1.plot(per, 'r', label='PER')
                ax2 = ax1.twinx()
                ax2.plot(x_thir_1st, 'b', label = itemName.index[i])
                ax1.set_ylabel('PER fwd')
                ax2.set_ylabel(itemName.index[i])
                ax1.legend(loc='upper left')
                ax2.legend(loc='upper right')
                plt.show()

            elif itemName.index[i] == thir_2nd :

                x_thir_2nd =  use_data.iloc[:,i]

                fig, ax1 = plt.subplots()
                plt.title('30일 시계열 - 2nd')
                ax1.plot(per, 'r', label='PER')
                ax2 = ax1.twinx()
                ax2.plot(x_thir_2nd, 'b', label = itemName.index[i])
                ax1.set_ylabel('PER fwd')
                ax2.set_ylabel(itemName.index[i])
                ax1.legend(loc='upper left')
                ax2.legend(loc='upper right')
                plt.show()

            elif itemName.index[i] == thir_3rd :

                x_thir_3rd =  use_data.iloc[:,i]

                fig, ax1 = plt.subplots()
                plt.title('30일 시계열 - 3rd')
                ax1.plot(per, 'r', label='PER')
                ax2 = ax1.twinx()
                ax2.plot(x_thir_3rd, 'b', label = itemName.index[i])
                ax1.set_ylabel('PER fwd')
                ax2.set_ylabel(itemName.index[i])
                ax1.legend(loc='upper left')
                ax2.legend(loc='upper right')
                plt.show()

Not much left to try....searched on google but couldnt find.


问:
Mudblazor - having MudTabs within MudCard and separate MudTabPanels (Header) and ChildContent (Body)
just wanted to migrate from bootstrap to mudblazor and hit a problem:

-> I want to have a parent MudCard element which should hold MudTabs. The Panels of the Mudtabs should be in the header, but the ChildContent should be hosted in card body.

I already have a workaround - just used a mudpaper instead of MudCard - but I want to know how could I achieve this. is there any recommended way for separation of Panels, better said TabContent and ChildContent?

Thank you guys!


问:
Finding the static chain of different variables in a given program
Given program:

Static Chain

```<code>  Position 1: A=(0,3) B=(2,4) C=(1,)

  Position 2: E=(0,) B=(1,) A=(3,)

  Position 3: A=(0,) D=(2,) E=(1,)

  I know how to find the chain offset, which is the first value in the coordinates, so I am pretty sure they are              correct although if they aren't please do correct.

   Although I have trouble finding the second coordinate which is the local offset, I think I did it correctly for              variables "a" and "b" although there is no C in the first ARI(big sub) which is where I got stuck. Can anyone           please help me finding the other ones?
</code>```

Body:
Given program:

Static Chain

  Position 1: A=(0,3) B=(2,4) C=(1,)

  Position 2: E=(0,) B=(1,) A=(3,)

  Position 3: A=(0,) D=(2,) E=(1,)

  I know how to find the chain offset, which is the first value in the coordinates, so I am pretty sure they are              correct although if they aren't please do correct.

   Although I have trouble finding the second coordinate which is the local offset, I think I did it correctly for              variables "a" and "b" although there is no C in the first ARI(big sub) which is where I got stuck. Can anyone           please help me finding the other ones?


问:
Why am I getting different results on different platforms (spyder vs visual studio)?
I'm using the BaselineRemoval function with IModPoly, but getting different results despite using the same code and datasets. I had a friend run the code and they get the same results that I do with visual studio.  Any idea why the results are different in spyder?  My code is below:

Edited to simplify the code

```<code>from BaselineRemoval import BaselineRemoval

polynomial_degree = 3 #only needed for IModPoly algorithm
input_array_train = data.copy()

print(input_array_train.shape)
print(input_array_train)

baseline_correction_train=BaselineRemoval(input_array_train).IModPoly(polynomial_degree)

train_raman_proc = baseline_correction_train

print(train_raman_proc.shape)
train_raman_proc
</code>```

I ran this same code on Spyder and Visual Studio, output is below:

Spyder:

```<code>(2042,)

[336167.00616779 335865.93248741 335585.7852715  ... 133592.04534896
 133576.80460859 133517.41650705]

(2042,)

array([40893.84981077, 40650.58294278, 40428.28300527, ...,
       39654.3524087 , 39840.20855015, 39982.01744302])
</code>```

Visual Studio:

```<code>(2042,)

[336167.00616779 335865.93248741 335585.7852715  ... 133592.04534896
 133576.80460859 133517.41650705]

(2042,)

array([32338.54977607, 32129.43948405, 31941.23853284, ...,
       39768.88844912, 39896.21948952, 39979.46997397])
</code>```

Notice how the input data arrays are the same, but the output baseline corrected arrays are different.

It seems to have something to do with the size of the array.  If I take a subsection of the array [0:1200], I get the same results from both.  And if I take the back half of the subsection [1201:2042] I also get the same results from both.  But if I run the whole array (or just a larger subsection, like [0:1300]), then they give different results.

Here's the plots of the baseline corrected output from spyder (top) and visual studio (bottom), note around 1300 it seems like the imodpoly restarts for spyder.

Spyder IModPoly Ouput

Visual Studio Output

Body:
I'm using the BaselineRemoval function with IModPoly, but getting different results despite using the same code and datasets. I had a friend run the code and they get the same results that I do with visual studio.  Any idea why the results are different in spyder?  My code is below:

Edited to simplify the code

from BaselineRemoval import BaselineRemoval

polynomial_degree = 3 #only needed for IModPoly algorithm
input_array_train = data.copy()

print(input_array_train.shape)
print(input_array_train)

baseline_correction_train=BaselineRemoval(input_array_train).IModPoly(polynomial_degree)

train_raman_proc = baseline_correction_train

print(train_raman_proc.shape)
train_raman_proc

I ran this same code on Spyder and Visual Studio, output is below:

Spyder:

(2042,)

[336167.00616779 335865.93248741 335585.7852715  ... 133592.04534896
 133576.80460859 133517.41650705]

(2042,)

array([40893.84981077, 40650.58294278, 40428.28300527, ...,
       39654.3524087 , 39840.20855015, 39982.01744302])

Visual Studio:

(2042,)

[336167.00616779 335865.93248741 335585.7852715  ... 133592.04534896
 133576.80460859 133517.41650705]

(2042,)

array([32338.54977607, 32129.43948405, 31941.23853284, ...,
       39768.88844912, 39896.21948952, 39979.46997397])

Notice how the input data arrays are the same, but the output baseline corrected arrays are different.

It seems to have something to do with the size of the array.  If I take a subsection of the array [0:1200], I get the same results from both.  And if I take the back half of the subsection [1201:2042] I also get the same results from both.  But if I run the whole array (or just a larger subsection, like [0:1300]), then they give different results.

Here's the plots of the baseline corrected output from spyder (top) and visual studio (bottom), note around 1300 it seems like the imodpoly restarts for spyder.

Spyder IModPoly Ouput

Visual Studio Output


问:
My program doesn't display the correct calculations
I'm making a credit score calculator for my class and the only problem I'm having with my code is that none of the calculations are turning out correctly. This is my code for the logic portion

```<code>def calculate_score():
    name = entry_name.get()
    highschool_checked = int(highschool.get())
    college_checked = int(college.get())
    university_checked = int(university.get())
    income = int(entry_income.get())
    savings = int(entry_savings.get())

    para1 = 0

    if int(income) >= 20000:
        para1 = 1
    elif int(income) >= 60000:
        para1 = 2
    elif int(income) >= 90000:
        para1 = 3

    para2 = 1

    if int(highschool_checked) == 1:
        para2 = 1
    elif int(college_checked) == 1:
        para2 = 2
    elif int(university_checked) == 1:
        para2 = 3

    para3 = 0

    if int(savings) >= 5000:
        para3 = 1
    elif int(savings) >= 10000:
        para3 = 2
    elif int(savings) >= 20000:
        para3 = 3

    score = 2*para1 + 3*para2 + para3

    if score >= 8:
        result = str(name) + ", your credit score is " + str(score) + ". You are qualified for credit."
    else: result = str(name) + ", your credit score is " + str(score) + ". You are not qualified for credit."

    label_result = tkinter.Label(text="")
    label_result.configure(text=result)
    label_result.grid(row=6, column=0)
</code>```

This code is all within a "Calculate Credit Score" button. I've checked for any errors and there are none but whenever I run the program it always gives me the wrong result.

I tried a test case by entering every parameter at the max setting (income = $90000, education = University, savings = $20000) and the expected output is supposed to be a credit score of 18. But when I run the program it gives me a credit score of 12. I even tried in the python shell and it still gave me a credit score of 12.

Body:
I'm making a credit score calculator for my class and the only problem I'm having with my code is that none of the calculations are turning out correctly. This is my code for the logic portion

def calculate_score():
    name = entry_name.get()
    highschool_checked = int(highschool.get())
    college_checked = int(college.get())
    university_checked = int(university.get())
    income = int(entry_income.get())
    savings = int(entry_savings.get())

    para1 = 0

    if int(income) >= 20000:
        para1 = 1
    elif int(income) >= 60000:
        para1 = 2
    elif int(income) >= 90000:
        para1 = 3

    para2 = 1

    if int(highschool_checked) == 1:
        para2 = 1
    elif int(college_checked) == 1:
        para2 = 2
    elif int(university_checked) == 1:
        para2 = 3

    para3 = 0

    if int(savings) >= 5000:
        para3 = 1
    elif int(savings) >= 10000:
        para3 = 2
    elif int(savings) >= 20000:
        para3 = 3

    score = 2*para1 + 3*para2 + para3

    if score >= 8:
        result = str(name) + ", your credit score is " + str(score) + ". You are qualified for credit."
    else: result = str(name) + ", your credit score is " + str(score) + ". You are not qualified for credit."

    label_result = tkinter.Label(text="")
    label_result.configure(text=result)
    label_result.grid(row=6, column=0)

This code is all within a "Calculate Credit Score" button. I've checked for any errors and there are none but whenever I run the program it always gives me the wrong result.

I tried a test case by entering every parameter at the max setting (income = $90000, education = University, savings = $20000) and the expected output is supposed to be a credit score of 18. But when I run the program it gives me a credit score of 12. I even tried in the python shell and it still gave me a credit score of 12.


问:
Using Node JS project as a VPN service
I know it's very uneccessary but i want to learn it is possible or not. Can i connect to my Node js project to use like a proxy, like a vpn? I can't access server shell of node js project so i can't setup openvpn or something. I want to connect my Node js project with remote device and surfing on the internet, using Node JS project as VPN.</p>

Title: Using Node JS project as a VPN service


问:
Is it possible to implement an EnvoyFilter for a out-going request?
I have implemented an EnvoyFilter for one of my services by following this sample. Now I want to implement a similar one, but it is for a service that is out of my control.

The current request flow is like this:

browser sends a request

istio ingress receives the request

the request is routed to the 3rd party service in the cluster but does not have a istio-proxy sidecar

I need to inject some headers at step 3 before routing the request to the other services. The header content is dynamic, and I need to make some HTTP requests to get the content.

Is there a filter that can do this? Or is it simply impossible with Istio?

Thanks


问:
Beautiful soup not identifying children of an element
I am trying to scrape this webpage. I am interested in scraping the text under , i.e. from "welcome to the site..." to "This offer won't last..."

Joe Job:   The DarkProfits web site offers all sorts of illegal goods and services for sale.

<NOINDEX>

Status:   False.

</NOINDEX>

Example:   [Collected on the Internet, 2003]

Welcome to the site www.darkprofits.com, it's us again, now we extended our offerings, here is a list:

1. Heroin, in liquid and crystal form.

2. Rocket fuel and Tomohawk rockets (serious enquiries only).

3. Other rockets (Air-to-Air), orders in batches of 10.

4. New shipment of cocaine has arrived, buy 9 grams and get 10th for free.

5. We also offer gay-slaves for sale, we offer only such service on the NET, you can choose the one you like, then get straight to business.

6. Fake currencies, such as Euros and US dollars, prices would match competition.

7. Also, as always, we offer widest range of child pornography and exclusive lolita galleries, to keep out clients busy.

Everyone is welcome, be it in States or any other place worldwide.

ATTENTION. Clearance offer. Buy 30 grams of heroin, get 5 free. Prepay your batch of rockets (air-to-air) and recieve a portable rocket-lacuncher for free.

www.darkprofits.com

This offer won't last! Only until 20th of August all our clients will also recieve a pack of 2 CDs, with best selection of child pornography.

```
</div>
</div>
</p>
<p>I tried using the find function from beautifulsoup. The code I used was:</p>
```testurl = "https://www.snopes.com/fact-check/dark-profits/"
user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'
HEADERS = {'User-agent':user_agent}
req = urllib.request.Request(testurl, headers = HEADERS) # visit disguised as browser
pagehtml = urllib.request.urlopen(req).read() # read the website
pagesoup = soup(pagehtml,'html.parser')

potentials = pagesoup.findAll("div", { "class" : "example" })
potentials[0]
potentials[0].find_children
```

potentials[0].find_children was not able to find anything. I have also tried potentials[0].findChildren() and it was notable to find anything either. Why is find_children not picking up the children of the div tag?

Body:
I am trying to scrape this webpage. I am interested in scraping the text under , i.e. from "welcome to the site..." to "This offer won't last..."

Joe Job:   The DarkProfits web site offers all sorts of illegal goods and services for sale.

<NOINDEX>

Status:   False.

</NOINDEX>

Example:   [Collected on the Internet, 2003]

Welcome to the site www.darkprofits.com, it's us again, now we extended our offerings, here is a list:

1. Heroin, in liquid and crystal form.

2. Rocket fuel and Tomohawk rockets (serious enquiries only).

3. Other rockets (Air-to-Air), orders in batches of 10.

4. New shipment of cocaine has arrived, buy 9 grams and get 10th for free.

5. We also offer gay-slaves for sale, we offer only such service on the NET, you can choose the one you like, then get straight to business.

6. Fake currencies, such as Euros and US dollars, prices would match competition.

7. Also, as always, we offer widest range of child pornography and exclusive lolita galleries, to keep out clients busy.

Everyone is welcome, be it in States or any other place worldwide.

ATTENTION. Clearance offer. Buy 30 grams of heroin, get 5 free. Prepay your batch of rockets (air-to-air) and recieve a portable rocket-lacuncher for free.

www.darkprofits.com

This offer won't last! Only until 20th of August all our clients will also recieve a pack of 2 CDs, with best selection of child pornography.

I tried using the find function from beautifulsoup. The code I used was:

testurl = "https://www.snopes.com/fact-check/dark-profits/"
user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'
HEADERS = {'User-agent':user_agent}
req = urllib.request.Request(testurl, headers = HEADERS) # visit disguised as browser
pagehtml = urllib.request.urlopen(req).read() # read the website
pagesoup = soup(pagehtml,'html.parser')

potentials = pagesoup.findAll("div", { "class" : "example" })
potentials[0]
potentials[0].find_children

potentials[0].find_children was not able to find anything. I have also tried potentials[0].findChildren() and it was notable to find anything either. Why is find_children not picking up the children of the div tag?


问:
I am getting a "System.StackOverflowException: 'Exception_WasThrown'" at InitializeComponent() , and I cant for the life of me figure out why
I'm trying to make a p2p chat application in c# with WPF and MVVM but I keep getting the error in the title at InitializeComponent(). I am providing all my files down below, please take a look.

MainWindow.xaml.cs file:

```<code>using System.Net.Sockets;
using System.Net;
using System;
using System.Windows;
using System.Windows.Input;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace P2PChat
{
    public partial class MainWindow : Window
    {
        private MainViewModel _viewModel;
        //private bool taskStarted = false;

        public MainWindow()
        {

            InitializeComponent();
            _viewModel = new MainViewModel();
            DataContext = _viewModel;
            _viewModel.Contacts = new List<Contact>();
            _viewModel.Username = Microsoft.VisualBasic.Interaction.InputBox("Enter your username:", "P2P Chat", "User");
            _viewModel.Port = Int32.Parse(Microsoft.VisualBasic.Interaction.InputBox("Enter the Port you want to listen from:", "P2P Chat", "8080"));
            this.Title = _viewModel.Username + " - " + GetLocalIPAddress();
            _viewModel.SelectedContact = new Contact("", "", 0);
            MessageBox.Show(GetLocalIPAddress());
            Task.Factory.StartNew(ListenForMessages);

        }
        // Event handler for when the user clicks the "Send" button
        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            string message = MessageTextBox.Text;
            MessageTextBox.Text = "";
            ChatListBox.Items.Add(_viewModel.Username + ": " + message);
            _viewModel.SendMessage(message);
        }

        // Event handler for when the user clicks the "Add Contact" button
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            string username = UsernameTextBox.Text;
            string ipAddress = IpAddressTextBox.Text;
            int contactPort = Int32.Parse(PortTextBox.Text);
            _viewModel.AddContact(username, ipAddress, contactPort, _viewModel.Port);
        }

        // Event handler for when the user clicks the "Remove" button
        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            object selectedItem = ContactListBox.SelectedItem;
            if (selectedItem == null)
            {
                MessageBox.Show("Please select a contact to remove.", "Error");
                return;
            }

            string contact = (string)ContactListBox.SelectedItem;
            _viewModel.SelectedContact = _viewModel.Contacts.Find(c => c.Username == contact);
            _viewModel.RemoveContact();

            ContactListBox.Items.Clear();
            foreach (Contact c in _viewModel.Contacts)
            {
                ContactListBox.Items.Add(c.ToString());
            }
        }

        // Event handler for when the user double-clicks a contact in the list
        private void ContactListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (_viewModel.Contacts != null)
            {
                string selectedUsername = (string)ContactListBox.SelectedItem;
                _viewModel.SelectedContact = _viewModel.Contacts.Find(c => c.Username == selectedUsername);

                ChatListBox.Items.Clear();
                foreach (string message in _viewModel.SelectedContact.Messages)
                {
                    ChatListBox.Items.Add(_viewModel.SelectedContact.Username + ": " + message);
                }
            }
        }

        public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("No network adapters with an IPv4 address in the system!");
        }

        private void ListenForMessages()
        {
            if (_viewModel.taskStarted)
            {
                // Task has already been started, so do nothing
                return;
            }

            // Set the taskStarted flag to true
            _viewModel.taskStarted = true;

            // Create a socket to listen for incoming messages
            var listener = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            // Bind the socket to the localhost IP address and port 8080
            listener.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(GetLocalIPAddress()), _viewModel.Port));
            listener.Listen(10);

            while (true)
            {
                var client = listener.Accept();
                var data = new byte[1024];
                int bytesReceived = client.Receive(data);
                string message = Encoding.ASCII.GetString(data, 0, bytesReceived);

                // Check if the message is a contact message
                if (message.StartsWith("CONTACT:"))
                {
                    // Extract the contact information from the message
                    string[] parts = message.Split(':');
                    string username = parts[1];
                    string ipAddress = parts[2];
                    int Contactport = Int32.Parse(parts[3]);

                    // Display a message box or some other UI element to allow the user to accept or reject the request
                    MessageBoxResult answer = MessageBox.Show("Do you want to add " + username + " as a contact?", "Add Contact", MessageBoxButton.YesNo);

                    if (MessageBoxResult.Yes == answer)
                    {

                        _viewModel.SendConfirmation(ipAddress, Contactport, _viewModel.Port, true);

                        // Add the contact to the list
                        Contact contact = new Contact(username, ipAddress, Contactport);
                        _viewModel.Contacts.Add(contact);
                        ContactListBox.Dispatcher.Invoke(() =>
                        {
                            ContactListBox.Items.Clear();
                            foreach (Contact c in _viewModel.Contacts)
                            {
                                ContactListBox.Items.Add(c.ToString());
                            }
                        });
                    }
                    else
                    {
                        _viewModel.SendConfirmation(ipAddress, Contactport, _viewModel.Port, false);
                    }
                }
                else if (message.StartsWith("RESPONSE:"))
                {

                    string[] parts = message.Split(':');
                    string response = parts[1];
                    string username = parts[2];
                    string ipAddress = parts[3];
                    int Contactport = Int32.Parse(parts[4]);
                    if (response == "True")
                    {
                        MessageBox.Show("The user " + username + " accepted your friend request");
                        Contact contact = new Contact(username, ipAddress, Contactport);
                        _viewModel.Contacts.Add(contact);
                        ContactListBox.Dispatcher.Invoke(() =>
                        {
                            ContactListBox.Items.Clear();
                            foreach (Contact c in _viewModel.Contacts)
                            {
                                ContactListBox.Items.Add(c.ToString());
                            }
                        });
                    }
                    else if (response == "False")
                    {
                        MessageBox.Show("The user " + username + " rejected your friend request");
                    }
                }
                else
                {
                    foreach (Contact c in _viewModel.Contacts)
                    {
                        if (c.ToString() == _viewModel.SelectedContact.Username)
                        {
                            // Handle regular messages here
                            SystemSounds.Hand.Play();
                            Dispatcher.Invoke(() => ChatListBox.Items.Add(_viewModel.SelectedContact.Username + ": " + message));
                            client.Close();
                        }
                    }
                }
            }
        }

    }
}
</code>```

MainWindowViewModel.cs file:

```<code>// ViewModel class
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Media;
using System.Text;
using System.Windows.Threading;
using System.Windows;
using System.Collections.ObjectModel;
using System.Net.Sockets;
using System.Net;

namespace P2PChat
{
    public class MainViewModel
    {
        //public ObservableCollection<Contact> Contacts { get; set; }
        // Properties
        public List<Contact> Contacts { get; set; }
        public Contact SelectedContact { get; set; }
        public string Username { get; set; }

        public string ip { get; set; }

        public int Port { get; set; }
        public bool Response { get; set; }

        public bool taskStarted = false;

        // Constructor
        public MainViewModel()
        {
            Contacts = new List<Contact>();
            SelectedContact = new Contact("", "", 0);
            ip = Contact.GetLocalIPAddress();
            //Task.Factory.StartNew(MainWindow.ListenForMessages());
}

        // Methods
        public void SendMessage(string message)
        {
            SelectedContact.SendMessage(message, SelectedContact.IpAddress, SelectedContact.Contactport);
        }

        public void AddContact(string username, string ipAddress, int contactPort, int port)
        {
            SelectedContact.SendContactInfo(username, ipAddress, contactPort, port);
        }

        public void RemoveContact()
        {
            Contacts.Remove(SelectedContact);
        }

        public void SendConfirmation(string Contactip, int Contactport, int port, bool answer)
        {
            string message;
            if (answer)
            {
                message = "RESPONSE:True" + ":" + Username + ":" + ip + ":" + port.ToString();
            }
            else
            {
                message = "RESPONSE:False" + ":" + Username + ":" + ip + ":" + port.ToString();
            }
            var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            socket.Connect(Contactip, Contactport);
            socket.Send(System.Text.Encoding.ASCII.GetBytes(message));
            socket.Close();
        }

    }
}

</code>```

MainWindow.xaml file:

```<code>
<Window x:Class="P2PChat.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:P2PChat"
        xmlns:vm="clr-namespace:P2PChat"
        mc:Ignorable="d"
        Title="P2P Chat" Height="600" Width="800">
    <Window.Resources>
        <vm:MainWindow x:Key="Locator"/>
    </Window.Resources>
    <Grid DataContext="{Binding Main, Source={StaticResource Locator}}">
        <ListBox x:Name="ContactListBox" HorizontalAlignment="Left" Height="400" Margin="10,10,0,0" VerticalAlignment="Top" Width="200"
                 ItemsSource="{Binding Contacts}"
                 DisplayMemberPath="Username"
                 SelectedItem="{Binding SelectedContact}"
                 MouseDoubleClick="ContactListBox_MouseDoubleClick"/>
        <ListBox x:Name="ChatListBox" HorizontalAlignment="Left" Height="375" Margin="230,10,0,0" VerticalAlignment="Top" Width="550"
                 ItemsSource="{Binding SelectedContact.Messages}"
                 DisplayMemberPath="Username"/>
        <TextBox x:Name="MessageTextBox" HorizontalAlignment="Left" Height="77" Margin="230,405,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="450"
                 Text="{Binding MessageText, UpdateSourceTrigger=PropertyChanged}"/>
        <Button x:Name="SendButton" HorizontalAlignment="Left" Margin="694,410,0,0" VerticalAlignment="Top" Width="75"
                Command="{Binding SendMessageCommand}"
                CommandParameter="{Binding MessageText}"
                Height="66"
                Content="Send"
                Click="SendButton_Click"/>
        <Button x:Name="AddButton" HorizontalAlignment="Left" Margin="47,523,0,0" VerticalAlignment="Top" Width="100"
                Command="{Binding AddContactCommand}"
                CommandParameter="{Binding Port}"
                Content="Add Contact"/>
        <Button x:Name="RemoveButton" HorizontalAlignment="Left" Margin="47,548,0,0" VerticalAlignment="Top" Width="100"
                Command="{Binding RemoveContactCommand}"
                CommandParameter="{Binding SelectedContact}"
                Content="Remove Contact"/>
        <TextBox x:Name="UsernameTextBox" HorizontalAlignment="Left" Height="23" Margin="47,425,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"
                 Text="{Binding ContactUsername, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox x:Name="IpAddressTextBox" HorizontalAlignment="Left" Height="23" Margin="47,453,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"
                 Text="{Binding ContactIpAddress, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox x:Name="PortTextBox" HorizontalAlignment="Left" Height="23" Margin="47,481,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"
                 Text="{Binding ContactPort, UpdateSourceTrigger=PropertyChanged}"/>
        <Label Content="Port:" HorizontalAlignment="Left" Margin="8,480,0,0" VerticalAlignment="Top"/>
        <Label Content="IP:" HorizontalAlignment="Left" Margin="20,456,0,0" VerticalAlignment="Top"/>
        <Label Content="Username:" HorizontalAlignment="Left" Margin="-19,425,0,0" VerticalAlignment="Top"/>
    </Grid>
</Window>

</code>```

It worked fine when I didnt use MVVM but apparently its a requirement for this assignment and I am really stumped.

Body:
I'm trying to make a p2p chat application in c# with WPF and MVVM but I keep getting the error in the title at InitializeComponent(). I am providing all my files down below, please take a look.

MainWindow.xaml.cs file:

using System.Net.Sockets;
using System.Net;
using System;
using System.Windows;
using System.Windows.Input;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace P2PChat
{
    public partial class MainWindow : Window
    {
        private MainViewModel _viewModel;
        //private bool taskStarted = false;

        public MainWindow()
        {

            InitializeComponent();
            _viewModel = new MainViewModel();
            DataContext = _viewModel;
            _viewModel.Contacts = new List<Contact>();
            _viewModel.Username = Microsoft.VisualBasic.Interaction.InputBox("Enter your username:", "P2P Chat", "User");
            _viewModel.Port = Int32.Parse(Microsoft.VisualBasic.Interaction.InputBox("Enter the Port you want to listen from:", "P2P Chat", "8080"));
            this.Title = _viewModel.Username + " - " + GetLocalIPAddress();
            _viewModel.SelectedContact = new Contact("", "", 0);
            MessageBox.Show(GetLocalIPAddress());
            Task.Factory.StartNew(ListenForMessages);

        }
        // Event handler for when the user clicks the "Send" button
        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            string message = MessageTextBox.Text;
            MessageTextBox.Text = "";
            ChatListBox.Items.Add(_viewModel.Username + ": " + message);
            _viewModel.SendMessage(message);
        }

        // Event handler for when the user clicks the "Add Contact" button
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            string username = UsernameTextBox.Text;
            string ipAddress = IpAddressTextBox.Text;
            int contactPort = Int32.Parse(PortTextBox.Text);
            _viewModel.AddContact(username, ipAddress, contactPort, _viewModel.Port);
        }

        // Event handler for when the user clicks the "Remove" button
        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            object selectedItem = ContactListBox.SelectedItem;
            if (selectedItem == null)
            {
                MessageBox.Show("Please select a contact to remove.", "Error");
                return;
            }

            string contact = (string)ContactListBox.SelectedItem;
            _viewModel.SelectedContact = _viewModel.Contacts.Find(c => c.Username == contact);
            _viewModel.RemoveContact();

            ContactListBox.Items.Clear();
            foreach (Contact c in _viewModel.Contacts)
            {
                ContactListBox.Items.Add(c.ToString());
            }
        }

        // Event handler for when the user double-clicks a contact in the list
        private void ContactListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (_viewModel.Contacts != null)
            {
                string selectedUsername = (string)ContactListBox.SelectedItem;
                _viewModel.SelectedContact = _viewModel.Contacts.Find(c => c.Username == selectedUsername);

                ChatListBox.Items.Clear();
                foreach (string message in _viewModel.SelectedContact.Messages)
                {
                    ChatListBox.Items.Add(_viewModel.SelectedContact.Username + ": " + message);
                }
            }
        }

        public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("No network adapters with an IPv4 address in the system!");
        }

        private void ListenForMessages()
        {
            if (_viewModel.taskStarted)
            {
                // Task has already been started, so do nothing
                return;
            }

            // Set the taskStarted flag to true
            _viewModel.taskStarted = true;

            // Create a socket to listen for incoming messages
            var listener = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            // Bind the socket to the localhost IP address and port 8080
            listener.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(GetLocalIPAddress()), _viewModel.Port));
            listener.Listen(10);

            while (true)
            {
                var client = listener.Accept();
                var data = new byte[1024];
                int bytesReceived = client.Receive(data);
                string message = Encoding.ASCII.GetString(data, 0, bytesReceived);

                // Check if the message is a contact message
                if (message.StartsWith("CONTACT:"))
                {
                    // Extract the contact information from the message
                    string[] parts = message.Split(':');
                    string username = parts[1];
                    string ipAddress = parts[2];
                    int Contactport = Int32.Parse(parts[3]);

                    // Display a message box or some other UI element to allow the user to accept or reject the request
                    MessageBoxResult answer = MessageBox.Show("Do you want to add " + username + " as a contact?", "Add Contact", MessageBoxButton.YesNo);

                    if (MessageBoxResult.Yes == answer)
                    {

                        _viewModel.SendConfirmation(ipAddress, Contactport, _viewModel.Port, true);

                        // Add the contact to the list
                        Contact contact = new Contact(username, ipAddress, Contactport);
                        _viewModel.Contacts.Add(contact);
                        ContactListBox.Dispatcher.Invoke(() =>
                        {
                            ContactListBox.Items.Clear();
                            foreach (Contact c in _viewModel.Contacts)
                            {
                                ContactListBox.Items.Add(c.ToString());
                            }
                        });
                    }
                    else
                    {
                        _viewModel.SendConfirmation(ipAddress, Contactport, _viewModel.Port, false);
                    }
                }
                else if (message.StartsWith("RESPONSE:"))
                {

                    string[] parts = message.Split(':');
                    string response = parts[1];
                    string username = parts[2];
                    string ipAddress = parts[3];
                    int Contactport = Int32.Parse(parts[4]);
                    if (response == "True")
                    {
                        MessageBox.Show("The user " + username + " accepted your friend request");
                        Contact contact = new Contact(username, ipAddress, Contactport);
                        _viewModel.Contacts.Add(contact);
                        ContactListBox.Dispatcher.Invoke(() =>
                        {
                            ContactListBox.Items.Clear();
                            foreach (Contact c in _viewModel.Contacts)
                            {
                                ContactListBox.Items.Add(c.ToString());
                            }
                        });
                    }
                    else if (response == "False")
                    {
                        MessageBox.Show("The user " + username + " rejected your friend request");
                    }
                }
                else
                {
                    foreach (Contact c in _viewModel.Contacts)
                    {
                        if (c.ToString() == _viewModel.SelectedContact.Username)
                        {
                            // Handle regular messages here
                            SystemSounds.Hand.Play();
                            Dispatcher.Invoke(() => ChatListBox.Items.Add(_viewModel.SelectedContact.Username + ": " + message));
                            client.Close();
                        }
                    }
                }
            }
        }

    }
}

MainWindowViewModel.cs file:

// ViewModel class
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Media;
using System.Text;
using System.Windows.Threading;
using System.Windows;
using System.Collections.ObjectModel;
using System.Net.Sockets;
using System.Net;

namespace P2PChat
{
    public class MainViewModel
    {
        //public ObservableCollection<Contact> Contacts { get; set; }
        // Properties
        public List<Contact> Contacts { get; set; }
        public Contact SelectedContact { get; set; }
        public string Username { get; set; }

        public string ip { get; set; }

        public int Port { get; set; }
        public bool Response { get; set; }

        public bool taskStarted = false;

        // Constructor
        public MainViewModel()
        {
            Contacts = new List<Contact>();
            SelectedContact = new Contact("", "", 0);
            ip = Contact.GetLocalIPAddress();
            //Task.Factory.StartNew(MainWindow.ListenForMessages());
}

        // Methods
        public void SendMessage(string message)
        {
            SelectedContact.SendMessage(message, SelectedContact.IpAddress, SelectedContact.Contactport);
        }

        public void AddContact(string username, string ipAddress, int contactPort, int port)
        {
            SelectedContact.SendContactInfo(username, ipAddress, contactPort, port);
        }

        public void RemoveContact()
        {
            Contacts.Remove(SelectedContact);
        }

        public void SendConfirmation(string Contactip, int Contactport, int port, bool answer)
        {
            string message;
            if (answer)
            {
                message = "RESPONSE:True" + ":" + Username + ":" + ip + ":" + port.ToString();
            }
            else
            {
                message = "RESPONSE:False" + ":" + Username + ":" + ip + ":" + port.ToString();
            }
            var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            socket.Connect(Contactip, Contactport);
            socket.Send(System.Text.Encoding.ASCII.GetBytes(message));
            socket.Close();
        }

    }
}

MainWindow.xaml file:

<Window x:Class="P2PChat.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:P2PChat"
        xmlns:vm="clr-namespace:P2PChat"
        mc:Ignorable="d"
        Title="P2P Chat" Height="600" Width="800">
    <Window.Resources>
        <vm:MainWindow x:Key="Locator"/>
    </Window.Resources>
    <Grid DataContext="{Binding Main, Source={StaticResource Locator}}">
        <ListBox x:Name="ContactListBox" HorizontalAlignment="Left" Height="400" Margin="10,10,0,0" VerticalAlignment="Top" Width="200"
                 ItemsSource="{Binding Contacts}"
                 DisplayMemberPath="Username"
                 SelectedItem="{Binding SelectedContact}"
                 MouseDoubleClick="ContactListBox_MouseDoubleClick"/>
        <ListBox x:Name="ChatListBox" HorizontalAlignment="Left" Height="375" Margin="230,10,0,0" VerticalAlignment="Top" Width="550"
                 ItemsSource="{Binding SelectedContact.Messages}"
                 DisplayMemberPath="Username"/>
        <TextBox x:Name="MessageTextBox" HorizontalAlignment="Left" Height="77" Margin="230,405,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="450"
                 Text="{Binding MessageText, UpdateSourceTrigger=PropertyChanged}"/>
        <Button x:Name="SendButton" HorizontalAlignment="Left" Margin="694,410,0,0" VerticalAlignment="Top" Width="75"
                Command="{Binding SendMessageCommand}"
                CommandParameter="{Binding MessageText}"
                Height="66"
                Content="Send"
                Click="SendButton_Click"/>
        <Button x:Name="AddButton" HorizontalAlignment="Left" Margin="47,523,0,0" VerticalAlignment="Top" Width="100"
                Command="{Binding AddContactCommand}"
                CommandParameter="{Binding Port}"
                Content="Add Contact"/>
        <Button x:Name="RemoveButton" HorizontalAlignment="Left" Margin="47,548,0,0" VerticalAlignment="Top" Width="100"
                Command="{Binding RemoveContactCommand}"
                CommandParameter="{Binding SelectedContact}"
                Content="Remove Contact"/>
        <TextBox x:Name="UsernameTextBox" HorizontalAlignment="Left" Height="23" Margin="47,425,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"
                 Text="{Binding ContactUsername, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox x:Name="IpAddressTextBox" HorizontalAlignment="Left" Height="23" Margin="47,453,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"
                 Text="{Binding ContactIpAddress, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox x:Name="PortTextBox" HorizontalAlignment="Left" Height="23" Margin="47,481,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"
                 Text="{Binding ContactPort, UpdateSourceTrigger=PropertyChanged}"/>

    </Grid>
</Window>

It worked fine when I didnt use MVVM but apparently its a requirement for this assignment and I am really stumped.


问:
Adjustable but consistent/raw feed from Camera X (no AE or AWB)
*Note: I figured out why the image was too dark at max SENSOR_SENSITIVITY: it was just a matter of EXPOSURE_TIME being too short, had to pump it up to 8 digits. Now all I have to do is save the values for SENSOR_SENSITIVITY and EXPOSURE_TIME.  So, this question is answered, unless there's a better way?

Using Camera X (Camera2Interop) I want to turn off auto-exposure and white balance.  Because I want to manually adjust the brightness, and ideally have it locked at that value until I adjust it again.

I'm not capturing an image but just working with the preview, and image analysis.

When turning CONTROL_MODE off or AE off the preview & analysis are black (unless pointed directly at light bulb), and I can get an image by adjusting SENSOR_SENSITIVITY, but the image is still too dark at maximum and has noise in it.  When I modify EXPOSURE_TIME the image goes 100% black no matter what.*

Using AE_LOCK + AE_EXPOSURE_COMPENSATION instead fixes the issue of the black preview and prevents auto-correction, but isn't consistent, for I don't have a way to reset the brightness to what was set previously.  For example: if I open the main camera app and go back to mine the brightness is now locked at a different value.

```<code>Camera2Interop.Extender extender = new Camera2Interop.Extender(builder);
//extender.setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);
//extender.setCaptureRequestOption(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION,-1);
extender.setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_MACRO);

//extender.setCaptureRequestOption(CaptureRequest.SENSOR_EXPOSURE_TIME,10);

//extender.setCaptureRequestOption(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_OFF);
//extender.setCaptureRequestOption(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF);
extender.setCaptureRequestOption(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_OFF);

//extender.setCaptureRequestOption(CaptureRequest.SENSOR_SENSITIVITY,99999);

extender.setCaptureRequestOption(CaptureRequest.CONTROL_AWB_LOCK,true);
extender.setCaptureRequestOption(CaptureRequest.CONTROL_AE_LOCK,true);
//extender.setCaptureRequestOption(CaptureRequest.BLACK_LEVEL_LOCK,true);
</code>```

Another issue is When adjusting brightness via EXPOSURE_COMPENSATION it seems to compound.  For example, if it's set to -3 the image gets a little darker with every start of the application, or probably every time startCameraX is run.  Perhaps this is an easy fix by moving it out of startcamera, but I was attempting to start or reset to it's previously set value.

```<code>ExposureState exposureState = camera.getCameraInfo().getExposureState();

if (!exposureState.isExposureCompensationSupported()) return;

Range<Integer> range = exposureState.getExposureCompensationRange();

int index = exposureState.getExposureCompensationIndex();

if (range.contains(1) && index != -3) {
    camera.getCameraControl().setExposureCompensationIndex(-3);
}
</code>```

Also, all the warning that come along with the camera2 interop extender makes it seem odd that's the official solution.

Other failed attempts: Canceling focus and metering, and set the metering point to 0x0 pixels.

```<code>camera.getCameraControl().cancelFocusAndMetering();//.setExposureCompensationIndex(12);
</code>```
```<code>MeteringPointFactory meteringPointFactory = previewView.getMeteringPointFactory();
MeteringPoint meteringPoint = meteringPointFactory.createPoint(0,0, 0);
FocusMeteringAction action = new FocusMeteringAction.Builder(meteringPoint).build();
        //.setAutoCancelDuration(1, TimeUnit.MICROSECONDS).build();
cameraControl.startFocusAndMetering(action);
</code>```

Body:
*Note: I figured out why the image was too dark at max SENSOR_SENSITIVITY: it was just a matter of EXPOSURE_TIME being too short, had to pump it up to 8 digits. Now all I have to do is save the values for SENSOR_SENSITIVITY and EXPOSURE_TIME.  So, this question is answered, unless there's a better way?

Using Camera X (Camera2Interop) I want to turn off auto-exposure and white balance.  Because I want to manually adjust the brightness, and ideally have it locked at that value until I adjust it again.

I'm not capturing an image but just working with the preview, and image analysis.

When turning CONTROL_MODE off or AE off the preview & analysis are black (unless pointed directly at light bulb), and I can get an image by adjusting SENSOR_SENSITIVITY, but the image is still too dark at maximum and has noise in it.  When I modify EXPOSURE_TIME the image goes 100% black no matter what.*

Using AE_LOCK + AE_EXPOSURE_COMPENSATION instead fixes the issue of the black preview and prevents auto-correction, but isn't consistent, for I don't have a way to reset the brightness to what was set previously.  For example: if I open the main camera app and go back to mine the brightness is now locked at a different value.

Camera2Interop.Extender extender = new Camera2Interop.Extender(builder);
//extender.setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);
//extender.setCaptureRequestOption(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION,-1);
extender.setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_MACRO);

//extender.setCaptureRequestOption(CaptureRequest.SENSOR_EXPOSURE_TIME,10);

//extender.setCaptureRequestOption(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_OFF);
//extender.setCaptureRequestOption(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF);
extender.setCaptureRequestOption(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_OFF);

//extender.setCaptureRequestOption(CaptureRequest.SENSOR_SENSITIVITY,99999);

extender.setCaptureRequestOption(CaptureRequest.CONTROL_AWB_LOCK,true);
extender.setCaptureRequestOption(CaptureRequest.CONTROL_AE_LOCK,true);
//extender.setCaptureRequestOption(CaptureRequest.BLACK_LEVEL_LOCK,true);

Another issue is When adjusting brightness via EXPOSURE_COMPENSATION it seems to compound.  For example, if it's set to -3 the image gets a little darker with every start of the application, or probably every time startCameraX is run.  Perhaps this is an easy fix by moving it out of startcamera, but I was attempting to start or reset to it's previously set value.

ExposureState exposureState = camera.getCameraInfo().getExposureState();

if (!exposureState.isExposureCompensationSupported()) return;

Range<Integer> range = exposureState.getExposureCompensationRange();

int index = exposureState.getExposureCompensationIndex();

if (range.contains(1) && index != -3) {
    camera.getCameraControl().setExposureCompensationIndex(-3);
}

Also, all the warning that come along with the camera2 interop extender makes it seem odd that's the official solution.

Other failed attempts: Canceling focus and metering, and set the metering point to 0x0 pixels.

camera.getCameraControl().cancelFocusAndMetering();//.setExposureCompensationIndex(12);

MeteringPointFactory meteringPointFactory = previewView.getMeteringPointFactory();
MeteringPoint meteringPoint = meteringPointFactory.createPoint(0,0, 0);
FocusMeteringAction action = new FocusMeteringAction.Builder(meteringPoint).build();
        //.setAutoCancelDuration(1, TimeUnit.MICROSECONDS).build();
cameraControl.startFocusAndMetering(action);


问:
Using alt_text argument in ph_with() function for PowerPoint

library(officer)
library(flextable)
library(tidyverse)

x <- read_pptx()

data_flex <- flextable(iris)

y <- add_slide(x, layout='Title Slide') %>%
  ph_with(value=data_flex,
          location=ph_location(left=0.5, top=0.5),
          alt_text = 'alt text test')

print(y, target='iris.pptx')
```

I've created automated powerpoint reports for work, and am now being required to add alt-text to charts and tables for ADA accessibility. The officer documentation shows an alt_text argument, but I haven't been able to get it to work. I've tried it as text, c(), and list(), but nothing seems to work. Are there any examples of how to use this argument?

Body:
library(officer)
library(flextable)
library(tidyverse)

x <- read_pptx()

data_flex <- flextable(iris)

y <- add_slide(x, layout='Title Slide') %>%
  ph_with(value=data_flex,
          location=ph_location(left=0.5, top=0.5),
          alt_text = 'alt text test')

print(y, target='iris.pptx')

I've created automated powerpoint reports for work, and am now being required to add alt-text to charts and tables for ADA accessibility. The officer documentation shows an alt_text argument, but I haven't been able to get it to work. I've tried it as text, c(), and list(), but nothing seems to work. Are there any examples of how to use this argument?


问:
How to send email from Python script using PHP script
I am trying to execute a php mail script from my python code with two variables, but I don't know how to initiate that php script which is on a live server from my python code while entering two variables:

```<code><?php
$sub= $_GET['sub'];
$mes= $_GET['mes'];
// send email
mail("test@gmail.com",$sub,$mes);
?>
</code>```

and I want to try to fill in two variables by just calling the url within python script something like:

domain.com/text.php?sub=subject&mes=message

```<code>   subject = My Subject is
   message = My Message is
   try:
      ping.verbose_ping('domain.com/text.php?sub=subject&mes=message, count=3)
   except subprocess.CalledProcessError:
      print ("Couldn't get a ping.")

</code>```

I tried to ping but its not working.

Body:
I am trying to execute a php mail script from my python code with two variables, but I don't know how to initiate that php script which is on a live server from my python code while entering two variables:

<?php
$sub= $_GET['sub'];
$mes= $_GET['mes'];
// send email
mail("test@gmail.com",$sub,$mes);
?>

and I want to try to fill in two variables by just calling the url within python script something like:

domain.com/text.php?sub=subject&mes=message

   subject = My Subject is
   message = My Message is
   try:
      ping.verbose_ping('domain.com/text.php?sub=subject&mes=message, count=3)
   except subprocess.CalledProcessError:
      print ("Couldn't get a ping.")

I tried to ping but its not working.


问:
Running "yarn install" in "aio" directory of Angular source code throws an error
When I run yarn install in angular/aio, I get the following error message:

$ node tools/cli-patches/patch.js
C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\common.js:401
      if (config.fatal) throw e;
                        ^

Error: exec:
    at Object.error (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\common.js:110:27)
    at execSync (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\exec.js:120:12)
    at Object._exec (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\exec.js:223:12)
    at Object.exec (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\common.js:335:23)
    at C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\tools\cli-patches\patch.js:11:27
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\tools\cli-patches\patch.js:11:8)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
```

I'm working with Angular v15 source code on Windows 10 Pro OS. I used NodeJS v18.12.1 LTS and v16.13.2, and Yarn v1.22.17.

I have tried to follow the instructions for documentation contribution stated in these links:

https://angular.io/guide/doc-update-start

https://angular.io/guide/doc-editing

I was expecting for a draft of the angular.io website to be served locally. However, I cannot run commands such as yarn build and yarn start to build the documentation since yarn install will keep throwing that error.

Why is this error message is being thrown, and what can I do so that it doesn't throw this error?

Body:
When I run yarn install in angular/aio, I get the following error message:

$ node tools/cli-patches/patch.js
C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\common.js:401
      if (config.fatal) throw e;
                        ^

Error: exec:
    at Object.error (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\common.js:110:27)
    at execSync (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\exec.js:120:12)
    at Object._exec (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\exec.js:223:12)
    at Object.exec (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\node_modules\shelljs\src\common.js:335:23)
    at C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\tools\cli-patches\patch.js:11:27
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (C:\Users\ACCOUNT_USERNAME\OneDrive\Desktop\github-projects\MY_GITHUB_USERNAME\angular\aio\tools\cli-patches\patch.js:11:8)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

I'm working with Angular v15 source code on Windows 10 Pro OS. I used NodeJS v18.12.1 LTS and v16.13.2, and Yarn v1.22.17.

I have tried to follow the instructions for documentation contribution stated in these links:

https://angular.io/guide/doc-update-start

https://angular.io/guide/doc-editing

I was expecting for a draft of the angular.io website to be served locally. However, I cannot run commands such as yarn build and yarn start to build the documentation since yarn install will keep throwing that error.

Why is this error message is being thrown, and what can I do so that it doesn't throw this error?