问:
Websocket failure to connect : React.js mongoDB express
I am currently working on user authentication on my web, I can create account and login locally but It shows error when I was testing in my domain. Thank you!

error message below:

**WebSocketClient.js:16 WebSocket connection to 'my_domain' failed: **

I am using react.js on my web

I am using heroku to deploy my web

I am running my server in 4000

/Cards is the page after I success to login

index.js (my server)

```<code>const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const authRoutes = require("./Routes/AuthRoutes");
const app = express();
const cookieParser = require("cookie-parser");
require("dotenv").config();

app.listen(4000, () => {
  console.log("Sever started on 4000");
});

mongoose.set("strictQuery", false);

mongoose
  .connect(process.env.DB_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Successfully connected to MongoDB Atlas!");
  })
  .catch((err) => {
    console.log(err.message);
  });

app.use(
  cors({
    origin: [
      "http://localhost:3000",
    ],
    method: ["GET", "POST"],
    credentials: true,
  })
);

app.use(cookieParser());
app.use(express.json());
app.use("/", authRoutes);

</code>```

Login.js (my login page)

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link, useNavigate } from "react-router-dom";
import { useCookies } from "react-cookie";
import { ToastContainer, toast } from "react-toastify";
import "../Login.css";

function Login() {
  const [cookies] = useCookies([]);
  const navigate = useNavigate();
  useEffect(() => {
    if (cookies.jwt) {
      navigate("/Cards");
    }
  }, [cookies, navigate]);

  const [values, setValues] = useState({ email: "", password: "" });
  const generateError = (error) =>
    toast.error(error, {
      position: "bottom-right",
    });
  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const { data } = await axios.post(
        "http://localhost:4000/login",
        {
          ...values,
        },
        { withCredentials: true }
      );
      if (data) {
        if (data.errors) {
          const { email, password } = data.errors;
          if (email) generateError(email);
          else if (password) generateError(password);
        } else {
          navigate("/Cards");
        }
      }
    } catch (ex) {
      console.log(ex);
    }
  };
</code>```

I am currently working on user authentication on my web, I can create account and login locally but It shows error when I was testing in my domain. Thank you!

Body:
I am currently working on user authentication on my web, I can create account and login locally but It shows error when I was testing in my domain. Thank you!

error message below:

**WebSocketClient.js:16 WebSocket connection to 'my_domain' failed: **

I am using react.js on my web

I am using heroku to deploy my web

I am running my server in 4000

/Cards is the page after I success to login

index.js (my server)

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const authRoutes = require("./Routes/AuthRoutes");
const app = express();
const cookieParser = require("cookie-parser");
require("dotenv").config();

app.listen(4000, () => {
  console.log("Sever started on 4000");
});

mongoose.set("strictQuery", false);

mongoose
  .connect(process.env.DB_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Successfully connected to MongoDB Atlas!");
  })
  .catch((err) => {
    console.log(err.message);
  });

app.use(
  cors({
    origin: [
      "http://localhost:3000",
    ],
    method: ["GET", "POST"],
    credentials: true,
  })
);

app.use(cookieParser());
app.use(express.json());
app.use("/", authRoutes);

Login.js (my login page)

import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link, useNavigate } from "react-router-dom";
import { useCookies } from "react-cookie";
import { ToastContainer, toast } from "react-toastify";
import "../Login.css";

function Login() {
  const [cookies] = useCookies([]);
  const navigate = useNavigate();
  useEffect(() => {
    if (cookies.jwt) {
      navigate("/Cards");
    }
  }, [cookies, navigate]);

  const [values, setValues] = useState({ email: "", password: "" });
  const generateError = (error) =>
    toast.error(error, {
      position: "bottom-right",
    });
  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const { data } = await axios.post(
        "http://localhost:4000/login",
        {
          ...values,
        },
        { withCredentials: true }
      );
      if (data) {
        if (data.errors) {
          const { email, password } = data.errors;
          if (email) generateError(email);
          else if (password) generateError(password);
        } else {
          navigate("/Cards");
        }
      }
    } catch (ex) {
      console.log(ex);
    }
  };

I am currently working on user authentication on my web, I can create account and login locally but It shows error when I was testing in my domain. Thank you!


来源: stackexchange

问:
isPlatformBrowser and google crawler
I am using angular universal. I make calls to back-end rest services only if (isPlatformBrowser(this.platformId)) is true i.e. only from the browser to avoid same rest services called twice.

Does google crawler see the page  as browser?  I would like back-end rest calls executed when google crawler fetches the page so that the page can get indexed correctly but otherwise I would not want rest services called twice

ContentLicense: CC BY-SA 4.0

Title: isPlatformBrowser and google crawler


问:
How to force all my async functions to be called with implicit await on NodeJS .mjs?
currently I´m developing on nodejs for a competition as I´m more concerned with programming speed than anything else. And I´m doing a completely synchronous process.
The issue is that I connect to MySQL with mysql2 (auth issues with mysql) which is not supported by sync-mysql so I´m forced to use async/await.
So my code is basically filled by unnecessary async/await and to top it up. From time to time I forget to put an await so I don´t notice inmediatelly what the issue is (unlike with non async code). While debugging of course, the debugger will just pass through the code without stoping after exiting the async function. And other nasty asynchronous programming overhead.
Is there a way to make all function calls in NodeJS to do the await through a command line argument?
Something like --AlwaysAwait. So it doesn´t matter how much asynchronicity is shoved into my dependencies, I can always have simple Synchronous code? (I do love async but not when I´m in a competition, it also killed another pet project of mine because it got unmaintainable for the same kind of debugging issues so really want to get rid of it.)
Here is an example of the code:

import mysqlPromise from "mysql2/promise.js";

let errorFunc = function (err) {
    console.log(err);
    throw err;
};
let configFile = 'config.json';
let config;
if (fs.existsSync(configFile)) {
    const data = fs.readFileSync(configFile,
        {encoding: 'utf8', flag: 'r'});
    config = JSON.parse(data);
}
//break point in this line
let conn = await mysqlPromise.createConnection(config).catch(errorFunc);
//if I forget the next await when I go out of execute i
let [result, fields] = await conn.execute('select ?+? as sum', [2, 2]).catch(errorFunc);
// if I don´t put await in previous line program will keep going without me noticing.
// plus individual catch overhead instead of simply using try and catch as usual if I even wanted that.
```

Remember, I want as less async implementation code as possible so I can focus on more "functionality" code.
Also a deep tutorial is welcome. I have read so many introductory stuff copied all over the web.

I tried searching online for a configuration (only returned basic async/await usage) and tried nodejs --help|grep -i await (only returned --no-experimental-repl-await)
I was expecting someone to already had this issue and found a way to ditch async/await syntax and promises, like PHP but with the perks of nodejs.

Body:
currently I´m developing on nodejs for a competition as I´m more concerned with programming speed than anything else. And I´m doing a completely synchronous process.
The issue is that I connect to MySQL with mysql2 (auth issues with mysql) which is not supported by sync-mysql so I´m forced to use async/await.
So my code is basically filled by unnecessary async/await and to top it up. From time to time I forget to put an await so I don´t notice inmediatelly what the issue is (unlike with non async code). While debugging of course, the debugger will just pass through the code without stoping after exiting the async function. And other nasty asynchronous programming overhead.
Is there a way to make all function calls in NodeJS to do the await through a command line argument?
Something like --AlwaysAwait. So it doesn´t matter how much asynchronicity is shoved into my dependencies, I can always have simple Synchronous code? (I do love async but not when I´m in a competition, it also killed another pet project of mine because it got unmaintainable for the same kind of debugging issues so really want to get rid of it.)
Here is an example of the code:

import mysqlPromise from "mysql2/promise.js";

let errorFunc = function (err) {
    console.log(err);
    throw err;
};
let configFile = 'config.json';
let config;
if (fs.existsSync(configFile)) {
    const data = fs.readFileSync(configFile,
        {encoding: 'utf8', flag: 'r'});
    config = JSON.parse(data);
}
//break point in this line
let conn = await mysqlPromise.createConnection(config).catch(errorFunc);
//if I forget the next await when I go out of execute i
let [result, fields] = await conn.execute('select ?+? as sum', [2, 2]).catch(errorFunc);
// if I don´t put await in previous line program will keep going without me noticing.
// plus individual catch overhead instead of simply using try and catch as usual if I even wanted that.

Remember, I want as less async implementation code as possible so I can focus on more "functionality" code.
Also a deep tutorial is welcome. I have read so many introductory stuff copied all over the web.

I tried searching online for a configuration (only returned basic async/await usage) and tried nodejs --help|grep -i await (only returned --no-experimental-repl-await)
I was expecting someone to already had this issue and found a way to ditch async/await syntax and promises, like PHP but with the perks of nodejs.


问:
Persistent Data With Colab on GCE VM
I have recently connected my Colab notebook to a custom GCE VM since the idea behind using a custom VM is to have dedicated resources, right? However, I do not understand why isn't there any way to mount VM's local directories to the Colab docker container so that we can have persistent data.

I can see two mounts:

```<code>"Mounts": [
    {
        "Type": "bind",
        "Source": "/tmp/colab-shared",
        "Destination": "/var/colab/shared",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    },
    {
        "Type": "bind",
        "Source": "/tmp/var-colab",
        "Destination": "/var/colab",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],

</code>```

Is there any workaround? I was using Google Drive, and it is very slow.

Title: Persistent Data With Colab on GCE VM

Body:
I have recently connected my Colab notebook to a custom GCE VM since the idea behind using a custom VM is to have dedicated resources, right? However, I do not understand why isn't there any way to mount VM's local directories to the Colab docker container so that we can have persistent data.

