问:
How to use GRIDLAYOUT dynamically to add views of different sizes? Android Studio
I am trying to make layout like this

I am trying to use GridLayout to achieve this but the issue I am getting is some buttons are small in size and some are bigger in size. For the small size buttons it should move the next button closer to the last button but its not doing that. Its doing this

Any Idea of how to achieve this with Grid Layout or any other layout. This is the code for grid layout I am using

```<code>    <GridLayout
        android:layout_width="match_parent"
        android:layout_marginTop="@dimen/_16ssp"
        android:columnCount="3"

        android:layout_marginHorizontal="@dimen/_16ssp"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="ALL"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>

    </GridLayout>
</code>```

Body:
I am trying to make layout like this

I am trying to use GridLayout to achieve this but the issue I am getting is some buttons are small in size and some are bigger in size. For the small size buttons it should move the next button closer to the last button but its not doing that. Its doing this

Any Idea of how to achieve this with Grid Layout or any other layout. This is the code for grid layout I am using

    <GridLayout
        android:layout_width="match_parent"
        android:layout_marginTop="@dimen/_16ssp"
        android:columnCount="3"

        android:layout_marginHorizontal="@dimen/_16ssp"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="ALL"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/_16ssp"
            android:layout_marginTop="@dimen/_16ssp"
            android:background="@drawable/grey_20dp_10op"
            android:paddingHorizontal="@dimen/_32ssp"
            android:paddingVertical="@dimen/_8ssp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Default"

                android:textColor="@color/black"
                android:textSize="@dimen/_12ssp"></TextView>
        </LinearLayout>

    </GridLayout>


来源: stackexchange

问:
Node, Ejs, Express, passing variables to partial views. issues with re-using the same code in the express routes. Need to condense code
I am a newbie to node, express and ejs. I am creating a blog website project.  I want to make use of EJS partials to stop repeating elements of code on my website. The simplified structure is

Blog

--js

--sql-helpers.js

--routes

--routes.js

--views

--homepage.ejs

--aboutpage.ejs

--header(Partial).ejs

The partial header ejs file is to be used on all webpages as it displays the title and author of the blog.

Here is a snippet of code from the routes file:

routes.js

```<code>router.get('/homepage', (req, res) => {

    const sql = 'SELECT * FROM authors';

    global.db.all(sql,[], function(err,rows){

          const blogInfo = rows[0];

          const params = {
            authorName:blogInfo.author_name,
            authorBlogTitle:blogInfo.authors_blog_title,
            authorSubtitle:blogInfo.authors_blog_subtitle
          };

        res.render('homepage', params);
      });

});

router.get('/aboutpage', (req,res) => {

  const sql = 'SELECT * FROM authors';

  global.db.all(sql,[], function(err,rows){

        const blogInfo = rows[0];

        const params = {
          authorName:blogInfo.author_name,
          authorBlogTitle:blogInfo.authors_blog_title,
          authorSubtitle:blogInfo.authors_blog_subtitle
        };

      res.render('aboutpage', params);
    });

});
</code>```

As you can see I am having to re-use the same code in each of the routes to fill the variables in the header(partial).ejs file.

The homepage.ejs file code is as follows:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <%- include('header(Partial)') %>
</body>
</html>
</code>```

The header(partial).ejs file looks like this:

```<code><header>
    <section>
        <h1 ><strong><%= authorBlogTitle %></strong></h1>
        <span><%= authorSubtitle %></span>
        <p ><small><%= authorName %></small></p>
    </section>
</header>
</code>```

To try and stop re-peating the same code i created a sql-helpers js file. as follows

```<code>const blogheader = function(callback){
    const sql = 'SELECT * FROM authors';

    global.db.all(sql,[], function(err,rows){

          const blogInfo = rows[0];

          const params = {
            authorName:blogInfo.author_name,
            authorBlogTitle:blogInfo.authors_blog_title,
            authorSubtitle:blogInfo.authors_blog_subtitle
          };
          callback(params);
      });

}

module.exports = {blogheader};
</code>```

updated routes.js file:

```<code>const helpers = require("../public/js/sql_scripts");

router.get('/settings', (req,res) => {

  let bloginfo = helpers.blogheader()

      res.render('settings', blogheader);

});

</code>```

My problems is I when i try and use this sql helper function in the routes I am getting a undefined value. Is this the best way to do it? How can wrap up my sql query so i dont have to repeat the same code in the routes? Is there a better way to use ejs partials?

I have been stuck on this issue for a number of days, searching the internet for an answer but I just havent found anything that helps me.

ContentLicense: CC BY-SA 4.0

Body:
I am a newbie to node, express and ejs. I am creating a blog website project.  I want to make use of EJS partials to stop repeating elements of code on my website. The simplified structure is

Blog

--js

--sql-helpers.js

--routes

--routes.js

--views

--homepage.ejs

--aboutpage.ejs

--header(Partial).ejs

The partial header ejs file is to be used on all webpages as it displays the title and author of the blog.

Here is a snippet of code from the routes file:

routes.js

router.get('/homepage', (req, res) => {

    const sql = 'SELECT * FROM authors';

    global.db.all(sql,[], function(err,rows){

          const blogInfo = rows[0];

          const params = {
            authorName:blogInfo.author_name,
            authorBlogTitle:blogInfo.authors_blog_title,
            authorSubtitle:blogInfo.authors_blog_subtitle
          };

        res.render('homepage', params);
      });

});

router.get('/aboutpage', (req,res) => {

  const sql = 'SELECT * FROM authors';

  global.db.all(sql,[], function(err,rows){

        const blogInfo = rows[0];

        const params = {
          authorName:blogInfo.author_name,
          authorBlogTitle:blogInfo.authors_blog_title,
          authorSubtitle:blogInfo.authors_blog_subtitle
        };

      res.render('aboutpage', params);
    });

});

As you can see I am having to re-use the same code in each of the routes to fill the variables in the header(partial).ejs file.

The homepage.ejs file code is as follows:

<!DOCTYPE html>

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

    <%- include('header(Partial)') %>

The header(partial).ejs file looks like this:

<%= authorBlogTitle %>

        <%= authorSubtitle %>

<%= authorName %>

To try and stop re-peating the same code i created a sql-helpers js file. as follows

const blogheader = function(callback){
    const sql = 'SELECT * FROM authors';

    global.db.all(sql,[], function(err,rows){

          const blogInfo = rows[0];

          const params = {
            authorName:blogInfo.author_name,
            authorBlogTitle:blogInfo.authors_blog_title,
            authorSubtitle:blogInfo.authors_blog_subtitle
          };
          callback(params);
      });

}

module.exports = {blogheader};

updated routes.js file:

const helpers = require("../public/js/sql_scripts");

router.get('/settings', (req,res) => {

  let bloginfo = helpers.blogheader()

      res.render('settings', blogheader);

});

My problems is I when i try and use this sql helper function in the routes I am getting a undefined value. Is this the best way to do it? How can wrap up my sql query so i dont have to repeat the same code in the routes? Is there a better way to use ejs partials?

I have been stuck on this issue for a number of days, searching the internet for an answer but I just havent found anything that helps me.


问:
Tensorflow warning: W tensorflow/core/data/root_dataset.cc:200] Optimization loop failed: CANCELLED: Operation was cancelled
I am getting this error when performing a custom training over a model, but the training seems to continue anyway... Is is something I should be worried about?

I tried with several batch size and learning rates, and more hyperparameter combination in general. The data is previously converted to tensorflow datasets before feeding them to the model


问:
How show absolute element outside cdk-virtual-scroll-viewport Angular
How can an element that is inside a cdk-virtual-scroll-viewport be superimposed and enlarged to go beyond cdk-virtual-scroll-viewport. At the same time, the cdk-virtual-scroll-viewport itself is located inside the mat-accordion. Also a tip how to take into account greater nesting when positioning. There is an option with absolute positioning, but because of the nesting is not clear where to put.[enter image description here](https://i.stack.imgur.com/S08AP.png)

The attempted scalable element is absolutely positioned, but it only cut out from the streams lement and cast under the bottom and did not lead beyond the virtual-scroll itself


问:
Material UI Grid doesn't strecth to full parent height
I am using Next.js and Material UI for a project.

My issue is that When Im using Material UI grid it doesn't stretch to its parent full Height.

Here is my index.tsx code:

```<code>import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useState } from 'react'

import Login from './login'

export default function Home() {
  const [isConnected, setIsConnected] = useState(false)
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main style={{height: "100%", backgroundColor: "red"}}>
        {isConnected? "AAA" : <Login/>}
      </main>
    </>
  )
}

