问:
Authentication with basic type api
After a good amount of time, I found the solution through an authentication plugin that is easy to install via composer with the command:

```<code>composer require "cakephp/authentication:^2.0"
</code>```

After that, just generate the crud via terminal and check them to send json type data. It can be done as follows:

```<code>$this->response
    ->withType('application/json')
    ->withStatus(200)
    ->withStringBody(json_encode($dataOrMessage));
</code>```

Add the function in entity to encrypt the password that the user registers:

```<code>protected function _setPassword(string $password) : ?string {
    if (strlen($password) > 0) {
        return (new DefaultPasswordHasher())->hash($password);
    }
}
</code>```

Implementing the AuthenticationServiceProviderInterface interface in the Application class and adding its requirements, in addition to the login and logout functions of the aforementioned plugin, you can view here

The login function will look something like this:

```<code>public function login() {
    if ($this->request->is('post')) {
        $result = $this->Authentication->getResult();

        if ($result && $result->isValid()) {
            return $this->response
                ->withType('application/json')
                ->withStatus(200)
                ->withStringBody(json_encode($result->getData()));
        } else {
            return $this->response
                ->withType('application/json')
                ->withStatus(401)
                ->withStringBody(json_encode(['message' => 'User or password incorrect!']));
        }
    }
}
</code>```

There is not only this solution, but it was the one I found and that I found to be easier to implement.

Title: Authentication with basic type api

Body:
After a good amount of time, I found the solution through an authentication plugin that is easy to install via composer with the command:

composer require "cakephp/authentication:^2.0"

After that, just generate the crud via terminal and check them to send json type data. It can be done as follows:

$this->response
    ->withType('application/json')
    ->withStatus(200)
    ->withStringBody(json_encode($dataOrMessage));

Add the function in entity to encrypt the password that the user registers:

protected function _setPassword(string $password) : ?string {
    if (strlen($password) > 0) {
        return (new DefaultPasswordHasher())->hash($password);
    }
}

Implementing the AuthenticationServiceProviderInterface interface in the Application class and adding its requirements, in addition to the login and logout functions of the aforementioned plugin, you can view here

The login function will look something like this:

public function login() {
    if ($this->request->is('post')) {
        $result = $this->Authentication->getResult();

        if ($result && $result->isValid()) {
            return $this->response
                ->withType('application/json')
                ->withStatus(200)
                ->withStringBody(json_encode($result->getData()));
        } else {
            return $this->response
                ->withType('application/json')
                ->withStatus(401)
                ->withStringBody(json_encode(['message' => 'User or password incorrect!']));
        }
    }
}

There is not only this solution, but it was the one I found and that I found to be easier to implement.


来源: stackexchange

问:
Using Google Wire with variadic function
I have a function that accepts variadic arguments, I normally uses it as the following

```<code>registry := repository.NewRepositoryRegistry(
    db,
    &repository.UserRepository{},
    // ...
)
</code>```

Now, I want to use it with Google Wire

```<code>func initializeRepository(cfg *config.Config) (*repository.RepositoryRegistry, error) {
    wire.Build(
        repository.RepositoryRegistry
    )

    return nil, nil
}
</code>```

But I receive the error

```<code>go run github.com/google/wire/cmd/wire ./internal/wire
cannot find package "." in:
        /opt/workspace/project/vendor/github.com/google/wire/cmd/wire
</code>```

What can be?

ContentLicense: CC BY-SA 4.0

Body:
I have a function that accepts variadic arguments, I normally uses it as the following

registry := repository.NewRepositoryRegistry(
    db,
    &repository.UserRepository{},
    // ...
)

Now, I want to use it with Google Wire

func initializeRepository(cfg *config.Config) (*repository.RepositoryRegistry, error) {
    wire.Build(
        repository.RepositoryRegistry
    )

    return nil, nil
}

But I receive the error

go run github.com/google/wire/cmd/wire ./internal/wire
cannot find package "." in:
        /opt/workspace/project/vendor/github.com/google/wire/cmd/wire

What can be?


问:
how to change color of one word in a sentence of .ini file?
I'm currently editing my custom date file which https://prnt.sc/TnWaC7alRjh2 you can see here. And I want to highlight the date itself away from other text, is it possible? How do I do that?

I have no idea what to do cause I'm completely green in stuff like this, but I guess I have to change something in this line?
FontColor=#Color255#=

Thank you.


问:
Is there any way to differentiate between null and undefined in GraphQL?
I find it really annoying that String can mean undefined, and null as well.

It's especially difficult when mapping through an object.

```<code>type Filters {
  id: String
  name: String
}
</code>```

can be

```<code>{ id: 'id', name: null }
</code>```
```<code>{ id: null, name: null }
</code>```
```<code>{ name: null }
</code>```
```<code>{ id: 'id' }
</code>```

etc.

I'm looking for a way which defines an input as either the user defines it in the specified type, or not at all.

Is it possible in a not too dirty way?

Body:
I find it really annoying that String can mean undefined, and null as well.

It's especially difficult when mapping through an object.

type Filters {
  id: String
  name: String
}

can be

{ id: 'id', name: null }

{ id: null, name: null }

{ name: null }

{ id: 'id' }

etc.

I'm looking for a way which defines an input as either the user defines it in the specified type, or not at all.

Is it possible in a not too dirty way?


问:
How to correctly generate a pair of SSH keys in java, that is compatible with OpenSSL
I'm trying to dynamically generate a pair of SSH keys in java, mimicking the behaviour of ssh-keygen. I intend to use those keys to communicate with an SSH server.

I have tried patching up and testing several pieces of code without success. The most recent piece of code I'm testing is this:

import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator;
import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil;
import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.SecureRandom;
import java.security.Security;

public class GenKeysTest {

    @Test
    void testCase1() throws IOException {
        Security.addProvider(new BouncyCastleProvider());

        AsymmetricCipherKeyPairGenerator gen = new Ed25519KeyPairGenerator();
        gen.init(new KeyGenerationParameters(new SecureRandom(), 255));
        AsymmetricCipherKeyPair keyPair = gen.generateKeyPair();

        byte[] priBytes = OpenSSHPrivateKeyUtil.encodePrivateKey(keyPair.getPrivate());
        write(priBytes, "ed25519", "OPENSSH PRIVATE KEY");

        byte[] pubBytes = OpenSSHPublicKeyUtil.encodePublicKey(keyPair.getPublic());
        write(pubBytes, "ed25519.pub", "OPENSSH PUBLIC KEY");
    }