I can see two mounts:

"Mounts": [
    {
        "Type": "bind",
        "Source": "/tmp/colab-shared",
        "Destination": "/var/colab/shared",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    },
    {
        "Type": "bind",
        "Source": "/tmp/var-colab",
        "Destination": "/var/colab",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],

Is there any workaround? I was using Google Drive, and it is very slow.


问:
To test console output in Junit for void main method
I need to write a Junit test, Since it do not have return type and arguments, I am getting difficulty to write it. Could anyone help in this ?</p>
```<code>public class IndexElement{
   public static void main(String[] args){
        int arr[] ={12,34,30,40};
        int lastele = 40;
        int index = 0;
        for(int i =0 ; i< arr.length; i++)
        { if(arr[i] == lastele)
          {
            index = i;
            break;
          }
        }
 System.out.println("Index of element" +index);
}
}
</code>```

Body:
I need to write a Junit test, Since it do not have return type and arguments, I am getting difficulty to write it. Could anyone help in this ?

public class IndexElement{
   public static void main(String[] args){
        int arr[] ={12,34,30,40};
        int lastele = 40;
        int index = 0;
        for(int i =0 ; i< arr.length; i++)
        { if(arr[i] == lastele)
          {
            index = i;
            break;
          }
        }
 System.out.println("Index of element" +index);
}
}


问:
In matplotlib animation, saving the animation looks different than showing them
I have written a matplotlib animation. In general terms it works well. However for some reason when I save it to a mp4 file, the output is not the same as when I show it

The part of the script for this is

```<code>anim = FuncAnimation(fig, ug_i,init_func=ug_i.init, frames=nf, interval=interval_ms, blit=True,repeat=False)
if args.save_video!=None:
    fps=1/args.time
    writervideo = FFMpegWriter(fps=fps)
    anim.save(args.save_video, writer=writervideo)
    print("done")
    plt.close()
else:
    plt.legend()
    plt.show()
</code>```

The difference is like this

Show
Video

No legend
legends shows

Grid
No Grid

X,Y labels
No X,Y labels

Text is written
Text does not appear

My most urgent feature that I want to fix how can I add a text to the plot that actually shows in the video

Right now I add a text with ax.text and set_text and set_position.
This text is returned every frame for the animation together with the lines but the text only shows when I do plt.show(). It does not show when I do anim.save(args.save_video, writer=writervideo)

How can I add text to an animation and that actually appears when saved to a video?

Body:
I have written a matplotlib animation. In general terms it works well. However for some reason when I save it to a mp4 file, the output is not the same as when I show it

The part of the script for this is

anim = FuncAnimation(fig, ug_i,init_func=ug_i.init, frames=nf, interval=interval_ms, blit=True,repeat=False)
if args.save_video!=None:
    fps=1/args.time
    writervideo = FFMpegWriter(fps=fps)
    anim.save(args.save_video, writer=writervideo)
    print("done")
    plt.close()
else:
    plt.legend()
    plt.show()

The difference is like this

Show
Video

No legend
legends shows

Grid
No Grid

X,Y labels
No X,Y labels

Text is written
Text does not appear

My most urgent feature that I want to fix how can I add a text to the plot that actually shows in the video

Right now I add a text with ax.text and set_text and set_position.
This text is returned every frame for the animation together with the lines but the text only shows when I do plt.show(). It does not show when I do anim.save(args.save_video, writer=writervideo)

How can I add text to an animation and that actually appears when saved to a video?


问:
How to use spring prototype scope for constructor arguments in case of interface
I have a legacy code, which I need to migrate using spring, and I have found one case like below

```<code>@Component // have to mark this as component
class ABC
{
  private static final class innerClass implements InterfaceClass
   {
     private String str;
     innerClass(String str){this.str = str};
     //some DAO methods..
     private Dao1 dao1;
     private Dao2 dao2;
   }
   private InterfaceClass intfClass;
   void getInnerClass(){
   if(intfClass == null || !(str.isEmpty())){
    intfClass = new innerClass (str);
    }
   }
}

public interface InterfaceClass{
... some methods declared..
}

</code>```

Now the inner class innerClass contains some DAO's which i need to autowire and class ABC is marked as @Component so hence i dont think so we can keep the inner class as @Component here?
The scope of the inner class needs to be a prototype.

So to implement it,

I tried one factory implementation, in which I commented on the inner class and made it as a separate class, refer below

```<code>class innerClass {  //inner class which I made as a separate class
private String str;
innerClass(String str){this.str = str}
     private Dao1 dao1;
     private Dao2 dao2;
}

public interface InterfaceClass{
... some methods declared..
}

@Configuration
class innerClassFactory
{
@Autowire Dao1 dao1;
@Autowire Dao2 dao2;

@Bean
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public InterfaceClass getInnerClassObj(String str){
return new innerClass(str);
}
}

@Compoenent
class ABC{
@Autowire innerClassFactory;
private InterfaceClass intfClass;
   void getInnerClass(){
   if(innerClassFactory == null || !(str.isEmpty())){
    intfClass = getInnerClassObj (str);
    }
   }

}

</code>```

After trying this still, the dao's are null, they aren't autowired
Also, the String str is populated earlier only,

Please suggest me any other option if possible.

Body:
I have a legacy code, which I need to migrate using spring, and I have found one case like below

@Component // have to mark this as component
class ABC
{
  private static final class innerClass implements InterfaceClass
   {
     private String str;
     innerClass(String str){this.str = str};
     //some DAO methods..
     private Dao1 dao1;
     private Dao2 dao2;
   }
   private InterfaceClass intfClass;
   void getInnerClass(){
   if(intfClass == null || !(str.isEmpty())){
    intfClass = new innerClass (str);
    }
   }
}

public interface InterfaceClass{
... some methods declared..
}

Now the inner class innerClass contains some DAO's which i need to autowire and class ABC is marked as @Component so hence i dont think so we can keep the inner class as @Component here?
The scope of the inner class needs to be a prototype.

So to implement it,

I tried one factory implementation, in which I commented on the inner class and made it as a separate class, refer below

class innerClass {  //inner class which I made as a separate class
private String str;
innerClass(String str){this.str = str}
     private Dao1 dao1;
     private Dao2 dao2;
}

public interface InterfaceClass{
... some methods declared..
}

@Configuration
class innerClassFactory
{
@Autowire Dao1 dao1;
@Autowire Dao2 dao2;

@Bean
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public InterfaceClass getInnerClassObj(String str){
return new innerClass(str);
}
}

@Compoenent
class ABC{
@Autowire innerClassFactory;
private InterfaceClass intfClass;
   void getInnerClass(){
   if(innerClassFactory == null || !(str.isEmpty())){
    intfClass = getInnerClassObj (str);
    }
   }

}

After trying this still, the dao's are null, they aren't autowired
Also, the String str is populated earlier only,

Please suggest me any other option if possible.


问:
How to build next.js with rollup?
I am going to build nextjs with rollup.
I couldn't find help doc or other source about rollup nextjs.

Here is my progress.
Please help me with sample code how to rollup nextjs.

I can build next.js with rollup. It is only one file bundle.js. How to start server using this file?

-rollup.config.js

```<code>import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";
import path from "path";

import pkg from "./package.json";

const extensions = [".js", ".jsx", ".ts", ".tsx", ".json"];
const babelConfig = path.resolve(__dirname, "babel.config.js");

export default {
  input: "pages/index.js",
  output: [
    {
      format: "es",
      exports: "named",
      file: 'dist/bundle.js',
      sourcemap: 'inline'
    }
  ],
  plugins: [
    babel({
      extensions,
      babelrc: false,
      babelHelpers: "bundled",
      configFile: babelConfig,
      exclude: "node_modules/**",
    }),
    resolve({ extensions }),
    commonjs({ extensions }),
  ],
  external: [
    "next/app",
    "effector-react/ssr",
    ...Object.keys(Object.assign({}, pkg.dependencies, pkg.peerDependencies)),
  ],
};

</code>```

-babel.config.js

```<code>module.exports = function (api) {
  api.cache.using(() => process.env.NODE_ENV);

  const presets = [
    [
      "@babel/preset-env",
      {
        loose: true,
        modules: false,
        shippedProposals: true,
        targets: {
          node: "12",
          browsers: [
            "last 2 Chrome versions",
            "last 2 Firefox versions",
            "last 2 Safari versions",
            "last 2 Edge versions",
          ],
        },
      },
    ],
    "@babel/preset-typescript",
    "@babel/preset-react",
  ];

  const plugins = [
    ["@babel/plugin-proposal-class-properties", { loose: true }],
    "@babel/plugin-proposal-nullish-coalescing-operator",
    "@babel/plugin-proposal-optional-chaining",
  ];

  return {
    presets,
    plugins,
  };
};

</code>```

-package.json

```<code>{
  "name": "example",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build-next": "next build",
    "start-next": "next start",
    "build-rollup": "rollup -c --bundleConfigAsCjs"
  },
  "dependencies": {
    "effector": "^21.8.11",
    "effector-next": "^1.2.0",
    "effector-react": "^21.3.2",
    "next": "10.1.3",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
    "@babel/plugin-proposal-optional-chaining": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "@babel/preset-typescript": "^7.18.6",
    "@rollup/plugin-babel": "^6.0.3",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "systemjs": "^6.13.0"
  }
}

</code>```

Title: How to build next.js with rollup?

Body:
I am going to build nextjs with rollup.
I couldn't find help doc or other source about rollup nextjs.

Here is my progress.
Please help me with sample code how to rollup nextjs.

I can build next.js with rollup. It is only one file bundle.js. How to start server using this file?

-rollup.config.js

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";
import path from "path";

import pkg from "./package.json";

const extensions = [".js", ".jsx", ".ts", ".tsx", ".json"];
const babelConfig = path.resolve(__dirname, "babel.config.js");

export default {
  input: "pages/index.js",
  output: [
    {
      format: "es",
      exports: "named",
      file: 'dist/bundle.js',
      sourcemap: 'inline'
    }
  ],
  plugins: [
    babel({
      extensions,
      babelrc: false,
      babelHelpers: "bundled",
      configFile: babelConfig,
      exclude: "node_modules/**",
    }),
    resolve({ extensions }),
    commonjs({ extensions }),
  ],
  external: [
    "next/app",
    "effector-react/ssr",
    ...Object.keys(Object.assign({}, pkg.dependencies, pkg.peerDependencies)),
  ],
};

-babel.config.js

module.exports = function (api) {
  api.cache.using(() => process.env.NODE_ENV);

  const presets = [
    [
      "@babel/preset-env",
      {
        loose: true,
        modules: false,
        shippedProposals: true,
        targets: {
          node: "12",
          browsers: [
            "last 2 Chrome versions",
            "last 2 Firefox versions",
            "last 2 Safari versions",
            "last 2 Edge versions",
          ],
        },
      },
    ],
    "@babel/preset-typescript",
    "@babel/preset-react",
  ];

  const plugins = [
    ["@babel/plugin-proposal-class-properties", { loose: true }],
    "@babel/plugin-proposal-nullish-coalescing-operator",
    "@babel/plugin-proposal-optional-chaining",
  ];

  return {
    presets,
    plugins,
  };
};

-package.json

{
  "name": "example",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build-next": "next build",
    "start-next": "next start",
    "build-rollup": "rollup -c --bundleConfigAsCjs"
  },
  "dependencies": {
    "effector": "^21.8.11",
    "effector-next": "^1.2.0",
    "effector-react": "^21.3.2",
    "next": "10.1.3",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
    "@babel/plugin-proposal-optional-chaining": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "@babel/preset-typescript": "^7.18.6",
    "@rollup/plugin-babel": "^6.0.3",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "systemjs": "^6.13.0"
  }
}