</code>```

Here is my Login page code:

```<code>import { useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';

import styles from '../styles/Login.module.css'
import { Grid } from '@mui/material';
import { height } from '@mui/system';

interface LoginPageProps {
  // Props go here
}

interface LoginPageState {
  username: string;
  password: string;
}

const LoginPage: React.FC<LoginPageProps> = (props: LoginPageProps) => {
  const [state, setState] = useState<LoginPageState>({
    username: '',
    password: '',
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    if (name === 'username') {
      setState({ ...state, username: value });
    } else if (name === 'password') {
      setState({ ...state, password: value });
    }
  };

  const handleSignup = () => {
    // Handle signup here
  };

  const handleSignin = () => {
    // Handle signin here
  };

  return (
    <Grid container
      direction="row"
      justifyContent="center"
      alignItems="stretch" xs={12} sm={12} md={12}
      style={{
        backgroundColor: "green"
      }}
    >
      <Grid item md={6}
      direction="column"
      >
        <Grid item xs={12} sm={12} md={12}>
          <Box
            className="form"
            component="form"
            sx={{
              height: "100%",
            }}
          >
            <div
            >
              <TextField
                label="Username"
                variant="outlined"
                name="username"
                value={state.username}
                onChange={handleChange}
                fullWidth
              />
              <TextField
                label="Password"
                variant="outlined"
                type="password"
                name="password"
                value={state.password}
                onChange={handleChange}
                fullWidth
                margin="normal"
              />
              <div />
              <Button className="signup" variant="contained" color="primary" onClick={handleSignup}>
                Sign Up
              </Button>
              <Button className="signin" variant="contained" color="secondary" onClick={handleSignin}>
                Sign In
              </Button>
            </div>
          </Box>
        </Grid>
      </Grid>
      <Grid item xs={6} sm={6} md={6}>
        design
      </Grid>
    </Grid>
  );
};

export default LoginPage;

</code>```

Here is my global.css file and its the only styling not applied inline:

```<code>html, body, #__next {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
</code>```

Im adding an img to clarify my issue.

red background is the main html tag - the parent

green background is the grid material ui component - the child

how to make the green component (the child) stretch its entire parent height?

Body:
I am using Next.js and Material UI for a project.

My issue is that When Im using Material UI grid it doesn't stretch to its parent full Height.

Here is my index.tsx code:

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useState } from 'react'

import Login from './login'

export default function Home() {
  const [isConnected, setIsConnected] = useState(false)
  return (
    <>

        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />

        {isConnected? "AAA" : <Login/>}

    </>
  )
}

Here is my Login page code:

import { useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';

import styles from '../styles/Login.module.css'
import { Grid } from '@mui/material';
import { height } from '@mui/system';

interface LoginPageProps {
  // Props go here
}

interface LoginPageState {
  username: string;
  password: string;
}

const LoginPage: React.FC<LoginPageProps> = (props: LoginPageProps) => {
  const [state, setState] = useState<LoginPageState>({
    username: '',
    password: '',
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    if (name === 'username') {
      setState({ ...state, username: value });
    } else if (name === 'password') {
      setState({ ...state, password: value });
    }
  };

  const handleSignup = () => {
    // Handle signup here
  };

  const handleSignin = () => {
    // Handle signin here
  };

  return (
    <Grid container
      direction="row"
      justifyContent="center"
      alignItems="stretch" xs={12} sm={12} md={12}
      style={{
        backgroundColor: "green"
      }}
    >
      <Grid item md={6}
      direction="column"
      >
        <Grid item xs={12} sm={12} md={12}>
          <Box
            className="form"
            component="form"
            sx={{
              height: "100%",
            }}
          >

              <TextField
                label="Username"
                variant="outlined"
                name="username"
                value={state.username}
                onChange={handleChange}
                fullWidth
              />
              <TextField
                label="Password"
                variant="outlined"
                type="password"
                name="password"
                value={state.password}
                onChange={handleChange}
                fullWidth
                margin="normal"
              />

              <Button className="signup" variant="contained" color="primary" onClick={handleSignup}>
                Sign Up
              </Button>
              <Button className="signin" variant="contained" color="secondary" onClick={handleSignin}>
                Sign In
              </Button>

          </Box>
        </Grid>
      </Grid>
      <Grid item xs={6} sm={6} md={6}>
        design
      </Grid>
    </Grid>
  );
};

export default LoginPage;

Here is my global.css file and its the only styling not applied inline:

html, body, #__next {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

Im adding an img to clarify my issue.

red background is the main html tag - the parent

green background is the grid material ui component - the child

how to make the green component (the child) stretch its entire parent height?


问:
How to get Video views count from Instgram Grapgh API in Android?
I am trying to fetch the Video Views count from Instagram API, but I can't find any API that provides the video counts, I have found this answer on Stackoverflow [How to retrieve video view count from Instagram API][1]

[1]: How to retrieve video view count from Instagram API but it doesn't work and gives me this error and response code

```<code>    {
"error": {
"message": "(#200) Provide valid app ID",
"type": "OAuthException",
"code": 200,
"fbtrace_id": "AZJFNJL_G3KzPu7VWUDlzsT"
}
}
</code>```

I can't even find this Instagram API on the documentation at all, How I can get the video views count from the video URl using Instgram Grapgh API? and does instgram provide this?

Body:
I am trying to fetch the Video Views count from Instagram API, but I can't find any API that provides the video counts, I have found this answer on Stackoverflow [How to retrieve video view count from Instagram API][1]

[1]: How to retrieve video view count from Instagram API but it doesn't work and gives me this error and response code

    {
"error": {
"message": "(#200) Provide valid app ID",
"type": "OAuthException",
"code": 200,
"fbtrace_id": "AZJFNJL_G3KzPu7VWUDlzsT"
}
}

I can't even find this Instagram API on the documentation at all, How I can get the video views count from the video URl using Instgram Grapgh API? and does instgram provide this?


问:
Node:events 491 happening when trying to run loadtest -n 300 http://localhost:3000
I am trying to run a sample nodejs application I saw on a video tutorial, and it is about simulating traffic on a server. But when I execute the above command given by the proctor, it creates an error.

Here is my code

```<code>const numCpus = require("os").cpus().length
const cluster = require("cluster");
const { createServer } = require("http");

if (cluster.isMaster) {
    console.log(`This is the master process`, process.pid);
    for(let i = 0; i < numCpus; i++ ) {
        cluster.fork();
    }

}
else {
    createServer((req,res) => {
        const message = `worker process ${process.pid}`
        console.log(message);
        res.end(message)
    }).listen(3000)
}

</code>```

and after I run

loadtest -n 300 http://localhost:3000

this error shows up

```<code>node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: read ENOTCONN
    at tryReadStart (node:net:674:20)
    at Socket._read (node:net:685:5)
    at Readable.read (node:internal/streams/readable:496:12)
    at Socket.read (node:net:741:39)
    at resume_ (node:internal/streams/readable:999:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on WriteStream instance at:
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  errno: -4053,
  code: 'ENOTCONN',
  syscall: 'read'
}
</code>```

Body:
I am trying to run a sample nodejs application I saw on a video tutorial, and it is about simulating traffic on a server. But when I execute the above command given by the proctor, it creates an error.

Here is my code

const numCpus = require("os").cpus().length
const cluster = require("cluster");
const { createServer } = require("http");

if (cluster.isMaster) {
    console.log(`This is the master process`, process.pid);
    for(let i = 0; i < numCpus; i++ ) {
        cluster.fork();
    }

}
else {
    createServer((req,res) => {
        const message = `worker process ${process.pid}`
        console.log(message);
        res.end(message)
    }).listen(3000)
}

and after I run

loadtest -n 300 http://localhost:3000

this error shows up

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: read ENOTCONN
    at tryReadStart (node:net:674:20)
    at Socket._read (node:net:685:5)
    at Readable.read (node:internal/streams/readable:496:12)
    at Socket.read (node:net:741:39)
    at resume_ (node:internal/streams/readable:999:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on WriteStream instance at:
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  errno: -4053,
  code: 'ENOTCONN',
  syscall: 'read'
}


问:
Modelica : Use interval as a parameter : how to do?
So, i'm a beginner with modelica and I am using  some clocked blocks for my model (i know that's not very good to have discrete behavior, but i am not enough good to avoid this...).

Now I have a periodicRealClock and I would like this clock to have the "Interval" parameter of the simulation.

Do you know how to use this simulation paramater as a block paramater ?

Thks for your help.

I tried with "Interval" but it not works (parameter doesn't exist)...


问:
Unable to integrate jQuery and Bootstrap in Spring Boot with JSP
I am getting following error on browser console as:

Following is my directory structure:

And I have tried adding these resources in the head tag and at the bottom as well. My JSP page is:

```<code><html>
<head>
<%@ include file="/WEB-INF/jsp/components/static-includes-top.jsp"%>
<meta charset="ISO-8859-1">
<title>DevHub</title>
</head>
<body>
    <h1 class="home">Home</h1>
    <div id="main-content-wrapper">
    </div>
    <%@ include file="/WEB-INF/jsp/components/static-includes-bottom.jsp"%>
</body>
</html>
</code>```

Where head tag has static-includes-top.jsp which is:

```<code><!-- Bootstrap 4.0-->
<link rel="stylesheet" type="text/css" href="<c:url value="/resources/static/default/assets/vendor_components/bootstrap/dist/css/bootstrap.css"/>" />

<!-- Bootstrap 4.0-->
<link rel="stylesheet" type="text/css" href="<c:url value="/resources/static/default/assets/vendor_components/bootstrap/dist/css/bootstrap-extend.css"/>" />

<!-- date picker -->
<link rel="stylesheet" type="text/css" href="<c:url value="/resources/static/default/assets/vendor_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css"/>" />
</code>```

And at the Bottom I have static-includes-bottom.jsp which is:

```<code><!-- jQuery 3 -->
<script type="text/javascript" src="<c:url value="/resources/static/default/assets/vendor_components/jquery/dist/jquery.min.js"></c:url>"></script>

<!-- Bootstrap 4.0-->
<script type="text/javascript" src="<c:url value="/resources/static/default/assets/vendor_components/bootstrap/dist/js/bootstrap.min.js"></c:url>"></script>

<!-- datepicker -->
<script type="text/javascript" src="<c:url value="/resources/static/default/assets/vendor_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></c:url>"></script>
</code>```

What am I doing wrong?

Body:
I am getting following error on browser console as:

Following is my directory structure:

And I have tried adding these resources in the head tag and at the bottom as well. My JSP page is:

<%@ include file="/WEB-INF/jsp/components/static-includes-top.jsp"%>
<meta charset="ISO-8859-1">
<title>DevHub</title>

Home

    <%@ include file="/WEB-INF/jsp/components/static-includes-bottom.jsp"%>

Where head tag has static-includes-top.jsp which is:

<link rel="stylesheet" type="text/css" href="<c:url value="/resources/static/default/assets/vendor_components/bootstrap/dist/css/bootstrap.css"/>" />

<link rel="stylesheet" type="text/css" href="<c:url value="/resources/static/default/assets/vendor_components/bootstrap/dist/css/bootstrap-extend.css"/>" />

<link rel="stylesheet" type="text/css" href="<c:url value="/resources/static/default/assets/vendor_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css"/>" />

And at the Bottom I have static-includes-bottom.jsp which is:

What am I doing wrong?


问:
How to translate text in ngTenplateOutletContext
```<code>
<ng-container   *ngSwitchCase="Notification.BLOCKED_DEVICE"

    [ngTemplateOutlet]="notificationInfo"

    [ngTemplateOutletContext]="{

      title: 'Device Blocked',

      description: 'Device is being blocked'

    }"

  ></ng-container>
</code>```

NotificationInfo has the following template

```<code>
 <ng-template #notificationInfo>

   <ng-template #notificationInfo let-title="title" let-description="description">

     <span *ngIf="output === 'title'">{{ title }}</span>

     <span *ngIf="output === 'description'">{{ description }}</span>

   </ng-template>

 </ng-template>
</code>```

I changed that to following

```<code>
 <ng-container *ngIf="USE_I18N; else notificationInfo">

 <ng-template #notificationInfoi18n let-title="title" let-description="description">

   <span i18n

 [appTranslate]="output === 'title'"

   >__TITLE__</span

 >

 <span i18n

 [appTranslate]="output === 'description'"

   >__DESCRIPTION__</span

 >

 </ng-template>

 </ng-container>
</code>```

If it was a
 or <h> I usually do <h i18n appTranslate>abc</h> This is my first time doing internationalization. I was thinking to define a set of objects with those properties in the class that could be used as a values when we switch case in the template.

Body:
<ng-container   *ngSwitchCase="Notification.BLOCKED_DEVICE"

    [ngTemplateOutlet]="notificationInfo"

    [ngTemplateOutletContext]="{

      title: 'Device Blocked',

      description: 'Device is being blocked'

    }"

  ></ng-container>

NotificationInfo has the following template

 <ng-template #notificationInfo>

   <ng-template #notificationInfo let-title="title" let-description="description">

     {{ title }}

     {{ description }}

   </ng-template>

 </ng-template>

I changed that to following

 <ng-container *ngIf="USE_I18N; else notificationInfo">

 <ng-template #notificationInfoi18n let-title="title" let-description="description">

   __TITLE__

 __DESCRIPTION__

 </ng-template>

 </ng-container>

If it was a
 or <h> I usually do <h i18n appTranslate>abc</h> This is my first time doing internationalization. I was thinking to define a set of objects with those properties in the class that could be used as a values when we switch case in the template.


问:
I can't transfer data between angular components. I can't Decode data transfer between angular components
I want to transfer data between two components in my Angular project, I use @input for this, but when I navigate to the component I want to transfer with navigateByUrl, the data I send to the component is reset, how can I fix this?</p>
```<code>Code ;
Child Component :
  @Input() isModelist : boolean

parent Component :
            <sample-measurement-table [isModelist]="true"></sample-measurement-table>
</code>```

Body:
I want to transfer data between two components in my Angular project, I use @input for this, but when I navigate to the component I want to transfer with navigateByUrl, the data I send to the component is reset, how can I fix this?

Code ;
Child Component :
  @Input() isModelist : boolean

parent Component :
            <sample-measurement-table [isModelist]="true"></sample-measurement-table>


问:
Opening an Excel File in Python Disables Dynamic Arrays
I have an excel workbook that uses functions like OFFSET, UNIQUE, and FILTER which spill into other cells. I'm using python to analyze and write some data to the workbook, but after doing so these formulas revert into normal arrays. This means they now take up a fixed number of cells (however many they took up before opening the file in python) instead of adjusting to fit all of the data. I can revert the change by selecting the formula and hitting enter, but there are many of these formulas it's more work to fix them than to just print the data to a text file and paste it into excel manually. Is there any way to prevent this behavior?

I've been using openpyxl to open and save the workbook, but after encountering this issue also tried xlsxwriter and the dataframe to excel function from pandas. Both of them had the same issue as openpyxl. For context I am on python 3.11 and using the most recent version of these modules. I believe this issue is on the Python side and not the Excel side, so I don't think changing Excel settings will help, but maybe there is something there I missed.

Example:

I've created an empty workbook with two sheets, one called 'main' and one called 'input'. The 'main' sheet will analyze data from the 'input' sheet which will be entered with openpyxl. The data will just be values in the first column.

In cell A1 of the 'main' sheet, enter =OFFSET(input!A1,0,0,COUNTA(input!A:A),1).
This formula will just show a copy of the data. Since there currently isn't any data it gives a #REF! error, so it only takes up one cell.

Now I'll run the following python code to add the numbers 0-9 into the first column of the input sheet:

```<code>from openpyxl import load_workbook

wb = load_workbook('workbook.xlsx')
ws = wb['input']
for i in range(10):
    ws.append([i])

wb.save('workbook_2.xlsx')
</code>```

When opening the new file, cell A1 on the 'main' sheet only has the first value, 0, instead of the range 0--9. When selecting the cell, you can see the formula is now {=OFFSET(input!A1,0,0,COUNTA(input!A:A),1)}. The curly brackets make it an array, so it wont spill. By hitting enter in the formula the array is removed and the sheet properly becomes the full range.

If I can get this simple example to work, then expanding it to the data I'm using shouldn't be a problem.

Body:
I have an excel workbook that uses functions like OFFSET, UNIQUE, and FILTER which spill into other cells. I'm using python to analyze and write some data to the workbook, but after doing so these formulas revert into normal arrays. This means they now take up a fixed number of cells (however many they took up before opening the file in python) instead of adjusting to fit all of the data. I can revert the change by selecting the formula and hitting enter, but there are many of these formulas it's more work to fix them than to just print the data to a text file and paste it into excel manually. Is there any way to prevent this behavior?

I've been using openpyxl to open and save the workbook, but after encountering this issue also tried xlsxwriter and the dataframe to excel function from pandas. Both of them had the same issue as openpyxl. For context I am on python 3.11 and using the most recent version of these modules. I believe this issue is on the Python side and not the Excel side, so I don't think changing Excel settings will help, but maybe there is something there I missed.

Example:

I've created an empty workbook with two sheets, one called 'main' and one called 'input'. The 'main' sheet will analyze data from the 'input' sheet which will be entered with openpyxl. The data will just be values in the first column.

In cell A1 of the 'main' sheet, enter =OFFSET(input!A1,0,0,COUNTA(input!A:A),1).
This formula will just show a copy of the data. Since there currently isn't any data it gives a #REF! error, so it only takes up one cell.

Now I'll run the following python code to add the numbers 0-9 into the first column of the input sheet:

from openpyxl import load_workbook

wb = load_workbook('workbook.xlsx')
ws = wb['input']
for i in range(10):
    ws.append([i])

wb.save('workbook_2.xlsx')

When opening the new file, cell A1 on the 'main' sheet only has the first value, 0, instead of the range 0--9. When selecting the cell, you can see the formula is now {=OFFSET(input!A1,0,0,COUNTA(input!A:A),1)}. The curly brackets make it an array, so it wont spill. By hitting enter in the formula the array is removed and the sheet properly becomes the full range.

If I can get this simple example to work, then expanding it to the data I'm using shouldn't be a problem.


问:
PySide6.QtCore.QModelIndex.internalPointer() is not working, what am i doing wrong?
I need to access and edit a complex data structure via a gui. The data is organized as a tree structure. The individual nodes form data sets, which are partly organized differently. To navigate through the data structure I use a tree view. For the selected dataset in the tree view (the selected item), I open a separate view with which this particular dataset can be edited.
For the tree view I implemented my own model by subcalssing QAbstractItemModel. To access the individual datasets I implemented my own classes as tree items. The tree view can be populized with the items and shows the surface data structure correctly.

Now I want to access the datasets via the model. For this purpose I call QItemIndex.internalPointer(). This call causes a crash of the application without throwing an exception.
While debugging, I kept reducing the complexity of my source code. Even using QStandardItemModel and QStandardItem, the crash persistently occurs.

I made a simple code example which demonstrates the error. What am I doing wrong here?

```<code>   import sys
   from PySide6 import QtGui, QtWidgets

   app = QtWidgets.QApplication(sys.argv)
   tree = QtWidgets.QTreeView()
   model = QtGui.QStandardItemModel()
   item = QtGui.QStandardItem('item')
   model.appendRow(item)
   tree.setModel(model)
   tree.show()

   # this works
   print(item.index().constInternalPointer())

   # this crashes
   print(item.index().internalPointer())

   sys.exit(app.exec())
</code>```

Body:
I need to access and edit a complex data structure via a gui. The data is organized as a tree structure. The individual nodes form data sets, which are partly organized differently. To navigate through the data structure I use a tree view. For the selected dataset in the tree view (the selected item), I open a separate view with which this particular dataset can be edited.
For the tree view I implemented my own model by subcalssing QAbstractItemModel. To access the individual datasets I implemented my own classes as tree items. The tree view can be populized with the items and shows the surface data structure correctly.

Now I want to access the datasets via the model. For this purpose I call QItemIndex.internalPointer(). This call causes a crash of the application without throwing an exception.
While debugging, I kept reducing the complexity of my source code. Even using QStandardItemModel and QStandardItem, the crash persistently occurs.

I made a simple code example which demonstrates the error. What am I doing wrong here?

   import sys
   from PySide6 import QtGui, QtWidgets

   app = QtWidgets.QApplication(sys.argv)
   tree = QtWidgets.QTreeView()
   model = QtGui.QStandardItemModel()
   item = QtGui.QStandardItem('item')
   model.appendRow(item)
   tree.setModel(model)
   tree.show()

   # this works
   print(item.index().constInternalPointer())

   # this crashes
   print(item.index().internalPointer())

   sys.exit(app.exec())


问:
gnuplot setup VS Code
Can't setup gnuplot in VS Code on Mac ('gnuplot.h' file not found).

```<code>Here are what I did:
1) installed gnuplot via brew;
2) also installed Gnuplot extension in VS Code;
3) opened VS Code Settings and searched for Gnuplot;
4) in the Gnuplot: Gnuplot Path specified the path;
5) restarted VS Code;
6) run program but still got an error 'gnuplot.h' file not found.