    public void write(byte[] bytes, String fileName, String type) throws IOException {
        try (FileOutputStream out = new FileOutputStream(fileName)) {
            try (PemWriter w = new PemWriter(new OutputStreamWriter(out))) {
                w.writeObject(new PemObject(type, bytes));
            }
        }
    }
}
```
<p>I'm using the following dependencies:</p>
```dependencies {
    implementation 'org.bouncycastle:bcprov-jdk15on:1.67'
    implementation 'org.bouncycastle:bcpkix-jdk15on:1.67'

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
```

And I'm using these command to test the resulting keys:

ssh-keygen -l -f ed25519

ssh-keygen -l -f ed25519.pub

As far as I read, those commands should output the same text line which should look like this:

256 SHA256:REDACTED user@domain.com (ED25519)

Instead the output I get from ssh-keygen is similar to this:

ed25519.pub is not a public key file.

It would be very nice if someone could point me what am I missing.

Body:
I'm trying to dynamically generate a pair of SSH keys in java, mimicking the behaviour of ssh-keygen. I intend to use those keys to communicate with an SSH server.

I have tried patching up and testing several pieces of code without success. The most recent piece of code I'm testing is this:

import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator;
import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil;
import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.SecureRandom;
import java.security.Security;

public class GenKeysTest {

    @Test
    void testCase1() throws IOException {
        Security.addProvider(new BouncyCastleProvider());

        AsymmetricCipherKeyPairGenerator gen = new Ed25519KeyPairGenerator();
        gen.init(new KeyGenerationParameters(new SecureRandom(), 255));
        AsymmetricCipherKeyPair keyPair = gen.generateKeyPair();

        byte[] priBytes = OpenSSHPrivateKeyUtil.encodePrivateKey(keyPair.getPrivate());
        write(priBytes, "ed25519", "OPENSSH PRIVATE KEY");

        byte[] pubBytes = OpenSSHPublicKeyUtil.encodePublicKey(keyPair.getPublic());
        write(pubBytes, "ed25519.pub", "OPENSSH PUBLIC KEY");
    }

    public void write(byte[] bytes, String fileName, String type) throws IOException {
        try (FileOutputStream out = new FileOutputStream(fileName)) {
            try (PemWriter w = new PemWriter(new OutputStreamWriter(out))) {
                w.writeObject(new PemObject(type, bytes));
            }
        }
    }
}

I'm using the following dependencies:

dependencies {
    implementation 'org.bouncycastle:bcprov-jdk15on:1.67'
    implementation 'org.bouncycastle:bcpkix-jdk15on:1.67'

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

And I'm using these command to test the resulting keys:

ssh-keygen -l -f ed25519

ssh-keygen -l -f ed25519.pub

As far as I read, those commands should output the same text line which should look like this:

256 SHA256:REDACTED user@domain.com (ED25519)

Instead the output I get from ssh-keygen is similar to this:

ed25519.pub is not a public key file.

It would be very nice if someone could point me what am I missing.


问:
How to use connect-flash with passport-local
hello every one i was trying to use connect-flash with passport local but can not seem to find relevant info either on the docs and other sources,if any one can guide me on this and tell me what i went wrong ,thanks.And why does request to login-fail gives this error:-
ERROR is AxiosError: Request failed with status code 404
but when i test the route with rest client on vscode it responses perfectly like seen
here.
also when i check the database right after i click submit on the route
there will be two sessions stored consecutively one having the flash(the first) and the other not like this:-

```<code>session:
{"cookie":{"originalMaxAge":259200000,"expires":"2023-01-16T12:30:14.395Z","secure":false,"httpOnly":true,"path":"/"},"flash":{"error":["Incorrect password"]}}

session:
{"cookie":{"originalMaxAge":259200000,"expires":"2023-01-16T12:30:14.453Z","secure":false,"httpOnly":true,"path":"/"}}

</code>```

why this is happening?
userRoutes.js

```<code>const router = require("express").Router();
const passport = require("passport");
const { ObjectID } = require("mongodb");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcrypt");
const flash = require("connect-flash");

const User = require("../models/userModel.js");

router.route("/register").post(
  (req, res, next) => {
    User.findOne({ fullName: req.body.fullName }, (err, user) => {
      if (err) {
        next(err);
      } else if (user) {
        res.redirect("/");
      } else {
        const {
          fullName,
          email,
          id,
          department,
          stream,
          batch,
          sex,
          age,
          phoneNumber,
          password,
        } = req.body;
        const hash = bcrypt.hashSync(password, 12);
        console.log(hash);
        const newUser = new User({
          fullName,
          email,
          id,
          department,
          stream,
          batch,
          sex,
          age,
          phoneNumber,
          password: hash,
        });
        newUser.save((err, data) => {
          if (err) res.redirect("/");
          next(null, data);
        });
      }
    });
  },
  passport.authenticate("local", { failureRedirect: "/" }),
  (req, res, next) => {
    res.json({ user: "i am josh" });
  }
);

router
  .route("/login")
  .post(
    passport.authenticate("local", {
      failureRedirect: "/login-fail",
      failureFlash: true,
    }),
    (req, res) => {
      res.json({ user: "i am josh" });
    }
  );

router.route("/login-fail").get((req, res) => {
  // console.log(req.flash('error'));
  res.json({ user: "josh" });
});

router.route("/logout").get((req, res) => {
  req.logout();
  res.redirect("/");
});

passport.serializeUser((user, done) => {
  done(null, user._id);
});

passport.deserializeUser((id, done) => {
  User.findOne({ _id: new ObjectID(id) }, (err, doc) => {
    done(null, doc);
  });
});

const customFields = {
  usernameField: "email",
};

passport.use(
  new LocalStrategy(customFields, (email, password, done) => {
    User.findOne({ email }, (err, user) => {
      //console.log(`User ${user.username} attempted to log in.`);
      if (err) return done(err);
      if (!user) return done(null, false, { message: "email does not exist" });
      if (!bcrypt.compareSync(password, user.password)) {
        return done(null, false, { message: "Incorrect password" });
      }
      return done(null, user);
    });
  })
);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.json({ msg: "You are not authorized to view this page" });
}

module.exports = router;

</code>```

server.js

```<code>require("dotenv").config();
const express = require("express");
const app = express();
const flash = require("connect-flash");
const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo");
const cors = require("cors");

app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cors());

app.use(flash());
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    store: MongoStore.create({
      mongoUrl: process.env.DB,
      collection: "sessions",
    }),
    cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 3 },
  })
);

app.use(passport.initialize());
app.use(passport.session());

mongoose
  .connect(process.env.DB)
  .then(() => {
    console.log("DB connection successful");
  })
  .catch((err) => {
    console.log(`DB connection Error: ${err}`);
  });

const usersRouter = require("./routes/userRoutes");

app.use("/user", usersRouter);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`server is running on port ${PORT}`);
});

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

ya,have seen the same question here on stack over flow but none of the answers work

Body:
hello every one i was trying to use connect-flash with passport local but can not seem to find relevant info either on the docs and other sources,if any one can guide me on this and tell me what i went wrong ,thanks.And why does request to login-fail gives this error:-
ERROR is AxiosError: Request failed with status code 404
but when i test the route with rest client on vscode it responses perfectly like seen
here.
also when i check the database right after i click submit on the route
there will be two sessions stored consecutively one having the flash(the first) and the other not like this:-

session:
{"cookie":{"originalMaxAge":259200000,"expires":"2023-01-16T12:30:14.395Z","secure":false,"httpOnly":true,"path":"/"},"flash":{"error":["Incorrect password"]}}

session:
{"cookie":{"originalMaxAge":259200000,"expires":"2023-01-16T12:30:14.453Z","secure":false,"httpOnly":true,"path":"/"}}

why this is happening?
userRoutes.js

const router = require("express").Router();
const passport = require("passport");
const { ObjectID } = require("mongodb");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcrypt");
const flash = require("connect-flash");

const User = require("../models/userModel.js");

router.route("/register").post(
  (req, res, next) => {
    User.findOne({ fullName: req.body.fullName }, (err, user) => {
      if (err) {
        next(err);
      } else if (user) {
        res.redirect("/");
      } else {
        const {
          fullName,
          email,
          id,
          department,
          stream,
          batch,
          sex,
          age,
          phoneNumber,
          password,
        } = req.body;
        const hash = bcrypt.hashSync(password, 12);
        console.log(hash);
        const newUser = new User({
          fullName,
          email,
          id,
          department,
          stream,
          batch,
          sex,
          age,
          phoneNumber,
          password: hash,
        });
        newUser.save((err, data) => {
          if (err) res.redirect("/");
          next(null, data);
        });
      }
    });
  },
  passport.authenticate("local", { failureRedirect: "/" }),
  (req, res, next) => {
    res.json({ user: "i am josh" });
  }
);

router
  .route("/login")
  .post(
    passport.authenticate("local", {
      failureRedirect: "/login-fail",
      failureFlash: true,
    }),
    (req, res) => {
      res.json({ user: "i am josh" });
    }
  );

router.route("/login-fail").get((req, res) => {
  // console.log(req.flash('error'));
  res.json({ user: "josh" });
});

router.route("/logout").get((req, res) => {
  req.logout();
  res.redirect("/");
});

passport.serializeUser((user, done) => {
  done(null, user._id);
});

passport.deserializeUser((id, done) => {
  User.findOne({ _id: new ObjectID(id) }, (err, doc) => {
    done(null, doc);
  });
});

const customFields = {
  usernameField: "email",
};

passport.use(
  new LocalStrategy(customFields, (email, password, done) => {
    User.findOne({ email }, (err, user) => {
      //console.log(`User ${user.username} attempted to log in.`);
      if (err) return done(err);
      if (!user) return done(null, false, { message: "email does not exist" });
      if (!bcrypt.compareSync(password, user.password)) {
        return done(null, false, { message: "Incorrect password" });
      }
      return done(null, user);
    });
  })
);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.json({ msg: "You are not authorized to view this page" });
}

module.exports = router;

server.js

require("dotenv").config();
const express = require("express");
const app = express();
const flash = require("connect-flash");
const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo");
const cors = require("cors");

app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cors());

app.use(flash());
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    store: MongoStore.create({
      mongoUrl: process.env.DB,
      collection: "sessions",
    }),
    cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 3 },
  })
);

app.use(passport.initialize());
app.use(passport.session());

mongoose
  .connect(process.env.DB)
  .then(() => {
    console.log("DB connection successful");
  })
  .catch((err) => {
    console.log(`DB connection Error: ${err}`);
  });

const usersRouter = require("./routes/userRoutes");

app.use("/user", usersRouter);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`server is running on port ${PORT}`);
});

module.exports = app;

ya,have seen the same question here on stack over flow but none of the answers work


