问:
MEAN Stack http PUT request issue
i'm pretty new in MEAN STACK.

I make my API REST under Nodejs Express and mongoodb.
I use Angular 14 as client.

I made a little project where user can register / login / display user informations.
Now i'd like to add an update functionality. A simple form where user can update his name or his role. I'm stuck at this point and i'd like to know why my code don't work and how can i fix this. It's been 2 days i'm on it, that's why i'm there to have some informations.

This is my config.json

```<code>{
"development": {
    "PORT": 3000,
    "MONGODB_URI": "mongodb://localhost:27017/PangolinDB",
    "JWT_SECRET": "SECRET#123",
    "JWT_EXP": "10m"
},
"production": {
    "PORT": 80,
    "MONGODB_URI": "mongodb://xxxxx/DB_Name",
    "JWT_SECRET": "SECRET#123",
    "JWT_EXP": "2m"
 }
}
</code>```

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

user.model.js

```<code>const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

var userSchema = new mongoose.Schema({
fullName: {
    type: String,
    required: 'Full name can\'t be empty'
},
email: {
    type: String,
    required: 'Email can\'t be empty',
    unique: true
},
password: {
    type: String,
    required: 'Password can\'t be empty',
    minlength: [4, 'Password must be atleast 4 character long']
},
role: {
    type: String,
    required: 'Role can\'t be empty',
},
followers: {
    type: String,
},
following: {
    type: String,
},

saltSecret: String
});

// Custom validation for email
userSchema.path('email').validate((val) => {
emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.
 [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailRegex.test(val);
}, 'Invalid e-mail.');

// Events encrypt password
userSchema.pre('save', function (next) {
bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(this.password, salt, (err, hash) => {
        this.password = hash;
        this.saltSecret = salt;
        next();
    });
});
});

// Methods verify password
userSchema.methods.verifyPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

userSchema.methods.generateJwt = function () {
return jwt.sign({ _id: this._id},
    process.env.JWT_SECRET,
{
    expiresIn: process.env.JWT_EXP
});
}

mongoose.model('User', userSchema);
</code>```

routes.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>```

index.js

```<code>require('./config/config');
require('./models/db');
require('./config/passportConfig');
require('./routes/index.router')

const express = require('express');
 const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');

 //updated code

// end updtated code

const rtsIndex = require('./routes/index.router');
var app = express();
// middleware
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
app.use('/api', rtsIndex);

//
/* app.use('api',routeList); */
//

// error handler
app.use((err, req, res, next) => {
if (err.name === 'ValidationError') {
    var valErrors = [];
    Object.keys(err.errors).forEach(key => valErrors.push(err.errors[key].message));
    res.status(422).send(valErrors)
}
else{
    console.log(err);
}
});

// start server
app.listen(process.env.PORT, () => console.log(`Server started at port :

${process.env.PORT}`));

user.service.ts (angular 14)

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{

editUsr = new FormGroup({
fullName: new FormControl(null, [Validators.required]),
email: new FormControl(null, [Validators.required]),
  role: new FormControl(null, [Validators.required])
});

loading: boolean =true;
id: any;

constructor (
private userService : UserService,
private activateRoute : ActivatedRoute,
private route: Router
){}

ngOnInit(): void {
this.activateRoute.params.subscribe((data: any) =>{
  this.id = data['id'];
  this.userService.getOne(this.id).subscribe((res: any)=>{
    if (res.user != undefined){
      this.editUsr.get('fullName')?.setValue(res.user.fullName);
      this.editUsr.get('email')?.setValue(res.user.email);
      this.editUsr.get('role')?.setValue(res.user.role);
    }
  });
  this.loading = false;
});

}

addUser(){
const data: any = {
  fullName : this.editUsr.get('fullName')?.value,
  email : this.editUsr.get('email')?.value,
  role: this.editUsr.get('role')?.value
}

this.userService.edit(this.id, data).subscribe(()=>this.route.navigateByUrl('edit'));
}
}

*/

export class EditComponent implements OnInit {

getId:any;
updateForm: FormGroup;

constructor(
public formBuilder: FormBuilder,
private router: Router,
private ngZone: NgZone,
private activatedRoute: ActivatedRoute,
private UserService: UserService
) {
this.getId = this.activatedRoute.snapshot.paramMap.get('id');
this.UserService.getOne().subscribe(res=>{
  this.updateForm.patchValue({
    fullName: res['fullName'],
    email: res['email'],
    role: res['role']
  });
});
this.updateForm = this.formBuilder.group({
  fullName:[''],
  email:[''],
  role:[''],
 })

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

}
</code>```

edit.component.html

```<code><div class="row justify-content-center mt-5">
  <div class="col-md-4">
    <form [formGroup]="updateForm" (ngSubmit)="onUpdate()">
       <h2>Edit User</h2>
      <div class="form-group">
        <label for="fullName">FullName</label>
    <input class="form-control" type="text" formControlName="fullName" id="fullName" >
    </div>
   <div class="form-group">
    <label for="email">Email</label>
    <input class="form-control" type="text" formControlName="email" id="email">
   </div>
   <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>```

environment.ts

```<code>// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

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

/*
 * For easier debugging in development mode, you can import the following file
 * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
 *
 * This import should be commented out in production mode because it will have a negative

impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error';  // Included with Angular CLI.
</code>```

routes.ts

```<code>import { EditComponent } from './edit/edit.component';
 import { HomeComponent } from './home/home.component';
import { Routes } from "@angular/router";
import { UserComponent } from "./user/user.component";
import { SignUpComponent } from "./sign-up/sign-up.component";
import { SignInComponent } from "./user/sign-in/sign-in.component";
import { UserProfileComponent } from "./user-profile/user-profile.component";
import { AuthGuard } from "./auth/auth.guard";

 export const appRoutes: Routes = [
 {path:'home', component: HomeComponent},
 {path:'edit', component:EditComponent},
 {
path: 'signup', component: UserComponent,
children: [{ path:'', component: SignUpComponent}]
},
{
path: 'login', component: UserComponent,
children: [{ path:'', component: SignInComponent}]
},
{
 path: 'userprofile', component: UserProfileComponent,canActivate:[AuthGuard]
},
{
 path: '', redirectTo: '/login', pathMatch: 'full'
 }
];
</code>```

thanks in advance for the help :)

Title: MEAN Stack http PUT request issue

Body:
i'm pretty new in MEAN STACK.

I make my API REST under Nodejs Express and mongoodb.
I use Angular 14 as client.

I made a little project where user can register / login / display user informations.
Now i'd like to add an update functionality. A simple form where user can update his name or his role. I'm stuck at this point and i'd like to know why my code don't work and how can i fix this. It's been 2 days i'm on it, that's why i'm there to have some informations.

This is my config.json

{
"development": {
    "PORT": 3000,
    "MONGODB_URI": "mongodb://localhost:27017/PangolinDB",
    "JWT_SECRET": "SECRET#123",
    "JWT_EXP": "10m"
},
"production": {
    "PORT": 80,
    "MONGODB_URI": "mongodb://xxxxx/DB_Name",
    "JWT_SECRET": "SECRET#123",
    "JWT_EXP": "2m"
 }
}

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

user.model.js

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

var userSchema = new mongoose.Schema({
fullName: {
    type: String,
    required: 'Full name can\'t be empty'
},
email: {
    type: String,
    required: 'Email can\'t be empty',
    unique: true
},
password: {
    type: String,
    required: 'Password can\'t be empty',
    minlength: [4, 'Password must be atleast 4 character long']
},
role: {
    type: String,
    required: 'Role can\'t be empty',
},
followers: {
    type: String,
},
following: {
    type: String,
},

saltSecret: String
});

// Custom validation for email
userSchema.path('email').validate((val) => {
emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.
 [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailRegex.test(val);
}, 'Invalid e-mail.');

// Events encrypt password
userSchema.pre('save', function (next) {
bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(this.password, salt, (err, hash) => {
        this.password = hash;
        this.saltSecret = salt;
        next();
    });
});
});

// Methods verify password
userSchema.methods.verifyPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

userSchema.methods.generateJwt = function () {
return jwt.sign({ _id: this._id},
    process.env.JWT_SECRET,
{
    expiresIn: process.env.JWT_EXP
});
}

mongoose.model('User', userSchema);

routes.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;

index.js

require('./config/config');
require('./models/db');
require('./config/passportConfig');
require('./routes/index.router')

const express = require('express');
 const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');

 //updated code

// end updtated code

const rtsIndex = require('./routes/index.router');
var app = express();
// middleware
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
app.use('/api', rtsIndex);

//
/* app.use('api',routeList); */
//

// error handler
app.use((err, req, res, next) => {
if (err.name === 'ValidationError') {
    var valErrors = [];
    Object.keys(err.errors).forEach(key => valErrors.push(err.errors[key].message));
    res.status(422).send(valErrors)
}
else{
    console.log(err);
}
});

// start server
app.listen(process.env.PORT, () => console.log(`Server started at port :

${process.env.PORT}`));

user.service.ts (angular 14)

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{

editUsr = new FormGroup({
fullName: new FormControl(null, [Validators.required]),
email: new FormControl(null, [Validators.required]),
  role: new FormControl(null, [Validators.required])
});

loading: boolean =true;
id: any;

constructor (
private userService : UserService,
private activateRoute : ActivatedRoute,
private route: Router
){}

ngOnInit(): void {
this.activateRoute.params.subscribe((data: any) =>{
  this.id = data['id'];
  this.userService.getOne(this.id).subscribe((res: any)=>{
    if (res.user != undefined){
      this.editUsr.get('fullName')?.setValue(res.user.fullName);
      this.editUsr.get('email')?.setValue(res.user.email);
      this.editUsr.get('role')?.setValue(res.user.role);
    }
  });
  this.loading = false;
});

}

addUser(){
const data: any = {
  fullName : this.editUsr.get('fullName')?.value,
  email : this.editUsr.get('email')?.value,
  role: this.editUsr.get('role')?.value
}

this.userService.edit(this.id, data).subscribe(()=>this.route.navigateByUrl('edit'));
}
}

*/

export class EditComponent implements OnInit {

getId:any;
updateForm: FormGroup;

constructor(
public formBuilder: FormBuilder,
private router: Router,
private ngZone: NgZone,
private activatedRoute: ActivatedRoute,
private UserService: UserService
) {
this.getId = this.activatedRoute.snapshot.paramMap.get('id');
this.UserService.getOne().subscribe(res=>{
  this.updateForm.patchValue({
    fullName: res['fullName'],
    email: res['email'],
    role: res['role']
  });
});
this.updateForm = this.formBuilder.group({
  fullName:[''],
  email:[''],
  role:[''],
 })

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

}

edit.component.html

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

Edit User