Could you please advise how to set it up?
Thanks!
</code>```

Title: gnuplot setup VS Code

Body:
Can't setup gnuplot in VS Code on Mac ('gnuplot.h' file not found).

Here are what I did:
1) installed gnuplot via brew;
2) also installed Gnuplot extension in VS Code;
3) opened VS Code Settings and searched for Gnuplot;
4) in the Gnuplot: Gnuplot Path specified the path;
5) restarted VS Code;
6) run program but still got an error 'gnuplot.h' file not found.

Could you please advise how to set it up?
Thanks!


问:
Autowire Getting null whilw declare inside mockito test class at run time

I want to test my function what I created in my service class, when I
declare service class inside test class with the help of @Autowired
annotation It gives me null value. For your reference I post my codes
what I do in my project.

```<code>@SpringBootTest
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
public class RepGroupServiceImplTest {

    @Autowired
    private RepGroupServiceImpl repGroupServiceImpl;

    @MockBean
    private RepGroupManufacturerRepository repGroupManufacturerRepository;
    @MockBean
    private RepGroupRetailerRepository repgroupRetailerRepository;

    @Test
    public void buyerAccessRequestTest(){
        SearchRequest request = getSearchRequest();
        Set<String> manufactureIDset= new HashSet<String>();
        manufactureIDset.add("M1002415");
        if (repGroupServiceImpl == null) {
            System.out.println("Hey I am getting null value");
        } else {
           System.out.println("Hey I am not null");
        }

        System.out.println();
        Set<String> searchRequest = repGroupServiceImpl.buyerAccessRequest(request, manufactureIDset);

    }