问:
How can I use Partytown in Helmet?
When I try to use partytown inside my project, I cannot debug it and ~partytown/debug/partytown-sw.js'): A bad HTTP response code (404) was received when fetching the script. I'm getting an error can you help me please?

I use as

<Partytown debug={true} forward={['dataLayer.push']} /> <Helmet>

Title: How can I use Partytown in Helmet?


问:
How to Connect Salesforce Marketing Cloud to Microsoft Teams
I am trying to connect Salesforce Marketing Cloud to Microsoft Teams.

Has anyone successfully done this or can provide guidance on how to accomplish this task? I have checked the following article: https://www.linkedin.com/pulse/enabling-salesforce-marketing-cloud-connect-microsoft-somu-kommineni/ but am looking for any other resources or tips.

Any help is appreciated.


问:
Conditional class switch or Media Queries - Performance / Style better?
need help with the discussion since I didn't find the fast answer on that topic through a basic Google search.

I have a project, where I myself did pretty bad CSS architecture, having each website page owning its own stylesheet. It was due to reasons of the MVP and speed, so back then I knew I was doing bad thing, but it was faster than planning everything.

Right now I am refactoring my code, components, and stylesheets. I'm using more general classes and managed almost to clear a few pretty big spreadsheets. Which is good in my opinion.

However, I am in a situation, where for example I need to apply different widths, depending on mobile factor or desktop. And that's basically it.

I have classes like width-100, width-80 - which takes 100 or 80% of free spaces. Have also few for VW just in case.

On desktop I need width-80, on mobile width-100. Create specific class with those specific values for desktop and mobile I don't want (maybe I should). So I use conditional rendering of the classes.

```<code>!isMobile ? "width-100" : "width-80"
</code>```

plus any other classes if needed.

However, I am starting to think which thing is better - conditional class or creating some class with specific values and media queries for mobile?

React doesn't re-render to my knowledge the DOM tree, since V-DOM hasn't changed. Or am I wrong?

What do you think?

Body:
need help with the discussion since I didn't find the fast answer on that topic through a basic Google search.

I have a project, where I myself did pretty bad CSS architecture, having each website page owning its own stylesheet. It was due to reasons of the MVP and speed, so back then I knew I was doing bad thing, but it was faster than planning everything.

Right now I am refactoring my code, components, and stylesheets. I'm using more general classes and managed almost to clear a few pretty big spreadsheets. Which is good in my opinion.

However, I am in a situation, where for example I need to apply different widths, depending on mobile factor or desktop. And that's basically it.

I have classes like width-100, width-80 - which takes 100 or 80% of free spaces. Have also few for VW just in case.

On desktop I need width-80, on mobile width-100. Create specific class with those specific values for desktop and mobile I don't want (maybe I should). So I use conditional rendering of the classes.

!isMobile ? "width-100" : "width-80"

plus any other classes if needed.

However, I am starting to think which thing is better - conditional class or creating some class with specific values and media queries for mobile?

React doesn't re-render to my knowledge the DOM tree, since V-DOM hasn't changed. Or am I wrong?

What do you think?


问:
Error when trying to import react-chartjs-2
I am currently developing a software with Electron and for the graphic part, I wish to be able to display curves in real time with React and react-chartjs-2 except that when I imported the library for the curves, I had the following error :

```<code>ERROR in ./node_modules/chart.js/dist/chart.cjs 569:17
Module parse failed: Unexpected token (569:17)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     };
| class DatasetController {
>  static defaults = {};
|  static datasetElementType = null;
|  static dataElementType = null;
 @ ./node_modules/react-chartjs-2/dist/index.js 2:0-185 85:31-38 162:4-11 168:54-68 169:52-65 170:56-71 171:62-80 172:64-83 173:58-74 174:52-65 175:60-77
 @ ./src/js/App.js
 @ ./src/js/index.js
</code>```

Here is the code (webpack) :

Webpack.common.js :

```<code>const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/js/index.js',
  devtool: 'inline-source-map',
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [[
              '@babel/preset-env', {
                targets: {
                  esmodules: true
                }
              }],
              '@babel/preset-react']
          }
        }
      },
      {
        test: [/\.s[ac]ss$/i, /\.css$/i],
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      }
    ]
  },
  resolve: {
    extensions: ['.js'],
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'build', 'js'),
  },
};

</code>```

I tried to install cjs loader with these command npm i -D cjs-loader:

But i had a new error:

```<code>ERROR in ./node_modules/chart.js/dist/chart.cjs
Module build failed (from ./node_modules/cjs-loader/cjs-loader.js):
C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\cjs-loader\cjs-loader.js:23
import * as utils from './utils.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at new Script (node:vm:99:7)
    at NativeCompileCache._moduleCompile (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\v8-compile-cache\v8-compile-cache.js:242:18)
    at Module._compile (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\v8-compile-cache\v8-compile-cache.js:186:36)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Function.Module._load (node:internal/modules/cjs/loader:828:14)
    at Module.require (node:internal/modules/cjs/loader:1012:19)
    at require (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\v8-compile-cache\v8-compile-cache.js:161:20)
    at loadLoader (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\loader-runner\lib\loadLoader.js:18:17)
    at iteratePitchingLoaders (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\loader-runner\lib\LoaderRunner.js:169:2)
    at runLoaders (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\loader-runner\lib\LoaderRunner.js:365:2)
    at NormalModule.doBuild (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModule.js:295:3)
    at NormalModule.build (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModule.js:446:15)
    at Compilation.buildModule (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\Compilation.js:739:10)
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\Compilation.js:981:14
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:409:6
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:155:13
    at AsyncSeriesWaterfallHook.eval [as callAsync] (eval at create (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:138:29
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:346:9
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
 @ ./node_modules/react-chartjs-2/dist/index.js 2:0-185 85:31-38 162:4-11 168:54-68 169:52-65 170:56-71 171:62-80 172:64-83 173:58-74 174:52-65 175:60-77
 @ ./src/js/App.js
 @ ./src/js/index.js
</code>```

Body:
I am currently developing a software with Electron and for the graphic part, I wish to be able to display curves in real time with React and react-chartjs-2 except that when I imported the library for the curves, I had the following error :

ERROR in ./node_modules/chart.js/dist/chart.cjs 569:17
Module parse failed: Unexpected token (569:17)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     };
| class DatasetController {
>  static defaults = {};
|  static datasetElementType = null;
|  static dataElementType = null;
 @ ./node_modules/react-chartjs-2/dist/index.js 2:0-185 85:31-38 162:4-11 168:54-68 169:52-65 170:56-71 171:62-80 172:64-83 173:58-74 174:52-65 175:60-77
 @ ./src/js/App.js
 @ ./src/js/index.js

Here is the code (webpack) :

Webpack.common.js :

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/js/index.js',
  devtool: 'inline-source-map',
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [[
              '@babel/preset-env', {
                targets: {
                  esmodules: true
                }
              }],
              '@babel/preset-react']
          }
        }
      },
      {
        test: [/\.s[ac]ss$/i, /\.css$/i],
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      }
    ]
  },
  resolve: {
    extensions: ['.js'],
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'build', 'js'),
  },
};

I tried to install cjs loader with these command npm i -D cjs-loader:

But i had a new error:

