问:
Trying to Create a Dashboard for Data in Python
I am currently experiencing an error when attempting to run a template for a dashboard.

I am looking to see if line 7, 29 & 141 are simply formatting issues.

```<code>ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_1648\3613514742.py in <module>
      5     sidebar=[pn.pane.Markdown("# CO2 Emissions and Climate Change"),
      6              pn.pane.Markdown("#### Carbon dioxide emissions are the primary driver of global climate change. It’s widely recognised that to avoid the worst impacts of climate change, the world needs to urgently reduce emissions. But, how this responsibility is shared between regions, countries, and individuals has been an endless point of contention in international discussions."),
----> 7              pn.pane.PNG('climate_day.png', sizing_mode='scale_both'),
      8              pn.pane.Markdown("## Settings"),
      9              year_slider],

~\Anaconda3\lib\site-packages\panel\pane\image.py in __init__(self, object, **params)
     27         if isinstance(object, PurePath):
     28             object = str(object)
---> 29         super().__init__(object=object, **params)
     30
     31     def _type_error(self, object):

~\Anaconda3\lib\site-packages\panel\pane\base.py in __init__(self, object, **params)
    139         applies = self.applies(object, **(params if self._applies_kw else {}))
    140         if (isinstance(applies, bool) and not applies) and object is not None :
--> 141             self._type_error(object)
    142
    143         super().__init__(object=object, **params)

~\Anaconda3\lib\site-packages\panel\pane\image.py in _type_error(self, object)
     31     def _type_error(self, object):
     32         if isinstance(object, str):
---> 33             raise ValueError("%s pane cannot parse string that is not a filename "
     34                              "or URL." % type(self).__name__)
     35         super()._type_error(object)

ValueError: PNG pane cannot parse string that is not a filename or URL.

</code>```

Overall code below

```<code>template = pn.template.FastListTemplate(
    title='World CO2 emission dashboard',
    sidebar=[pn.pane.Markdown("# CO2 Emissions and Climate Change"),
             pn.pane.Markdown("#### Carbon dioxide emissions are the primary driver of global climate change. It’s widely recognised that to avoid the worst impacts of climate change, the world needs to urgently reduce emissions. But, how this responsibility is shared between regions, countries, and individuals has been an endless point of contention in international discussions."),
             pn.pane.PNG('climate_day.png', sizing_mode='scale_both'),
             pn.pane.Markdown("## Settings"),
             year_slider],
    main=[pn.Row(pn.Column(yaxis_co2,
                           co2_plot.panel(width=700), margin=(0,25)),
                 co2_table.panel(width=500)),
          pn.Row(pn.Column(co2_vs_gdp_scatterplot.panel(width=600), margin=(0,25)),
                 pn.Column(yaxis_co2_source, co2_source_bar_plot.panel(width=600)))],
    accent_base_color="#88d8b0",
    header_background="#88d8b0",
)
# template.show()
template.servable();
</code>```

I was attempting to create a dashboard layout using a template provided.

Body:
I am currently experiencing an error when attempting to run a template for a dashboard.

I am looking to see if line 7, 29 & 141 are simply formatting issues.

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_1648\3613514742.py in <module>
      5     sidebar=[pn.pane.Markdown("# CO2 Emissions and Climate Change"),
      6              pn.pane.Markdown("#### Carbon dioxide emissions are the primary driver of global climate change. It’s widely recognised that to avoid the worst impacts of climate change, the world needs to urgently reduce emissions. But, how this responsibility is shared between regions, countries, and individuals has been an endless point of contention in international discussions."),
----> 7              pn.pane.PNG('climate_day.png', sizing_mode='scale_both'),
      8              pn.pane.Markdown("## Settings"),
      9              year_slider],

~\Anaconda3\lib\site-packages\panel\pane\image.py in __init__(self, object, **params)
     27         if isinstance(object, PurePath):
     28             object = str(object)
---> 29         super().__init__(object=object, **params)
     30
     31     def _type_error(self, object):

~\Anaconda3\lib\site-packages\panel\pane\base.py in __init__(self, object, **params)
    139         applies = self.applies(object, **(params if self._applies_kw else {}))
    140         if (isinstance(applies, bool) and not applies) and object is not None :
--> 141             self._type_error(object)
    142
    143         super().__init__(object=object, **params)

~\Anaconda3\lib\site-packages\panel\pane\image.py in _type_error(self, object)
     31     def _type_error(self, object):
     32         if isinstance(object, str):
---> 33             raise ValueError("%s pane cannot parse string that is not a filename "
     34                              "or URL." % type(self).__name__)
     35         super()._type_error(object)

ValueError: PNG pane cannot parse string that is not a filename or URL.

Overall code below

template = pn.template.FastListTemplate(
    title='World CO2 emission dashboard',
    sidebar=[pn.pane.Markdown("# CO2 Emissions and Climate Change"),
             pn.pane.Markdown("#### Carbon dioxide emissions are the primary driver of global climate change. It’s widely recognised that to avoid the worst impacts of climate change, the world needs to urgently reduce emissions. But, how this responsibility is shared between regions, countries, and individuals has been an endless point of contention in international discussions."),
             pn.pane.PNG('climate_day.png', sizing_mode='scale_both'),
             pn.pane.Markdown("## Settings"),
             year_slider],
    main=[pn.Row(pn.Column(yaxis_co2,
                           co2_plot.panel(width=700), margin=(0,25)),
                 co2_table.panel(width=500)),
          pn.Row(pn.Column(co2_vs_gdp_scatterplot.panel(width=600), margin=(0,25)),
                 pn.Column(yaxis_co2_source, co2_source_bar_plot.panel(width=600)))],
    accent_base_color="#88d8b0",
    header_background="#88d8b0",
)
# template.show()
template.servable();

I was attempting to create a dashboard layout using a template provided.


来源: stackexchange

问:
How to make my DB stream work when a change occures?
I'm trying to insert new message to my Mongodb DB, but the on function doesn't work (should work when stream change occurs) and I get 404 error when I'm using Postman to send the request. What's wrong with the code?

I'm using mongoose 6.7.0

server.js

```<code>import express from "express";
import mongoose from "mongoose";
import "dotenv/config";
import Messages from "./messageSchema.js";
import Pusher from "pusher";

// app config
const app = express();
const port = process.env.PORT;

// middleware
app.use(express.json());

//DB config
mongoose.connect(process.env.MONGO_URI);
const db = mongoose.connection;

db.once("open", () => {
  console.log("DB connected");

  const messageCollection = db.collection("MessageModels");
  const stream = messageCollection.watch();
  stream.on("change", (data) => {
    console.log("The change", data);

    if (data.operationType === "insert") {
      const msgContent = data.fullDocument;
      pusher.trigger("messages", "inserted", {
        message: msgContent.message,
        sender: msgContent.sender,
        timestamp: msgContent.timestamp,
        recieved: msgContent.recieved,
      });
    }
  });
});

// API routes
app.get("/", (req, res) => res.status(200).send("Health"));

app.get("/api/messages/all", (req, res) => {
  Messages.find((err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });

  app.post("/api/messages/new", (req, res) => {
    const messageContent = req.body;
    Messages.create(messageContent, (err, data) => {
      if (err) {
        res.status(500).send(err);
      }
      if (data) {
        res.status(201).send(messageContent);
      }
    });
  });
});

// listen to port
app.listen(port, () => console.log(`Listening on port ${port}`));
</code>```

messageSchema.js

```<code>import mongoose from "mongoose";

const messageSchema = new mongoose.Schema({
  message: String,
  sender: String,
  timestamp: String,
  recieved: Boolean,
});

export default mongoose.model("MessageModel", messageSchema);
</code>```