    private SearchRequest getSearchRequest() {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setRepGroupID("R2132");
            searchRequest.setRetailerID("B364124");
            searchRequest.setRetailerStatus("ACTIVE");
            searchRequest.setActive(null);
            return searchRequest;
    }
</code>```

my repGroupServiceImpl gives null value ,Autowire not working
properly.

Body:
I want to test my function what I created in my service class, when I
declare service class inside test class with the help of @Autowired
annotation It gives me null value. For your reference I post my codes
what I do in my project.

@SpringBootTest
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
public class RepGroupServiceImplTest {

    @Autowired
    private RepGroupServiceImpl repGroupServiceImpl;

    @MockBean
    private RepGroupManufacturerRepository repGroupManufacturerRepository;
    @MockBean
    private RepGroupRetailerRepository repgroupRetailerRepository;

    @Test
    public void buyerAccessRequestTest(){
        SearchRequest request = getSearchRequest();
        Set<String> manufactureIDset= new HashSet<String>();
        manufactureIDset.add("M1002415");
        if (repGroupServiceImpl == null) {
            System.out.println("Hey I am getting null value");
        } else {
           System.out.println("Hey I am not null");
        }

        System.out.println();
        Set<String> searchRequest = repGroupServiceImpl.buyerAccessRequest(request, manufactureIDset);

    }

    private SearchRequest getSearchRequest() {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setRepGroupID("R2132");
            searchRequest.setRetailerID("B364124");
            searchRequest.setRetailerStatus("ACTIVE");
            searchRequest.setActive(null);
            return searchRequest;
    }

my repGroupServiceImpl gives null value ,Autowire not working
properly.


问:
face-api.js is giving some error in binary when running on the browser with vite
I am trying to implement face-api.js into my college project. But it is giving me an error on load which is not really helpful.

My Js Code:

```<code>import * as faceapi from "face-api.js"

Promise.all([
    faceapi.loadFaceRecognitionModel("/models"),
    faceapi.loadFaceLandmarkModel("/models"),
    faceapi.loadSsdMobilenetv1Model("/models")
]).then(start)
function start(){
    console.log("Loaded");
}
</code>```

Html Code:

```<code><body>
    <input type="file" name="" id="fileUpload">
    <script src="./script.js" type="module"></script>
</body>
</code>```

The error:

```<code>�|����~��y���{������������x���������������������������������w��������������������~���z��~���������������������w���������~��������y���}�����������������������n�������t����{�������������������h�����l����|�o����}�����~��������~}z����������z��}����~���������}z�������������~������q���������������������������������������}�w������������������������s������n�������}~���x}{|�z{|w�u|�x������v�|�{�}}���~�xvy����}���~��w����wy{z��z��z~w}|}�p���m����x���}...
</code>```

Body:
I am trying to implement face-api.js into my college project. But it is giving me an error on load which is not really helpful.

My Js Code:

import * as faceapi from "face-api.js"

Promise.all([
    faceapi.loadFaceRecognitionModel("/models"),
    faceapi.loadFaceLandmarkModel("/models"),
    faceapi.loadSsdMobilenetv1Model("/models")
]).then(start)
function start(){
    console.log("Loaded");
}

Html Code:

    <input type="file" name="" id="fileUpload">

The error:

�|����~��y���{������������x���������������������������������w��������������������~���z��~���������������������w���������~��������y���}�����������������������n�������t����{�������������������h�����l����|�o����}�����~��������~}z����������z��}����~���������}z�������������~������q���������������������������������������}�w������������������������s������n�������}~���x}{|�z{|w�u|�x������v�|�{�}}���~�xvy����}���~��w����wy{z��z��z~w}|}�p���m����x���}...


问:
How can I resolve API requests that work properly in postman and in my browser, but return TypeError: Failed to fetch when used with fetch()?
I am attempting to access an API when a button is clicked on a webpage using the fetch() command. My code as is works with the omdb API, but when I try to use Flixed (https://flixed.io/docs/api#overview) (both APIs are related to getting streaming data for movies/tv) the query fails with TypeError: Failed to fetch.

However, when I try to use an identical URL in my browser or in postman, the query returns JSON data as expected. I suspect that there is a cors error happening, but the message I receive back has status 200 and I'm not sure what I need to do to resolve it.

Here is the code I am running inside of a function in my script tag:
`

```<code>    fetch("https://api.flixed.io/v1/movies/0208092?idType=imdb&apiKey=8MqjZtMPW1LUUEydpqjzULeQ6EmBfbEg", {
      method: 'GET',
    })
      .then(response => {
        return response.json();
      })
      .then((data) => {
        results = document.getElementById("resultsText");
        results.innerText = data;
        results.style.display = "block";
      })
      .catch((error) => {
        results = document.getElementById("resultsText");
        results.innerText = error.message;
        results.style.display = "block";
      });
</code>```

`

I have tried searching on StackOverflow for similar issues, and have experimented with different headers and cors settings, but I have not been able to get any response other than the TypeError when accessing the Flixed API. I am unfortunately relatively new to web dev in particular, so my knowledge of API requests is limited, and my troubleshooting skills in this matter are limited to what I can find online. All the explanations I have been able to find online relating to cors issues seem to assume a level of pre-understanding I don't have, despite my attempts to implement them. So any level of explanation for such a solution would be greatly appreciated.

Body:
I am attempting to access an API when a button is clicked on a webpage using the fetch() command. My code as is works with the omdb API, but when I try to use Flixed (https://flixed.io/docs/api#overview) (both APIs are related to getting streaming data for movies/tv) the query fails with TypeError: Failed to fetch.

However, when I try to use an identical URL in my browser or in postman, the query returns JSON data as expected. I suspect that there is a cors error happening, but the message I receive back has status 200 and I'm not sure what I need to do to resolve it.

Here is the code I am running inside of a function in my script tag:
`

    fetch("https://api.flixed.io/v1/movies/0208092?idType=imdb&apiKey=8MqjZtMPW1LUUEydpqjzULeQ6EmBfbEg", {
      method: 'GET',
    })
      .then(response => {
        return response.json();
      })
      .then((data) => {
        results = document.getElementById("resultsText");
        results.innerText = data;
        results.style.display = "block";
      })
      .catch((error) => {
        results = document.getElementById("resultsText");
        results.innerText = error.message;
        results.style.display = "block";
      });