        FullName
    <input class="form-control" type="text" formControlName="fullName" id="fullName" >

    Email
    <input class="form-control" type="text" formControlName="email" id="email">

    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!

environment.ts

// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

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

/*
 * For easier debugging in development mode, you can import the following file
 * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
 *
 * This import should be commented out in production mode because it will have a negative

impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error';  // Included with Angular CLI.

routes.ts

import { EditComponent } from './edit/edit.component';
 import { HomeComponent } from './home/home.component';
import { Routes } from "@angular/router";
import { UserComponent } from "./user/user.component";
import { SignUpComponent } from "./sign-up/sign-up.component";
import { SignInComponent } from "./user/sign-in/sign-in.component";
import { UserProfileComponent } from "./user-profile/user-profile.component";
import { AuthGuard } from "./auth/auth.guard";

 export const appRoutes: Routes = [
 {path:'home', component: HomeComponent},
 {path:'edit', component:EditComponent},
 {
path: 'signup', component: UserComponent,
children: [{ path:'', component: SignUpComponent}]
},
{
path: 'login', component: UserComponent,
children: [{ path:'', component: SignInComponent}]
},
{
 path: 'userprofile', component: UserProfileComponent,canActivate:[AuthGuard]
},
{
 path: '', redirectTo: '/login', pathMatch: 'full'
 }
];

thanks in advance for the help :)


来源: stackexchange

问:
Static build of nginx fails with http_image_filter_module
I am trying to create a static build of nginx so that I can copy it easily to a different server.

I tried to both install the libgd-dev library using a package manager, and to build it from source in /usr/local but when I add the option `--with-http_image_filter_module I still get an error that it was not found:

checking for GD library ... not found checking for GD library in
/usr/local/ ... not found checking for GD library in /usr/pkg/ ... not
found checking for GD library in /opt/local/ ... not found
./configure: error: the HTTP image filter module requires the GD
library. You can either do not enable the module or install the
libraries.

Can I specify the path of that library somehow?  Or put it in another path that will work?

ContentLicense: CC BY-SA 4.0


问:
changing a rows backrow color in grid view based on the value of a field
How can I set the back color of a row in asp gridview based on the value of a field in the row?

I gave tried variations of the following code:

```<code>   Sub ongridviewrowdatabound_gvBudgetView(ByVal o As Object, ByVal e As EventArgs)
        For Each row As GridViewRow In gvBudgetView.Rows
            For i As Integer = 0 To row.Count() - 1
                If rows(i).Cell(6).value = 0 Then
                    Cell(6).BackColor = "red"
                End If
            Next
        Next
    End Sub
</code>```

What I'm trying to do is get the program to read each row and set the backcolor based on the checkbox. I've tried several variations of the above code but can't get it run. I would appreciate any help I can get. --Chuck

```<code></code>```

Body:
How can I set the back color of a row in asp gridview based on the value of a field in the row?

I gave tried variations of the following code:

   Sub ongridviewrowdatabound_gvBudgetView(ByVal o As Object, ByVal e As EventArgs)
        For Each row As GridViewRow In gvBudgetView.Rows
            For i As Integer = 0 To row.Count() - 1
                If rows(i).Cell(6).value = 0 Then
                    Cell(6).BackColor = "red"
                End If
            Next
        Next
    End Sub

What I'm trying to do is get the program to read each row and set the backcolor based on the checkbox. I've tried several variations of the above code but can't get it run. I would appreciate any help I can get. --Chuck


问:
Process getting too many Lock wait timeout exceeded errors
So I'm working on a project that have the following schema on a MySQL 5.7 database:

```<code>CREATE TABLE `voucher` (
  `id` varchar(36) NOT NULL,
  `voucher_status_id` int(11) NOT NULL,
  `situation_code` varchar(30) DEFAULT NULL,
  `organization_id` int(11) DEFAULT NULL,
  `code` varchar(15) NOT NULL,
  `authorization_code` varchar(7) NOT NULL
   .. other columns omitted for brevity
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

This table have ~ 2M rows and stores a pool of Vouchers.

The system get vouchers with voucher_status_id = 1 to sell.

The sale process is basically:

The user inputs the quantity X of Vouchers he wants to buy.

The application query the database with this select: SELECT v.* FROM voucher v where v.voucher_status_id = ? and v.organization_id = ? limit X for update

Then do the rest (update the voucher status, etc), and commit the transaction.

Things to notice: there's no SKIP LOCKED feature available, because this application is using MySQL 5.7; this pool of vouchers exist because the process of generating a voucher code is complex and made by a scheduled process on another system that load this table; the id column is a UUID v4

As you noticed, the select statement from above does lock some rows and it causes a lot of problems to the other sales concurrently happening and often (really) inccurs in Lock wait timeout exceeded errors.

By reading MySQL documentation, I found that it locks all the rows it has to scan while doing select ... for update statements.

A SELECT ... FOR UPDATE reads the latest available data, setting
exclusive locks on each row it reads. Thus, it sets the same locks a
searched SQL UPDATE would set on the rows.

The application is getting tons of Lock wait timeout exceeded errors. How can this be avoided in this case?

Another dev proposed randomly select rows by using ORDER BY RAND(), but it would end up with the same problem as a test I made clearly showed us:

Transaction A:

```<code>begin;
select * from voucher v where v.voucher_status_id = 1
    and organization_id = 5
    order by rand()
    limit 5
    for update;
</code>```

Transaction B:

```<code>begin;
select * from voucher v where v.voucher_status_id = 1
    and organization_id = 5
    order by rand()
    limit 10
    for update;
</code>```

Transaction B gets locked until Transaction A is commited.

How would you solve such situation?

Body:
So I'm working on a project that have the following schema on a MySQL 5.7 database:

CREATE TABLE `voucher` (
  `id` varchar(36) NOT NULL,
  `voucher_status_id` int(11) NOT NULL,
  `situation_code` varchar(30) DEFAULT NULL,
  `organization_id` int(11) DEFAULT NULL,
  `code` varchar(15) NOT NULL,
  `authorization_code` varchar(7) NOT NULL
   .. other columns omitted for brevity
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

This table have ~ 2M rows and stores a pool of Vouchers.

The system get vouchers with voucher_status_id = 1 to sell.

The sale process is basically:

The user inputs the quantity X of Vouchers he wants to buy.

The application query the database with this select: SELECT v.* FROM voucher v where v.voucher_status_id = ? and v.organization_id = ? limit X for update

Then do the rest (update the voucher status, etc), and commit the transaction.

Things to notice: there's no SKIP LOCKED feature available, because this application is using MySQL 5.7; this pool of vouchers exist because the process of generating a voucher code is complex and made by a scheduled process on another system that load this table; the id column is a UUID v4

As you noticed, the select statement from above does lock some rows and it causes a lot of problems to the other sales concurrently happening and often (really) inccurs in Lock wait timeout exceeded errors.

By reading MySQL documentation, I found that it locks all the rows it has to scan while doing select ... for update statements.

A SELECT ... FOR UPDATE reads the latest available data, setting
exclusive locks on each row it reads. Thus, it sets the same locks a
searched SQL UPDATE would set on the rows.

The application is getting tons of Lock wait timeout exceeded errors. How can this be avoided in this case?

Another dev proposed randomly select rows by using ORDER BY RAND(), but it would end up with the same problem as a test I made clearly showed us:

Transaction A:

begin;
select * from voucher v where v.voucher_status_id = 1
    and organization_id = 5
    order by rand()
    limit 5
    for update;

Transaction B:

begin;
select * from voucher v where v.voucher_status_id = 1
    and organization_id = 5
    order by rand()
    limit 10
    for update;

Transaction B gets locked until Transaction A is commited.

How would you solve such situation?


问:
Python Jinja2: How to add an empty row in a table, which is created from a nested loop
I create a table from 2 for loops, and I'd like to add an empty row when each inner loop is finished.

Do I need to keep track of both outer loop and inner loop for it, like this? Or is there a better way to do it?

```<code><table border="1" style="border-collapse:collapse;">
    {% for dict in table_data %}
    {% set outer_loop = loop %}
        {% for test_name, test_dict in dict["tests_data"].items() %}
            ....
            {% if not outer_loop.last or not loop.last %}  <!-- Add an empty row -->
                <tr bgcolor="FFFFFF">
                    <td colspan="{{titles|length}}"><br/></td>
                </tr>
            {% endif %}
        {% endfor %}
    {% endfor %}
</table>
</code>```

Body:
I create a table from 2 for loops, and I'd like to add an empty row when each inner loop is finished.

Do I need to keep track of both outer loop and inner loop for it, like this? Or is there a better way to do it?

    {% for dict in table_data %}
    {% set outer_loop = loop %}
        {% for test_name, test_dict in dict["tests_data"].items() %}
            ....
            {% if not outer_loop.last or not loop.last %}

            {% endif %}
        {% endfor %}
    {% endfor %}


问:
how to save array of object in rails controller
The issue I am facing is the array of objects is saved as an array of string of objects. Below is the code. The params coming from the frontend are corrected and in the required format but after saving the array is saved as an array of string of objects.

```<code>def create
  binding.pry_remote
  @report = Report.new(report_params)
  @report.save
end

private

def report_params
  params.require(:report).permit(:type,
                                     header: [:text, :value]
end
</code>```

params coming from frontend

```<code><ActionController::Parameters {"report"=>{"type"=>"asd 7", "header"=>[{"text"=>"ID", "value"=>"id"}, {"text"=>"First Name", "value"=>"first_name"}], "controller"=>"my_account/reports", "action"=>"create", "format"=>"json"} permitted: false>
</code>```

report_params

```<code><ActionController::Parameters {"type"=>"asd 7", "header"=>[<ActionController::Parameters {"text"=>"ID", "value"=>"id"} permitted: true>, <ActionController::Parameters {"text"=>"First Name", "value"=>"first_name"} permitted: true>]} permitted: true>
</code>```

After the record is saved, the header is saved as an array of string objects instead of an array of objects. I don't know where I am going wrong.

```<code><Report id: 6, header: ["{\"text\"=>\"ID\", \"value\"=>\"id\"}", "{\"text\"=>\"First Name\", \"value\"=>\"first_name\"}"], type: "asd 7">
</code>```

Body:
The issue I am facing is the array of objects is saved as an array of string of objects. Below is the code. The params coming from the frontend are corrected and in the required format but after saving the array is saved as an array of string of objects.

def create
  binding.pry_remote
  @report = Report.new(report_params)
  @report.save
end

private

def report_params
  params.require(:report).permit(:type,
                                     header: [:text, :value]
end

params coming from frontend

<ActionController::Parameters {"report"=>{"type"=>"asd 7", "header"=>[{"text"=>"ID", "value"=>"id"}, {"text"=>"First Name", "value"=>"first_name"}], "controller"=>"my_account/reports", "action"=>"create", "format"=>"json"} permitted: false>

report_params

<ActionController::Parameters {"type"=>"asd 7", "header"=>[<ActionController::Parameters {"text"=>"ID", "value"=>"id"} permitted: true>, <ActionController::Parameters {"text"=>"First Name", "value"=>"first_name"} permitted: true>]} permitted: true>

After the record is saved, the header is saved as an array of string objects instead of an array of objects. I don't know where I am going wrong.

<Report id: 6, header: ["{\"text\"=>\"ID\", \"value\"=>\"id\"}", "{\"text\"=>\"First Name\", \"value\"=>\"first_name\"}"], type: "asd 7">


问:
Apk appears to be invalid error while installing signed apk in Android 12
I checked different answers but didn't find any solution working. I am still facing apk appears to be invalid error in Android 12. It installs in one Android 12 Samsung device but not in other with same OS and manufacturer. I tried uninstalling all older versions of that app.


问:
Trying to read ALL memory address from a procces on Windows with C#, but fail
I'm trying to get ALL the memory addresses and it's values from a PROCCESS with C# on Windows but I can't, I don't know how to reach ALL of them... Please can Anyone helpme!?

Want to get All the addresses and it's values and put them into TXT file or TEXTAREA on my form.

Here an image from I get: enter image description here

And This is the code that I'm trying

```<code>
using System;
using System.ComponentModel;
using System.Windows.Forms;
using Memory;

public class Form1 : Form
{
    private Mem o = new Mem();

    public Form1()
    {
        int procIdFromName = o.GetProcIdFromName("notepad");
        if (procIdFromName > 0)
        {
            o.OpenProcess(procIdFromName);
            MessageBox.Show("NOTEPAD OPEN: "+procIdFromName.ToString(), "Notepad Open", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        } else {
            MessageBox.Show("NOTEPAD CLOSED", "Notepad Closed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}
</code>```

Body:
I'm trying to get ALL the memory addresses and it's values from a PROCCESS with C# on Windows but I can't, I don't know how to reach ALL of them... Please can Anyone helpme!?

Want to get All the addresses and it's values and put them into TXT file or TEXTAREA on my form.

Here an image from I get: enter image description here

And This is the code that I'm trying

using System;
using System.ComponentModel;
using System.Windows.Forms;
using Memory;

public class Form1 : Form
{
    private Mem o = new Mem();

    public Form1()
    {
        int procIdFromName = o.GetProcIdFromName("notepad");
        if (procIdFromName > 0)
        {
            o.OpenProcess(procIdFromName);
            MessageBox.Show("NOTEPAD OPEN: "+procIdFromName.ToString(), "Notepad Open", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        } else {
            MessageBox.Show("NOTEPAD CLOSED", "Notepad Closed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}


问:
Github multi-dimensional query
I am trying to query the Github RestAPI v. X-GitHub-Api-Version to find line changes (addition, deletions), user, date, repository_name for any repositories in an organization that have files of a particular file extension.  Not seeing a clear path forward with this, do I need to file all files using {{baseUrl}}/search/code?q=org:{{org}}+extension:tf, then take those outputs iterating over and querying commits for a file and then extract the details from the commit details?

Title: Github multi-dimensional query


问:
how to download a generated pdf file using playwright?
I'm trying to download a file using playwright, this file is generated which means the url doesn't ends with a '.pdf' and forcing this link in the url doesn't start the download. I was abble to navigate until the pdf is generated but how can I download it now ?

here is my code:

const {chromium} = require('playwright');
const path = require('path');

(async () => {
    const browser = await chromium.launch({
        headless: true,
    });
    const context = await browser.newContext({
        acceptDownloads: true
    });
    const page = await context.newPage();

    const downloadPath = path.join(__dirname, 'edt');

    await page.goto('https://planif.eppe.ui/jsp/custom/eppee/easyMyPlanning.jsp');
    await page.getByLabel('Identifiant :').click();
    await page.getByLabel('Identifiant :').fill('myusername');
    await page.getByLabel('Identifiant :').press('Tab');
    await page.getByLabel('Mot de passe :').fill('mysecretpassword');
    await page.getByLabel('Mot de passe :').press('Enter');
    await page.getByRole('combobox').selectOption('10');
    await page.getByRole('button', { name: 'Submit' }).click();
    await page.locator('.footer > a').click();
    const page1Promise = page.waitForEvent('popup');
    await page.frameLocator('frame[name="link"]').getByRole('link', { name: 'Export PDF...' }).click();
    const page1 = await page1Promise;
    const downloadPromise = page1.waitForEvent('download');
    await page1.getByRole('button', { name: 'Submit' }).click();
    const download = await downloadPromise;
    await download.saveAs(path.join(downloadPath, 'edt.pdf'));
    await browser.close();
})();

```

with this code I end up having the browser waiting for me to try to download the file how can I automate this ?

ps: with this code and with my browser in non headless mode I end up on this page end if I manualy press the download button it works

Body:
I'm trying to download a file using playwright, this file is generated which means the url doesn't ends with a '.pdf' and forcing this link in the url doesn't start the download. I was abble to navigate until the pdf is generated but how can I download it now ?

here is my code:

const {chromium} = require('playwright');
const path = require('path');

(async () => {
    const browser = await chromium.launch({
        headless: true,
    });
    const context = await browser.newContext({
        acceptDownloads: true
    });
    const page = await context.newPage();

    const downloadPath = path.join(__dirname, 'edt');

    await page.goto('https://planif.eppe.ui/jsp/custom/eppee/easyMyPlanning.jsp');
    await page.getByLabel('Identifiant :').click();
    await page.getByLabel('Identifiant :').fill('myusername');
    await page.getByLabel('Identifiant :').press('Tab');
    await page.getByLabel('Mot de passe :').fill('mysecretpassword');
    await page.getByLabel('Mot de passe :').press('Enter');
    await page.getByRole('combobox').selectOption('10');
    await page.getByRole('button', { name: 'Submit' }).click();
    await page.locator('.footer > a').click();
    const page1Promise = page.waitForEvent('popup');
    await page.frameLocator('frame[name="link"]').getByRole('link', { name: 'Export PDF...' }).click();
    const page1 = await page1Promise;
    const downloadPromise = page1.waitForEvent('download');
    await page1.getByRole('button', { name: 'Submit' }).click();
    const download = await downloadPromise;
    await download.saveAs(path.join(downloadPath, 'edt.pdf'));
    await browser.close();
})();

with this code I end up having the browser waiting for me to try to download the file how can I automate this ?

ps: with this code and with my browser in non headless mode I end up on this page end if I manualy press the download button it works


问:
Expose different modules for different build targets (electron app vs. web)
I have an app that I want build as an Electron app (using electron-builder) or build for deployment to a web server. With the Electron app, I have the app (from inside the Electron renderer) read and write from the FileSystem (using Node's FS). I want to use BrowserFS instead when in a browser environment. How can I follow the following pseudocode so that it works in browsers and with Electron?</p>
```<code>if ( inside_node & fs_available ){
  require(fs);
}else{
  require(browserfs);
  fs.customBrowserfsFunction();
}
fs.doSomething();
</code>```

Body:
I have an app that I want build as an Electron app (using electron-builder) or build for deployment to a web server. With the Electron app, I have the app (from inside the Electron renderer) read and write from the FileSystem (using Node's FS). I want to use BrowserFS instead when in a browser environment. How can I follow the following pseudocode so that it works in browsers and with Electron?

if ( inside_node & fs_available ){
  require(fs);
}else{
  require(browserfs);
  fs.customBrowserfsFunction();
}
fs.doSomething();


问:
Can Spring Cloud Stream bind to the same function multiple times?
Given the simple application:

@SpringBootApplication
public class StreamApp {

    @Bean
    Consumer<Message<?>> logSink() { return System.out::println; }

    public static void main(String[] args) {
        SpringApplication.run(StreamApp.class, args);
    }
}
```
<p>I can bind a destination such as a Kafka topic to the <code>logSink</code> function by supplying config:</p>
```spring.cloud.stream.bindings.logSink-in-0.destination=dogs-topic
```
<p>Is there a way I could create another separate binding using the same <code>logSink</code> function? I know that the destination property accepts a comma separated list, but I want the ability to configure the bindings separately.</p>
<p>I can do this by setting an alias on the function, i.e. <code>@Bean({"logSinkOne", "logSinkTwo"})</code> and then supplying config:</p>
```spring.cloud.stream.bindings.logSinkOne-in-0.destination=dogs-topic
spring.cloud.stream.bindings.logSinkTwo-in-0.destination=cats-topic
```

however it would be great to avoid adding these alias's ahead of time.

Body:
Given the simple application:

@SpringBootApplication
public class StreamApp {

    @Bean
    Consumer<Message<?>> logSink() { return System.out::println; }

    public static void main(String[] args) {
        SpringApplication.run(StreamApp.class, args);
    }
}

I can bind a destination such as a Kafka topic to the logSink function by supplying config:

spring.cloud.stream.bindings.logSink-in-0.destination=dogs-topic

Is there a way I could create another separate binding using the same logSink function? I know that the destination property accepts a comma separated list, but I want the ability to configure the bindings separately.

I can do this by setting an alias on the function, i.e. @Bean({"logSinkOne", "logSinkTwo"}) and then supplying config:

spring.cloud.stream.bindings.logSinkOne-in-0.destination=dogs-topic
spring.cloud.stream.bindings.logSinkTwo-in-0.destination=cats-topic

however it would be great to avoid adding these alias's ahead of time.


问:
How to open a program from the system tray in windows 11 with python
I want to open my keyboard software that's hidden in the system tray on startup for it to load the current keyboard layout, and then close the program.

The current problem is if the program is not open on the desktop and if it's only in the system tray (taskbar hidden icons tray) the .FindWindow returns 0

So i need to open the program from the system tray so it can load everything

```<code>from time import sleep
import psutil
import win32gui
import win32con

def end_task(task_name):
    for proc in psutil.process_iter():
        if proc.name() == task_name:
            hwnd = win32gui.FindWindow(None, "CMSEngine")
            print(hwnd)
            win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
            sleep(10)
            proc.kill()

# sleep(240)
end_task("CMS.exe")
</code>```

Body:
I want to open my keyboard software that's hidden in the system tray on startup for it to load the current keyboard layout, and then close the program.

The current problem is if the program is not open on the desktop and if it's only in the system tray (taskbar hidden icons tray) the .FindWindow returns 0

So i need to open the program from the system tray so it can load everything

from time import sleep
import psutil
import win32gui
import win32con

def end_task(task_name):
    for proc in psutil.process_iter():
        if proc.name() == task_name:
            hwnd = win32gui.FindWindow(None, "CMSEngine")
            print(hwnd)
            win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
            sleep(10)
            proc.kill()

# sleep(240)
end_task("CMS.exe")


问:
Java EXIficient issue using schema-informed grammar for JAR-based XSD
Have been using JAXB and EXIficient library to marshall objects to XML then compress the XML to EXI.  Able to send the EXI over the wire and recover the XML.  The schemas and binding files reside under my projects src/main/resources/xsd folder.  Able to run my prototype application successfully from IDE (Gradle, IntelliJ). Have packaged the app and resources into an uber/fat JAR and created a set of run scripts.  Running app via the command line is failing when building the EXI grammar for the top-level XSD.

My initial snippet for the EXI factory setup looked like this:

var SCHEMA_PATH = "xsd/my-root.xsd";
var exiFactory = DefaultEXIFactory.newInstance();

URL xsdResource = EXICodec.class.getClassLoader().getResource(SCHEMA_PATH);
checkNotNull(xsdResource);
var xsdAbsPath = xsdResource.getFile();

// Following OK when run from within IDE.
// Following generates exception when trying to locate the XSD in uber JAR.
exiFactory.setGrammars(GrammarFactory.newInstance().createGrammars(xsdAbsPath));

exiFactory.getEncodingOptions().setOption(EncodingOptions.INCLUDE_COOKIE, true);
exiFactory.setCodingMode(CodingMode.COMPRESSION);
```
<p>It failed as follows</p>
```com.siemens.ct.exi.core.exceptions.EXIException: XML Schema document (file:/mnt/c/Users/user1/my-project/tmp-install/myapp-0.1/lib/myapp-0.1.jar!/xsd/my-root.xsd) not found.
```
<p>Basically, the XSD cannot be found in the uber/fat JAR.  Looking at the JAR contents I saw the expected <strong>/xsd/my-root.xsd</strong> entry.  Realized that I can't access the schema as a <strong>file</strong> as its not really a file but a resource bundled in the jar.</p>
<p>Tweaked my EXI factory setup as follows</p>
<pre class="lang-java prettyprint-override"><code>
exiFactory = DefaultEXIFactory.newInstance();

var xsdInputStream = ClassLoader.getSystemResourceAsStream(SCHEMA_PATH);

// Seeing exceptions as XSDs referenced from top-level XSD can't be located within JAR
exiFactory.setGrammars(GrammarFactory.newInstance().createGrammars(xsdInputStream));

exiFactory.getEncodingOptions().setOption(EncodingOptions.INCLUDE_COOKIE, true);
exiFactory.setCodingMode(CodingMode.COMPRESSION);
</code>```

Got a bit further but ran into problems locating the XSDs referenced from my top-level XSD.  E.g. entries such as the following in the top-level XSD s

<xs:import namespace="http://someURL/someVersion/" schemaLocation="../other/common.xsd"/>
```
<p>led to errors like the following when creating the grammar</p>
<pre class="lang-xml prettyprint-override"><code>com.siemens.ct.exi.core.exceptions.EXIException: Problem occured while building XML Schema Model (XSModel)!
. [xs-warning] schema_reference.4: Failed to read schema document '../other/common.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
</code>```

Body:
Have been using JAXB and EXIficient library to marshall objects to XML then compress the XML to EXI.  Able to send the EXI over the wire and recover the XML.  The schemas and binding files reside under my projects src/main/resources/xsd folder.  Able to run my prototype application successfully from IDE (Gradle, IntelliJ). Have packaged the app and resources into an uber/fat JAR and created a set of run scripts.  Running app via the command line is failing when building the EXI grammar for the top-level XSD.

My initial snippet for the EXI factory setup looked like this:

var SCHEMA_PATH = "xsd/my-root.xsd";
var exiFactory = DefaultEXIFactory.newInstance();

URL xsdResource = EXICodec.class.getClassLoader().getResource(SCHEMA_PATH);
checkNotNull(xsdResource);
var xsdAbsPath = xsdResource.getFile();

// Following OK when run from within IDE.
// Following generates exception when trying to locate the XSD in uber JAR.
exiFactory.setGrammars(GrammarFactory.newInstance().createGrammars(xsdAbsPath));

exiFactory.getEncodingOptions().setOption(EncodingOptions.INCLUDE_COOKIE, true);
exiFactory.setCodingMode(CodingMode.COMPRESSION);

It failed as follows

com.siemens.ct.exi.core.exceptions.EXIException: XML Schema document (file:/mnt/c/Users/user1/my-project/tmp-install/myapp-0.1/lib/myapp-0.1.jar!/xsd/my-root.xsd) not found.

Basically, the XSD cannot be found in the uber/fat JAR.  Looking at the JAR contents I saw the expected /xsd/my-root.xsd entry.  Realized that I can't access the schema as a file as its not really a file but a resource bundled in the jar.

Tweaked my EXI factory setup as follows

exiFactory = DefaultEXIFactory.newInstance();

var xsdInputStream = ClassLoader.getSystemResourceAsStream(SCHEMA_PATH);

// Seeing exceptions as XSDs referenced from top-level XSD can't be located within JAR
exiFactory.setGrammars(GrammarFactory.newInstance().createGrammars(xsdInputStream));

exiFactory.getEncodingOptions().setOption(EncodingOptions.INCLUDE_COOKIE, true);
exiFactory.setCodingMode(CodingMode.COMPRESSION);

Got a bit further but ran into problems locating the XSDs referenced from my top-level XSD.  E.g. entries such as the following in the top-level XSD s

<xs:import namespace="http://someURL/someVersion/" schemaLocation="../other/common.xsd"/>

led to errors like the following when creating the grammar

com.siemens.ct.exi.core.exceptions.EXIException: Problem occured while building XML Schema Model (XSModel)!
. [xs-warning] schema_reference.4: Failed to read schema document '../other/common.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.


问:
Compose: Infinite animation with variable speed
I have this code to get an infinite rotation animation:

```<code>@Composable
fun RotatingObject(rpm: Int) {
    val infiniteTransition = rememberInfiniteTransition()
    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 1000,
                easing = LinearEasing
            )
        )
    )

    Surface(
        Modifier
            .size(100.dp)
            .graphicsLayer { rotationZ = rotation},
        color = Color.Gray
    ) {}
}
</code>```

I want the rpm parameter to define the number of revolutions per minute the object should make while spinning. I have tried setting durationMillis to 60000 / rpm but the speed stays the same after rpm changes.

How can I get the speed to change after the initial composition?

Requirements

The rotation angle should not jump or jitter - it should always continually change based on the current rpm.

The solution should be friendly to animated rpm values to allow for smoothly changing speed over time.

I would prefer a solution that doesn't cause avoidable recompositions.

Edit:

After trying countless different things, each of which had something wrong with it, I'm going to share the least wrong outcome.

```<code>@Composable
fun RotatingObject(rpm: Int) {
    var rotation by remember { mutableStateOf(0f) }
    val infiniteTransition = rememberInfiniteTransition()
    val ticker by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 1000,
                easing = LinearEasing
            )
        )
    )

    LaunchedEffect(ticker) {
        rotation += 0.1f * rpm
    }

    Surface(
        Modifier
            .size(100.dp)
            .graphicsLayer { rotationZ = rotation},
        color = Color.Gray
    ) {}
}
</code>```

I track the rotation value as state and manually change it inside a LaunchedEffect. The relaunching of the effect is controlled by the infinite transition. This makes the rotation update at the expected frame rate. 0.1f * rpm is the conversion of rpm to 'degrees per frame' at 60Hz.

So, this behaves as I want it to, however, in order to get here I made an assumption that I feel is not safe to make. This code requires that the effect is relaunched at a constant frequency of 60Hz. Since I didn't see this defined anywhere, this might just be the case on my system.

Also, if I do more operations inside the effect, it sometimes decides not to update the rotation at all, meaning that this is not a reliable way to do this. Therefore I feel that this is not a correct solution and I'm afraid it may not behave the same on different systems or at different times even. I currently have no choice but to use this, so if you have any ideas or suggestions, please share.

Body:
I have this code to get an infinite rotation animation:

@Composable
fun RotatingObject(rpm: Int) {
    val infiniteTransition = rememberInfiniteTransition()
    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 1000,
                easing = LinearEasing
            )
        )
    )

    Surface(
        Modifier
            .size(100.dp)
            .graphicsLayer { rotationZ = rotation},
        color = Color.Gray
    ) {}
}

I want the rpm parameter to define the number of revolutions per minute the object should make while spinning. I have tried setting durationMillis to 60000 / rpm but the speed stays the same after rpm changes.

How can I get the speed to change after the initial composition?

Requirements

The rotation angle should not jump or jitter - it should always continually change based on the current rpm.

The solution should be friendly to animated rpm values to allow for smoothly changing speed over time.

I would prefer a solution that doesn't cause avoidable recompositions.

Edit:

After trying countless different things, each of which had something wrong with it, I'm going to share the least wrong outcome.

@Composable
fun RotatingObject(rpm: Int) {
    var rotation by remember { mutableStateOf(0f) }
    val infiniteTransition = rememberInfiniteTransition()
    val ticker by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 1000,
                easing = LinearEasing
            )
        )
    )

    LaunchedEffect(ticker) {
        rotation += 0.1f * rpm
    }

    Surface(
        Modifier
            .size(100.dp)
            .graphicsLayer { rotationZ = rotation},
        color = Color.Gray
    ) {}
}

I track the rotation value as state and manually change it inside a LaunchedEffect. The relaunching of the effect is controlled by the infinite transition. This makes the rotation update at the expected frame rate. 0.1f * rpm is the conversion of rpm to 'degrees per frame' at 60Hz.

So, this behaves as I want it to, however, in order to get here I made an assumption that I feel is not safe to make. This code requires that the effect is relaunched at a constant frequency of 60Hz. Since I didn't see this defined anywhere, this might just be the case on my system.

Also, if I do more operations inside the effect, it sometimes decides not to update the rotation at all, meaning that this is not a reliable way to do this. Therefore I feel that this is not a correct solution and I'm afraid it may not behave the same on different systems or at different times even. I currently have no choice but to use this, so if you have any ideas or suggestions, please share.


问:
Share routes and other files between two or more Aurelia projects
I want my website and mobile application (runs in a WebView) share the same code. Both website and mobile application use <router-view></router-view>. I want my website to use different index.ejs, app.html, app.js and layout.html than mobile application, but use the same routes and other files? Is it possible to configure two Aurelia projects to sit in the same folder and use different files?

Or using two folders with symlinks is the only option?


问:
How to send AT commands to ESP32 LilyGo-T-Call-SIM800?
I've been working with a LilyGo-TCall-SIM800 module for several days, trying to get out of a dead end.

I have tried an example from "random nerd tutorials" which works correctly. The module connects to the internet and can send data to the cloud.

I have the problem to send AT commands to the SIM800L chip integrated in the module. I can't get the chip to react back.

I have tried using Serial1 and Serial2. I have also tried configuring the RX and TX transmission pins, and I have tried with different baudrates. Always with negative results... when sending the "AT\r" command to the SIM800L, it should return "OK". But it never does.

I have simplified the code as much as possible to minimize errors:

```<code>/*
 Name:      TestAT.ino
 Created:   08/12/2022 23:15:28
 Author:    user
*/

// Set serial for debug console (to the Serial Monitor, speed 115200)
#define SerialMon Serial

// Comunications between ESP32 and SIM800L
#define SerialAT Serial1

//Comunications between ESP32 ans SIM800L go thought TX and RX pins on Serial1 Port
#define MODEM_RX1 16
#define MODEM_TX1 17

void setup() {
    // Set console baud rate
    SerialMon.begin(115200);
    delay(1000);

    //Set SerialAT baud rate
    SerialAT.begin(38400, SERIAL_8N1, MODEM_RX1, MODEM_TX1);

    //Set timeLimit for SerialAT reads
    SerialAT.setTimeout(2000);

}

void loop() {
     String  returned = "";
     char ATcommand[] = { 'A','T','\r' };

    SerialAT.print(ATcommand);
    delay(1000);
    returned = SerialAT.readString();

    SerialMon.print(millis());
    SerialMon.print(" - ");
    SerialMon.print(ATcommand);
    SerialMon.print(" - SerialAT returned:");
    SerialMon.println(returned);

}
</code>```

Anybody can help me out on this? Any idea or sugestion?

Thanks in advance

```<code></code>```

Body:
I've been working with a LilyGo-TCall-SIM800 module for several days, trying to get out of a dead end.

I have tried an example from "random nerd tutorials" which works correctly. The module connects to the internet and can send data to the cloud.

I have the problem to send AT commands to the SIM800L chip integrated in the module. I can't get the chip to react back.

I have tried using Serial1 and Serial2. I have also tried configuring the RX and TX transmission pins, and I have tried with different baudrates. Always with negative results... when sending the "AT\r" command to the SIM800L, it should return "OK". But it never does.

I have simplified the code as much as possible to minimize errors:

/*
 Name:      TestAT.ino
 Created:   08/12/2022 23:15:28
 Author:    user
*/

// Set serial for debug console (to the Serial Monitor, speed 115200)
#define SerialMon Serial

// Comunications between ESP32 and SIM800L
#define SerialAT Serial1

//Comunications between ESP32 ans SIM800L go thought TX and RX pins on Serial1 Port
#define MODEM_RX1 16
#define MODEM_TX1 17

void setup() {
    // Set console baud rate
    SerialMon.begin(115200);
    delay(1000);

    //Set SerialAT baud rate
    SerialAT.begin(38400, SERIAL_8N1, MODEM_RX1, MODEM_TX1);

    //Set timeLimit for SerialAT reads
    SerialAT.setTimeout(2000);

}

void loop() {
     String  returned = "";
     char ATcommand[] = { 'A','T','\r' };

    SerialAT.print(ATcommand);
    delay(1000);
    returned = SerialAT.readString();

    SerialMon.print(millis());
    SerialMon.print(" - ");
    SerialMon.print(ATcommand);
    SerialMon.print(" - SerialAT returned:");
    SerialMon.println(returned);

}

Anybody can help me out on this? Any idea or sugestion?

Thanks in advance


问:
Running a command on all files in PowerShell command prompt
I know there are several questions and answers about this - I tried them all - none of them worked for me.

How do I do the equivalent of this (which works in cmd) in a PowerShell command?

```<code>for %f in (*.mp4) do "C:\Program Files\DVR-Scan\dvr-scan.exe" -i %f -d events/ -tc
</code>```

I tried this:

```<code>Get-ChildItem -File | Foreach {"C:\Program Files\DVR-Scan\dvr-scan.exe" -i $_.fullname -d events/ -tc }
</code>```

And like this:

```<code>Get-ChildItem -File | Foreach {"C:\Program Files\DVR-Scan\dvr-scan.exe -i $_.fullname -d events/ -tc "}
</code>```

And like this:

```<code>ls -file | & { "C:\Program Files\DVR-Scan\dvr-scan.exe -i $_.fullname -d events/ -tc " }
</code>```

So what's the right way to do it?

EDIT: This question is not a duplicate of this one. In the other question they are asking about the equivalent of a Bash command. I am asking about the equivalent of a cmd command. Even if the answers are the same, it is not the same question.

Body:
I know there are several questions and answers about this - I tried them all - none of them worked for me.

How do I do the equivalent of this (which works in cmd) in a PowerShell command?

for %f in (*.mp4) do "C:\Program Files\DVR-Scan\dvr-scan.exe" -i %f -d events/ -tc

I tried this:

Get-ChildItem -File | Foreach {"C:\Program Files\DVR-Scan\dvr-scan.exe" -i $_.fullname -d events/ -tc }

And like this:

Get-ChildItem -File | Foreach {"C:\Program Files\DVR-Scan\dvr-scan.exe -i $_.fullname -d events/ -tc "}

And like this:

ls -file | & { "C:\Program Files\DVR-Scan\dvr-scan.exe -i $_.fullname -d events/ -tc " }

So what's the right way to do it?

EDIT: This question is not a duplicate of this one. In the other question they are asking about the equivalent of a Bash command. I am asking about the equivalent of a cmd command. Even if the answers are the same, it is not the same question.


问:
'ForkAwareLocal' object has no attribute 'connection' in manager.list() append
I'm downloading files from a bucket and passing them to an in-memory object.
(it is not possible to save as a file in a folder).

And for that I'm using multiprocessing.

I need it to take the object, transform it into a dataframe and append it to a list or dictionary, whatever.

The problem is that I can't get a return from the function using multipreprocessing, so I did it with manager.list().

But, I can't do an append, for some reason.

In this code, object blobs is just a <google.api_core.page_iterator.HTTPIterator>

That I extract from another def, I iterate on that blob to get the link to each of the files in the bucket.

```<code>  def download_bucket(dataframe,blob):
        file_path = blob.name
        print(f"downloading {file_path}")
        parquet_bytes = blob.download_as_bytes() # Download
        parquet_bytes = io.BytesIO(parquet_bytes)t
        df = pd.read_parquet(parquet_bytes)
        dataframe.append(df)
        blob.delete()