I tried using onChange function and other similar functions, but it still didn't work.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to insert new message to my Mongodb DB, but the on function doesn't work (should work when stream change occurs) and I get 404 error when I'm using Postman to send the request. What's wrong with the code?

I'm using mongoose 6.7.0

server.js

import express from "express";
import mongoose from "mongoose";
import "dotenv/config";
import Messages from "./messageSchema.js";
import Pusher from "pusher";

// app config
const app = express();
const port = process.env.PORT;

// middleware
app.use(express.json());

//DB config
mongoose.connect(process.env.MONGO_URI);
const db = mongoose.connection;

db.once("open", () => {
  console.log("DB connected");

  const messageCollection = db.collection("MessageModels");
  const stream = messageCollection.watch();
  stream.on("change", (data) => {
    console.log("The change", data);

    if (data.operationType === "insert") {
      const msgContent = data.fullDocument;
      pusher.trigger("messages", "inserted", {
        message: msgContent.message,
        sender: msgContent.sender,
        timestamp: msgContent.timestamp,
        recieved: msgContent.recieved,
      });
    }
  });
});

// API routes
app.get("/", (req, res) => res.status(200).send("Health"));

app.get("/api/messages/all", (req, res) => {
  Messages.find((err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });

  app.post("/api/messages/new", (req, res) => {
    const messageContent = req.body;
    Messages.create(messageContent, (err, data) => {
      if (err) {
        res.status(500).send(err);
      }
      if (data) {
        res.status(201).send(messageContent);
      }
    });
  });
});

// listen to port
app.listen(port, () => console.log(`Listening on port ${port}`));

messageSchema.js

import mongoose from "mongoose";

const messageSchema = new mongoose.Schema({
  message: String,
  sender: String,
  timestamp: String,
  recieved: Boolean,
});

export default mongoose.model("MessageModel", messageSchema);

I tried using onChange function and other similar functions, but it still didn't work.


问:
Route one hostname to different root folder using .htaccess
I have a main domain for my web hosting account, let's call it maindomain.com. I also have a totally different domain which is handled by the same hosting account, let's call it sub.otherdomain.com.

The folder structure looks like this:

```<code>public_html
   .htaccess
   index.php                <-- prints "maindomain.com index.php"
   test.php                 <-- prints "maindomain.com test.php"
   sub.otherdomain.com
      index.php             <-- prints "sub.otherdomain.com index.php"
      test.php              <-- prints "sub.otherdomain.com test.php"
      test
          index.php         <-- prints "sub.otherdomain.com test/index.php"
          test.php          <-- prints "sub.otherdomain.com test/test.php"
</code>```

Now, as you can imagine, I want all requests for anything under sub.otherdomain.com to go to the folder /sub.otherdomain.com.

So in my .htaccess I put

```<code>RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^sub\.otherdomain\.com$ [NC]
RewriteRule ^ sub.otherdomain.com%{REQUEST_URI} [END]
</code>```

It seems to work as long as I end the URL with a slash and don't provide a filename, but not otherwise...

```<code>These are working okay
------------------------
Url: https://sub.otherdomain.com/
Expected output: "sub.otherdomain.com index.php"
Actual output:   "sub.otherdomain.com index.php"

Url: https://sub.otherdomain.com/test/
Expected output: "sub.otherdomain.com test/index.php"
Actual output:   "sub.otherdomain.com test/index.php"

The rest don't work
-------------------
Url: https://sub.otherdomain.com/test.php
Expected output: "sub.otherdomain.com test.php"
Actual output:   "File not found"

Url: https://sub.otherdomain.com/index.php
Expected output: "sub.otherdomain.com index.php"
Actual output:   "maindomain.com index.php"

Url: https://sub.otherdomain.com/test/test.php
Expected output: "sub.otherdomain.com test/test.php"
Actual output:   "maindomain.com test.php"

</code>```

I tried different variations of the .htaccess file, but none work the way I expect it to.

Even if I try

```<code>RewriteCond %{HTTP_HOST} ^sub\.otherdomain\.com$ [NC]
RewriteRule . sub.otherdomain.com/test.php [END]
</code>```

I get the output

```<code>"maindomain.com test.php"
</code>```

It's as if .htaccess is not invoked at all if I specify a file that actually exists...

Body:
I have a main domain for my web hosting account, let's call it maindomain.com. I also have a totally different domain which is handled by the same hosting account, let's call it sub.otherdomain.com.

The folder structure looks like this:

public_html
   .htaccess
   index.php                <-- prints "maindomain.com index.php"
   test.php                 <-- prints "maindomain.com test.php"
   sub.otherdomain.com
      index.php             <-- prints "sub.otherdomain.com index.php"
      test.php              <-- prints "sub.otherdomain.com test.php"
      test
          index.php         <-- prints "sub.otherdomain.com test/index.php"
          test.php          <-- prints "sub.otherdomain.com test/test.php"

Now, as you can imagine, I want all requests for anything under sub.otherdomain.com to go to the folder /sub.otherdomain.com.

So in my .htaccess I put

RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^sub\.otherdomain\.com$ [NC]
RewriteRule ^ sub.otherdomain.com%{REQUEST_URI} [END]

It seems to work as long as I end the URL with a slash and don't provide a filename, but not otherwise...

These are working okay
------------------------
Url: https://sub.otherdomain.com/
Expected output: "sub.otherdomain.com index.php"
Actual output:   "sub.otherdomain.com index.php"

Url: https://sub.otherdomain.com/test/
Expected output: "sub.otherdomain.com test/index.php"
Actual output:   "sub.otherdomain.com test/index.php"

The rest don't work
-------------------
Url: https://sub.otherdomain.com/test.php
Expected output: "sub.otherdomain.com test.php"
Actual output:   "File not found"

Url: https://sub.otherdomain.com/index.php
Expected output: "sub.otherdomain.com index.php"
Actual output:   "maindomain.com index.php"

Url: https://sub.otherdomain.com/test/test.php
Expected output: "sub.otherdomain.com test/test.php"
Actual output:   "maindomain.com test.php"

I tried different variations of the .htaccess file, but none work the way I expect it to.

Even if I try

RewriteCond %{HTTP_HOST} ^sub\.otherdomain\.com$ [NC]
RewriteRule . sub.otherdomain.com/test.php [END]

I get the output

"maindomain.com test.php"

It's as if .htaccess is not invoked at all if I specify a file that actually exists...


问:
Next JS and Vercel Enviroment Variable problem
I used env variables through getServerSideProps and sent them to other components through props.

When I checked in the network tab, they are visible in the form of pageProps: { private_key : xxx }

How can I completely hide these variables?


问:
Can't downgrade Numpy version, multiple errors arrive
I am trying to downgrade my numpy version to 1.16.6 due to a dependency on installing mxnet package, which only works with python<=1.17.0. I already understood that mxnet installation is very consuming so I tried to perform the downgrading of numpy.

I tried downgrade using

```<code>pip install --upgrade numpy==1.16.6
</code>```

But I got the following list of errors:

```<code>C:\Users\samue>pip install --use-pep517 --upgrade numpy==1.16.6
Collecting numpy==1.16.6
  Using cached numpy-1.16.6.zip (5.1 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [260 lines of output]
      Running from numpy source directory.
      <string>:394: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\misc_util.py:476: SyntaxWarning: "is" with a literal. Did you mean "=="?
        return is_string(s) and ('*' in s or '?' is s)
      blas_opt_info:
      blas_mkl_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries mkl_rt not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      blis_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries blis not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      Could not locate executable g77
      Could not locate executable f77
      customize IntelVisualFCompiler
      Could not locate executable ifort
      Could not locate executable ifl
      customize AbsoftFCompiler
      Could not locate executable f90
      customize CompaqVisualFCompiler
      Could not locate executable DF
      customize IntelItaniumVisualFCompiler
      Could not locate executable efl
      customize Gnu95FCompiler
      Could not locate executable gfortran
      Could not locate executable f95
      customize G95FCompiler
      Could not locate executable g95
      customize IntelEM64VisualFCompiler
      customize IntelEM64TFCompiler
      Could not locate executable efort
      Could not locate executable efc
      customize PGroupFlangCompiler
      Could not locate executable flang
      don't know how to compile Fortran code on platform 'nt'
        NOT AVAILABLE

      atlas_3_10_blas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_3_10_blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_blas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      accelerate_info:
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Atlas (http://math-atlas.sourceforge.net/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [atlas]) or by setting
          the ATLAS environment variable.
        self.calc_info()
      blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries blas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Blas (http://www.netlib.org/blas/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [blas]) or by setting
          the BLAS environment variable.
        self.calc_info()
      blas_src_info:
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Blas (http://www.netlib.org/blas/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [blas_src]) or by setting
          the BLAS_SRC environment variable.
        self.calc_info()
        NOT AVAILABLE

      'svnversion' is not recognized as an internal or external command,
      operable program or batch file.
      non-existing path in 'numpy\\distutils': 'site.cfg'
      lapack_opt_info:
      lapack_mkl_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries mkl_rt not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_lapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_clapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas,lapack not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_3_10_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
        NOT AVAILABLE

      atlas_3_10_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_3_10_info'>
        NOT AVAILABLE

      atlas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_threads_info'>
        NOT AVAILABLE

      atlas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_info'>
        NOT AVAILABLE

      lapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Lapack (http://www.netlib.org/lapack/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [lapack]) or by setting
          the LAPACK environment variable.
        self.calc_info()
      lapack_src_info:
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Lapack (http://www.netlib.org/lapack/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [lapack_src]) or by setting
          the LAPACK_SRC environment variable.
        self.calc_info()
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-build-env-9woykmkf\overlay\Lib\site-packages\setuptools\_distutils\dist.py:265: UserWarning: Unknown distribution option: 'define_macros'
        warnings.warn(msg)
      running dist_info
      running build_src
      build_src
      building py_modules sources
      creating build
      creating build\src.win-amd64-3.9
      creating build\src.win-amd64-3.9\numpy
      creating build\src.win-amd64-3.9\numpy\distutils
      building library "npymath" sources
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

</code>```

Has anybody any solution to this?

I also tried pip install --use-pep517 --upgrade numpy==1.16.6 as suggested here: https://github.com/pypa/pip/issues/8559 but still hasn't worked..

Any help is welcome!

Body:
I am trying to downgrade my numpy version to 1.16.6 due to a dependency on installing mxnet package, which only works with python<=1.17.0. I already understood that mxnet installation is very consuming so I tried to perform the downgrading of numpy.

I tried downgrade using

pip install --upgrade numpy==1.16.6

But I got the following list of errors:

C:\Users\samue>pip install --use-pep517 --upgrade numpy==1.16.6
Collecting numpy==1.16.6
  Using cached numpy-1.16.6.zip (5.1 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [260 lines of output]
      Running from numpy source directory.
      <string>:394: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\misc_util.py:476: SyntaxWarning: "is" with a literal. Did you mean "=="?
        return is_string(s) and ('*' in s or '?' is s)
      blas_opt_info:
      blas_mkl_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries mkl_rt not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      blis_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries blis not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      Could not locate executable g77
      Could not locate executable f77
      customize IntelVisualFCompiler
      Could not locate executable ifort
      Could not locate executable ifl
      customize AbsoftFCompiler
      Could not locate executable f90
      customize CompaqVisualFCompiler
      Could not locate executable DF
      customize IntelItaniumVisualFCompiler
      Could not locate executable efl
      customize Gnu95FCompiler
      Could not locate executable gfortran
      Could not locate executable f95
      customize G95FCompiler
      Could not locate executable g95
      customize IntelEM64VisualFCompiler
      customize IntelEM64TFCompiler
      Could not locate executable efort
      Could not locate executable efc
      customize PGroupFlangCompiler
      Could not locate executable flang
      don't know how to compile Fortran code on platform 'nt'
        NOT AVAILABLE

      atlas_3_10_blas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_3_10_blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_blas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      accelerate_info:
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Atlas (http://math-atlas.sourceforge.net/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [atlas]) or by setting
          the ATLAS environment variable.
        self.calc_info()
      blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries blas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Blas (http://www.netlib.org/blas/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [blas]) or by setting
          the BLAS environment variable.
        self.calc_info()
      blas_src_info:
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Blas (http://www.netlib.org/blas/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [blas_src]) or by setting
          the BLAS_SRC environment variable.
        self.calc_info()
        NOT AVAILABLE

      'svnversion' is not recognized as an internal or external command,
      operable program or batch file.
      non-existing path in 'numpy\\distutils': 'site.cfg'
      lapack_opt_info:
      lapack_mkl_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries mkl_rt not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_lapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_clapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas,lapack not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_3_10_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
        NOT AVAILABLE

      atlas_3_10_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_3_10_info'>
        NOT AVAILABLE

      atlas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_threads_info'>
        NOT AVAILABLE

      atlas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in c:\users\samue\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_info'>
        NOT AVAILABLE

      lapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack not found in ['c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\samue\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Lapack (http://www.netlib.org/lapack/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [lapack]) or by setting
          the LAPACK environment variable.
        self.calc_info()
      lapack_src_info:
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-install-up62lows\numpy_79e7dc8c18464429a86c23cba4fb7260\numpy\distutils\system_info.py:639: UserWarning:
          Lapack (http://www.netlib.org/lapack/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [lapack_src]) or by setting
          the LAPACK_SRC environment variable.
        self.calc_info()
        NOT AVAILABLE

      C:\Users\samue\AppData\Local\Temp\pip-build-env-9woykmkf\overlay\Lib\site-packages\setuptools\_distutils\dist.py:265: UserWarning: Unknown distribution option: 'define_macros'
        warnings.warn(msg)
      running dist_info
      running build_src
      build_src
      building py_modules sources
      creating build
      creating build\src.win-amd64-3.9
      creating build\src.win-amd64-3.9\numpy
      creating build\src.win-amd64-3.9\numpy\distutils
      building library "npymath" sources
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Has anybody any solution to this?

I also tried pip install --use-pep517 --upgrade numpy==1.16.6 as suggested here: https://github.com/pypa/pip/issues/8559 but still hasn't worked..

Any help is welcome!


问:
How to create a Duplex stream where unshift works
I need to 'splice' stdin/stdout from a child process into a readable/writable stream in Node.JS. I have a function that does this, but I recently learned that calling unshift on the Duplex doesn't lead to the next read including the unshifted buffer.

Can anyone spot the bug in my code?

```<code>it("unshift duplex", async function () {
    function splice(readable: NodeJS.ReadableStream, writable: NodeJS.WritableStream): Duplex {
        const duplex = new Duplex({
            write(chunk, encoding, callback) {
                writable.write(chunk, encoding, callback);
            },

            final(callback) {
                writable.end(callback);
            },
        });

        // All reads and events come directly from the readable stream.
        duplex.read = readable.read.bind(readable);
        duplex.on = readable.on.bind(readable) as any;

        return duplex;
    }

    readable = new PassThrough();
    writable = new PassThrough();
    duplex = splice(readable, writable);

    duplex.unshift(Buffer.from([1, 2, 3]))
    const result = duplex.read()
    expect(result).toEqual(Buffer.from([1, 2, 3])) // ERROR: Expected null to equal Buffer [ 1, 2, 3 ]
})
</code>```

Body:
I need to 'splice' stdin/stdout from a child process into a readable/writable stream in Node.JS. I have a function that does this, but I recently learned that calling unshift on the Duplex doesn't lead to the next read including the unshifted buffer.

Can anyone spot the bug in my code?

it("unshift duplex", async function () {
    function splice(readable: NodeJS.ReadableStream, writable: NodeJS.WritableStream): Duplex {
        const duplex = new Duplex({
            write(chunk, encoding, callback) {
                writable.write(chunk, encoding, callback);
            },

            final(callback) {
                writable.end(callback);
            },
        });

        // All reads and events come directly from the readable stream.
        duplex.read = readable.read.bind(readable);
        duplex.on = readable.on.bind(readable) as any;

        return duplex;
    }

    readable = new PassThrough();
    writable = new PassThrough();
    duplex = splice(readable, writable);

    duplex.unshift(Buffer.from([1, 2, 3]))
    const result = duplex.read()
    expect(result).toEqual(Buffer.from([1, 2, 3])) // ERROR: Expected null to equal Buffer [ 1, 2, 3 ]
})


问:
FileStream read file time out
I am using this code to read a Windows spooler file on vb.net:

Dim SpoolFileStream As New FileStream(SpoolFilename, FileMode.Open, FileAccess.Read, FileShare.Read)

'\\ Open a binary reader for the spool file using above encoding
Dim SpoolBinaryReader As New BinaryReader(SpoolFileStream, Encoding.GetEncoding(857))
```

The filestream is always giving a read timeout error

Title: FileStream read file time out

Body:
I am using this code to read a Windows spooler file on vb.net:

Dim SpoolFileStream As New FileStream(SpoolFilename, FileMode.Open, FileAccess.Read, FileShare.Read)

'\\ Open a binary reader for the spool file using above encoding
Dim SpoolBinaryReader As New BinaryReader(SpoolFileStream, Encoding.GetEncoding(857))

The filestream is always giving a read timeout error


问:
TypeError when reading in a fits file but not with a fits.fz file
I have a function to read in and plot a FITS image which works perfectly fine when I read in a '.fits.fz' file but breaks down and gives a TypeError when I try running the same code with a '.fits' file.

Here's a snippet of the code:

```<code>import sys
from astropy.io import ascii
import os
import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import fits
import seaborn as sns
import warnings
from astropy.wcs import WCS, FITSFixedWarning
from astropy.utils.data import get_pkg_data_filename
from astropy.visualization import ZScaleInterval

filename = get_pkg_data_filename('filename.fits') # alternatively, 'filename.fits.fz'
hdu = fits.open(filename)

with warnings.catch_warnings():
            # Ignore a warning on using DATE-OBS in place of MJD-OBS
    warnings.filterwarnings('ignore', message="'datfix' made the change",
                                    category=FITSFixedWarning)
    wcs = WCS(hdu[1].header)

image_data = fits.getdata(filename)
zscale = ZScaleInterval()
vmin, vmax = zscale.get_limits(image_data)

plt.figure(figsize=(10, 20))
ax = plt.subplot(projection=wcs)
im = ax.imshow(image_data, cmap=plt.cm.magma, vmin=vmin, vmax=vmax, origin='lower')

plt.tight_layout()
plt.show()
plt.close()

</code>```

This is the error:

```<code>TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code>```

From what I gather, it's a problem with the image_data itself but I have no idea how to fix that.

Body:
I have a function to read in and plot a FITS image which works perfectly fine when I read in a '.fits.fz' file but breaks down and gives a TypeError when I try running the same code with a '.fits' file.

Here's a snippet of the code:

import sys
from astropy.io import ascii
import os
import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import fits
import seaborn as sns
import warnings
from astropy.wcs import WCS, FITSFixedWarning
from astropy.utils.data import get_pkg_data_filename
from astropy.visualization import ZScaleInterval

filename = get_pkg_data_filename('filename.fits') # alternatively, 'filename.fits.fz'
hdu = fits.open(filename)

with warnings.catch_warnings():
            # Ignore a warning on using DATE-OBS in place of MJD-OBS
    warnings.filterwarnings('ignore', message="'datfix' made the change",
                                    category=FITSFixedWarning)
    wcs = WCS(hdu[1].header)

image_data = fits.getdata(filename)
zscale = ZScaleInterval()
vmin, vmax = zscale.get_limits(image_data)

plt.figure(figsize=(10, 20))
ax = plt.subplot(projection=wcs)
im = ax.imshow(image_data, cmap=plt.cm.magma, vmin=vmin, vmax=vmax, origin='lower')

plt.tight_layout()
plt.show()
plt.close()

This is the error:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

From what I gather, it's a problem with the image_data itself but I have no idea how to fix that.


问:
generating Pythagorean quadruples
How do you generate a list of Pythagorean quadruples

def quadruple_py(num):
quad_list = []
for n in range(1, num):
for m in range(n+1, num+1):
for p in range(m+1, num+2):
for q in range(p+1, num+3):
if n2 + m2 + p2 + q2> num:
break
if n % 2 == 1 and m % 2 == 1 and p % 2 == 1 and q % 2 == 1:
continue
if mygcd(n, m) != 1:
continue
w,e,r,t = mergesort([m2+n2-p2-q2, 2(mq+np), 2(nq-mp), n2+m2+p2+q2])
quad_list.append((w,e,r,t))
return quad_list

Title: generating Pythagorean quadruples


问:
Suffix Tree - All common substrings
The problem is as following:

Given 2 strings X and Y, I want to find the all (longest) common substrings, hence all substrings that appear in X and in Y and are maximal. for instance - if X = gttcatwg, Y = twgacgtt.
return gtt and twg, not substrings of those (for instance gt).

It is Given that both share the same letters (with the same number of appearances) and both of same length.

O(N) algorithm.

suggestion:

build a generalized suffix tree. (Ukkonnen's algo)

get all deepest (string wise) nodes that have leaves from both X and Y.

from the above mentioned nodes remove all nodes that have suffix links in their subtree.

it seems like it is not enough.
an example:
X = abcabc
Y= bcaabc
should return : bc, abc and bca
but returns abc and bca.

Title: Suffix Tree - All common substrings


问:
Why won't this local enum class / lambda function combination work correctly?
This is a boilerplate OnInitDialog handler for CDialog project. I added a enum class and lambda to it:

```<code>BOOL CMFCApplication8Dlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != nullptr)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon

    // TODO: Add extra initialization here
    enum class EnumStudentItemType
    {
        BibleReading,
        InitialCall,
        ReturnVisit,
        BibleStudy,
        Talk,
        Other
    };

    auto GetStudentItemType = &[](CString strType) -> EnumStudentItemType
    {
        if (strType == L"Bible Reading")
        {
            return EnumStudentItemType::BibleReading;
        }
        if (strType == L"Initial Call")
        {
            return EnumStudentItemType::InitialCall;
        }
        if (strType == L"Return Visit")
        {
            return EnumStudentItemType::ReturnVisit;
        }
        if (strType == L"Bible Study")
        {
            return EnumStudentItemType::BibleStudy;
        }
        if (strType == L"Talk")
        {
            return EnumStudentItemType::Talk;
        }

        return EnumStudentItemType::Other;
    };

    auto eType = GetStudentItemType(L"Bible Reading");

    return TRUE;  // return TRUE  unless you set the focus to a control
}
</code>```

It does not like this line:

```<code>auto eType = GetStudentItemType(L"Bible Reading");
</code>```

If I move the enum class into the header, and turn the GetStudentItemType method into a function defined in the header, then that line of code which attempts to get the type does not display errors in the IDE.

So:

How do we define a enum class inside a function (not needed anywhere else)? And ...

Use it as a return value for a lambda?

Body:
This is a boilerplate OnInitDialog handler for CDialog project. I added a enum class and lambda to it:

BOOL CMFCApplication8Dlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != nullptr)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon

    // TODO: Add extra initialization here
    enum class EnumStudentItemType
    {
        BibleReading,
        InitialCall,
        ReturnVisit,
        BibleStudy,
        Talk,
        Other
    };

    auto GetStudentItemType = &[](CString strType) -> EnumStudentItemType
    {
        if (strType == L"Bible Reading")
        {
            return EnumStudentItemType::BibleReading;
        }
        if (strType == L"Initial Call")
        {
            return EnumStudentItemType::InitialCall;
        }
        if (strType == L"Return Visit")
        {
            return EnumStudentItemType::ReturnVisit;
        }
        if (strType == L"Bible Study")
        {
            return EnumStudentItemType::BibleStudy;
        }
        if (strType == L"Talk")
        {
            return EnumStudentItemType::Talk;
        }

        return EnumStudentItemType::Other;
    };

    auto eType = GetStudentItemType(L"Bible Reading");

    return TRUE;  // return TRUE  unless you set the focus to a control
}

It does not like this line:

auto eType = GetStudentItemType(L"Bible Reading");

If I move the enum class into the header, and turn the GetStudentItemType method into a function defined in the header, then that line of code which attempts to get the type does not display errors in the IDE.

So:

How do we define a enum class inside a function (not needed anywhere else)? And ...

Use it as a return value for a lambda?


问:
Problem with accessing elements from DOM in react
I have a tree component in react. The children of a node are added in the DOM only after I expand that node. After I expand a node I want to modify some children of that node, but also a request is made and the expanding takes a bit of time, and I need to set a timeout to be able to modify the children. How can I modify the children only after they appear in the DOM?

`

```<code>import React from "react";
import { useDispatch, useSelector } from "react-redux";
import {
    setSelectedKeys,
    setExpandedKeys,
    setDetails
} from "../../../../actions/tree";
import {doPost} from "../../../../helpers/_http";

const NNPButton  = ({ treeType, selectedDb }) => {
    let dispatch = useDispatch();
    let selectedKeys = useSelector(state => state.tree[treeType].selectedKeys);
    const expandedKeys = useSelector(state => state.tree[treeType].expandedKeys);
    const getSubTreeOnDemand = async (org_id) => {
        const posting = await doPost("ajax/getSubTreeOnDemand", {
            db_name: selectedDb,
            db_type: "Global",
            org_id,
        });
        if (posting.status === 200) {
            return posting.data
        }
    }
    const handleNNPClick = async () => {
        if(expandedKeys.indexOf(selectedKeys[0]) === -1) {
            dispatch(setExpandedKeys([...expandedKeys, selectedKeys[0]], treeType));
        }
        let subTreeOrgs = await getSubTreeOnDemand(selectedKeys[0]);
            console.log(subTreeOrgs);
            setTimeout(() => {
                subTreeOrgs.forEach(org => {
                    document.querySelector(`[title='${org.name} (${org.lm_nokia_name})']`).style.backgroundColor = "red";
                })
            }, 200)
    }
    return(
        <button
            className="dbsButtons"
            id="checkOrgRight"
            type="button"
            data-toggle="tooltip"
            data-placement="botton"
            title="Checks org that is clicked on and his direct children if they comply with Nokia Naming Policy!"
            onClick={() => handleNNPClick()}
        >
            <span className="glyphicon glyphicon-check"></span>
            NNP
        </button>
    );
}

export default NNPBu
</code>```

`

Body:
I have a tree component in react. The children of a node are added in the DOM only after I expand that node. After I expand a node I want to modify some children of that node, but also a request is made and the expanding takes a bit of time, and I need to set a timeout to be able to modify the children. How can I modify the children only after they appear in the DOM?

`

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import {
    setSelectedKeys,
    setExpandedKeys,
    setDetails
} from "../../../../actions/tree";
import {doPost} from "../../../../helpers/_http";

const NNPButton  = ({ treeType, selectedDb }) => {
    let dispatch = useDispatch();
    let selectedKeys = useSelector(state => state.tree[treeType].selectedKeys);
    const expandedKeys = useSelector(state => state.tree[treeType].expandedKeys);
    const getSubTreeOnDemand = async (org_id) => {
        const posting = await doPost("ajax/getSubTreeOnDemand", {
            db_name: selectedDb,
            db_type: "Global",
            org_id,
        });
        if (posting.status === 200) {
            return posting.data
        }
    }
    const handleNNPClick = async () => {
        if(expandedKeys.indexOf(selectedKeys[0]) === -1) {
            dispatch(setExpandedKeys([...expandedKeys, selectedKeys[0]], treeType));
        }
        let subTreeOrgs = await getSubTreeOnDemand(selectedKeys[0]);
            console.log(subTreeOrgs);
            setTimeout(() => {
                subTreeOrgs.forEach(org => {
                    document.querySelector(`[title='${org.name} (${org.lm_nokia_name})']`).style.backgroundColor = "red";
                })
            }, 200)
    }
    return(
        <button
            className="dbsButtons"
            id="checkOrgRight"
            type="button"
            data-toggle="tooltip"
            data-placement="botton"
            title="Checks org that is clicked on and his direct children if they comply with Nokia Naming Policy!"
            onClick={() => handleNNPClick()}
        >

            NNP
        </button>
    );
}

export default NNPBu

`


问:
Pass string as link in allure report message
I am trying to pass a link in assertion error message in the allure report for example:

```<code>assert expression, '...www.google.com...'
</code>```

locally this isn't a problem as i see that in the terminal web addresses are formatted automatically to a URL however when i run the same test on a remote machine the generated allure report shows the same address as a regular string.
I tried using parselib.parse functions (like quote and urlparse) but it didn't help.
I also couldn't find any questions or answers to that anywhere online, the only option i found was attaching the link to the allure report but that is not my goal.

I would like to be able to click on the link appearing in the assertion error message as it may contain several links that i don't want to attach to the report itself.

Example report - marked in this report is the links i want to be clickable

Body:
I am trying to pass a link in assertion error message in the allure report for example:

assert expression, '...www.google.com...'

locally this isn't a problem as i see that in the terminal web addresses are formatted automatically to a URL however when i run the same test on a remote machine the generated allure report shows the same address as a regular string.
I tried using parselib.parse functions (like quote and urlparse) but it didn't help.
I also couldn't find any questions or answers to that anywhere online, the only option i found was attaching the link to the allure report but that is not my goal.

I would like to be able to click on the link appearing in the assertion error message as it may contain several links that i don't want to attach to the report itself.

Example report - marked in this report is the links i want to be clickable


问:
Refund stripe payment
I am using the stripe connect feature. The payment feature is working fine but when I run stripe.refunds.create() method to refund the payment, though it returns successful status but the stripe dashboard does not update.

Request:

const intent = await stripe.refunds.create({
  payment_intent: booking.paymentIntent,
  reason: 'requested_by_customer',
});
```
<p><strong>Response:</strong></p>
<pre class="lang-js prettyprint-override"><code>{
  id: 're_*********************',
  object: 'refund',
  amount: 20000,
  balance_transaction: 'txn_*********************',
  charge: 'ch_*********************',
  created: 1670775881,
  currency: 'usd',
  metadata: {},
  payment_intent: 'pi_*********************',
  reason: 'requested_by_customer',
  receipt_number: null,
  source_transfer_reversal: null,
  status: 'succeeded',
  transfer_reversal: null
}
</code>```

Dashboard:

I am new to stripe. If I am doing anything wrong please help me to find it or give me any article or doc. The stripe doc seems huge and confusing to me.

Title: Refund stripe payment

Body:
I am using the stripe connect feature. The payment feature is working fine but when I run stripe.refunds.create() method to refund the payment, though it returns successful status but the stripe dashboard does not update.

Request:

const intent = await stripe.refunds.create({
  payment_intent: booking.paymentIntent,
  reason: 'requested_by_customer',
});

Response:

{
  id: 're_*********************',
  object: 'refund',
  amount: 20000,
  balance_transaction: 'txn_*********************',
  charge: 'ch_*********************',
  created: 1670775881,
  currency: 'usd',
  metadata: {},
  payment_intent: 'pi_*********************',
  reason: 'requested_by_customer',
  receipt_number: null,
  source_transfer_reversal: null,
  status: 'succeeded',
  transfer_reversal: null
}

Dashboard:

I am new to stripe. If I am doing anything wrong please help me to find it or give me any article or doc. The stripe doc seems huge and confusing to me.


问:
how to set a NX custom command with configuration vars?
So inside my NX workspace, I got multiple projects that need to be deployed differently.

What I would like to have is a deployment script that sorts out the development and production enviroments.

So I would like to be able to run nx run-many -target=deploy --configuration=production

And then have something like this:

"deploy": {
  "executor": "nx:run-commands",
  "configuration": {
    "production": {"deploymentBucket": "s3://prod-bucket"},
    "development": {"deploymentBucket": "s3://dev-bucket"}
  },
  "options": {
    "command": "echo b {deploymentBucket} f"
  }
}
```

So that I can run it in my ci pipeline.

Body:
So inside my NX workspace, I got multiple projects that need to be deployed differently.

What I would like to have is a deployment script that sorts out the development and production enviroments.

So I would like to be able to run nx run-many -target=deploy --configuration=production

And then have something like this:

"deploy": {
  "executor": "nx:run-commands",
  "configuration": {
    "production": {"deploymentBucket": "s3://prod-bucket"},
    "development": {"deploymentBucket": "s3://dev-bucket"}
  },
  "options": {
    "command": "echo b {deploymentBucket} f"
  }
}

So that I can run it in my ci pipeline.


问:
Pygame sprites disappears
I'm working on a doom style game that uses RayCasting and sprites objects. But my sprites disappears after the player turns right side around the image.

This is video with my problem:https://www.youtube.com/watch?v=oWBGlVdpGSg

I tried shrinking the image and also editing them with ImageMagick Display. Nothing helped and I'm desperate.

I follow this video: https://youtu.be/ECqUrT7IdqQ?t=1480

And here is my code (sprite objects):

```<code>import pygame as pg
from settings import *
import os
from collections import deque

class SpriteObject:
    def __init__(self, game, path="resources/sprites/static_sprites/candlebra.png",
                 pos=(10.5, 3.5), scale=0.7, shift=0.27):

        self.game = game
        self.player = game.player
        self.x, self.y = pos
        self.image = pg.image.load(path).convert_alpha()
        self.IMAGE_WIDTH = self.image.get_width()
        self.IMAGE_HALF_WIDTH = self.image.get_width() // 2
        self.IMAGE_RATIO = self.IMAGE_WIDTH / self.image.get_height()
        self.dx, self.dy, self.theta, self.screen_x, self.dist, self.norm_dist = 0, 0, 0, 0, 1, 1
        self.sprite_half_width = 0
        self.SPRITE_SCALE = scale
        self.SPRITE_HEIGHT_SHIFT = shift

    def get_sprite_projection(self):
        proj = SCREEN_DIS / self.norm_dist * self.SPRITE_SCALE
        proj_width, proj_height = proj * self.IMAGE_RATIO, proj

        image = pg.transform.scale(self.image, (proj_width, proj_height))

        self.sprite_half_width = proj_width // 2
        height_shift = proj_height * self.SPRITE_HEIGHT_SHIFT
        pos = self.screen_x - self.sprite_half_width, HALF_HEIGHT - proj_height // 2 + height_shift

        self.game.raycasting.objects_to_render.append((self.norm_dist, image, pos))

    def get_sprite(self):
        dx = self.x - self.player.x
        dy = self.y - self.player.y
        self.dx, self.dy = dx, dy
        self.theta = math.atan2(dy, dx)

        delta = self.theta - self.player.angle
        if (dx > 0 and self.player.angle > math.pi) or (dx < 0 and dy < 0):
            delta += math.tau

        delta_rays = delta / DELTA_ANGLE
        self.screen_x = (HALP_NUM_RAYS + delta_rays) * SCALE

        self.dist = math.hypot(dx, dy)
        self.norm_dist = self.dist * math.cos(delta)
        if -self.IMAGE_HALF_WIDTH < self.screen_x < (WIDTH + self.IMAGE_HALF_WIDTH) and self.norm_dist > 0.9:
            self.get_sprite_projection()

    def update(self):
        self.get_sprite()

class AnimatedSprites(SpriteObject):
    def __init__(self, game, path="resources/sprites/animated_sprites/green_light/0.png",
                 pos=(11.5, 3.5), scale=0.8, shift=0.15, animation_time=120):
        super().__init__(game, path, pos, scale, shift)
        self.animation_time = animation_time
        self.path = path.rsplit("/", 1)[0]
        self.images = self.get_images(self.path)
        self.animation_time_prev = pg.time.get_ticks()
        self.animation_trigger = False

    def update(self):
        super().update()
        self.check_animation_time()
        self.animate(self.images)

    def animate(self, images):
        if self.animation_trigger:
            images.rotate(-1)
            self.image = images[0]

    def check_animation_time(self):
        self.animation_trigger = False
        time_now = pg.time.get_ticks()
        if time_now - self.animation_time_prev > self.animation_time:
            self.animation_time_prev = time_now
            self.animation_trigger = True

    def get_images(self, path):
        images = deque()
        for file_name in os.listdir(path):
            if os.path.isfile(os.path.join(path, file_name)):
                img = pg.image.load(path + "/" + file_name).convert_alpha()
                images.append(img)
        return images
</code>```

Here is main :

```<code>import pygame as pg
import sys
from settings import *
from map import *
from player import *
from raycasting import *
from object_renderer import *
from sprite_object import *
from object_handler import *

class Game:
    def __init__(self):
        pg.init()
        pg.mouse.set_visible(False)
        self.screen = pg.display.set_mode(RES)
        self.clock = pg.time.Clock()
        self.delta_time = 1
        self.new_game()

    def new_game(self):
        self.map = Map(self)
        self.player = Player(self)
        self.object_renderer = ObjectRenderer(self)
        self.raycasting = RayCasting(self)
        self.object_handler = ObjectHandler(self)

    def update(self):
        self.player.update()
        self.raycasting.update()
        self.object_handler.update()
        pg.display.flip()
        self.delta_time = self.clock.tick(FPS)
        pg.display.set_caption(f"{self.clock.get_fps()} :.1f")

    def draw(self):
        #self.screen.fill("black")
        self.object_renderer.draw()
        # self.map.draw()
        # self.player.draw()

    def check_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
                pg.quit()
                sys.exit()

    def run(self):
        while True:
            self.check_events()
            self.update()
            self.draw()

if __name__ == "__main__":
    game = Game()
    game.run()
</code>```

Title: Pygame sprites disappears

Body:
I'm working on a doom style game that uses RayCasting and sprites objects. But my sprites disappears after the player turns right side around the image.

This is video with my problem:https://www.youtube.com/watch?v=oWBGlVdpGSg

I tried shrinking the image and also editing them with ImageMagick Display. Nothing helped and I'm desperate.

I follow this video: https://youtu.be/ECqUrT7IdqQ?t=1480

And here is my code (sprite objects):

import pygame as pg
from settings import *
import os
from collections import deque

class SpriteObject:
    def __init__(self, game, path="resources/sprites/static_sprites/candlebra.png",
                 pos=(10.5, 3.5), scale=0.7, shift=0.27):

        self.game = game
        self.player = game.player
        self.x, self.y = pos
        self.image = pg.image.load(path).convert_alpha()
        self.IMAGE_WIDTH = self.image.get_width()
        self.IMAGE_HALF_WIDTH = self.image.get_width() // 2
        self.IMAGE_RATIO = self.IMAGE_WIDTH / self.image.get_height()
        self.dx, self.dy, self.theta, self.screen_x, self.dist, self.norm_dist = 0, 0, 0, 0, 1, 1
        self.sprite_half_width = 0
        self.SPRITE_SCALE = scale
        self.SPRITE_HEIGHT_SHIFT = shift

    def get_sprite_projection(self):
        proj = SCREEN_DIS / self.norm_dist * self.SPRITE_SCALE
        proj_width, proj_height = proj * self.IMAGE_RATIO, proj

        image = pg.transform.scale(self.image, (proj_width, proj_height))

        self.sprite_half_width = proj_width // 2
        height_shift = proj_height * self.SPRITE_HEIGHT_SHIFT
        pos = self.screen_x - self.sprite_half_width, HALF_HEIGHT - proj_height // 2 + height_shift

        self.game.raycasting.objects_to_render.append((self.norm_dist, image, pos))

    def get_sprite(self):
        dx = self.x - self.player.x
        dy = self.y - self.player.y
        self.dx, self.dy = dx, dy
        self.theta = math.atan2(dy, dx)

        delta = self.theta - self.player.angle
        if (dx > 0 and self.player.angle > math.pi) or (dx < 0 and dy < 0):
            delta += math.tau

        delta_rays = delta / DELTA_ANGLE
        self.screen_x = (HALP_NUM_RAYS + delta_rays) * SCALE

        self.dist = math.hypot(dx, dy)
        self.norm_dist = self.dist * math.cos(delta)
        if -self.IMAGE_HALF_WIDTH < self.screen_x < (WIDTH + self.IMAGE_HALF_WIDTH) and self.norm_dist > 0.9:
            self.get_sprite_projection()

    def update(self):
        self.get_sprite()

class AnimatedSprites(SpriteObject):
    def __init__(self, game, path="resources/sprites/animated_sprites/green_light/0.png",
                 pos=(11.5, 3.5), scale=0.8, shift=0.15, animation_time=120):
        super().__init__(game, path, pos, scale, shift)
        self.animation_time = animation_time
        self.path = path.rsplit("/", 1)[0]
        self.images = self.get_images(self.path)
        self.animation_time_prev = pg.time.get_ticks()
        self.animation_trigger = False

    def update(self):
        super().update()
        self.check_animation_time()
        self.animate(self.images)

    def animate(self, images):
        if self.animation_trigger:
            images.rotate(-1)
            self.image = images[0]

    def check_animation_time(self):
        self.animation_trigger = False
        time_now = pg.time.get_ticks()
        if time_now - self.animation_time_prev > self.animation_time:
            self.animation_time_prev = time_now
            self.animation_trigger = True

    def get_images(self, path):
        images = deque()
        for file_name in os.listdir(path):
            if os.path.isfile(os.path.join(path, file_name)):
                img = pg.image.load(path + "/" + file_name).convert_alpha()
                images.append(img)
        return images

Here is main :

import pygame as pg
import sys
from settings import *
from map import *
from player import *
from raycasting import *
from object_renderer import *
from sprite_object import *
from object_handler import *

class Game:
    def __init__(self):
        pg.init()
        pg.mouse.set_visible(False)
        self.screen = pg.display.set_mode(RES)
        self.clock = pg.time.Clock()
        self.delta_time = 1
        self.new_game()

    def new_game(self):
        self.map = Map(self)
        self.player = Player(self)
        self.object_renderer = ObjectRenderer(self)
        self.raycasting = RayCasting(self)
        self.object_handler = ObjectHandler(self)

    def update(self):
        self.player.update()
        self.raycasting.update()
        self.object_handler.update()
        pg.display.flip()
        self.delta_time = self.clock.tick(FPS)
        pg.display.set_caption(f"{self.clock.get_fps()} :.1f")

    def draw(self):
        #self.screen.fill("black")
        self.object_renderer.draw()
        # self.map.draw()
        # self.player.draw()

    def check_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
                pg.quit()
                sys.exit()

    def run(self):
        while True:
            self.check_events()
            self.update()
            self.draw()

if __name__ == "__main__":
    game = Game()
    game.run()


问:
Scraping data from https://cardano.ideascale.com webpage, but server noticed I am using Internet Explorer

I am scraping the content of this link. And my procedure is:

GET-TOKEN to get a Bearer token.

GET Fork Gitcoin and deploy on Cardano using the above token in the header and get json content in response.

My issue was when i run my below code, when run get /detail I got response as I am using Internet  Explorer to access, that is weird because my request header has "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36".

We noticed you are using Internet Explorer. We don\'t have support for this browser in Incoming Moderation!

We recommend using the Microsoft Edge Browser, Chrome, Firefox or Safari. Click for more
                info.

```
<ul>
<li><p>Can anyone explain the error and teach me how to fix it?</p>
</li>
<li><p>Below is my python code.</p>
</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import requests

def get_content(url):
    s = requests.session()

    response = s.get(f"https://cardano.ideascale.com/a/community/api/get-token")
    if response.status_code != 200:
        print(f"\033[4m\033[1m{response.status_code}\033[0m")
        return None

    cookies = response.cookies

    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
        'Accept': 'application/json,',
        'Accept-Language': 'en-US,en;q=0.5',
        'Accept-Encoding': 'gzip, deflate',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Authorization': f'Bearer {response.content.decode("utf-8")}',
        'Alt-Used': 'cardano.ideascale.com',
        'Connection': 'keep-alive',
        'Referer': url,
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'TE': 'trailers',
    }

    #import ipdb; ipdb.set_trace()
    response = s.get(f"{url}/detail", headers=headers, cookies=cookies)
    print(response.content)

get_content("https://cardano.ideascale.com/c/idea/317821")
</code>```

Body:
I am scraping the content of this link. And my procedure is:

GET-TOKEN to get a Bearer token.

GET Fork Gitcoin and deploy on Cardano using the above token in the header and get json content in response.

My issue was when i run my below code, when run get /detail I got response as I am using Internet  Explorer to access, that is weird because my request header has "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36".

We noticed you are using Internet Explorer. We don\'t have support for this browser in Incoming Moderation!

We recommend using the Microsoft Edge Browser, Chrome, Firefox or Safari. Click for more
                info.

Can anyone explain the error and teach me how to fix it?

Below is my python code.

import requests

def get_content(url):
    s = requests.session()

    response = s.get(f"https://cardano.ideascale.com/a/community/api/get-token")
    if response.status_code != 200:
        print(f"\033[4m\033[1m{response.status_code}\033[0m")
        return None

    cookies = response.cookies

    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
        'Accept': 'application/json,',
        'Accept-Language': 'en-US,en;q=0.5',
        'Accept-Encoding': 'gzip, deflate',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Authorization': f'Bearer {response.content.decode("utf-8")}',
        'Alt-Used': 'cardano.ideascale.com',
        'Connection': 'keep-alive',
        'Referer': url,
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'TE': 'trailers',
    }

    #import ipdb; ipdb.set_trace()
    response = s.get(f"{url}/detail", headers=headers, cookies=cookies)
    print(response.content)

get_content("https://cardano.ideascale.com/c/idea/317821")


问:
Color detection in android (java) delivers wrong RGB values
I am trying to make a program in Android Studio using java, where I can determine the RGB values at the point where the user clicked on the image. The code is working so far, but it gives wrong RGB values as output. They also seem to vary, based on the location where I click, even if the color that should be put out is the same. My guess is, that there is something up with the Bitmap, that I don't know about.

My MainActivity :

```<code>package com.example.fitme;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        final int evX = (int) ev.getX();
        final  int evY = (int) ev.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN :
                break;
            case MotionEvent.ACTION_UP :
                ImageView img = (ImageView) findViewById (R.id.body_front_map);
                img.setDrawingCacheEnabled(true);
                Bitmap imgbmp = Bitmap.createBitmap(img.getDrawingCache());
                img.setDrawingCacheEnabled(false);
                int pxl = imgbmp.getPixel(evX, evY);
                int redComponent = Color.red(pxl);
                int greenComponent = Color.green(pxl);
                int blueComponent = Color.blue(pxl);

                Toast.makeText(MainActivity.this,"RED: "+redComponent+" GREEN: "+greenComponent+" BLUE: "+blueComponent, Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }
}
</code>```

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/body_front_map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:background="@drawable/body_front_map"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The Image I am trying to use

Body:
I am trying to make a program in Android Studio using java, where I can determine the RGB values at the point where the user clicked on the image. The code is working so far, but it gives wrong RGB values as output. They also seem to vary, based on the location where I click, even if the color that should be put out is the same. My guess is, that there is something up with the Bitmap, that I don't know about.

My MainActivity :

package com.example.fitme;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        final int evX = (int) ev.getX();
        final  int evY = (int) ev.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN :
                break;
            case MotionEvent.ACTION_UP :
                ImageView img = (ImageView) findViewById (R.id.body_front_map);
                img.setDrawingCacheEnabled(true);
                Bitmap imgbmp = Bitmap.createBitmap(img.getDrawingCache());
                img.setDrawingCacheEnabled(false);
                int pxl = imgbmp.getPixel(evX, evY);
                int redComponent = Color.red(pxl);
                int greenComponent = Color.green(pxl);
                int blueComponent = Color.blue(pxl);

                Toast.makeText(MainActivity.this,"RED: "+redComponent+" GREEN: "+greenComponent+" BLUE: "+blueComponent, Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/body_front_map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:background="@drawable/body_front_map"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

The Image I am trying to use


问:
How to send large custom struct over HTTP in Rust lang using reqwest, tokio and actix_web

Issue

I have a client that needs to send the following custom data structure to an API:

```<code>#[derive(Serialize, Deserialize)]
pub struct FheSum {
    pub server_keys: ServerKey,
    pub value1: FheUint8,
    pub value2: FheUint8,
}
</code>```

The code for the client is the following:

```<code>let fhe_post: FheSum = FheSum {
        server_keys: server_keys.to_owned(),
        value1: value_api.to_owned(),
        value2: value_api_2.to_owned(),
};

let client = reqwest::blocking::Client::builder()
        .timeout(None)
        .build().unwrap();

let response = client
        .post("http://127.0.0.1:8000/computesum")
        .json(&fhe_post)
        .send().unwrap();

let response_json: Result<FheSumResult, reqwest::Error> = response.json();

match response_json {
        Ok(j) => {
            let result_api: u8 = FheUint8::decrypt(&j.result, &client_keys);
            println!("Final Result: {}", result_api)
        },
        Err(e) => println!("{:}", e),
};
</code>```

In the API, I have the following definition of an HttpServer:

```<code>HttpServer::new(|| {
        let json_cfg = actix_web::web::JsonConfig::default()
        .limit(std::usize::MAX);

        App::new()
        .app_data(json_cfg)
        .service(integers::computesum)
    })
    .client_disconnect_timeout(std::time::Duration::from_secs(3000))
    .client_request_timeout(std::time::Duration::from_secs(3000))
    .max_connection_rate(std::usize::MAX)
    .bind(("127.0.0.1", 8000))?
    .run()
    .await
</code>```

And the associated endpoint the client is trying to access:

```<code>#[post("/computesum")]
pub async fn computesum(req: Json<FheSum>) -> HttpResponse {
    let req: FheSum = req.into_inner();
    let recovered: FheSum = FheSum::new(
        req.server_keys,
        req.value1,
        req.value2,
    );

    set_server_key(recovered.server_keys);

    let result_api_enc: FheSumResult = FheSumResult::new(recovered.value1 + recovered.value2);

    HttpResponse::Ok()
        .content_type(ContentType::json())
        .json(&result_api_enc)
}
</code>```

Problem

The structs are the same in both the client and the server. This code works when using common data types such as Strings. The issue is when using this data structures. The memory occupied, obtained with mem::size_of_val which returns the size in bytes, is the following:

```<code>Size 1: 2488
Size 2: 32
Size 3: 32
</code>```

The result has been obtained in bytes, so, given the limit established in the HttpServer, this shouldn't be an issue. Timeouts have also been set at much higher values than commonly needed.
Even with this changes, the client always shows Killed, and doesn't display the answer from the server, not giving any clues on what the problem might be.

The client is killing the process before being able to process the server's response. I want to find a way to send these custom data types to the HTTP server without the connection closing before the operation has finished.

I have already tried different libraries for the client such as the acw crate, apart from reqwest and the result is the same. I have also tried not using reqwest in blocking mode, and the error persists.

Body:
Issue

I have a client that needs to send the following custom data structure to an API:

#[derive(Serialize, Deserialize)]
pub struct FheSum {
    pub server_keys: ServerKey,
    pub value1: FheUint8,
    pub value2: FheUint8,
}

The code for the client is the following:

let fhe_post: FheSum = FheSum {
        server_keys: server_keys.to_owned(),
        value1: value_api.to_owned(),
        value2: value_api_2.to_owned(),
};

let client = reqwest::blocking::Client::builder()
        .timeout(None)
        .build().unwrap();

let response = client
        .post("http://127.0.0.1:8000/computesum")
        .json(&fhe_post)
        .send().unwrap();

let response_json: Result<FheSumResult, reqwest::Error> = response.json();

match response_json {
        Ok(j) => {
            let result_api: u8 = FheUint8::decrypt(&j.result, &client_keys);
            println!("Final Result: {}", result_api)
        },
        Err(e) => println!("{:}", e),
};

In the API, I have the following definition of an HttpServer:

HttpServer::new(|| {
        let json_cfg = actix_web::web::JsonConfig::default()
        .limit(std::usize::MAX);

        App::new()
        .app_data(json_cfg)
        .service(integers::computesum)
    })
    .client_disconnect_timeout(std::time::Duration::from_secs(3000))
    .client_request_timeout(std::time::Duration::from_secs(3000))
    .max_connection_rate(std::usize::MAX)
    .bind(("127.0.0.1", 8000))?
    .run()
    .await

And the associated endpoint the client is trying to access:

#[post("/computesum")]
pub async fn computesum(req: Json<FheSum>) -> HttpResponse {
    let req: FheSum = req.into_inner();
    let recovered: FheSum = FheSum::new(
        req.server_keys,
        req.value1,
        req.value2,
    );

    set_server_key(recovered.server_keys);

    let result_api_enc: FheSumResult = FheSumResult::new(recovered.value1 + recovered.value2);

    HttpResponse::Ok()
        .content_type(ContentType::json())
        .json(&result_api_enc)
}

Problem

The structs are the same in both the client and the server. This code works when using common data types such as Strings. The issue is when using this data structures. The memory occupied, obtained with mem::size_of_val which returns the size in bytes, is the following:

Size 1: 2488
Size 2: 32
Size 3: 32

The result has been obtained in bytes, so, given the limit established in the HttpServer, this shouldn't be an issue. Timeouts have also been set at much higher values than commonly needed.
Even with this changes, the client always shows Killed, and doesn't display the answer from the server, not giving any clues on what the problem might be.

The client is killing the process before being able to process the server's response. I want to find a way to send these custom data types to the HTTP server without the connection closing before the operation has finished.

I have already tried different libraries for the client such as the acw crate, apart from reqwest and the result is the same. I have also tried not using reqwest in blocking mode, and the error persists.