问:
R Keras 'verbose' not showing outputs even when the verbose value is set to '1' or '2'
I have been struggling to produce a printed output in my R-console for each epoch when using Keras. This is even when 'verbose' is set to a value of '1' or '2'.

Please see the following code:

```<code>cifar <- dataset_cifar10()
x_train <- cifar$train$x/255
x_test <- cifar$test$x/255
y_train <- to_categorical(cifar$train$y, num_classes = 10)
y_test <- to_categorical(cifar$test$y, num_classes = 10)

model <-  keras_model_sequential() %>%
  layer_conv_2d(filters = 16, kernel_size = 2, padding = 'same', activation = 'relu', input_shape = c(32,32,3)) %>%
    layer_max_pooling_2d(pool_size = 2) %>%
    layer_conv_2d(filters = 32, kernel_size = 2, padding = 'same', activation = 'relu') %>%
    layer_max_pooling_2d(pool_size = 2) %>%
    layer_conv_2d(filters = 64, kernel_size = 2, padding = 'same', activation = 'relu') %>%
    layer_max_pooling_2d(pool_size =2) %>%
    layer_dropout(0.3) %>%
    layer_flatten() %>%
    layer_dense(500, activation = 'relu') %>%
    layer_dropout(0.4) %>%
    layer_dense(10, activation = 'softmax')

model %>% compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics= 'accuracy')

checkpointer <- callback_model_checkpoint(filepath = 'model.weights.best.hdf5', verbose = 1, save_best_only = 'true')

k <- model %>% fit(x_train, y_train, batch_size = 32, epochs = 5, validation_data = list(x_test, y_test), callbacks = checkpointer, verbose = 1, shuffle = 'true')

</code>```

Whenever I run my last line of code, I see no printed output for each epoch.

I am looking for an output like the following each time an epoch is completed:

```<code>Epoch 1/5
Epoch 00000: val_loss improved from inf to 1.35820, saving model to model.weights.best.hdf5
46s - loss: 1.6192 - acc: 0.4140 - val_loss: 1.3582 - val_acc: 0.5166

</code>```

Any help at all would be greatly appreciated!

Body:
I have been struggling to produce a printed output in my R-console for each epoch when using Keras. This is even when 'verbose' is set to a value of '1' or '2'.

Please see the following code:

cifar <- dataset_cifar10()
x_train <- cifar$train$x/255
x_test <- cifar$test$x/255
y_train <- to_categorical(cifar$train$y, num_classes = 10)
y_test <- to_categorical(cifar$test$y, num_classes = 10)

model <-  keras_model_sequential() %>%
  layer_conv_2d(filters = 16, kernel_size = 2, padding = 'same', activation = 'relu', input_shape = c(32,32,3)) %>%
    layer_max_pooling_2d(pool_size = 2) %>%
    layer_conv_2d(filters = 32, kernel_size = 2, padding = 'same', activation = 'relu') %>%
    layer_max_pooling_2d(pool_size = 2) %>%
    layer_conv_2d(filters = 64, kernel_size = 2, padding = 'same', activation = 'relu') %>%
    layer_max_pooling_2d(pool_size =2) %>%
    layer_dropout(0.3) %>%
    layer_flatten() %>%
    layer_dense(500, activation = 'relu') %>%
    layer_dropout(0.4) %>%
    layer_dense(10, activation = 'softmax')

model %>% compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics= 'accuracy')

checkpointer <- callback_model_checkpoint(filepath = 'model.weights.best.hdf5', verbose = 1, save_best_only = 'true')

k <- model %>% fit(x_train, y_train, batch_size = 32, epochs = 5, validation_data = list(x_test, y_test), callbacks = checkpointer, verbose = 1, shuffle = 'true')

Whenever I run my last line of code, I see no printed output for each epoch.

I am looking for an output like the following each time an epoch is completed:

Epoch 1/5
Epoch 00000: val_loss improved from inf to 1.35820, saving model to model.weights.best.hdf5
46s - loss: 1.6192 - acc: 0.4140 - val_loss: 1.3582 - val_acc: 0.5166

Any help at all would be greatly appreciated!


问:
issue with configuring django_ace
i'm trying to create a web application that incorporates a light-weight ide but i am having trouble integrating a code editor with syntax highlighting with django. when i try to use the ace widget configurations, none of the settings i add seem to work but the widget is still rendered.

views.py

```<code>from django.shortcuts import render
from . import forms

# Create your views here
def index(request):
    return render(request, 'main.html', context={'ace_editor': forms.EditorForm})
</code>```

forms.py

```<code>from django import forms
from django_ace import AceWidget

class EditorForm(forms.Form):
    text = forms.CharField(widget=AceWidget(
        mode="java",
        theme="twilight",
        wordwrap=False,
        width="5000px",
        height="300px",
        minlines=None,
        maxlines=None,
        showprintmargin=False,
        showinvisibles=False,
        usesofttabs=True,
        tabsize=None,
        fontsize=None,
        toolbar=True,
        readonly=False,
        showgutter=True,
        behaviours=True,
    ))
</code>```

main.html

```<code><p>hi</p>
{{ ace_editor }}
</code>```

output

Title: issue with configuring django_ace

Body:
i'm trying to create a web application that incorporates a light-weight ide but i am having trouble integrating a code editor with syntax highlighting with django. when i try to use the ace widget configurations, none of the settings i add seem to work but the widget is still rendered.

views.py

from django.shortcuts import render
from . import forms

# Create your views here
def index(request):
    return render(request, 'main.html', context={'ace_editor': forms.EditorForm})

forms.py

from django import forms
from django_ace import AceWidget

class EditorForm(forms.Form):
    text = forms.CharField(widget=AceWidget(
        mode="java",
        theme="twilight",
        wordwrap=False,
        width="5000px",
        height="300px",
        minlines=None,
        maxlines=None,
        showprintmargin=False,
        showinvisibles=False,
        usesofttabs=True,
        tabsize=None,
        fontsize=None,
        toolbar=True,
        readonly=False,
        showgutter=True,
        behaviours=True,
    ))

main.html

hi

{{ ace_editor }}

output


问:
MongoDB aggregate claculating the outdated collection
I'm working on a social media app and I'm having this problem, I have a collection for friends to store friend requests and the relationship between users and everything works fine, but I'm working on a post('save') middleware and aggrgate pipeline to count the number of friends per user per process which also worked But the problem is aggrgate pipeline counting friends before update collection eg if user accepts friend request it counts friends without this new friend.

Is there any solution to this or best way to do it?

Here is the code