`

I have tried searching on StackOverflow for similar issues, and have experimented with different headers and cors settings, but I have not been able to get any response other than the TypeError when accessing the Flixed API. I am unfortunately relatively new to web dev in particular, so my knowledge of API requests is limited, and my troubleshooting skills in this matter are limited to what I can find online. All the explanations I have been able to find online relating to cors issues seem to assume a level of pre-understanding I don't have, despite my attempts to implement them. So any level of explanation for such a solution would be greatly appreciated.


问:
Redo logfiles for mySQL database
I want to have my database safer by using redo logfiles.

I read some articles about it online, but I have no idea where to start using this.

Where and how can I configure this?

Title: Redo logfiles for mySQL database


问:
USBPcap shows several messages with the same IRP ID?
I'm retro-engineering the USB protocol of a piece of musical equipment : a BOSS effect pedal with an USB port. I have a BOSS software that controls the pedal but I want to control it from a python script.

I'm using USBPcap in WireShark to sniff the USB interface when the BOSS software is controlling it. Then I connect to the pedal with PYUSB (libusb0 backend) and reproduce the stream.

This setup works well for a lot of commands, but not for this specific one. That is, when I reproduce the datastream with pyusb I don't see/hear the expected change on the pedal.

The command consists of a sequence of 2 MIDI-over-USB SYSEX messages from host to device.

This is the usbpcap capture I'm seeing with the BOSS software ("good" frame) :

```<code>1b 00 50 da fb 76 88 ca ff ff 00 00 00 00 09 00
00 01 00 08 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 00 00 00 04 00 00 00 06
00 f7 7e

1b 00 50 da fb 76 88 ca ff ff 00 00 00 00 09 00
00 01 00 08 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 7f 00 01 04 00 00 00 06
00 f7 7e
</code>```

And this is the usbpcap capture when sent with pyusb ("bad" frame) :

```<code>1b 00 20 da 2d 80 88 ca ff ff 00 00 00 00 09 00
00 01 00 0b 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 00 00 00 04 00 00 00 06
00 f7 00

1b 00 20 fa 97 7b 88 ca ff ff 00 00 00 00 09 00
00 01 00 0b 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 7f 00 01 04 00 00 00 06
00 f7 00
</code>```

As you can see, the only differences are :

last byte --> padding : this data is ignored so this should not make any difference

byte 19 --> device address : I had to unplug/replug the device between the 2 captures so it changed address

bytes 2:5 --> IRP ID are the same for the 2 sysex messages in the "good" frame, but different in the "bad" frame.

I understand that IRP ID is part of the USBPcap pseudo-header so not actually sent over the wire.

A bunch of questions:

How can 2 messages have the same IRP ID / what does that imply from the driver?

How can I reproduce that with pyusb/libusb0?

Do you think that IRP ID difference might be the cause of this command having no effect on the HW?

Thanks in advance!

Body:
I'm retro-engineering the USB protocol of a piece of musical equipment : a BOSS effect pedal with an USB port. I have a BOSS software that controls the pedal but I want to control it from a python script.

I'm using USBPcap in WireShark to sniff the USB interface when the BOSS software is controlling it. Then I connect to the pedal with PYUSB (libusb0 backend) and reproduce the stream.

This setup works well for a lot of commands, but not for this specific one. That is, when I reproduce the datastream with pyusb I don't see/hear the expected change on the pedal.

The command consists of a sequence of 2 MIDI-over-USB SYSEX messages from host to device.

This is the usbpcap capture I'm seeing with the BOSS software ("good" frame) :

1b 00 50 da fb 76 88 ca ff ff 00 00 00 00 09 00
00 01 00 08 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 00 00 00 04 00 00 00 06
00 f7 7e

1b 00 50 da fb 76 88 ca ff ff 00 00 00 00 09 00
00 01 00 08 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 7f 00 01 04 00 00 00 06
00 f7 7e

And this is the usbpcap capture when sent with pyusb ("bad" frame) :

1b 00 20 da 2d 80 88 ca ff ff 00 00 00 00 09 00
00 01 00 0b 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 00 00 00 04 00 00 00 06
00 f7 00

1b 00 20 fa 97 7b 88 ca ff ff 00 00 00 00 09 00
00 01 00 0b 00 03 03 18 00 00 00 04 f0 41 10 04
00 00 00 04 00 1d 12 04 7f 00 01 04 00 00 00 06
00 f7 00

As you can see, the only differences are :

last byte --> padding : this data is ignored so this should not make any difference

byte 19 --> device address : I had to unplug/replug the device between the 2 captures so it changed address

bytes 2:5 --> IRP ID are the same for the 2 sysex messages in the "good" frame, but different in the "bad" frame.

I understand that IRP ID is part of the USBPcap pseudo-header so not actually sent over the wire.

A bunch of questions:

How can 2 messages have the same IRP ID / what does that imply from the driver?

How can I reproduce that with pyusb/libusb0?

Do you think that IRP ID difference might be the cause of this command having no effect on the HW?

Thanks in advance!


问:
vscode keybindings of web for desktop
Is there a way to use the web-keybinding for the desktop?
With "web" I mean for example GitHub Codespaces.

Background: I am switching from a different editor, and need to learn the new keybindings. I want to learn the keybindings of the web version, because I think that this would be useful for fixing stuff in pull-requests. I want to use the same keybindings in both places.

I googled for that, but only found unrelated pages.

Title: vscode keybindings of web for desktop


问:
matplotlib.pyplot.xticks generates unwanted texts above the graph
I am trying to visualize my data using plt.plot(), I need to play with xticks but whenever I call plt.xticks or plt.yticks, the output generates unwanted texts above my graph, the graph it prints out seems to be accurate but I don't know how to get rid of those unwanted text values. Any suggestions?

```<code>plt.plot(df_hourly['Hour'], df_hourly['Net Traffic'])
plt.xticks(np.arange(24), rotation = 45)
</code>```

[Those are the unwanted texts](https://i.stack.imgur.com/cjB3Y.png)

Body:
I am trying to visualize my data using plt.plot(), I need to play with xticks but whenever I call plt.xticks or plt.yticks, the output generates unwanted texts above my graph, the graph it prints out seems to be accurate but I don't know how to get rid of those unwanted text values. Any suggestions?

plt.plot(df_hourly['Hour'], df_hourly['Net Traffic'])
plt.xticks(np.arange(24), rotation = 45)

[Those are the unwanted texts](https://i.stack.imgur.com/cjB3Y.png)


问:
How to read response content with content-type as "image/svg+xml" in DOT NET CORE
I'm trying to read the response content which is coming as svg format. But not able to find the content within the response object.
I'm expecting some svg content within it.

Here is the code snippet:

```<code>_httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "image/svg+xml");
var resultAsAsync = await _httpClient.PostAsJsonAsync(_url, JsonSerializer.Deserialize<object>(requestBody), cancellationToken);
var response = await resultAsAsync.Content.ReadFromJsonAsync<ChartsDO>(); // Failing as the response is not type of JSON
</code>```

StatusCode is coming as 200(Ok), content type "{image/svg+xml}" and has content length of 19331.

In postman, it runs fine, and if I want I can save the response object to svg directly.

I'm using .NET CORE 5.
Any help is highly appreciable. Thanks.

Body:
I'm trying to read the response content which is coming as svg format. But not able to find the content within the response object.
I'm expecting some svg content within it.

Here is the code snippet:

_httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "image/svg+xml");
var resultAsAsync = await _httpClient.PostAsJsonAsync(_url, JsonSerializer.Deserialize<object>(requestBody), cancellationToken);
var response = await resultAsAsync.Content.ReadFromJsonAsync<ChartsDO>(); // Failing as the response is not type of JSON

StatusCode is coming as 200(Ok), content type "{image/svg+xml}" and has content length of 19331.

In postman, it runs fine, and if I want I can save the response object to svg directly.

I'm using .NET CORE 5.
Any help is highly appreciable. Thanks.


问:
python requests post 500: Internal Server Error
I'm creating a project with python requests where it will register an account for me with captcha-solving integration; I came across a problem with the error 500: Internal Server Error.  Here is the code:

```<code>def captchastart():
    async_responses = asyncio.run(solve_captcha_async(nums))
    for your_dic in async_responses:
        for key in your_dic:
            return(your_dic['gRecaptchaResponse'])