    if __name__ == '__main__':
        with Manager() as manager:
            dataframe = manager.list()
            print("Esta funcionando")
            processes = [Process(target=download_bucket, args=(dataframe,blob)) for blob in blobs]
            for process in processes:
                process.start()
            for process in processes:
                process.join()
            df = []
            for li in dataframe:
                df.append(li)
            df = pd.concat(df)
</code>```

When the bucket has few files, it works, but when it has more than 3000 files it returns the following error.

```<code> File "/usr/local/lib/python3.8/multiprocessing/managers.py", line 827, in _callmethod
        conn = self._tls.connection
      File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
        self.run()
      File "/usr/local/lib/python3.8/multiprocessing/managers.py", line 827, in _callmethod
        conn = self._tls.connection
      File "/usr/local/lib/python3.8/multiprocessing/managers.py", line 827, in _callmethod
        conn = self._tls.connection
    AttributeError: 'ForkAwareLocal' object has no attribute 'connection'

</code>```

I searched in several places about it, but I didn't find anything that could help me.

Body:
I'm downloading files from a bucket and passing them to an in-memory object.
(it is not possible to save as a file in a folder).

And for that I'm using multiprocessing.

I need it to take the object, transform it into a dataframe and append it to a list or dictionary, whatever.

The problem is that I can't get a return from the function using multipreprocessing, so I did it with manager.list().

But, I can't do an append, for some reason.

In this code, object blobs is just a <google.api_core.page_iterator.HTTPIterator>

That I extract from another def, I iterate on that blob to get the link to each of the files in the bucket.

  def download_bucket(dataframe,blob):
        file_path = blob.name
        print(f"downloading {file_path}")
        parquet_bytes = blob.download_as_bytes() # Download
        parquet_bytes = io.BytesIO(parquet_bytes)t
        df = pd.read_parquet(parquet_bytes)
        dataframe.append(df)
        blob.delete()

    if __name__ == '__main__':
        with Manager() as manager:
            dataframe = manager.list()
            print("Esta funcionando")
            processes = [Process(target=download_bucket, args=(dataframe,blob)) for blob in blobs]
            for process in processes:
                process.start()
            for process in processes:
                process.join()
            df = []
            for li in dataframe:
                df.append(li)
            df = pd.concat(df)

When the bucket has few files, it works, but when it has more than 3000 files it returns the following error.

 File "/usr/local/lib/python3.8/multiprocessing/managers.py", line 827, in _callmethod
        conn = self._tls.connection
      File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
        self.run()
      File "/usr/local/lib/python3.8/multiprocessing/managers.py", line 827, in _callmethod
        conn = self._tls.connection
      File "/usr/local/lib/python3.8/multiprocessing/managers.py", line 827, in _callmethod
        conn = self._tls.connection
    AttributeError: 'ForkAwareLocal' object has no attribute 'connection'

I searched in several places about it, but I didn't find anything that could help me.


问:
How do I know which routes are handled by a controller in Ruby on Rails?
I am trying to write a script/program that given a controller file name, can programmatically determine which routes are served by this controller. This should work for inheritance use cases as well. For example:

```<code>class UserController < UserBaseController

end
</code>```
```<code>class UserBaseController
  def update
    # changes made here
  end
end
</code>```

Running the script given the UserBaseController should return something like: PUT users/:id

How can I go about doing this? I tried using rails routes. However, the routes map to the child class and not the parent class which is where the change was actually made.

Thank you!

Body:
I am trying to write a script/program that given a controller file name, can programmatically determine which routes are served by this controller. This should work for inheritance use cases as well. For example:

class UserController < UserBaseController

end

class UserBaseController
  def update
    # changes made here
  end
end

Running the script given the UserBaseController should return something like: PUT users/:id

How can I go about doing this? I tried using rails routes. However, the routes map to the child class and not the parent class which is where the change was actually made.

Thank you!


问:
Redirecting read requests traffic to AWS Aurora RDS read replica
My project is using hibernate. I have created a read replica using the AWS console for Aurora RDS to balance the load. When I make read requests I don't see the requests going to my read replica.

Does Aurora RDS handles the read requests by it's own? or I need to implement this in my application to redirect the read requests traffic to the read replica.

I checked multiple articles and I didn't find any information on built in functionality to redirect read requests.

Article 1: This article suggests to use Spring cloud dependency and annotate the transactions with readOnly=true

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-aws-jdbc</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
</code>```
```<code>@Transactional(readOnly = true)
</code>```

Article 2: This article suggests to use the Route 53 and use the weighted class

I will have only one writer instance and one read replica. Need some help on choosing which method is a better option.

If there is a built in functionality in Aurora RDS how do I use.

Is there any other alternative apart from the above two?

Body:
My project is using hibernate. I have created a read replica using the AWS console for Aurora RDS to balance the load. When I make read requests I don't see the requests going to my read replica.

Does Aurora RDS handles the read requests by it's own? or I need to implement this in my application to redirect the read requests traffic to the read replica.

I checked multiple articles and I didn't find any information on built in functionality to redirect read requests.

Article 1: This article suggests to use Spring cloud dependency and annotate the transactions with readOnly=true

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-aws-jdbc</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

@Transactional(readOnly = true)

Article 2: This article suggests to use the Route 53 and use the weighted class

I will have only one writer instance and one read replica. Need some help on choosing which method is a better option.

If there is a built in functionality in Aurora RDS how do I use.

Is there any other alternative apart from the above two?


问:
My pyglet Batches don't have an add() attribute
Almost every example I can find of adding a vertex list to Batches in pyglet involves invoking the Batch's add() method, but for some reason Batches I create don't have any such method. I am able to add shapes to batches via pyglet.shapes objects, but I want to be able to do it the other way instead.

Here's an example of something I've tried. The problem occurs at the end of this snippet, where I try to use add() right after creating a new Batch.

```<code>import pyglet
from pyglet.window import key

class Player:
    def __init__(self, pos, color):
        self.pos = pos
        self.color = color
        self.speed = 5

    def move(self, direction):
        if direction[0] == 0 and direction[1] == 0: return;
        self.pos = addV(self.pos, scaleV(direction, self.speed / magnitude(direction)))

class Block:
    def __init__(self, x, y, w, h, nomask = False):
        self.nomask = nomask
        self.w, self.h = w, h
        self.l, self.r, self.b, self.t = x, x+w, y, y+h

class MainWindow(pyglet.window.Window):
    def __init__(self):
        super().__init__()

        pyglet.clock.schedule_interval(self.update, 1/60.0)

        self.player = Player((10, 10), (255, 0, 0))
        self.blocks = [Block(50, 50, 100, 50)]

        self.blockBatch = pyglet.graphics.Batch()

        for b in self.blocks:
            self.blockBatch.add(4, pyglet.gl.GL_POLYGON, None, ("v2i", (b.l,b.b,b.l,b.t,b.r,b.t,b.r,b.b)), ("c3B", (0,0,255)*4))
</code>```

Any ideas as to why this might be happening? Is it a version issue?

Here's the error output:

```<code>Traceback (most recent call last):
  File "C:\Users\(me)\OneDrive\Desktop\Coding\Python\CTF\scripts\masktest.py", line 85, in <module>
    window = MainWindow()
             ^^^^^^^^^^^^
  File "C:\Users\(me)\OneDrive\Desktop\Coding\Python\CTF\scripts\masktest.py", line 52, in __init__
    self.blockBatch.add(4, pyglet.gl.GL_POLYGON, None, ("v2i", (b.l,b.b,b.l,b.t,b.r,b.t,b.r,b.b)), ("c3B", (0,0,255)*4))
    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'Batch' object has no attribute 'add'
</code>```

Body:
Almost every example I can find of adding a vertex list to Batches in pyglet involves invoking the Batch's add() method, but for some reason Batches I create don't have any such method. I am able to add shapes to batches via pyglet.shapes objects, but I want to be able to do it the other way instead.

Here's an example of something I've tried. The problem occurs at the end of this snippet, where I try to use add() right after creating a new Batch.

import pyglet
from pyglet.window import key

class Player:
    def __init__(self, pos, color):
        self.pos = pos
        self.color = color
        self.speed = 5