```<code>const mongoose = require('mongoose');
const User = require('./userModel');

const FriendSchema = new mongoose.Schema({
  sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  recipient: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  status: {
    type: String,
    enum: ['pending', 'accepted', 'cancelled'],
    required: true,
  },
  createdAt: { type: Date, default: Date.now },
});

FriendSchema.statics.calcFriends = async function (senderID, recipientID) {
  const senderIDstats = await this.aggregate([
    {
      $match: {
        $or: [
          { sender: senderID, status: 'accepted' },
          { recipient: senderID, status: 'accepted' },
        ],
      },
    },
    {
      $group: {
        _id: null,
        count: { $sum: 1 },
      },
    },
  ]);
  const recipientIDstats = await this.aggregate([
    {
      $match: {
        $or: [
          { sender: recipientID, status: 'accepted' },
          { recipient: recipientID, status: 'accepted' },
        ],
      },
    },

    {
      $group: {
        _id: null,
        count: { $sum: 1 },
      },
    },
  ]);

  await User.bulkWrite([
    {
      updateOne: {
        filter: { _id: senderID },
        update: {
          friendsCount: senderIDstats.length > 0 ? senderIDstats[0]?.count : 0,
        },
      },
    },
    {
      updateOne: {
        filter: { _id: recipientID },
        update: {
          friendsCount:
            recipientIDstats.length > 0 ? recipientIDstats[0]?.count : 0,
        },
      },
    },
  ]);
};

FriendSchema.index({ sender: 1, recipient: 1 }, { unique: true });

FriendSchema.post('save', function () {
  this.constructor.calcFriends(this.sender, this.recipient);
});

const Friend = mongoose.model('Friend', FriendSchema);

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

Body:
I'm working on a social media app and I'm having this problem, I have a collection for friends to store friend requests and the relationship between users and everything works fine, but I'm working on a post('save') middleware and aggrgate pipeline to count the number of friends per user per process which also worked But the problem is aggrgate pipeline counting friends before update collection eg if user accepts friend request it counts friends without this new friend.

Is there any solution to this or best way to do it?

Here is the code

const mongoose = require('mongoose');
const User = require('./userModel');

const FriendSchema = new mongoose.Schema({
  sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  recipient: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  status: {
    type: String,
    enum: ['pending', 'accepted', 'cancelled'],
    required: true,
  },
  createdAt: { type: Date, default: Date.now },
});

FriendSchema.statics.calcFriends = async function (senderID, recipientID) {
  const senderIDstats = await this.aggregate([
    {
      $match: {
        $or: [
          { sender: senderID, status: 'accepted' },
          { recipient: senderID, status: 'accepted' },
        ],
      },
    },
    {
      $group: {
        _id: null,
        count: { $sum: 1 },
      },
    },
  ]);
  const recipientIDstats = await this.aggregate([
    {
      $match: {
        $or: [
          { sender: recipientID, status: 'accepted' },
          { recipient: recipientID, status: 'accepted' },
        ],
      },
    },

    {
      $group: {
        _id: null,
        count: { $sum: 1 },
      },
    },
  ]);

  await User.bulkWrite([
    {
      updateOne: {
        filter: { _id: senderID },
        update: {
          friendsCount: senderIDstats.length > 0 ? senderIDstats[0]?.count : 0,
        },
      },
    },
    {
      updateOne: {
        filter: { _id: recipientID },
        update: {
          friendsCount:
            recipientIDstats.length > 0 ? recipientIDstats[0]?.count : 0,
        },
      },
    },
  ]);
};

FriendSchema.index({ sender: 1, recipient: 1 }, { unique: true });

FriendSchema.post('save', function () {
  this.constructor.calcFriends(this.sender, this.recipient);
});

const Friend = mongoose.model('Friend', FriendSchema);

module.exports = Friend;


问:
How to query a text with '&' in salesforce rest API?
I want to query a condition that include & in salesforce using rest API.

Eg:

{{instance_url}}/services/data/v55.0/queryAll?q=SELECT+FIELDS(STANDARD)+FROM+Case+WHERE+Status+IN+('Started','In
Progress &  Review','Completed')

It splitting the query by &. So I changed & to %26 (url encoded of &), now the Salesforce not identified its status.


问:
Is there limitation to attach something to report portal with pabot
I using robotframework-reportportal 5.3.0 to send the attachment to reportportal with this command It work

```<code>robot --listener robotframework_reportportal.listener \
  --variable RP_UUID:'xxx-xxx-xx-xxx-xxx' \
  --variable RP_ENDPOINT:'http://127.0.0.1:8080' \
  --variable RP_LAUNCH:'superadmin_TEST_EXAMPLE' \
  --variable RP_PROJECT:'superadmin_personal' \
  -v app:/xx/xx/xx.apk \
  ./path/to/testcase/
</code>```

but then i want to run the test parallel by using pabot and it not attach anything to my reportportal

```<code>pabot --pabotlib \
  --listener robotframework_reportportal.listener \
  --variable RP_UUID:'xxx-xxx-xxx-xxx-xxxx' \
  --variable RP_ENDPOINT:'http://127.0.0.1' \
  --variable RP_LAUNCH:'superadmin_TEST_EXAMPLE' \
  --variable RP_LAUNCH_UUID:'xxx-xxx-xxx-xxx-xxx' \
  --variable RP_PROJECT:'superadmin_personal' \
  -v platform:android \
  -v app:/xxx/xx/xxx/xxx.apk \
  ./path/to/testcase/
</code>```

to attach the screenshot i'm follow this document

i want to send attach screenshot to reportportal with pabot command

Body:
I using robotframework-reportportal 5.3.0 to send the attachment to reportportal with this command It work

robot --listener robotframework_reportportal.listener \
  --variable RP_UUID:'xxx-xxx-xx-xxx-xxx' \
  --variable RP_ENDPOINT:'http://127.0.0.1:8080' \
  --variable RP_LAUNCH:'superadmin_TEST_EXAMPLE' \
  --variable RP_PROJECT:'superadmin_personal' \
  -v app:/xx/xx/xx.apk \
  ./path/to/testcase/

but then i want to run the test parallel by using pabot and it not attach anything to my reportportal

pabot --pabotlib \
  --listener robotframework_reportportal.listener \
  --variable RP_UUID:'xxx-xxx-xxx-xxx-xxxx' \
  --variable RP_ENDPOINT:'http://127.0.0.1' \
  --variable RP_LAUNCH:'superadmin_TEST_EXAMPLE' \
  --variable RP_LAUNCH_UUID:'xxx-xxx-xxx-xxx-xxx' \
  --variable RP_PROJECT:'superadmin_personal' \
  -v platform:android \
  -v app:/xxx/xx/xxx/xxx.apk \
  ./path/to/testcase/

to attach the screenshot i'm follow this document

i want to send attach screenshot to reportportal with pabot command


问:
How to slow down Android UI rending?
How can I slow down UI rending in Android to get an idea of how UI is rending?
There is an option in Developer Tools where you can slow down animation speed.

My UI is changing with some flashing, but I am not able to get actual since too fast.
Is there any tool or some idea for a workaround to emulate "slow rendering".

Any tool specific to compose is also welcomed.

Title: How to slow down Android UI rending?


问:
ActionController::InvalidAuthenticityToken on server having ssl
I have current got this error:

```<code>ActionController::InvalidAuthenticityToken in PostController#create
</code>```

I research many answers and tried many solutions but it's still error.

Problem my page on local works ok, but on server it work error.

I checked nginx.config

```<code>server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  sub1.mydomain.com;
        root         /usr/share/nginx/html;
        ssl_certificate /etc/letsencrypt/live/sub1.mydomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/sub1.mydomain.com/privkey.pem;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

        location / {
            proxy_pass http://localhost:3200/;
        }
    }
server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  sub2.mydomain.com;
        root         /usr/share/nginx/html;

        location / {
            proxy_pass http://localhost:4000/;
        }
    }