data = captchastart()
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
    'content-type': "application/json"
}
url = 'https://discord.com/api/v9/auth/register'
Payload = {
    'captcha_key': data,
    'consent': 'true',
    'date_of_birth': '1995-03-01',
    'email': 'random@gmail.com',
    'gift_code_sku_id': 'null',
    'invite': 'null',
    'password': 'PASSWORD',
    'promotional_email_opt_in': 'false',
    'username': 'username'

}
proxy = {
    'https': ""
}
y = json.dumps(Payload)
print("uploading to destination")
r = requests.post(url, json=y, headers=headers,proxies=proxy)
print(r.text)
</code>```

What I did so far:

My problem started at the part where the 'captcha_key' value needs to be fulfilled when its called/needed by the server. I tried just having the function there as the value, hoping it would have the same effect, but comes to another problem, where the data is not JSON serializable.

Then I tried using the python dumps method and it works! The data become JSON and the problem never occurs again, but when I sent my request to the destination, I received the 500: Internal Server Error response.

I did a test where I send out the data without the function  'captcha_key' value and without the JSON dump method; it worked well just requiring the 'captcha_key' value.

I need help finding what caused the Error, and if what I did to the 'captcha_key' value is right (basically I want it so when the server asks for a 'captcha_key' value the function will start doing the captcha-solving task! and return the captcha answer).

Anything is appreciated, I tried searching through StackOverflow but I just can't hit the right keyword since English is not my main language. If there is a post regarding this, I'm very sorry and will delete this post.

The code might look stupid but I did the best I could haha sorry guys. Thank you for your precious time!

Body:
I'm creating a project with python requests where it will register an account for me with captcha-solving integration; I came across a problem with the error 500: Internal Server Error.  Here is the code:

def captchastart():
    async_responses = asyncio.run(solve_captcha_async(nums))
    for your_dic in async_responses:
        for key in your_dic:
            return(your_dic['gRecaptchaResponse'])

data = captchastart()
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
    'content-type': "application/json"
}
url = 'https://discord.com/api/v9/auth/register'
Payload = {
    'captcha_key': data,
    'consent': 'true',
    'date_of_birth': '1995-03-01',
    'email': 'random@gmail.com',
    'gift_code_sku_id': 'null',
    'invite': 'null',
    'password': 'PASSWORD',
    'promotional_email_opt_in': 'false',
    'username': 'username'

}
proxy = {
    'https': ""
}
y = json.dumps(Payload)
print("uploading to destination")
r = requests.post(url, json=y, headers=headers,proxies=proxy)
print(r.text)

What I did so far:

My problem started at the part where the 'captcha_key' value needs to be fulfilled when its called/needed by the server. I tried just having the function there as the value, hoping it would have the same effect, but comes to another problem, where the data is not JSON serializable.

Then I tried using the python dumps method and it works! The data become JSON and the problem never occurs again, but when I sent my request to the destination, I received the 500: Internal Server Error response.

I did a test where I send out the data without the function  'captcha_key' value and without the JSON dump method; it worked well just requiring the 'captcha_key' value.

I need help finding what caused the Error, and if what I did to the 'captcha_key' value is right (basically I want it so when the server asks for a 'captcha_key' value the function will start doing the captcha-solving task! and return the captcha answer).

Anything is appreciated, I tried searching through StackOverflow but I just can't hit the right keyword since English is not my main language. If there is a post regarding this, I'm very sorry and will delete this post.

The code might look stupid but I did the best I could haha sorry guys. Thank you for your precious time!


问:
C# WPF MVVM Binding to a Grid but only specific members
I'm struggling to figure out how to populate a grid from a  I have in my ModelView.  I have implemented the INotifyPropertyChanged.  The best I can do so far is the grid populates the headers only but no data below.  Though that would be nice if I could get that far.  But I really only need to specify a couple of columns to get the results I need.  Description and Barcode.

I can see from MyParts list, there are hundred of items loaded.  Again I only need to see 2 columns not all 50. So far no dice.  Maybe my issue is I don't know what to say in the binding column.  Putting Binding="{Binding Description}" doesn't do anything.  I tried being specific with something like this MyParts.Description.

I should mention I have a button that is being used that does a launches an openfileDialog.  Loads a file and dumps it into part List.  not sure if that matters or not.

```<code><Window x:Class="MyCarParts.MainWindow"
        .....
        xmlns:local="clr-namespace:MyCarParts"
        xmlns:viewModel="clr-namespace:MyCarParts.ViewModels"

        <Window.Resources>
            <viewModel:FileProcessViewModel x:Key="file_vm"></viewModel:FileProcessViewModel>
        </Window.Resources>

         <DataGrid ItemsSource="{Binding Source={StaticResource file_vm}, Path=MyParts}" x:Name="gridPartDetails">
            <DataGrid.Columns>
            <DataGridTextColumn Header="Barcode"     IsReadOnly="True" Binding="{Binding Not Sure What To Put}"/>
            <DataGridTextColumn Header="Description" IsReadOnly="True" Binding="{Binding Not Sure What To Put}"/>

        </DataGrid>

<Button x:Name="TaskButton" Command="{Binding Source={StaticResource file_vm},Path=FileLoadCommand}" Content="Path"/>