    def move(self, direction):
        if direction[0] == 0 and direction[1] == 0: return;
        self.pos = addV(self.pos, scaleV(direction, self.speed / magnitude(direction)))

class Block:
    def __init__(self, x, y, w, h, nomask = False):
        self.nomask = nomask
        self.w, self.h = w, h
        self.l, self.r, self.b, self.t = x, x+w, y, y+h

class MainWindow(pyglet.window.Window):
    def __init__(self):
        super().__init__()

        pyglet.clock.schedule_interval(self.update, 1/60.0)

        self.player = Player((10, 10), (255, 0, 0))
        self.blocks = [Block(50, 50, 100, 50)]

        self.blockBatch = pyglet.graphics.Batch()

        for b in self.blocks:
            self.blockBatch.add(4, pyglet.gl.GL_POLYGON, None, ("v2i", (b.l,b.b,b.l,b.t,b.r,b.t,b.r,b.b)), ("c3B", (0,0,255)*4))

Any ideas as to why this might be happening? Is it a version issue?

Here's the error output:

Traceback (most recent call last):
  File "C:\Users\(me)\OneDrive\Desktop\Coding\Python\CTF\scripts\masktest.py", line 85, in <module>
    window = MainWindow()
             ^^^^^^^^^^^^
  File "C:\Users\(me)\OneDrive\Desktop\Coding\Python\CTF\scripts\masktest.py", line 52, in __init__
    self.blockBatch.add(4, pyglet.gl.GL_POLYGON, None, ("v2i", (b.l,b.b,b.l,b.t,b.r,b.t,b.r,b.b)), ("c3B", (0,0,255)*4))
    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'Batch' object has no attribute 'add'