</code>```

Body:
I have current got this error:

ActionController::InvalidAuthenticityToken in PostController#create

I research many answers and tried many solutions but it's still error.

Problem my page on local works ok, but on server it work error.

I checked nginx.config

server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  sub1.mydomain.com;
        root         /usr/share/nginx/html;
        ssl_certificate /etc/letsencrypt/live/sub1.mydomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/sub1.mydomain.com/privkey.pem;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

        location / {
            proxy_pass http://localhost:3200/;
        }
    }
server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  sub2.mydomain.com;
        root         /usr/share/nginx/html;

        location / {
            proxy_pass http://localhost:4000/;
        }
    }


问:
How to wait Retrofit2 response handling properly with Coroutine?
I would like to write a code that puts a token in the header for api call. When the token is expired after some minutes, requesting token process is invoked and after the process is getting completed, the api call should be called again with refreshed token.

for that, I am using Coroutine and suspend fun for Retrofit Response.

However, when a token is needed, the api is called again without waiting for the token-requesting api and its callback to finish.

How can I properly await for both executions of getting Response from api call and handling it in the main thread?

Below is the code I wrote.

ApiViewModel

fun <T> apiCall(
    api: suspend () -> Response<RecvBase<T>>,
    callback: ((T) -> Unit)? = null
) {
    viewModelScope.launch {
        val result = api()
        result.body()?.let { recv ->
            if (recv.isTokenRefreshingRequired) {
                val tokenProcess = async { requestNewToken() }
                tokenProcess.await()
                apiCall(api, callback)
                return@launch
            }
            // handle with callback
        }
    }
}

private suspend fun requestAccessToken() {
    viewModelScope.launch {
        val result = service.requestNewToken()
        result.body()?.data?.let {
            token = it
        }
    }
}
```
<h3>ApiService</h3>
<pre class="lang-kotlin prettyprint-override"><code>interface ApiService {
    @POST("/newToken")
    suspend fun requestNewToken(...): Response<RecvBase<String>>
}
</code>```

I used async - await, launch - join, but neither of them had worked. I assume that the code waits for execution just until requesting token api is called, then not waiting for its callback invoked.

Body:
I would like to write a code that puts a token in the header for api call. When the token is expired after some minutes, requesting token process is invoked and after the process is getting completed, the api call should be called again with refreshed token.

for that, I am using Coroutine and suspend fun for Retrofit Response.

However, when a token is needed, the api is called again without waiting for the token-requesting api and its callback to finish.

How can I properly await for both executions of getting Response from api call and handling it in the main thread?

Below is the code I wrote.

ApiViewModel

fun <T> apiCall(
    api: suspend () -> Response<RecvBase<T>>,
    callback: ((T) -> Unit)? = null
) {
    viewModelScope.launch {
        val result = api()
        result.body()?.let { recv ->
            if (recv.isTokenRefreshingRequired) {
                val tokenProcess = async { requestNewToken() }
                tokenProcess.await()
                apiCall(api, callback)
                return@launch
            }
            // handle with callback
        }
    }
}

private suspend fun requestAccessToken() {
    viewModelScope.launch {
        val result = service.requestNewToken()
        result.body()?.data?.let {
            token = it
        }
    }
}

ApiService

interface ApiService {
    @POST("/newToken")
    suspend fun requestNewToken(...): Response<RecvBase<String>>
}

I used async - await, launch - join, but neither of them had worked. I assume that the code waits for execution just until requesting token api is called, then not waiting for its callback invoked.


问:
Can I use CSRF token as value for state parameter in OAuth flow?
While implementing Azure OAuth flow I have used state parameter, Azure docs says about state param:

A value included in the request that is also returned in the token response. It can be a string of any content that you wish. A randomly generated unique value is typically used for preventing cross-site request forgery attacks. The value can also encode information about the user's state in the app before the authentication request occurred. For instance, it could encode the page or view they were on.

So, My web application is already generating such unique string and that is a CSRf token (UUID). So I used the same CSRF token (UUID) and passed to state parameter. When response comes from OAuth provider I have crossed with the CSRF token from session.

But, recently security team in my company said CSRF token should not used in this way. According to them

A CRSF token is a secret that should not be shared. Using it as a state value is therefore improper use of the CSRF token and introduces a (small) security risk.

But, if I look closely at other normal (non-Oauth) requests then the same CSRF token is passed in request header, so I asked them that if CSRF token is secret then why it is being passed in request header that could also "introduces a (small) security risk." the answer I received is not convincing. Hence asking this question on this large forum:

Can we use CSRF token as a value for state parameter in OAuth request? Is there any security risk involve if we use CSRF token as state parameter?


问:
Why is my code printing out more print statements then it should?
Heyo all. I just got a raspberry pi 4 and I moved my code from my PC to the pi and when I ran and fixed it so it could run. I started to notice that it printed out more then it should. I looked it up but I couldn't find any help or reason why it does it. Code is

```<code>#!/usr/bin/python3
from os import system
system('cls')
print('heyo')
</code>```

output is

I have found out if I add a sleep timer I no longer get that problem.

I found out what caused it that is why I did not have code from my main program but I never found out exactly why it does it nor how to fix it without sleeping.

Notes: originally wrote it on windows 10 on my main PC I ported it over to my PI on the raspberry PI OS lite (I assume it is a Linux base OS). I changed the "clear" command to "cls" cause I am used to it. I am using VS code via SSH to the file. I am also using SSH to start the program. I run the code as:

```<code>./main.py
</code>```

I did chmod +x test.py   I am using python version 3.6.7. I am sorry if this seems basic or I made it way to confusing or there is a super super simple way to fix it (besides time.sleep). Thank you all for any help/input. Have a good night or good day.

Edit: I did not change anything but now it works for some reason. I have no clue why or how but for some reason it does.

Body:
Heyo all. I just got a raspberry pi 4 and I moved my code from my PC to the pi and when I ran and fixed it so it could run. I started to notice that it printed out more then it should. I looked it up but I couldn't find any help or reason why it does it. Code is

#!/usr/bin/python3
from os import system
system('cls')
print('heyo')

output is

I have found out if I add a sleep timer I no longer get that problem.

I found out what caused it that is why I did not have code from my main program but I never found out exactly why it does it nor how to fix it without sleeping.

Notes: originally wrote it on windows 10 on my main PC I ported it over to my PI on the raspberry PI OS lite (I assume it is a Linux base OS). I changed the "clear" command to "cls" cause I am used to it. I am using VS code via SSH to the file. I am also using SSH to start the program. I run the code as:

./main.py

I did chmod +x test.py   I am using python version 3.6.7. I am sorry if this seems basic or I made it way to confusing or there is a super super simple way to fix it (besides time.sleep). Thank you all for any help/input. Have a good night or good day.

Edit: I did not change anything but now it works for some reason. I have no clue why or how but for some reason it does.


问:
Tomcat errror! localhost didn’t send any data
I am installing tomcat with mysql + eclipse to run a simple web page with search function. I followed the example from here: https://www.roseindia.net/jsp/searchbook.shtml
However, when I submitted the form, error was displayed.
I changed the tomcat port from 8080 to 8085 so when I browsed the local host 8085, it also displayed error. Moreover, when I run another jsp file, the port shown is 8080 not 8085 as I set default.

I tried several solution on google and stackoverflow also but it did not work. I did not know the reasons why. Quite strangelly, I did the same with the example https://www.roseindia.net/jsp/searchbook.shtml from my computer at home. It worked without error.


问:
Read merge in hbase
I am trying to understand how read and write happens in hbase and how hbase does the caching.
From various articles and videos, I found that a read merge happens when a read request is made to hbase. What I understood is:

Whenever read request made, block cache is first checked for the data.

Then memstore is checked. If data found in both block cache or memstore, data is sent to client.

Else fetched from hfiles.

My doubts are

whether both block cache and memstore is always checked for the data? or whether memstore will be ignored if found in block cache.

If memstore not checked (since found in blockcache),how will client get latest value if there was an edit in memstore?

I created a new table. I added one row. I issued get command to fetch the data. I obtained the data but I didn't see any change in cache hits and reads of block cache. Why?

I know there are multiple questions but all these are linked to read merge and hbase caching. I need a clarity on these concepts and I could not find any in documentation.

Title: Read merge in hbase


问:
CI/CD setup using Gradle, Git, CodeArtifact & CodeBuild with multiple libraries
At present we have more than 10 libraries consumed and deployed across 4 services. There are some libraries like common utilities and protos which are consumed by other libraries, so there is a dependency hierarchy in the libraries as well, all the way leading to the service.

We are facing multiple challenges in deploying any change to the library.
We use Gradle for dependency management, Code Artifact for maven repository management, Code Pipeline for CD, ECR for service docker image storing and ECS for service deployment.

Issue 1: Auto Version Management/Increment using CodeArtifact, Git and Gradle.
When a library is changed (Minor changes without any backward compatibility issues), we don't increment the version. We push the changes to master, which triggers a CodePipeline and builds the library by taking any dependent libraries from CodeArtifact. We follow a manual process to delete the current Library-1.0.0 CodeArtifact so that new artifacts can be published. Removal of existing artifacts is a manual process as well as risky as this prevents easy rollbacks.

Issue 2: Rebuilding and Republishing all child libraries if a root library is changed
When a parent library is changed, all the libraries that depend on it need to be rebuilt using the latest parent library artifact before releasing the changes to service. If we don't do that, and directly rebuild the service, only the service will have the latest code of the library, but all the other libraries still use the old library code, leading to unexpected behaviour.

Ideal expectation here is -> When a service image is getting created, a single or latest version of the library should be used by the service and by all the dependent libraries. Only one version of the library should be active in a service, as part of dependency conflict resolution.

Issue 3: Rollback the deployments
Right now rollbacks are impossible. We delete all the old version library artifacts, so it's impossible to rollback a deployment, the only way to rollback a deployment is to revert all the libraries in git and rebuild, republish all libraries. Would like to know what is the best practice for rollbacks and CI/CD using CodeArtifact, Gradle and Git.

Please help in finding out what we are doing wrong and the correct way to setup CI/CD using Gradle, CodeArtifact and CodeBuild.


问:
Access to image at 'URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm Getting this error while fetching Rapid API From Pure JavaScript.

I am using this API For Fetching Instagram Posts, Reels and more: https://rapidapi.com/arraybobo/api/instagram-media-downloader

HTML

```<code><h1>Download Instagram Posts</h1>
    <input type="text" placeholder="Enter URL" /><br />
    <div id="Info"></div>
    <button onclick="HandleReq()">Download</button>
</code>```

CSS

```<code> * {
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
          Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue",
          sans-serif;
      }
      body {
        padding: 20px 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }
      input {
        padding: 10px;
        border-radius: 5px;
        border: none;
        background: white;
        color: blue;
        border: 1px solid silver;
        width: 70%;
      }
      h1 {
        text-align: center;
      }
      button {
        padding: 10px 20px;
        border-radius: 5px;
        margin: 10px 10px;
        background: black;
        color: yellow;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
      }
      button:hover {
        background: yellow;
        color: black;
      }
      div {
        display: flex;
        justify-content: center;
        width: 90%;
        flex-direction: column;
        flex-wrap: wrap;
        text-align: center;
        object-fit: cover;
        overflow: scroll;
      }
      img {
        width: 400px;
        height: 400px;
      }
      @media only screen and (max-width: 768px) {
        body{
            padding: 10px;
        }
        div{
            width: 100%;
        }
        img{
            width: 95%;
            height: auto;
        }
      }
</code>```

JAVASCRIPT

```<code>let content = document.getElementById("Info");
      function HandleReq() {
        const options = {
          method: "GET",
          headers: {
            "X-RapidAPI-Key":
              "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "X-RapidAPI-Host": "instagram-media-downloader.p.rapidapi.com",
          },
        };

        fetch(
          "https://instagram-media-downloader.p.rapidapi.com/rapid/post.php?url=https%3A%2F%2Fwww.instagram.com%2Fp%2FBhr1Ca9lcT0%2F",
          options
        )
          .then((response) => response.json())
          .then(
            (response) =>
              (content.innerHTML = `<img src=${response.image} crossorigin="anonymous"><br /><span>${response.caption}</span>`)
          )
          .catch((err) => console.error(err));
      }