</code>```
```<code>public class FileProcessViewModel : INotifyPropertyChanged
{
    private List<Part> _MyParts;

    public List<Part> MyParts
    {
        get { return _MyParts; }
        set
        {
            _MyParts = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
}
</code>```

I have also tried adding this in and changed the Datagrid.  Still nothing.

```<code>    <Window.DataContext>
        <viewModel:FileProcessViewModel/>
    </Window.DataContext>

<DataGrid ItemsSource="{Binding MyParts}" x:Name="MyParts" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Barcode" Binding="{Binding MyParts.Barcode}"/>

</code>```

Body:
I'm struggling to figure out how to populate a grid from a  I have in my ModelView.  I have implemented the INotifyPropertyChanged.  The best I can do so far is the grid populates the headers only but no data below.  Though that would be nice if I could get that far.  But I really only need to specify a couple of columns to get the results I need.  Description and Barcode.

I can see from MyParts list, there are hundred of items loaded.  Again I only need to see 2 columns not all 50. So far no dice.  Maybe my issue is I don't know what to say in the binding column.  Putting Binding="{Binding Description}" doesn't do anything.  I tried being specific with something like this MyParts.Description.

I should mention I have a button that is being used that does a launches an openfileDialog.  Loads a file and dumps it into part List.  not sure if that matters or not.

<Window x:Class="MyCarParts.MainWindow"
        .....
        xmlns:local="clr-namespace:MyCarParts"
        xmlns:viewModel="clr-namespace:MyCarParts.ViewModels"

        <Window.Resources>
            <viewModel:FileProcessViewModel x:Key="file_vm"></viewModel:FileProcessViewModel>
        </Window.Resources>

         <DataGrid ItemsSource="{Binding Source={StaticResource file_vm}, Path=MyParts}" x:Name="gridPartDetails">
            <DataGrid.Columns>
            <DataGridTextColumn Header="Barcode"     IsReadOnly="True" Binding="{Binding Not Sure What To Put}"/>
            <DataGridTextColumn Header="Description" IsReadOnly="True" Binding="{Binding Not Sure What To Put}"/>

        </DataGrid>

<Button x:Name="TaskButton" Command="{Binding Source={StaticResource file_vm},Path=FileLoadCommand}" Content="Path"/>

public class FileProcessViewModel : INotifyPropertyChanged
{
    private List<Part> _MyParts;

    public List<Part> MyParts
    {
        get { return _MyParts; }
        set
        {
            _MyParts = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
}

I have also tried adding this in and changed the Datagrid.  Still nothing.

    <Window.DataContext>
        <viewModel:FileProcessViewModel/>
    </Window.DataContext>

<DataGrid ItemsSource="{Binding MyParts}" x:Name="MyParts" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Barcode" Binding="{Binding MyParts.Barcode}"/>


问:
Unable to process request due to missing initial state
I'm creating an app with Angular, Ionic and Firebase and all was working well, but when I make with capacitor the app for android studio for creating the apk, when I run the app on the tablet I can't log in with Google, it says what you see in the title or error 403 when I run it on a virtual android device in android studio.

What can I do for solving this? I've been a few days reading things but nothing worked.

I tried changing the authDomain of my firebase enviroment and installing reCaptcha for verifying app(didn't manage to install it correcly).


问:
Configuring OpenTelemetry ContextStorage in Java
I'm having an issue with OpenTelemetry in Java.

I am in the process of transitioning from Opentracing to OpenTelemetry on a library that is using vert.x. I have included vertx-opentelemetry library, which includes VertxContextStorageProvider class.

This class is then set as the default context storage.

My issue is that this relies on vert.x being initialized, and breaks my tests which are testing certain parts that just don't need to initialize vert.x to be tested.

I saw that I can set a system property to enforce OpenTelemetry to load the default context provider. But, honestly, that seems like an overkill if I need to do it in all of my test classes.

Is there any way I can use the default (ThreadLocalContextStorage) implementation?

I tried creating my own implementation of context provider, but the ClassLoader didn't load it, and still loaded only the vert.x implementation.


问:
Iterating over 1D array nested in object ndarrays
I have the following data formats:

type1 = np.array([...], dtype='float64') # vector of floats

type2 = np.array([type1, type1, ...], dtype='object') # array of type 1

type3 = np.array([type2, type2, ...], dtype='object') # array of type 2

(Just to focus the attention: type1 would be timeseries signal, and higher order types would constructed by splitting signal into smaller and smaller chunks of different sizes)

Now, I'd like to apply a function (e.g. filtering) to each 1D vector (type) witch the following requirements:

iterator accepts type1, type2 or type3 data and applies function to each type1 element.

it's possible to iterate over 2 arrays of the same dimensionality

it's possible to extract additional info from iterator.

So the signature could be like:

```<code>out = apply([main_array, aux_array], function_to_apply, **kwargs)
</code>```

with main_array modified inside apply

Possible way to go, could be np.nditer like here:
Vectorwise iteration of nD array with nditer
however I haven't been able to create working solution yet.
Any ideas?

EDIT:
Thanks @JeromeRichards and @hpaulj for pointing right direction. I ended up with such recursive solution:

```<code>def zip_none(data, aux):
    '''zip routine with none broadcasting'''
    return zip(data, *aux) if aux is not None else zip(data)

def apply_1d(data, func, aux=None, **kwargs):
    '''Apply `func` to each 1d vector in data. Params:
    data - list of input data or np 1D array
    aux - list of additional input data. Each element of aux should share dimensionality with data
    func - function to be applied
    kwargs - params to be passed to `func`'''
    if isinstance(data, list):
        result = []
        multi_output = False
        for x, *y in zip_none(data, aux):
            aux = y if y else None
            tmp = apply_1d(x, func, aux=aux, **kwargs)
            result.append(tmp)

            if isinstance(tmp, tuple):
                multi_output = True

        if multi_output:
            result = tuple(list(out) for out in zip(*result))

    else:
        return func(data, *aux, **kwargs) if aux is not None else func(data, **kwargs)

    return result
</code>```

Body:
I have the following data formats:

type1 = np.array([...], dtype='float64') # vector of floats

type2 = np.array([type1, type1, ...], dtype='object') # array of type 1

type3 = np.array([type2, type2, ...], dtype='object') # array of type 2

(Just to focus the attention: type1 would be timeseries signal, and higher order types would constructed by splitting signal into smaller and smaller chunks of different sizes)

Now, I'd like to apply a function (e.g. filtering) to each 1D vector (type) witch the following requirements:

iterator accepts type1, type2 or type3 data and applies function to each type1 element.

it's possible to iterate over 2 arrays of the same dimensionality

it's possible to extract additional info from iterator.

So the signature could be like:

out = apply([main_array, aux_array], function_to_apply, **kwargs)

with main_array modified inside apply

Possible way to go, could be np.nditer like here:
Vectorwise iteration of nD array with nditer
however I haven't been able to create working solution yet.
Any ideas?

EDIT:
Thanks @JeromeRichards and @hpaulj for pointing right direction. I ended up with such recursive solution:

def zip_none(data, aux):
    '''zip routine with none broadcasting'''
    return zip(data, *aux) if aux is not None else zip(data)

def apply_1d(data, func, aux=None, **kwargs):
    '''Apply `func` to each 1d vector in data. Params:
    data - list of input data or np 1D array
    aux - list of additional input data. Each element of aux should share dimensionality with data
    func - function to be applied
    kwargs - params to be passed to `func`'''
    if isinstance(data, list):
        result = []
        multi_output = False
        for x, *y in zip_none(data, aux):
            aux = y if y else None
            tmp = apply_1d(x, func, aux=aux, **kwargs)
            result.append(tmp)

            if isinstance(tmp, tuple):
                multi_output = True

        if multi_output:
            result = tuple(list(out) for out in zip(*result))

    else:
        return func(data, *aux, **kwargs) if aux is not None else func(data, **kwargs)

    return result


问:
Firebase function read data from json and write to firestore db
How can I create a function in Firebase Functions for a lot of data, for example, I have 110,000 records with Json and each of these records become a document in Firestore.

```<code>const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({
  credential: admin.credential.applicationDefault(),
});
const geohash = require("ngeohash");
const fs = require("fs");
const db = admin.firestore();
const archiveRef = db.collection("ReportsDebugTS");
db.settings({ignoreUndefinedProperties: true});
exports.scheduledFunction = functions.pubsub
    .schedule("every 900 minutes").onRun((context) => {
      fs.readFile("static_camera.json", (err, data)=>{
        if (err) throw err;
        const reportt = JSON.parse(data);
        let aa = 0;
        for (let i=0; i < reportt.length; i++) {
          aa++;
          const _geoLocation = [reportt[i].latitude, reportt[i].longitude];
          archiveRef.doc().set({
            g: geohash.encode(reportt[i].latitude, reportt[i].longitude),
            geoLocation: _geoLocation,
            reportAddress: "",
            reportByUID: "supper_admin_1",
            reportId: "ts",
            reportTimeStamp: Date.now(),
            reportType: 10,
          }).then(() => {
            console.log("Write succeeded!");
          });
        }
        console.log(aa);
      });
      return null;
    });
</code>```

I've done this myself and the action works, but no documents are added to the Firestore, but when I reduce the number of records, the action works without problems.

Body:
How can I create a function in Firebase Functions for a lot of data, for example, I have 110,000 records with Json and each of these records become a document in Firestore.

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({
  credential: admin.credential.applicationDefault(),
});
const geohash = require("ngeohash");
const fs = require("fs");
const db = admin.firestore();
const archiveRef = db.collection("ReportsDebugTS");
db.settings({ignoreUndefinedProperties: true});
exports.scheduledFunction = functions.pubsub
    .schedule("every 900 minutes").onRun((context) => {
      fs.readFile("static_camera.json", (err, data)=>{
        if (err) throw err;
        const reportt = JSON.parse(data);
        let aa = 0;
        for (let i=0; i < reportt.length; i++) {
          aa++;
          const _geoLocation = [reportt[i].latitude, reportt[i].longitude];
          archiveRef.doc().set({
            g: geohash.encode(reportt[i].latitude, reportt[i].longitude),
            geoLocation: _geoLocation,
            reportAddress: "",
            reportByUID: "supper_admin_1",
            reportId: "ts",
            reportTimeStamp: Date.now(),
            reportType: 10,
          }).then(() => {
            console.log("Write succeeded!");
          });
        }
        console.log(aa);
      });
      return null;
    });

I've done this myself and the action works, but no documents are added to the Firestore, but when I reduce the number of records, the action works without problems.


问:
How to Run Multiple Scrapy Spiders in Sequence?
My code:
It's code start scrapy spiders

```<code>def start_crawling():
    spiders = [spdier1, spider2]
    runner = CrawlerProcess()

    @defer.inlineCallbacks
    def crawl():
        for spider in spiders:
            yield runner.crawl(spider, (task.id, True, None))
        reactor.stop()

    while True:
        a = time.time()
        crawl()
        reactor.run()
        print("crawl time: " + str(time.time() - a))

if name == "main":
   start_crawling()
</code>```

But i have an error:
twisted.internet.error.ReactorNotRestartable
How i can fix this?

log error:

```<code>2022-12-27 21:10:39 [scrapy.core.engine] INFO: Spider opened
2022-12-27 21:10:39 [scrapy.extensions.logstats] INFO: Crawled   pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2022-12-27 21:10:39 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
Traceback (most recent call last):
File "//./scraper.py", line 49, in <module>
start_crawling()
File "//./scraper.py", line 44, in start_crawling
reactor.run()
File "/usr/local/lib/python3.10/site-packages/twisted/internet/base.py", line 1317, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "/usr/local/lib/python3.10/site-packages/twisted/internet/base.py", line 1299, in
ReactorBase.startRunning(cast(ReactorBase, self))
File "/usr/local/lib/python3.10/site-packages/twisted/internet/base.py", line 843, in
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable
</code>```

Body:
My code:
It's code start scrapy spiders

def start_crawling():
    spiders = [spdier1, spider2]
    runner = CrawlerProcess()

    @defer.inlineCallbacks
    def crawl():
        for spider in spiders:
            yield runner.crawl(spider, (task.id, True, None))
        reactor.stop()

    while True:
        a = time.time()
        crawl()
        reactor.run()
        print("crawl time: " + str(time.time() - a))

if name == "main":
   start_crawling()

But i have an error:
twisted.internet.error.ReactorNotRestartable
How i can fix this?

log error:

2022-12-27 21:10:39 [scrapy.core.engine] INFO: Spider opened
2022-12-27 21:10:39 [scrapy.extensions.logstats] INFO: Crawled   pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2022-12-27 21:10:39 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
Traceback (most recent call last):
File "//./scraper.py", line 49, in <module>
start_crawling()
File "//./scraper.py", line 44, in start_crawling
reactor.run()
File "/usr/local/lib/python3.10/site-packages/twisted/internet/base.py", line 1317, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "/usr/local/lib/python3.10/site-packages/twisted/internet/base.py", line 1299, in
ReactorBase.startRunning(cast(ReactorBase, self))
File "/usr/local/lib/python3.10/site-packages/twisted/internet/base.py", line 843, in
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable


问:
when transfering frontend to laravel, part of the js code does not work
The js file is connected correctly, it is visible when viewing the page code in the browser, but some functions do not work. Function addField and deleteField work just fine. The rest is not but there are no errors in the pannel.

While if I put the whole frontend in a folder like the html file, js file and open this page in the browser, then everything works the way it was intended.

Sorry, the code is clumsy, but I need it in any form:

$("div#photo_0").hide();

$('.show_popup').click(function() {
    var popup_id = $('#' + $(this).attr("rel"));
    $(popup_id).show();
    $('.overlay_popup').show();
})
$('.overlay_popup').click(function() {
    $('.overlay_popup, .popup').hide();
})

function addField() {
    if ($("#photo div").length < 12) {
        var photo = $("div#photo_0").html();

        if ($("#photo div").length == 2) {
            p_id = 1;
        } else {
            p_id = parseInt(
                $('#photo div')
                    .last()
                    .attr('id')
                    .replace(/[^0-9]/gi, '')
            ) + 1;
        }
        $("div#photo").append(photo);

        $('div#photo')
            .children()
            .last()
            .attr('id', "p_" + p_id)
            .attr('onclick', "deleteField(" + p_id + ")");
    } else {
        alert("10 photos!")
    }

}
function deleteField(p_id) {
    var id = '#p_' + p_id
    $(id).remove();
}
```

Put already working code in laravel and expect it to work

Body:
The js file is connected correctly, it is visible when viewing the page code in the browser, but some functions do not work. Function addField and deleteField work just fine. The rest is not but there are no errors in the pannel.

While if I put the whole frontend in a folder like the html file, js file and open this page in the browser, then everything works the way it was intended.

Sorry, the code is clumsy, but I need it in any form:

$("div#photo_0").hide();

$('.show_popup').click(function() {
    var popup_id = $('#' + $(this).attr("rel"));
    $(popup_id).show();
    $('.overlay_popup').show();
})
$('.overlay_popup').click(function() {
    $('.overlay_popup, .popup').hide();
})

function addField() {
    if ($("#photo div").length < 12) {
        var photo = $("div#photo_0").html();

        if ($("#photo div").length == 2) {
            p_id = 1;
        } else {
            p_id = parseInt(
                $('#photo div')
                    .last()
                    .attr('id')
                    .replace(/[^0-9]/gi, '')
            ) + 1;
        }
        $("div#photo").append(photo);

        $('div#photo')
            .children()
            .last()
            .attr('id', "p_" + p_id)
            .attr('onclick', "deleteField(" + p_id + ")");
    } else {
        alert("10 photos!")
    }

}
function deleteField(p_id) {
    var id = '#p_' + p_id
    $(id).remove();
}

Put already working code in laravel and expect it to work


问:
Make Next.js wait for async polyfill
I am trying to polyfill Intl.NumberFormat with the code below. It checks if it should, and then if it needs it, it does an async import. If I call this at top level in _app.tsx sometimes the frontend renders but an error pops up like below screenshot.

Is it possible to tell Next.js to wait for this promise before continuing?

```<code>import {shouldPolyfill} from '@formatjs/intl-numberformat/should-polyfill'
async function polyfill(locale: string) {
  const unsupportedLocale = shouldPolyfill(locale)
  // This locale is supported
  if (!unsupportedLocale) {
    return
  }
  // Load the polyfill 1st BEFORE loading data
  await import('@formatjs/intl-numberformat/polyfill-force')
  await import(`@formatjs/intl-numberformat/locale-data/${unsupportedLocale}`)
}
</code>```

Title: Make Next.js wait for async polyfill

Body:
I am trying to polyfill Intl.NumberFormat with the code below. It checks if it should, and then if it needs it, it does an async import. If I call this at top level in _app.tsx sometimes the frontend renders but an error pops up like below screenshot.

Is it possible to tell Next.js to wait for this promise before continuing?

import {shouldPolyfill} from '@formatjs/intl-numberformat/should-polyfill'
async function polyfill(locale: string) {
  const unsupportedLocale = shouldPolyfill(locale)
  // This locale is supported
  if (!unsupportedLocale) {
    return
  }
  // Load the polyfill 1st BEFORE loading data
  await import('@formatjs/intl-numberformat/polyfill-force')
  await import(`@formatjs/intl-numberformat/locale-data/${unsupportedLocale}`)
}


问:
Logstash Filter for Cisco ASA Source Destination and Communication
I want to configure logstash filter to see asa logs with communication detail.

LOG Sample:

Dec 27 02:48:08 Test-FW : %ASA-6-302014: Teardown TCP connection 3505833084 for Test-OUT:192.168.1.10/58538 to Mgmt-IN:192.168.100.10/1159 duration 0:00:00 bytes 4153 TCP FINs from Test-OUT

Need for Below Data filter:
Source IP: 192.168.1.10
Destination IP: 192.168.100.10
Source Port: 58538
Destination Port: 1159
Source Zone: Test-OUT
Destination Zone: Mgmt-IN
Protocol: TCP
Device Name: Test-FW
Size: 4153 Bytes (Optional)

Below configuraiton not working:

```<code>input {
beats {
port => 5044
}
}
filter {
grok {
id => "ASA"
match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:[%{POSINT:syslog_pid}])?: %{GREEDYDATA:syslog_message}" }
#       add_field => [ "received_at", "%{@timestamp}" ]
#       add_field => [ "received_from", "%{host}" ] }

}
grok {
id => "ALLOW-SRC-DST"
match => { "syslog_message" => "inside:%{HOSTNAME:inside_host}/%{NUMBER:inside_port} to outside:%{HOSTNAME:outside_host}/%{NUMBER:outside_port}" }
}
#syslog_pri { }
#      date { match => [ "syslog_timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ]
#    }
}

output {
if [@metadata][pipeline] {
elasticsearch {
hosts => ["http://localhost:9200"]
manage_template => false
index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
pipeline => "%{[@metadata][pipeline]}"
}
}
else {
elasticsearch {
hosts => ["http://localhost:9200"]
manage_template => false
index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
}
}

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

Body:
I want to configure logstash filter to see asa logs with communication detail.

LOG Sample:

Dec 27 02:48:08 Test-FW : %ASA-6-302014: Teardown TCP connection 3505833084 for Test-OUT:192.168.1.10/58538 to Mgmt-IN:192.168.100.10/1159 duration 0:00:00 bytes 4153 TCP FINs from Test-OUT

Need for Below Data filter:
Source IP: 192.168.1.10
Destination IP: 192.168.100.10
Source Port: 58538
Destination Port: 1159
Source Zone: Test-OUT
Destination Zone: Mgmt-IN
Protocol: TCP
Device Name: Test-FW
Size: 4153 Bytes (Optional)

Below configuraiton not working:

input {
beats {
port => 5044
}
}
filter {
grok {
id => "ASA"
match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:[%{POSINT:syslog_pid}])?: %{GREEDYDATA:syslog_message}" }
#       add_field => [ "received_at", "%{@timestamp}" ]
#       add_field => [ "received_from", "%{host}" ] }

}
grok {
id => "ALLOW-SRC-DST"
match => { "syslog_message" => "inside:%{HOSTNAME:inside_host}/%{NUMBER:inside_port} to outside:%{HOSTNAME:outside_host}/%{NUMBER:outside_port}" }
}
#syslog_pri { }
#      date { match => [ "syslog_timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ]
#    }
}

output {
if [@metadata][pipeline] {
elasticsearch {
hosts => ["http://localhost:9200"]
manage_template => false
index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
pipeline => "%{[@metadata][pipeline]}"
}
}
else {
elasticsearch {
hosts => ["http://localhost:9200"]
manage_template => false
index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
}
}

`


问:
What's the dispatch method of this function?
What's the dispatch method of the function in the snippet?

```<code>extension KeyedDecodingContainer where Key == JsonCodingKey {
    @inline(__always)
    func decode<T: Decodable>(key: String) throws -> T {
        return try decode(T.self, forKey: JsonCodingKey(key))
    }
}
</code>```

I thought it should be static but measuring performance yields almost the same result as dynamic dispatch.

On one hand, it's generic function and it should be dispatched statically, on the other hand there's a protocol conformance which means dynamic dispatching.

Body:
What's the dispatch method of the function in the snippet?

extension KeyedDecodingContainer where Key == JsonCodingKey {
    @inline(__always)
    func decode<T: Decodable>(key: String) throws -> T {
        return try decode(T.self, forKey: JsonCodingKey(key))
    }
}

I thought it should be static but measuring performance yields almost the same result as dynamic dispatch.

On one hand, it's generic function and it should be dispatched statically, on the other hand there's a protocol conformance which means dynamic dispatching.


问:
How to introduce a code patch into Wix directories.wxs file using cMake
I am using cMake with Wix to generate my installer executable. I have my executable ready, but I am unable to get a shortcut on the desktop and include my program in the Windows Start menu.
To achieve these two goals, I want to inject some code into the files generated by wix, specifically in the directories.wxs file:

```<code><Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFiles64Folder">
                <Directory Id="INSTALL_PREFIX_1" Name="myApp">
                    <Directory Id="INSTALL_ROOT" Name="myApp Studio">
                        <Directory Id="CM_DP_MYAPP_RUNTIME.Data" Name="Data">
                            <Directory Id="CM_DP_MYAPP_RUNTIME.Data.ConfigurationFiles" Name="ConfigurationFiles"/>
                        </Directory>
                    </Directory>
                </Directory>
            </Directory>
           <!--CODE MUST BE INJECTED HERE-->
        </Directory>
    </Fragment>
</Wix>
</code>```

The code must be injected where the comment is. The main problem is that a code patch is injected like this:

```<code><CPackWiXPatch>
  <CPackWiXFragment Id=XXXX>
      <ComponentRef Id="ApplicationShortcut" />
      <ComponentRef Id="ApplicationShortcutDesktop" />
  </CPackWiXFragment>
</CPackWiXPatch>
</code>```

XXX is the ID of the xml tag where the code patch will be injected, in this case it would have to be TARGETDIR. The problem is that if I set the ID as TARGETDIR it returns the following error:

```<code>Some xml patch fragments did not have matching ids: 'targetdir'
</code>```

Does anyone know how I can specify an id to inject my code at that point?

Body:
I am using cMake with Wix to generate my installer executable. I have my executable ready, but I am unable to get a shortcut on the desktop and include my program in the Windows Start menu.
To achieve these two goals, I want to inject some code into the files generated by wix, specifically in the directories.wxs file:

<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFiles64Folder">
                <Directory Id="INSTALL_PREFIX_1" Name="myApp">
                    <Directory Id="INSTALL_ROOT" Name="myApp Studio">
                        <Directory Id="CM_DP_MYAPP_RUNTIME.Data" Name="Data">
                            <Directory Id="CM_DP_MYAPP_RUNTIME.Data.ConfigurationFiles" Name="ConfigurationFiles"/>
                        </Directory>
                    </Directory>
                </Directory>
            </Directory>

        </Directory>
    </Fragment>
</Wix>

The code must be injected where the comment is. The main problem is that a code patch is injected like this:

<CPackWiXPatch>
  <CPackWiXFragment Id=XXXX>
      <ComponentRef Id="ApplicationShortcut" />
      <ComponentRef Id="ApplicationShortcutDesktop" />
  </CPackWiXFragment>
</CPackWiXPatch>

XXX is the ID of the xml tag where the code patch will be injected, in this case it would have to be TARGETDIR. The problem is that if I set the ID as TARGETDIR it returns the following error:

Some xml patch fragments did not have matching ids: 'targetdir'

Does anyone know how I can specify an id to inject my code at that point?