ERROR in ./node_modules/chart.js/dist/chart.cjs
Module build failed (from ./node_modules/cjs-loader/cjs-loader.js):
C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\cjs-loader\cjs-loader.js:23
import * as utils from './utils.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at new Script (node:vm:99:7)
    at NativeCompileCache._moduleCompile (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\v8-compile-cache\v8-compile-cache.js:242:18)
    at Module._compile (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\v8-compile-cache\v8-compile-cache.js:186:36)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Function.Module._load (node:internal/modules/cjs/loader:828:14)
    at Module.require (node:internal/modules/cjs/loader:1012:19)
    at require (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\v8-compile-cache\v8-compile-cache.js:161:20)
    at loadLoader (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\loader-runner\lib\loadLoader.js:18:17)
    at iteratePitchingLoaders (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\loader-runner\lib\LoaderRunner.js:169:2)
    at runLoaders (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\loader-runner\lib\LoaderRunner.js:365:2)
    at NormalModule.doBuild (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModule.js:295:3)
    at NormalModule.build (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModule.js:446:15)
    at Compilation.buildModule (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\Compilation.js:739:10)
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\Compilation.js:981:14
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:409:6
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:155:13
    at AsyncSeriesWaterfallHook.eval [as callAsync] (eval at create (C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:138:29
    at C:\Users\cantr\Desktop\Stage ingenieur komiflo\Sail Vision\Electron-React\node_modules\webpack\lib\NormalModuleFactory.js:346:9
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
 @ ./node_modules/react-chartjs-2/dist/index.js 2:0-185 85:31-38 162:4-11 168:54-68 169:52-65 170:56-71 171:62-80 172:64-83 173:58-74 174:52-65 175:60-77
 @ ./src/js/App.js
 @ ./src/js/index.js


问:
Borrow-checker behavior in if - else blocks
Thanks to @jmb for pointing out that this is a known compiler limitation that has to do with lexical lifetimes. There is likely no easy way to solve the issue currently.

I ended up working around it by refactoring my code not to use the returned reference from self._read_to_buffer(), but to access the internal buffer directly.

if &self.buffer != "err" {
    Ok(&self.buffer)
} else {
    // The next line contains the explanation of the error, so read it
    let e = self._read_to_buffer();
    Err(format!("Unable to read line because of error: {e}"))
}
```
<p>This was not a particularly nice solution for my actual problem as it involved exposing private variables through multiple layers of abstraction. A better solution may be possible though e.g. [https://crates.io/crates/polonius-the-crab], but I have not yet been able to get one to work. I am also not sure that I'm comfortable with bringing that crate into production.</p>
<hr />
<p>Consider an input that contains either valid lines, or the message "err" followed by and explanation of the error, e.g:</p>
```"foo
err
explanation
bar
baz"
```
<p>You want to return the line if it was valid, or an error with the included explanation otherwise.</p>
<pre class="lang-rust prettyprint-override"><code>use std::io::{BufRead, Cursor};

fn main() {
    let mut s = ValidLineReader {
        input: Cursor::new("foo\nerr\nexplanation\nbar\nbaz"),
        buffer: String::new(),
    };

    dbg!(s.next_line());
    dbg!(s.next_line());
    dbg!(s.next_line());
    dbg!(s.next_line());
}

struct ValidLineReader {
    input: Cursor<&'static str>,
    buffer: String,
}

impl ValidLineReader {
    pub fn next_line(&mut self) -> Result<&str, String> {
        let next = self._read_to_buffer();
        if next != "err" {
            Ok(next)
        } else {
            // The next line contains the explanation of the error, so read it
            let e = self._read_to_buffer();
            Err(format!("Unable to read line because of error: {e}"))
        }
    }

    fn _read_to_buffer(&mut self) -> &str {
        self.input.read_line(&mut self.buffer).unwrap();
        &self.buffer
    }
}
</code>```

This will fail with the following error message:

```<code>  --> src/main.rs:27:21
   |
21 |     pub fn next_line(&mut self) -> Result<&str, String> {
   |                      - let's call the lifetime of this reference `'1`
22 |         let next = self._read_to_buffer();
   |                    ---------------------- first mutable borrow occurs here
23 |         if next != "err" {
24 |             Ok(next)
   |             -------- returning this value requires that `*self` is borrowed for `'1`
...
27 |             let e = self._read_to_buffer();
   |                     ^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
</code>```

I understand that doing something like

let e = self._read_to_buffer();
println!("Unable to read line because of error: {e}");
Ok(next)
```

would be a reference error, since a call to self._read_to_buffer() mutates the buffer that next is pointing to. But we do not use next in the else branch, so why does the compiler seem to think that it is still borrowed?

Body:
Thanks to @jmb for pointing out that this is a known compiler limitation that has to do with lexical lifetimes. There is likely no easy way to solve the issue currently.

I ended up working around it by refactoring my code not to use the returned reference from self._read_to_buffer(), but to access the internal buffer directly.

if &self.buffer != "err" {
    Ok(&self.buffer)
} else {
    // The next line contains the explanation of the error, so read it
    let e = self._read_to_buffer();
    Err(format!("Unable to read line because of error: {e}"))
}

This was not a particularly nice solution for my actual problem as it involved exposing private variables through multiple layers of abstraction. A better solution may be possible though e.g. [https://crates.io/crates/polonius-the-crab], but I have not yet been able to get one to work. I am also not sure that I'm comfortable with bringing that crate into production.

Consider an input that contains either valid lines, or the message "err" followed by and explanation of the error, e.g:

"foo
err
explanation
bar
baz"

You want to return the line if it was valid, or an error with the included explanation otherwise.

use std::io::{BufRead, Cursor};

fn main() {
    let mut s = ValidLineReader {
        input: Cursor::new("foo\nerr\nexplanation\nbar\nbaz"),
        buffer: String::new(),
    };

    dbg!(s.next_line());
    dbg!(s.next_line());
    dbg!(s.next_line());
    dbg!(s.next_line());
}

struct ValidLineReader {
    input: Cursor<&'static str>,
    buffer: String,
}

impl ValidLineReader {
    pub fn next_line(&mut self) -> Result<&str, String> {
        let next = self._read_to_buffer();
        if next != "err" {
            Ok(next)
        } else {
            // The next line contains the explanation of the error, so read it
            let e = self._read_to_buffer();
            Err(format!("Unable to read line because of error: {e}"))
        }
    }

    fn _read_to_buffer(&mut self) -> &str {
        self.input.read_line(&mut self.buffer).unwrap();
        &self.buffer
    }
}

This will fail with the following error message:

  --> src/main.rs:27:21
   |
21 |     pub fn next_line(&mut self) -> Result<&str, String> {
   |                      - let's call the lifetime of this reference `'1`
22 |         let next = self._read_to_buffer();
   |                    ---------------------- first mutable borrow occurs here
23 |         if next != "err" {
24 |             Ok(next)
   |             -------- returning this value requires that `*self` is borrowed for `'1`
...
27 |             let e = self._read_to_buffer();
   |                     ^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here

I understand that doing something like

let e = self._read_to_buffer();
println!("Unable to read line because of error: {e}");
Ok(next)

would be a reference error, since a call to self._read_to_buffer() mutates the buffer that next is pointing to. But we do not use next in the else branch, so why does the compiler seem to think that it is still borrowed?


问:
How to show a black screen when an Android app goes in background
For security reasons I want to show a black (in dark mode) and white full screen (in light mode) when the app goes in the background.

The standard approach should probably be to use FLAG_SECURE but this will not cover the entire screen (e.g., if the status bar is of a different color you will see it) and the background color is not customizable.

After I also compared the solution created by common banks and finance apps like N26, Revolut, Unstoppable Domain, etc. I came to the conclusion that they are using something different. They are able to render a full black/white screen without content.

Which approach are these companies using?

I also tried to show a black view on top (listening to the onPause on the main activity) and removing it onResume and although the black view is added the screen shown in the recent apps is still the previous one.

I tried react-native and vanilla android apps.


问:
mod_rewrite: adding a rule causes it to break (error 500)
I have the following mod_rewrite rules:

```<code>RewriteRule ^stats/$ stats/index.php
RewriteRule ^adm/$ adm/index.php
RewriteRule ^iphone/$ iphone/index.php
RewriteRule ^android/$ android/index.php
RewriteRule ^([^/\.]+)/?$ index.php?page=$1
RewriteRule ^([^/\.]+)/([0-9]+)/$ index.php?page=$1&pn=$2
RewriteRule ^categories/([^/\.]+)/([0-9]+)/$ index.php?cat_name=$1&pn=$2
RewriteRule ^([^/\.]+)/([^/\.]+)/$ index.php?app_name=$2
RewriteRule ^([^/\.]+)/([a-zA-Z]+)-([^/\.]+)/$ index.php?app_name=$2-$3
RewriteRule ^news/([^/\.]+).(html|htm)$ index.php?news_url=$1
</code>```

However, when I add the following line:

```<code>RewriteRule ^faq/([^/\.]+)/?$ index.php?page=$1 [L]
</code>```

it breaks, I assumed it's because a conflict between rule 5, so I added it before that, but still - no go... can anyone shed some light on how to incorporate this rule in my htaccess?

Edit:
When looking at the error logs (took a while, cause had to set up a subdomain to not hurt the main site):

```<code>[Thu Sep 22 01:04:06 2011] [alert] [client 212.199.198.140] /home/my71/*/.htaccess: RewriteRule: bad flag delimiters
</code>```

Edit 2: don't have access to my htpdconfig, but the htaccess:

```<code>#WWW TO NON WWW

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{REQUEST_URI} [A-Z]
RewriteMap  lc int:tolower

RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteRule (.*) ${lc:$1} [R=301,L]

#URL REWRITES

RewriteRule ^stats/$ stats/index.php
RewriteRule ^adm/$ adm/index.php
RewriteRule ^iphone/$ iphone/index.php
RewriteRule ^android/$ android/index.php
RewriteRule ^([^/\.]+)/+$ index.php?page=$1
RewriteRule ^([^/\.]+)/([0-9]+)/$ index.php?page=$1&pn=$2
RewriteRule ^categories/([^/\.]+)/([0-9]+)/$ index.php?cat_name=$1&pn=$2
RewriteRule ^(?!.*faq)([^\/.]+)\/([^\/.]+)\/$ index.php?app_name=$2
RewriteRule ^news/([^/\.]+).(html)$ index.php?news_url=$1
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Or, compress certain file types by extension:
<Files *.html>
SetOutputFilter DEFLATE
</Files>
</code>```

Thanks, Itai

ContentLicense: CC BY-SA 3.0

Body:
I have the following mod_rewrite rules:

RewriteRule ^stats/$ stats/index.php
RewriteRule ^adm/$ adm/index.php
RewriteRule ^iphone/$ iphone/index.php
RewriteRule ^android/$ android/index.php
RewriteRule ^([^/\.]+)/?$ index.php?page=$1
RewriteRule ^([^/\.]+)/([0-9]+)/$ index.php?page=$1&pn=$2
RewriteRule ^categories/([^/\.]+)/([0-9]+)/$ index.php?cat_name=$1&pn=$2
RewriteRule ^([^/\.]+)/([^/\.]+)/$ index.php?app_name=$2
RewriteRule ^([^/\.]+)/([a-zA-Z]+)-([^/\.]+)/$ index.php?app_name=$2-$3
RewriteRule ^news/([^/\.]+).(html|htm)$ index.php?news_url=$1

However, when I add the following line:

RewriteRule ^faq/([^/\.]+)/?$ index.php?page=$1 [L]

it breaks, I assumed it's because a conflict between rule 5, so I added it before that, but still - no go... can anyone shed some light on how to incorporate this rule in my htaccess?

Edit:
When looking at the error logs (took a while, cause had to set up a subdomain to not hurt the main site):

[Thu Sep 22 01:04:06 2011] [alert] [client 212.199.198.140] /home/my71/*/.htaccess: RewriteRule: bad flag delimiters

Edit 2: don't have access to my htpdconfig, but the htaccess:

#WWW TO NON WWW

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{REQUEST_URI} [A-Z]
RewriteMap  lc int:tolower

RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteRule (.*) ${lc:$1} [R=301,L]

#URL REWRITES

RewriteRule ^stats/$ stats/index.php
RewriteRule ^adm/$ adm/index.php
RewriteRule ^iphone/$ iphone/index.php
RewriteRule ^android/$ android/index.php
RewriteRule ^([^/\.]+)/+$ index.php?page=$1
RewriteRule ^([^/\.]+)/([0-9]+)/$ index.php?page=$1&pn=$2
RewriteRule ^categories/([^/\.]+)/([0-9]+)/$ index.php?cat_name=$1&pn=$2
RewriteRule ^(?!.*faq)([^\/.]+)\/([^\/.]+)\/$ index.php?app_name=$2
RewriteRule ^news/([^/\.]+).(html)$ index.php?news_url=$1
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Or, compress certain file types by extension:
<Files *.html>
SetOutputFilter DEFLATE
</Files>

Thanks, Itai


问:
Vue JS not Composition API
I am connected to my database using the fetch API/LocalHost, I have two components: 1 first contains the request for the data and also has the template (main), and the other contains cards (widget) of values, what I wanted is to put in the widget the api I do in the main. I can do this by using the props in widget and the import with the v-bind in the html element, but the value does not render, only when I make a change in the widget code that the value appears.
Another observation, is that in the main I have filters that I use in the body, which filters also

```<code>// PRINCIPAL
<script>
import Widget from "./widget.vue";
export default {
   page: {
        title: "pagee",
        meta: [{ name: "description", content: appConfig.description }],
      },
      components: {
        Layout,
        PageHeader,
        Vue3ChartJs,
        flatPickr,
        SimpleBar, Widget
},
setup() {
const ValorVendaTotal = ref(0)
const Level1 = async (starDate,endDate,p_items) => {
      const url = `http://localhost:1800/dash/0/${starDate}/${endDate}`
      const respons = await fetch(url,{
          method: 'POST',
          body: JSON.stringify({
              items: p_items,
            }),
              headers: {
                  'Content-type': 'application/json; charset=UTF-8'
              },
        });
        const _venda = dataJs.map(v => v.venda)
        let Total = 0
        _venda.map(v => Total += parseFloat(v))
        ValorVendaTotal.value = Total
  }
</code>```
```<code><template>
      <Widget :ValorVendaTotal = "ValorVendaTotal" />
<template/>
</code>```
```<code>//WIDGET
<script>
export default {
  props: {
    ValorVendaTotal: {
      type: Number
    }
  },
  setup(props) {
   console.log(props)
    return {
      crmWidgets:
        {
          id: 1,
          label: "Campaign Sent",
          badge: "ri-arrow-up-circle-line text-success",
          icon: "ri-space-ship-line",
          counter: props.ValorVendaTotal,
          decimals: 0,
          suffix: "",
          prefix: "",
        },
      }
    }
  </script>
<template>
<div class="card crm-widget">
    <div class="card-body p-0">
      <div class="row row-cols-xxl-5 row-cols-md-3 row-cols-1 g-0">
        <div class="col" v-for="(item, index) of crmWidgets" :key="index">
          <div class="py-4 px-3">
            <h5 class="text-muted text-uppercase fs-13">
              {{ item.label }}
              <i :class="`${item.badge} fs-18 float-end align-middle`"></i>
            </h5>
            <div class="d-flex align-items-center">
              <div class="flex-shrink-0">
                <i :class="`${item.icon} display-6 text-muted`"></i>
              </div>
              <div class="flex-grow-1 ms-3">
                <h2 class="mb-0">
                  {{item.prefix}}
                <span> {{ item.counter }} </span>
                  {{item.suffix}}
                </h2>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
</code>```

what happens is that the value is not reactive in the main, causing it to only update when I move some line of code into widget (probably by rendering)

Title: Vue JS not Composition API

Body:
I am connected to my database using the fetch API/LocalHost, I have two components: 1 first contains the request for the data and also has the template (main), and the other contains cards (widget) of values, what I wanted is to put in the widget the api I do in the main. I can do this by using the props in widget and the import with the v-bind in the html element, but the value does not render, only when I make a change in the widget code that the value appears.
Another observation, is that in the main I have filters that I use in the body, which filters also

// PRINCIPAL

<template>

              {{ item.label }}
              <i :class="`${item.badge} fs-18 float-end align-middle`">

                <i :class="`${item.icon} display-6 text-muted`">

                  {{item.prefix}}
                 {{ item.counter }}
                  {{item.suffix}}

</template>

what happens is that the value is not reactive in the main, causing it to only update when I move some line of code into widget (probably by rendering)


问:
How long is the pip extra index url valid from the Azure Pipeline PipAuthenticate task
I'm trying to find out for how long the credentials added to the PIP_EXTRA_INDEX_URL environment variable are valid when generated by the ADO Pipeline Task PipAuthenticate@1.

I'm using them to build a Docker image which I in turn use as a base image for other docker build pipelines, and sometimes the pip install command in those fails because the credentials are invalid.

I regenerate the base image every midnight, thinking that the credentials would last at least 24 hours, but perhaps they get invalidated when a certain number of PipAuthenticate@1 tasks have run in other pipelines?

I cannot find any documentation around this anywhere, so hoping to find an expert here.


问:
Cypress error : Cannot set properties of undefined (setting '_testConfig')
I recently upgraded my cypress from 9X version to 10X version and installed cypress-grep plugin and wants to run Test specs based on the Tags I passed in the spec files.
After I upgrade, the cypress-grep works fine, but, getting error while running a specific spec and shows like

Cannot set properties of undefined (setting '_testConfig')

what needs to be done for this?


问:
Folium Layer Control costumizing opportunities with css html code
Folium library let us to costumize legend at html map, now I want to costumize it like qgis legend,

I tried to costumize it but managed only write this code:

lgd_txt = '{txt}'

group0 = folium.FeatureGroup(name = lgd_txt.format(txt = name_of_layer,col = style))
for i in range(len(temp_df)):
            folium.CircleMarker(
                                (
                                temp_df.iloc[i]['latitude_'],
                                temp_df.iloc[i]['longitude_']
                                ),
                                color = style,
                                radius=2,popup = f'{temp_df.iloc[i]}'
                                ).add_to(group0)

map.add_child(group0)

```

I want to add for example circle with name of the layer and the color of added circle I like to be the layer color, the way it is in qgis. Please if you have something like this already done just give me code example!

Body:
Folium library let us to costumize legend at html map, now I want to costumize it like qgis legend,

I tried to costumize it but managed only write this code:

lgd_txt = '{txt}'

group0 = folium.FeatureGroup(name = lgd_txt.format(txt = name_of_layer,col = style))
for i in range(len(temp_df)):
            folium.CircleMarker(
                                (
                                temp_df.iloc[i]['latitude_'],
                                temp_df.iloc[i]['longitude_']
                                ),
                                color = style,
                                radius=2,popup = f'{temp_df.iloc[i]}'
                                ).add_to(group0)

map.add_child(group0)

I want to add for example circle with name of the layer and the color of added circle I like to be the layer color, the way it is in qgis. Please if you have something like this already done just give me code example!


问:
Payload CMS use Magic Login Strategy from passport.js
I want to be able to log into Payload admin panel using magic login.
The problem is that the payload docs aren't very specific about how to implement Passport strategies. Also the public demo of payload doesn't mention passport anywhere.

https://payloadcms.com/docs/authentication/config#strategies

https://github.com/payloadcms/public-demo

I created a new payload app using npx create-payload-app and chosing the blog template. Then I npm installed the packages passport and passport-magic-login and edited the Users.ts file so that payload uses the MagicLoginStrategy to authenticate. This is the state where i am stuck at the moment because trying to run the project throws a bunch of errors apparently relating to webpack and polyfills.

Users.ts

```<code>import { CollectionConfig } from "payload/types";

import MagicLoginStrategy from "passport-magic-login";

const sendEmail = (a, b, c, d) => {
  console.log("sendEmail");
  console.log(a, b, c, d);
};

const verify = (a, b) => {
  console.log("verify");
  console.log(a, b);
};

const Users: CollectionConfig = {
  slug: "users",
  auth: {
    tokenExpiration: 7200,
    maxLoginAttempts: 5,
    lockTime: 600 * 1000,
    strategies: [
      {
        strategy: new MagicLoginStrategy({
          secret: "my-secret",
          callbackUrl: `api/auth/magiclink/callback`,
          sendMagicLink: async (destination, href, _, req) => {
            await sendEmail(destination, href, _, req);
          },
          verify: async (payload, callback) => {
            verify(payload, callback);
          },
        }),
      },
    ],
  },
  admin: {
    useAsTitle: "email",
  },
  access: {
    read: () => true,
  },
  fields: [
    // Email added by default
    {
      name: "name",
      type: "text",
    },
  ],
};

export default Users;
</code>```

Error Log

```<code>ERROR in ./node_modules/jwa/index.js 5:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jwa'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

ERROR in ./node_modules/jws/lib/data-stream.js 3:13-30
Module not found: Error: Can't resolve 'stream' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/jws/lib/data-stream.js 4:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

ERROR in ./node_modules/jws/lib/sign-stream.js 5:13-30
Module not found: Error: Can't resolve 'stream' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/jws/lib/sign-stream.js 7:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

ERROR in ./node_modules/jws/lib/verify-stream.js 5:13-30
Module not found: Error: Can't resolve 'stream' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/jws/lib/verify-stream.js 7:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

webpack compiled with 7 errors
</code>```

Body:
I want to be able to log into Payload admin panel using magic login.
The problem is that the payload docs aren't very specific about how to implement Passport strategies. Also the public demo of payload doesn't mention passport anywhere.

https://payloadcms.com/docs/authentication/config#strategies

https://github.com/payloadcms/public-demo

I created a new payload app using npx create-payload-app and chosing the blog template. Then I npm installed the packages passport and passport-magic-login and edited the Users.ts file so that payload uses the MagicLoginStrategy to authenticate. This is the state where i am stuck at the moment because trying to run the project throws a bunch of errors apparently relating to webpack and polyfills.

Users.ts

import { CollectionConfig } from "payload/types";

import MagicLoginStrategy from "passport-magic-login";

const sendEmail = (a, b, c, d) => {
  console.log("sendEmail");
  console.log(a, b, c, d);
};

const verify = (a, b) => {
  console.log("verify");
  console.log(a, b);
};

const Users: CollectionConfig = {
  slug: "users",
  auth: {
    tokenExpiration: 7200,
    maxLoginAttempts: 5,
    lockTime: 600 * 1000,
    strategies: [
      {
        strategy: new MagicLoginStrategy({
          secret: "my-secret",
          callbackUrl: `api/auth/magiclink/callback`,
          sendMagicLink: async (destination, href, _, req) => {
            await sendEmail(destination, href, _, req);
          },
          verify: async (payload, callback) => {
            verify(payload, callback);
          },
        }),
      },
    ],
  },
  admin: {
    useAsTitle: "email",
  },
  access: {
    read: () => true,
  },
  fields: [
    // Email added by default
    {
      name: "name",
      type: "text",
    },
  ],
};

export default Users;

Error Log

ERROR in ./node_modules/jwa/index.js 5:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jwa'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

ERROR in ./node_modules/jws/lib/data-stream.js 3:13-30
Module not found: Error: Can't resolve 'stream' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/jws/lib/data-stream.js 4:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

ERROR in ./node_modules/jws/lib/sign-stream.js 5:13-30
Module not found: Error: Can't resolve 'stream' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/jws/lib/sign-stream.js 7:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

ERROR in ./node_modules/jws/lib/verify-stream.js 5:13-30
Module not found: Error: Can't resolve 'stream' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/jws/lib/verify-stream.js 7:11-26
Module not found: Error: Can't resolve 'util' in '/Users/mathias/Documents/coding/payload-passport-test2/node_modules/jws/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

webpack compiled with 7 errors


问:
I have a JSON formatted output as below, how to access and valid the outputs of each node with Assert statement
I have a JSON formatted output as below, how to access and valid the outputs of each node with Assert statement

```<code>{
  "Type": "Page",
  "X": 0,
  "Y": 0,
  "Width": 696,
  "Height": 888,
  "Children": [
    {
      "Type": "Column",
      "X": 0,
      "Y": 0,
      "Width": 696,
      "Height": 888,
      "Children": [
        {
          "Type": "Paragraph",
          "X": 209,
          "Y": 290,
          "Width": 248,
          "Height": 24,
          "Children": [
            {
              "Type": "Line",
              "X": 209,
              "Y": 290,
              "Width": 248,
              "Height": 24,
              "Children": [
                {
                  "Type": "Word",
                  "X": 209,
                  "Y": 290,
                  "Width": 49,
                  "Height": 24,
                  "Children": [

                  ],
                  "Content": "Core"
                },
                {
                  "Type": "Word",
                  "X": 263,
                  "Y": 290,
                  "Width": 106,
                  "Height": 24,
                  "Children": [

                  ],
                  "Content": "Enterprise"
                },
                {
                  "Type": "Word",
                  "X": 375,
                  "Y": 290,
                  "Width": 82,
                  "Height": 24,
                  "Children": [

                  ],
                  "Content": "Installer"
                }
              ],
              "Content": null
            }
          ],
          "Content": null
        },
        {
          "Type": "Paragraph",
          "X": 580,
          "Y": 803,
          "Width": 79,
          "Height": 13,
          "Children": [
            {
              "Type": "Line",
              "X": 580,
              "Y": 803,
              "Width": 79,
              "Height": 13,
              "Children": [
                {
                  "Type": "Word",
                  "X": 580,
                  "Y": 803,
                  "Width": 46,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "Version"
                },
                {
                  "Type": "Word",
                  "X": 629,
                  "Y": 803,
                  "Width": 12,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "8."
                },
                {
                  "Type": "Word",
                  "X": 640,
                  "Y": 803,
                  "Width": 12,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "0."
                },
                {
                  "Type": "Word",
                  "X": 651,
                  "Y": 803,
                  "Width": 8,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "0"
                }
              ],
              "Content": null
            }
          ],
          "Content": null
        }
      ],
      "Content": null
    }
  ],
  "Content": null
}
</code>```

Looking for solutions

Body:
I have a JSON formatted output as below, how to access and valid the outputs of each node with Assert statement

{
  "Type": "Page",
  "X": 0,
  "Y": 0,
  "Width": 696,
  "Height": 888,
  "Children": [
    {
      "Type": "Column",
      "X": 0,
      "Y": 0,
      "Width": 696,
      "Height": 888,
      "Children": [
        {
          "Type": "Paragraph",
          "X": 209,
          "Y": 290,
          "Width": 248,
          "Height": 24,
          "Children": [
            {
              "Type": "Line",
              "X": 209,
              "Y": 290,
              "Width": 248,
              "Height": 24,
              "Children": [
                {
                  "Type": "Word",
                  "X": 209,
                  "Y": 290,
                  "Width": 49,
                  "Height": 24,
                  "Children": [

                  ],
                  "Content": "Core"
                },
                {
                  "Type": "Word",
                  "X": 263,
                  "Y": 290,
                  "Width": 106,
                  "Height": 24,
                  "Children": [

                  ],
                  "Content": "Enterprise"
                },
                {
                  "Type": "Word",
                  "X": 375,
                  "Y": 290,
                  "Width": 82,
                  "Height": 24,
                  "Children": [

                  ],
                  "Content": "Installer"
                }
              ],
              "Content": null
            }
          ],
          "Content": null
        },
        {
          "Type": "Paragraph",
          "X": 580,
          "Y": 803,
          "Width": 79,
          "Height": 13,
          "Children": [
            {
              "Type": "Line",
              "X": 580,
              "Y": 803,
              "Width": 79,
              "Height": 13,
              "Children": [
                {
                  "Type": "Word",
                  "X": 580,
                  "Y": 803,
                  "Width": 46,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "Version"
                },
                {
                  "Type": "Word",
                  "X": 629,
                  "Y": 803,
                  "Width": 12,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "8."
                },
                {
                  "Type": "Word",
                  "X": 640,
                  "Y": 803,
                  "Width": 12,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "0."
                },
                {
                  "Type": "Word",
                  "X": 651,
                  "Y": 803,
                  "Width": 8,
                  "Height": 13,
                  "Children": [

                  ],
                  "Content": "0"
                }
              ],
              "Content": null
            }
          ],
          "Content": null
        }
      ],
      "Content": null
    }
  ],
  "Content": null
}

Looking for solutions


问:
fetched data is not rendered by react
My super-simple application fails to fetch and display data.
help me to solve the problem , please, I'm stuck.

my api seems to be basically working, but it fails somewhere on the way to client.

hope, the code snippets I attach will be enough.

thanx!

app.js (mongoDB connection string is hidden):

```<code>var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require("cors");

var app = express();
app.set('veiw engine', 'ejs')
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const { MongoClient } = require("mongodb");
const uri = "...intentionally hidden...";
const client = new MongoClient(uri);
const database = client.db('holdocsDB');
const records = database.collection('records');

app.get('/users', async (req, res) => {
    // try {
        const cursor = await records.find();
        const results = await cursor.toArray();
        const objectStringified = results.map(record => JSON.stringify(record));
        const recordsNoId = [];
        for ( recordString of objectStringified ) {
          record = JSON.parse(recordString);
          let recordValuesArr = Object.values(record);
          let recordNoId = recordValuesArr.slice(1);
          recordsNoId.push(recordNoId);}
        }
      )

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
  });

  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.json('error');
  });

module.exports = app;

</code>```

SingleRecord.js

```<code>const SingleRecord = (firstName, age) => {
    return (
      <li className="singe-record">
        {firstName} is {age} years old.
      </li>
    );
  }

  export default SingleRecord;
</code>```

Display.js:

```<code>import React from 'react';
import { useState, useEffect } from 'react';
import './display.css';
import SingleRecord from './SingleRecord';

function Display() {
  const [records, setRecords] = useState();
  const fetchRecords = () => {
    let data;
    fetch('http://localhost:3001/users')
        .then(async response => {
            const isJson = response.headers.get('content-type')?.includes('application/json');
            const data = isJson ? await response.json() : null;

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
            }
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
    return data;
  }

    useEffect(() => {
        let dataFetched = fetchRecords();
    // eslint-disable-next-line react-hooks/exhaustive-deps
        setRecords(dataFetched);
    }, []);

    console.log("records after fetching data:" + records);

    if (!records) {
        return null;
    }

    return (
        <div className="records-display">
          <h2>Records:</h2>
          <ul className ="records-list">
            {records && records.map(record => (
              <SingleRecord firstName={record.firstName} age={record.age} />
            ))}
          </ul>
        </div>
    );
}

export default Display;

</code>```

output in chrome console:
(https://i.stack.imgur.com/MrYXk.png)

Title: fetched data is not rendered by react

Body:
My super-simple application fails to fetch and display data.
help me to solve the problem , please, I'm stuck.

my api seems to be basically working, but it fails somewhere on the way to client.

hope, the code snippets I attach will be enough.

thanx!

app.js (mongoDB connection string is hidden):

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require("cors");

var app = express();
app.set('veiw engine', 'ejs')
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const { MongoClient } = require("mongodb");
const uri = "...intentionally hidden...";
const client = new MongoClient(uri);
const database = client.db('holdocsDB');
const records = database.collection('records');

app.get('/users', async (req, res) => {
    // try {
        const cursor = await records.find();
        const results = await cursor.toArray();
        const objectStringified = results.map(record => JSON.stringify(record));
        const recordsNoId = [];
        for ( recordString of objectStringified ) {
          record = JSON.parse(recordString);
          let recordValuesArr = Object.values(record);
          let recordNoId = recordValuesArr.slice(1);
          recordsNoId.push(recordNoId);}
        }
      )

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
  });

  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.json('error');
  });

module.exports = app;

SingleRecord.js

const SingleRecord = (firstName, age) => {
    return (

        {firstName} is {age} years old.

    );
  }

  export default SingleRecord;

Display.js:

import React from 'react';
import { useState, useEffect } from 'react';
import './display.css';
import SingleRecord from './SingleRecord';

function Display() {
  const [records, setRecords] = useState();
  const fetchRecords = () => {
    let data;
    fetch('http://localhost:3001/users')
        .then(async response => {
            const isJson = response.headers.get('content-type')?.includes('application/json');
            const data = isJson ? await response.json() : null;

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
            }
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
    return data;
  }

    useEffect(() => {
        let dataFetched = fetchRecords();
    // eslint-disable-next-line react-hooks/exhaustive-deps
        setRecords(dataFetched);
    }, []);

    console.log("records after fetching data:" + records);

    if (!records) {
        return null;
    }

    return (

Records:

            {records && records.map(record => (
              <SingleRecord firstName={record.firstName} age={record.age} />
            ))}

    );
}

export default Display;

output in chrome console:
(https://i.stack.imgur.com/MrYXk.png)


问:
How to run action while ensuring job runs every time regardless of needs skipped?
I am trying to deploy a pull request to an Azure Web App using GitHub Actions. I have four jobs: pre-build, build, deploy and deploy-update. The pre-build job creates an Azure resource, the build job builds the application, deploys job deploy the application for frist time when pr is opened and the deploy-update job updates the deployed application.

The problem is that when the pull request is updated, the pre-build job is skipped, but the build job still runs. I want the deploy-update job to run only when the build job is successful and the pull request is updated. However, the deploy-update job is getting skipped because the pre-build job is not running.

How can I ensure that the deploy-update job runs only when the build job is successful and the pull request is updated, even if the pre-build job is skipped?

GitHub action :

```<code>jobs:
  pre-build:
    if: (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.action != 'closed'
    runs-on: ubuntu-latest
    name: Pre-Build Checks
    steps:
      # Azure resource creation steps here

  build:
    if: always() && github.event.action != 'closed'
    runs-on: ubuntu-latest
    needs: pre-build
    name: Build Job
    steps:
      # Build steps here

  deploy:
    if: (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.action != 'closed'
    runs-on: ubuntu-latest
    needs: build
    name: Deploy Job
    steps:
      # Deploy steps here

  deploy-update:
    if: (github.event.action == 'synchronize')  && github.event.action != 'closed'
    runs-on: ubuntu-latest
    needs: build
    name: Deploy Update Job
    steps:
      # Deploy-update steps here

</code>```

Any suggestion?

Body:
I am trying to deploy a pull request to an Azure Web App using GitHub Actions. I have four jobs: pre-build, build, deploy and deploy-update. The pre-build job creates an Azure resource, the build job builds the application, deploys job deploy the application for frist time when pr is opened and the deploy-update job updates the deployed application.

The problem is that when the pull request is updated, the pre-build job is skipped, but the build job still runs. I want the deploy-update job to run only when the build job is successful and the pull request is updated. However, the deploy-update job is getting skipped because the pre-build job is not running.

How can I ensure that the deploy-update job runs only when the build job is successful and the pull request is updated, even if the pre-build job is skipped?

GitHub action :

jobs:
  pre-build:
    if: (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.action != 'closed'
    runs-on: ubuntu-latest
    name: Pre-Build Checks
    steps:
      # Azure resource creation steps here

  build:
    if: always() && github.event.action != 'closed'
    runs-on: ubuntu-latest
    needs: pre-build
    name: Build Job
    steps:
      # Build steps here

  deploy:
    if: (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.action != 'closed'
    runs-on: ubuntu-latest
    needs: build
    name: Deploy Job
    steps:
      # Deploy steps here

  deploy-update:
    if: (github.event.action == 'synchronize')  && github.event.action != 'closed'
    runs-on: ubuntu-latest
    needs: build
    name: Deploy Update Job
    steps:
      # Deploy-update steps here

Any suggestion?


问:
Pass ng-content into another component as ng-content
I have got CollapsibleComponent which uses CollapsibleActionsComponent in it. I would like to be able to pass additional action buttons into CollapsibleActionsComponent through CollapsibleComponent as shown in example:

CollapsibleActionsComponent:

```<code><div class="actions">
  <ng-content></ng-content> // this is where I would expect "Additional button" to be projected
  <button>Common button</button>
</div>
</code>```

CollapsibleComponent:

```<code><div class="header">
  ...

  <app-collapsible-actions>
    <ng-content select="[slot=moreCustomActions]"></ng-content>
  </app-collapsible-actions>
</div>

<div class="body">
  <ng-content select="[slot=body]"></ng-content>
</div>
</code>```

AppComponent:

```<code><app-collapsible>
  <div slot="moreCustomActions">
    <button>Additional button</button>
  </div>

  <div slot=body>
    <p>...</p>
  </div>
</app-collapsible>
</code>```

The additional button is not shown. This is probably duplicate of some previous question, but I was not able to find it.

During writing this question I realized that I can get rid of the CollapsibleActionsComponent and move it up into CollapsibleComponent because I am not using it elsewhere. However let's assume I would use it.

Body:
I have got CollapsibleComponent which uses CollapsibleActionsComponent in it. I would like to be able to pass additional action buttons into CollapsibleActionsComponent through CollapsibleComponent as shown in example:

CollapsibleActionsComponent:

  <ng-content></ng-content> // this is where I would expect "Additional button" to be projected
  <button>Common button</button>

CollapsibleComponent:

  ...

  <app-collapsible-actions>
    <ng-content select="[slot=moreCustomActions]"></ng-content>
  </app-collapsible-actions>

  <ng-content select="[slot=body]"></ng-content>

AppComponent:

<app-collapsible>

    <button>Additional button</button>

...

</app-collapsible>

The additional button is not shown. This is probably duplicate of some previous question, but I was not able to find it.

During writing this question I realized that I can get rid of the CollapsibleActionsComponent and move it up into CollapsibleComponent because I am not using it elsewhere. However let's assume I would use it.


问:
Writing to CoreData on LocationManager Update
currently I am playing around with swiftui, CoreData and CoreLocation.
My goal is to store waypoints and calculate their distances to the current Location while moving. These distances should be written to CoreData and shown in the UI.

I am getting location updates in the Location Managers "didUpdateLocations", but what is the smartest way to write to CoreData from here?

I thought, I could just "merge" the DataController and LocationManager into one class, but

1: I can not access CoreData in the DataController itself

2: I can not create an observed object of the LocationManager anymore, since it does not provide a fetchrequest.

I'd really appreciate a slight hint here, since I don't know what to google anymore ;)

My DataController looks like this:

```<code>import CoreData
import Foundation

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "Positions")

    init() {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
            }
        }
    }

}

</code>```

And my LocationManager looks like this:

```<code>import Foundation
import Combine
import CoreLocation

class LocManager: NSObject, ObservableObject, CLLocationManagerDelegate {

    @Published var location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    @Published var altitude: Double = 0
    @Published var degrees: Double = 0

    private let locationManager: CLLocationManager

    override init() {

        //LocationManager INIT
        self.locationManager = CLLocationManager()
        super.init()

        self.locationManager.delegate = self
        self.setup()
    }

    private func setup() {

        // set accuracy
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation

        //update filter
        //self.locationManager.headingFilter = kCLHeadingFilterNone //High Power usage
        self.locationManager.headingFilter = 0.5
        self.locationManager.distanceFilter = 1

        if CLLocationManager.headingAvailable() {
            self.locationManager.startUpdatingLocation()
            self.locationManager.startUpdatingHeading()
        }

    }

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        self.degrees = -1 * newHeading.magneticHeading
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        location = locations.first!.coordinate
        altitude = locations.first!.altitude

        /*
        I cant access CoreData here, can I?
        */

    }

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
            switch locationManager.authorizationStatus {
            case .authorizedWhenInUse:
                locationManager.requestWhenInUseAuthorization()
                break

            case .restricted:
                break

            case .denied:
                break

            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
                break

            default:
                break
            }
        }

}

</code>```

Thanks for your help!

Body:
currently I am playing around with swiftui, CoreData and CoreLocation.
My goal is to store waypoints and calculate their distances to the current Location while moving. These distances should be written to CoreData and shown in the UI.

I am getting location updates in the Location Managers "didUpdateLocations", but what is the smartest way to write to CoreData from here?

I thought, I could just "merge" the DataController and LocationManager into one class, but

1: I can not access CoreData in the DataController itself

2: I can not create an observed object of the LocationManager anymore, since it does not provide a fetchrequest.

I'd really appreciate a slight hint here, since I don't know what to google anymore ;)

My DataController looks like this:

import CoreData
import Foundation

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "Positions")

    init() {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
            }
        }
    }

}

And my LocationManager looks like this:

import Foundation
import Combine
import CoreLocation

class LocManager: NSObject, ObservableObject, CLLocationManagerDelegate {

    @Published var location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    @Published var altitude: Double = 0
    @Published var degrees: Double = 0

    private let locationManager: CLLocationManager

    override init() {

        //LocationManager INIT
        self.locationManager = CLLocationManager()
        super.init()

        self.locationManager.delegate = self
        self.setup()
    }

    private func setup() {

        // set accuracy
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation

        //update filter
        //self.locationManager.headingFilter = kCLHeadingFilterNone //High Power usage
        self.locationManager.headingFilter = 0.5
        self.locationManager.distanceFilter = 1

        if CLLocationManager.headingAvailable() {
            self.locationManager.startUpdatingLocation()
            self.locationManager.startUpdatingHeading()
        }

    }

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        self.degrees = -1 * newHeading.magneticHeading
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        location = locations.first!.coordinate
        altitude = locations.first!.altitude

        /*
        I cant access CoreData here, can I?
        */

    }

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
            switch locationManager.authorizationStatus {
            case .authorizedWhenInUse:
                locationManager.requestWhenInUseAuthorization()
                break

            case .restricted:
                break

            case .denied:
                break

            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
                break

            default:
                break
            }
        }

}

Thanks for your help!


问:
Configuring nginx to handle errors via nodejs app
I have question about nginx configuration - I want to pass error handling into nodejs application (frontend app), so for eg. 404 error (and others) will be handled by nodejs app.

The "problem" is, that the app is running directly via nginx (it doesn't use it's internal mini-web server as many nodejs apps).

nginx configuration is as simply as possible:

```<code>server {
    listen       80;
    server_name  *.somedomain.com;
    return 301 https://$host$request_uri;
}

server {
        listen 443 ssl;
        server_name *.somedomain.com;
        ssl_certificate /etc/letsencrypt/live/somedomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/somedomain.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/somedomain.com/chain.pem;
        root /usr/share/nginx/html;
}

</code>```

Want to configure error handling via nodejs application, instead nginx.

Body:
I have question about nginx configuration - I want to pass error handling into nodejs application (frontend app), so for eg. 404 error (and others) will be handled by nodejs app.

The "problem" is, that the app is running directly via nginx (it doesn't use it's internal mini-web server as many nodejs apps).

nginx configuration is as simply as possible:

server {
    listen       80;
    server_name  *.somedomain.com;
    return 301 https://$host$request_uri;
}

server {
        listen 443 ssl;
        server_name *.somedomain.com;
        ssl_certificate /etc/letsencrypt/live/somedomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/somedomain.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/somedomain.com/chain.pem;
        root /usr/share/nginx/html;
}

Want to configure error handling via nodejs application, instead nginx.


问:
DtypeWarning: Columns (67) have mixed types. Specify dtype option on import or set low_memory=False. with bad memory error in pandas
I have been working on csv file which has more than 57 columns and I am getting below mentioned warning message

DtypeWarning: Columns (67) have mixed types. Specify dtype option on import or set low_memory=False

even after using low_memory = False while reading the csv  file whenever i am dropping unwanted columns my ipynb is getting closed and I am getting bad memory error message I have used below code for reading my csv files

df = pd.read_csv('ip.csv',encoding='cp1252',low_memory=False)

is there any other alternative to handle Error code: out of memory error

df = pd.read_csv('ip.csv',encoding='cp1252',low_memory=False)