</code>```

ERROR:

Access to image at 'https://scontent-waw1-1.cdninstagram.com/v/t51.2885-15/30602671_1678191385592964_4808612725670281216_n.jpg?stp=dst-jpg_e35&_nc_ht=scontent-waw1-1.cdninstagram.com&_nc_cat=100&_nc_ohc=EgfXllD6SRkAX_J5kmD&edm=AP_V10EBAAAA&ccb=7-5&oh=00_AfBTpmvDIasoQL07BiUPM7NOB-6HiuiJsOCutPsfc2W5bg&oe=63AECFC2&_nc_sid=4f375e' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

INSTAGRAM POST TRYING TO FETCH

https://www.instagram.com/p/Cmgu8B7vAnH/?utm_source=ig_web_copy_link

Please Help, Thank You!

I Tried Adding This In Image But Not Able To Display the CDN Image in My Localhost...

```<code>crossorigin="anonymous"
</code>```

Please Help Me How To Solve This CORS Policy and Where To Add Your answer...

I'm a Beginners and trying to make a Instagram downloader tool.

Body:
I'm Getting this error while fetching Rapid API From Pure JavaScript.

I am using this API For Fetching Instagram Posts, Reels and more: https://rapidapi.com/arraybobo/api/instagram-media-downloader

HTML

Download Instagram Posts

    <input type="text" placeholder="Enter URL" />

    <button onclick="HandleReq()">Download</button>

CSS

 * {
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
          Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue",
          sans-serif;
      }
      body {
        padding: 20px 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }
      input {
        padding: 10px;
        border-radius: 5px;
        border: none;
        background: white;
        color: blue;
        border: 1px solid silver;
        width: 70%;
      }
      h1 {
        text-align: center;
      }
      button {
        padding: 10px 20px;
        border-radius: 5px;
        margin: 10px 10px;
        background: black;
        color: yellow;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
      }
      button:hover {
        background: yellow;
        color: black;
      }
      div {
        display: flex;
        justify-content: center;
        width: 90%;
        flex-direction: column;
        flex-wrap: wrap;
        text-align: center;
        object-fit: cover;
        overflow: scroll;
      }
      img {
        width: 400px;
        height: 400px;
      }
      @media only screen and (max-width: 768px) {
        body{
            padding: 10px;
        }
        div{
            width: 100%;
        }
        img{
            width: 95%;
            height: auto;
        }
      }

JAVASCRIPT

let content = document.getElementById("Info");
      function HandleReq() {
        const options = {
          method: "GET",
          headers: {
            "X-RapidAPI-Key":
              "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "X-RapidAPI-Host": "instagram-media-downloader.p.rapidapi.com",
          },
        };

        fetch(
          "https://instagram-media-downloader.p.rapidapi.com/rapid/post.php?url=https%3A%2F%2Fwww.instagram.com%2Fp%2FBhr1Ca9lcT0%2F",
          options
        )
          .then((response) => response.json())
          .then(
            (response) =>
              (content.innerHTML = `<img src=${response.image} crossorigin="anonymous"><br /><span>${response.caption}</span>`)
          )
          .catch((err) => console.error(err));
      }

ERROR:

Access to image at 'https://scontent-waw1-1.cdninstagram.com/v/t51.2885-15/30602671_1678191385592964_4808612725670281216_n.jpg?stp=dst-jpg_e35&_nc_ht=scontent-waw1-1.cdninstagram.com&_nc_cat=100&_nc_ohc=EgfXllD6SRkAX_J5kmD&edm=AP_V10EBAAAA&ccb=7-5&oh=00_AfBTpmvDIasoQL07BiUPM7NOB-6HiuiJsOCutPsfc2W5bg&oe=63AECFC2&_nc_sid=4f375e' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

INSTAGRAM POST TRYING TO FETCH

https://www.instagram.com/p/Cmgu8B7vAnH/?utm_source=ig_web_copy_link

Please Help, Thank You!

I Tried Adding This In Image But Not Able To Display the CDN Image in My Localhost...

crossorigin="anonymous"

Please Help Me How To Solve This CORS Policy and Where To Add Your answer...

I'm a Beginners and trying to make a Instagram downloader tool.


问:
How to attach to chrome from Running Object Table (ROT)? Interop GetActiveObject
I can not find to attach to chrome. How to GetActiveObject of Chrome and Dom Element access.</p>


问:
How could I close VsCode's Collapsible Block Comments"
When I open a new file, VsCode generally expands everything by default. When there is a large amount of code in a single file, I usually use ctrl+k, ctrl+ number to quickly collapse the specified level.

I love this feature, but it always collapses jsDoc comments, aka block comments or multiline comments.This makes the code unreadable, since a big part of the comment is for me to read.

For example：

VsCode's existing folding effects:

When I fold the code with ctrl+k, ctrl+ number, the jsDoc comment is folded like this.

The effect I want:

I want the comment code never to be folded when I fold the code.

All the articles on Google talk about folding comments, but I don't want to fold comments.
How can VsCode be set up so that it does not collapse multiple lines of comment code? Or it can be solved by a plug-in.

I did a lot of searches on Google and they all talked about how to fold comments, using //region to create a custom fold area, different from my question.

In VsCode, I found the "Collapse all block comments" shortcut, but not the "expand all block comments" shortcut


问:
Insert Data into Particular Rows from a Different Controller
I have two tables, InHandOrder & ExpRegistry. These table have a common column OrderNo.

When I insert data into the ExpRegistry table, it checks if InHandOrder table's OrderNo is equal to ExpRegistry table's OrderNo; if so, some of the column will automatically save into InHandOrder table that particular row in which OrderNo is matches.

I have tried something but data didn't save into the particular row but it's added a new row and save the data.

ExpRegistry controller class:

```<code>[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Create(ExpRegistry obj)
{
    if (ModelState.IsValid)
    {
        _unitOfWork.ExpRegistry.Add(obj);
        _unitOfWork.Save();

        IEnumerable<InHandOrder> objInHandOrderList = _unitOfWork.InHandOrder.GetAll().ToList();

        var checkOrderNo = objInHandOrderList.FirstOrDefault(i => i.OrderNo == obj.OrderNo);
        _unitOfWork.InHandOrder.Add(new InHandOrder()
            {
                InvoiceNo = obj.InvoiceNo,
                ShipQty = obj.ShipQty,
                InvoiceValue = obj.InvoiceValue
            });

        _unitOfWork.Save();

        return CreatedAtAction("GetDetails", new { id = obj.Id }, obj);
    }

    _logger.LogError($"Something went wrong in the {nameof(Create)}");
    return StatusCode(500, "Internal Server Error, Please Try Again Later!");
}
</code>```

InHandOrder model class:

```<code>public class InHandOrder
{
    [Key()]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    // Purchase Order
    public int? ContractListId { get; set; }

    [ForeignKey("ContractListId")]
    [ValidateNever]
    public ContractList? ContractList { get; set; }

    public string? OrderNo { get; set; }

    public int? StyleListId { get; set; }

    [ForeignKey("StyleListId")]
    [ValidateNever]
    public StyleList? StyleList { get; set; }

    public int? SeasonListId { get; set; }

    [ForeignKey("SeasonListId")]
    [ValidateNever]
    public SeasonList? SeasonList { get; set; }

    public DateTime? Shipment { get; set; }
    public int? TotalQuantity { get; set; }
    public decimal? UnitPrice { get; set; }
    public decimal? PoValue { get; set; }

    public int? CountryListId { get; set; }

    [ForeignKey("CountryListId")]
    [ValidateNever]
    public CountryList? CountryList { get; set; }

    // Export Register
    public string? InvoiceNo { get; set; }
    public int? ShipQty { get; set; }

    public decimal? InvoiceValue { get; set; }
    public decimal? ShortValue { get; set; }
    public int? ShortQty { get; set; }
}
</code>```

Here, InvoiceNo, ShipQty, InvoiceValue, shortValue, ShortQty fields will be saved when ExpRegistry is saved.

ExpRegistry model class:

```<code>public class ExpRegistry
{
    [Key]
    public int Id { get; set; }
    public int? PoId { get; set; }

    [DisplayName("Exp No")]
    public string? ExpNo { get; set; }
    [DisplayName("UNIT")]
    public int? UnitListId { get; set; }
    [ForeignKey("UnitListId")]
    [ValidateNever]
    public UnitList? UnitList { get; set; }

    [Display(Name = "DATE")] //EXP ISSUE DATE
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? ExpIssueDate { get; set; }

    [DisplayName("ORDER NO")]
    [ValidateNever]
    public string? OrderNo { get; set; }

    [DisplayName("INVOICE NO")]
    [ValidateNever]
    public string? InvoiceNo { get; set; }

    [DisplayName("SHIPPED QTY")]
    [ValidateNever]
    public int? ShipQty { get; set; }

    [DisplayName("VALUE")]
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
    [ValidateNever]
    public decimal? InvoiceValue { get; set; }
}
</code>```

Please Help me to solve the issue. Thank you.

Body:
I have two tables, InHandOrder & ExpRegistry. These table have a common column OrderNo.

When I insert data into the ExpRegistry table, it checks if InHandOrder table's OrderNo is equal to ExpRegistry table's OrderNo; if so, some of the column will automatically save into InHandOrder table that particular row in which OrderNo is matches.

I have tried something but data didn't save into the particular row but it's added a new row and save the data.

ExpRegistry controller class:

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Create(ExpRegistry obj)
{
    if (ModelState.IsValid)
    {
        _unitOfWork.ExpRegistry.Add(obj);
        _unitOfWork.Save();

        IEnumerable<InHandOrder> objInHandOrderList = _unitOfWork.InHandOrder.GetAll().ToList();

        var checkOrderNo = objInHandOrderList.FirstOrDefault(i => i.OrderNo == obj.OrderNo);
        _unitOfWork.InHandOrder.Add(new InHandOrder()
            {
                InvoiceNo = obj.InvoiceNo,
                ShipQty = obj.ShipQty,
                InvoiceValue = obj.InvoiceValue
            });

        _unitOfWork.Save();

        return CreatedAtAction("GetDetails", new { id = obj.Id }, obj);
    }

    _logger.LogError($"Something went wrong in the {nameof(Create)}");
    return StatusCode(500, "Internal Server Error, Please Try Again Later!");
}

InHandOrder model class:

public class InHandOrder
{
    [Key()]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    // Purchase Order
    public int? ContractListId { get; set; }

    [ForeignKey("ContractListId")]
    [ValidateNever]
    public ContractList? ContractList { get; set; }

    public string? OrderNo { get; set; }

    public int? StyleListId { get; set; }

    [ForeignKey("StyleListId")]
    [ValidateNever]
    public StyleList? StyleList { get; set; }

    public int? SeasonListId { get; set; }

    [ForeignKey("SeasonListId")]
    [ValidateNever]
    public SeasonList? SeasonList { get; set; }

    public DateTime? Shipment { get; set; }
    public int? TotalQuantity { get; set; }
    public decimal? UnitPrice { get; set; }
    public decimal? PoValue { get; set; }

    public int? CountryListId { get; set; }

    [ForeignKey("CountryListId")]
    [ValidateNever]
    public CountryList? CountryList { get; set; }

    // Export Register
    public string? InvoiceNo { get; set; }
    public int? ShipQty { get; set; }

    public decimal? InvoiceValue { get; set; }
    public decimal? ShortValue { get; set; }
    public int? ShortQty { get; set; }
}

Here, InvoiceNo, ShipQty, InvoiceValue, shortValue, ShortQty fields will be saved when ExpRegistry is saved.

ExpRegistry model class:

public class ExpRegistry
{
    [Key]
    public int Id { get; set; }
    public int? PoId { get; set; }

    [DisplayName("Exp No")]
    public string? ExpNo { get; set; }
    [DisplayName("UNIT")]
    public int? UnitListId { get; set; }
    [ForeignKey("UnitListId")]
    [ValidateNever]
    public UnitList? UnitList { get; set; }

    [Display(Name = "DATE")] //EXP ISSUE DATE
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? ExpIssueDate { get; set; }

    [DisplayName("ORDER NO")]
    [ValidateNever]
    public string? OrderNo { get; set; }

    [DisplayName("INVOICE NO")]
    [ValidateNever]
    public string? InvoiceNo { get; set; }

    [DisplayName("SHIPPED QTY")]
    [ValidateNever]
    public int? ShipQty { get; set; }

    [DisplayName("VALUE")]
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
    [ValidateNever]
    public decimal? InvoiceValue { get; set; }
}

Please Help me to solve the issue. Thank you.


问:
Invalid Datetime format: 1366 Incorrect integer value LARAVEL
I'm trying to update or insert multiple data when a post approve. Insert condition is working but update function giving error.

(SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer
value: '[10000,10000]' for column
parijattech_web_app.palika_to_school_kriyakalap.cash at row 3 update
palika_to_school_kriyakalap SET cash = [ 10000, 10000 ],
palika_to_school_kriyakalap.updated_at = 2022 -12 -26 04: 58: 52 WHERE
kriya_name IN (SALARY, POSHAK) AND school_id IN (24, 24))

My code is so messy. So, how can i improve my coding skill?

Here is my Controller

```<code>

public function approve(Request $request, $biniyojan_id)
{
    $upudate = DB::table('biniyojan')
    ->where('biniyojan_id', $biniyojan_id)
    ->update(['biniyojan_status' => 1]);

        if ($upudate) {
            $budget_data = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)->where('biniyojan_id', $biniyojan_id)->get();
            $kriya = Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
                ->whereIn('school_id', $budget_data->pluck('school_id'))
                ->get();

            $budget_cash = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)
                ->whereIn('school_id', $kriya->pluck('school_id'))
                ->whereIn('kriyakalap', $kriya->pluck('kriya_name'))
                ->get();

            $updated_bini = $budget_cash->pluck('cash')->toArray();
            $updated_kriya_cash = $kriya->pluck('cash')->toArray();

            $newArray = array_map(function () {
                return array_sum(func_get_args());
            }, $updated_bini, $updated_kriya_cash);

            if ($kriya->pluck('school_id') == $budget_data->pluck('school_id')) {

                Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
                    ->whereIn('school_id', $budget_data->pluck('school_id'))
                    ->update(['cash' => $newArray]);
            } else {

                foreach ($budget_data as $bud) {
                    $data = [
                        'school_id' => $bud->school_id,
                        'kriya_name' => $bud->kriyakalap,
                        'cash' => $bud->cash,
                    ];
                    Palika_ToSchool_Kriyakalap::where('kriya_name' != $bud->kriyakalap)
                        ->insert($data);
                }

            }
            return redirect()->back()->with('status', 'Approved!!!');
        }
        else{
            return redirect()->back()->with('error', 'Error!!!');
        }
}

</code>```

Body:
I'm trying to update or insert multiple data when a post approve. Insert condition is working but update function giving error.

(SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer
value: '[10000,10000]' for column
parijattech_web_app.palika_to_school_kriyakalap.cash at row 3 update
palika_to_school_kriyakalap SET cash = [ 10000, 10000 ],
palika_to_school_kriyakalap.updated_at = 2022 -12 -26 04: 58: 52 WHERE
kriya_name IN (SALARY, POSHAK) AND school_id IN (24, 24))

My code is so messy. So, how can i improve my coding skill?

Here is my Controller

public function approve(Request $request, $biniyojan_id)
{
    $upudate = DB::table('biniyojan')
    ->where('biniyojan_id', $biniyojan_id)
    ->update(['biniyojan_status' => 1]);

        if ($upudate) {
            $budget_data = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)->where('biniyojan_id', $biniyojan_id)->get();
            $kriya = Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
                ->whereIn('school_id', $budget_data->pluck('school_id'))
                ->get();

            $budget_cash = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)
                ->whereIn('school_id', $kriya->pluck('school_id'))
                ->whereIn('kriyakalap', $kriya->pluck('kriya_name'))
                ->get();

            $updated_bini = $budget_cash->pluck('cash')->toArray();
            $updated_kriya_cash = $kriya->pluck('cash')->toArray();

            $newArray = array_map(function () {
                return array_sum(func_get_args());
            }, $updated_bini, $updated_kriya_cash);

            if ($kriya->pluck('school_id') == $budget_data->pluck('school_id')) {

                Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
                    ->whereIn('school_id', $budget_data->pluck('school_id'))
                    ->update(['cash' => $newArray]);
            } else {

                foreach ($budget_data as $bud) {
                    $data = [
                        'school_id' => $bud->school_id,
                        'kriya_name' => $bud->kriyakalap,
                        'cash' => $bud->cash,
                    ];
                    Palika_ToSchool_Kriyakalap::where('kriya_name' != $bud->kriyakalap)
                        ->insert($data);
                }

            }
            return redirect()->back()->with('status', 'Approved!!!');
        }
        else{
            return redirect()->back()->with('error', 'Error!!!');
        }
}


问:
how to solve system.argumentexception parameter is not valid. at system.drawing.bitmap..ctor(int32 width, int32 height, pixelformat format)
i have a project that captures images by basler camera and for this i have a onimagegrabbed Function that grabs image.
while running my project in any cpu it i did not getting any error. but when i turned to x86 , project runs but after 2 or 3 seconds I am getting exception message " system.argumentexception parameter is not valid. at system.drawing.bitmap..ctor(int32 width, int32 height, pixelformat format) ."

also gettig this message in this in console tab
"Exception thrown: 'System.ArgumentException' in System.Drawing.dll"

the exception message screenshot is here

heres what i have tried

```<code>private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
        {
            bool invokeRequired = base.InvokeRequired;
            if (invokeRequired)
            {
                base.BeginInvoke(new EventHandler<ImageGrabbedEventArgs>(this.OnImageGrabbed), new object[]
                {
                    sender,
                    e.Clone()
                });
            }
            else
            {
                try
                {
                    this.grabResult = e.GrabResult;
                    bool isValid = this.grabResult.IsValid;
                    if (isValid)
                    {
                        bool flag = !this.stopWatch.IsRunning || this.stopWatch.ElapsedMilliseconds > 33L;
                        if (flag)
                        {
                            this.stopWatch.Restart();
                            Bitmap bitmap =  new Bitmap(this.grabResult.Width, this.grabResult.Height, PixelFormat.Format32bppRgb);
                            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                            this.converter.OutputPixelFormat = PixelType.BGRA8packed;
                            IntPtr scan = bitmapData.Scan0;
                            this.converter.Convert(scan, (long)(bitmapData.Stride * bitmap.Height), this.grabResult);
                            bitmap.UnlockBits(bitmapData);
                            object obj = this.lockObject;
                            lock (obj)
                            {
                                Bitmap bitmap2 = this.DisplayWindow.Image as Bitmap;
                                bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                this.gb = this.CreateNonIndexedImage(bitmap);
                                this.DisplayWindow.Image = bitmap;
                                bool flag3 = bitmap2 != null;
                                if (flag3)
                                {
                                    bitmap2.Dispose();

                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    e.DisposeGrabResultIfClone();
                }
            }
        }
</code>```

the line:150  is " Bitmap bitmap =  new Bitmap(this.grabResult.Width, this.grabResult.Height, PixelFormat.Format32bppRgb);"

Body:
i have a project that captures images by basler camera and for this i have a onimagegrabbed Function that grabs image.
while running my project in any cpu it i did not getting any error. but when i turned to x86 , project runs but after 2 or 3 seconds I am getting exception message " system.argumentexception parameter is not valid. at system.drawing.bitmap..ctor(int32 width, int32 height, pixelformat format) ."

also gettig this message in this in console tab
"Exception thrown: 'System.ArgumentException' in System.Drawing.dll"

the exception message screenshot is here

heres what i have tried

private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
        {
            bool invokeRequired = base.InvokeRequired;
            if (invokeRequired)
            {
                base.BeginInvoke(new EventHandler<ImageGrabbedEventArgs>(this.OnImageGrabbed), new object[]
                {
                    sender,
                    e.Clone()
                });
            }
            else
            {
                try
                {
                    this.grabResult = e.GrabResult;
                    bool isValid = this.grabResult.IsValid;
                    if (isValid)
                    {
                        bool flag = !this.stopWatch.IsRunning || this.stopWatch.ElapsedMilliseconds > 33L;
                        if (flag)
                        {
                            this.stopWatch.Restart();
                            Bitmap bitmap =  new Bitmap(this.grabResult.Width, this.grabResult.Height, PixelFormat.Format32bppRgb);
                            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                            this.converter.OutputPixelFormat = PixelType.BGRA8packed;
                            IntPtr scan = bitmapData.Scan0;
                            this.converter.Convert(scan, (long)(bitmapData.Stride * bitmap.Height), this.grabResult);
                            bitmap.UnlockBits(bitmapData);
                            object obj = this.lockObject;
                            lock (obj)
                            {
                                Bitmap bitmap2 = this.DisplayWindow.Image as Bitmap;
                                bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                this.gb = this.CreateNonIndexedImage(bitmap);
                                this.DisplayWindow.Image = bitmap;
                                bool flag3 = bitmap2 != null;
                                if (flag3)
                                {
                                    bitmap2.Dispose();

                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    e.DisposeGrabResultIfClone();
                }
            }
        }

the line:150  is " Bitmap bitmap =  new Bitmap(this.grabResult.Width, this.grabResult.Height, PixelFormat.Format32bppRgb);"


问:
How to search for profiles in firestore using vue
I'm Trying to be able to search for specific profiles in a database but I don't know how to get what I put into the input field to return the profiles close to what has been typed in heres what I have so Far hopefully it will make more sense.

```<code><script>

import { ref } from 'vue'
import getPremium from "../Composables/getPremium.js";
import getStandard from "../Composables/getStandard.js";
import getBasic from "../Composables/getBasic.js";
import { computed } from 'vue'
import getCollection from '../Composables/getCollection';
const {Premium} = getPremium();
const selectedProfile = ref(Premium)
const query = ref('')
const filteredPeople = computed(() =>
    query.value === ''
      ? Premium
      : Premium.filter((person) => {
          return person.toLowerCase().includes(query.value.toLowerCase())
        })
  )

export default {
    setup() {

const { documents: Premium } = getCollection(
      'Premium',
      ['name', '==', selectedProfile.value]
    )

    return { Premium, selectedProfile }

    }
}

</script>

<template>
<p>home comoonent</p>
<form>
  <div class="inline-block">
    <Input v-model="selectedProfile" @change="query = $event.target.value" placeholder="  Search Escort Name" class="h-7 bg-neutral-700 text-neutral-400 m-4 inline-flex rounded"/>

        {{ person }}

    </div>
  </form>
 <p>Escorts</p>
 <div class="grid gap-x-4 grid-cols-2 grid-rows-fit mx-5 md:grid md:gap-2 md:grid-cols-4 md:grid-rows-fit md:mx-20 lg:grid lg:gap-4 lg:grid-cols-4 lg:grid-rows-fit lg:mx-20 xl:grid xl:gap-4 xl:grid-cols-4 xl:grid-rows-fit xl:mx-20 2xl:grid 2xl:gap-4 2xl:grid-cols-4 2xl:grid-rows-fit 2xl:mx-20">

 <div v-for =" Premiums in Premium" :key="Premiums.id" >
 <router-link :to="{ name: 'Samplepremium', params: { id: Premiums.id }}">
 <div class= "hover:scale-105 transition ease-in-out duration-300 bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-900 text-neutral-400 font-bold rounded-xl">
  <br>
     <p>{{ Premiums.name }}</p>
     <img :src= "Premiums.Pic1"  class="object-contain ml-6 w-60 h-80 transition ease-in-out duration-300">
     <div class="grid grid-cols-2 grid-rows-fit text-left ml-6">

     <p>name:</p>
     <p>{{ Premiums.name }}</p>

    </div><br>
  </div>
  </router-link>
  </div>
</code>```

So I realise that if I have the name == selectedProfile it wont get any close searchs only a specific profile names I'm just unsure how I can combine the filteredPeople into the query and how to stop the page from reloading and deleting whats in the input field every time I try and enter a search.
I hope what I've shown makes some sense and that someone might have any ideas on how to do this any help what be greatly appreciated thanks.

Body:
I'm Trying to be able to search for specific profiles in a database but I don't know how to get what I put into the input field to return the profiles close to what has been typed in heres what I have so Far hopefully it will make more sense.

<template>

home comoonent

<form>

    <Input v-model="selectedProfile" @change="query = $event.target.value" placeholder="  Search Escort Name" class="h-7 bg-neutral-700 text-neutral-400 m-4 inline-flex rounded"/>

        {{ person }}

  </form>

Escorts

 <router-link :to="{ name: 'Samplepremium', params: { id: Premiums.id }}">

{{ Premiums.name }}

name:

{{ Premiums.name }}

  </router-link>

So I realise that if I have the name == selectedProfile it wont get any close searchs only a specific profile names I'm just unsure how I can combine the filteredPeople into the query and how to stop the page from reloading and deleting whats in the input field every time I try and enter a search.
I hope what I've shown makes some sense and that someone might have any ideas on how to do this any help what be greatly appreciated thanks.


问:
Eliminate port in the url with nginx
`I want to connect to containers via nginx location blocks without making the port visible in the url for a large scale application my current block is:

```<code>location ~"/name/(.*)/(.*)/([0-9])/"{
set port $3;
proxy_pass http://128.0.0.7:$port;
proxy_header Host $host;
}
</code>```

I want to access the url /name/(.)/(.)/([0-9])/ with this (.*) unique id instead of ([0-9]) port
`

Title: Eliminate port in the url with nginx

Body:
`I want to connect to containers via nginx location blocks without making the port visible in the url for a large scale application my current block is:

location ~"/name/(.*)/(.*)/([0-9])/"{
set port $3;
proxy_pass http://128.0.0.7:$port;
proxy_header Host $host;
}

I want to access the url /name/(.)/(.)/([0-9])/ with this (.*) unique id instead of ([0-9]) port
`


问:
How to keep a React component running in the background for report generation while navigating to other screens?
I am generating a report for multiple datasets by overlaying WMS images from GeoServer as a slideshow and taking screenshots using the html2canvas library.

The problem is that if the user navigates to another component or screen, then the slideshow component unmounts and report generation stops. Is there a way to keep the slideshow component running in the background using React.Suspense or any other method?

Here is an example of the component that is generating the report:

```<code>import React, { useEffect } from 'react';
import html2canvas from 'html2canvas';

function ReportGenerator() {
  useEffect(() => {
    // Load WMS layers and take screenshots
    // ...
  }, []);

  return (
    <div>
      {/* Map and WMS layers */}
    </div>
  );
}

export default ReportGenerator;

</code>```

Is there any other way or a better way to handle this issue?

To give you a better overview of my component structure, it is set up as follows:

```<code>App
|____Switch
|     |___Route
|     |    |___MapScreen
|     |            |____ Layout
|     |                     |____Sidebar
|     |                     |____Main
|     |                              |____Wrapper
|     |                                       |_____MapLayout
|     |                                       |_____ReportGenerator
|     |___Route
|     |     |___DashboardScreen
|     |              |____ Layout
|     |                       |__Sidebar
|     |                       |____Main
|     |                            |_____NewsFeedList
|     |                                       |_____DataCard
|     |                                       |_____Buttons
</code>```

Body:
I am generating a report for multiple datasets by overlaying WMS images from GeoServer as a slideshow and taking screenshots using the html2canvas library.

The problem is that if the user navigates to another component or screen, then the slideshow component unmounts and report generation stops. Is there a way to keep the slideshow component running in the background using React.Suspense or any other method?

Here is an example of the component that is generating the report:

import React, { useEffect } from 'react';
import html2canvas from 'html2canvas';

function ReportGenerator() {
  useEffect(() => {
    // Load WMS layers and take screenshots
    // ...
  }, []);

  return (

      {/* Map and WMS layers */}

  );
}

export default ReportGenerator;

Is there any other way or a better way to handle this issue?

To give you a better overview of my component structure, it is set up as follows:

App
|____Switch
|     |___Route
|     |    |___MapScreen
|     |            |____ Layout
|     |                     |____Sidebar
|     |                     |____Main
|     |                              |____Wrapper
|     |                                       |_____MapLayout
|     |                                       |_____ReportGenerator
|     |___Route
|     |     |___DashboardScreen
|     |              |____ Layout
|     |                       |__Sidebar
|     |                       |____Main
|     |                            |_____NewsFeedList
|     |                                       |_____DataCard
|     |                                       |_____Buttons