问:
How to get parameter from GET on ORMAdapter
I use this plugin https://packagist.org/packages/omines/datatables-bundle for my datatable on symfony and i searcg system with GET parameter pass on link $is_delete=true if user click on like to display projects deleted only, when user have click on this pagen, the page reload with new parameter $is_delete=true

When i have this parameter, i want to edit my ORMAdapter but he don't work, because i think the datatable is load on another HTTP Request without my previous GET parameter from original page ?

```<code>->createAdapter(ORMAdapter::class, [
      'entity' => Project::class,
      'query' => function (QueryBuilder $builder, DataTableState $state) use ($request) {
          if($request->get('is_delete') === 'true') {
              $builder
                  ->select('p')
                  ->from(Project::class, 'p')
                  ->where('p.isActive = false')
                  ->andWhere('YEAR(p.addedAt) = :year')
                  ->setParameter('year', date('Y'));
          } else {
              $builder
                  ->select('p')
                  ->from(Project::class, 'p')
                  ->where('p.isActive = true')
                  ->andWhere('YEAR(p.addedAt) = :year')
                  ->setParameter('year', date('Y'));
          }
          dump($test);
          dump($state->getGlobalSearch());
      }
  ])
</code>```

If you can help me thx a lot

Body:
I use this plugin https://packagist.org/packages/omines/datatables-bundle for my datatable on symfony and i searcg system with GET parameter pass on link $is_delete=true if user click on like to display projects deleted only, when user have click on this pagen, the page reload with new parameter $is_delete=true

When i have this parameter, i want to edit my ORMAdapter but he don't work, because i think the datatable is load on another HTTP Request without my previous GET parameter from original page ?

->createAdapter(ORMAdapter::class, [
      'entity' => Project::class,
      'query' => function (QueryBuilder $builder, DataTableState $state) use ($request) {
          if($request->get('is_delete') === 'true') {
              $builder
                  ->select('p')
                  ->from(Project::class, 'p')
                  ->where('p.isActive = false')
                  ->andWhere('YEAR(p.addedAt) = :year')
                  ->setParameter('year', date('Y'));
          } else {
              $builder
                  ->select('p')
                  ->from(Project::class, 'p')
                  ->where('p.isActive = true')
                  ->andWhere('YEAR(p.addedAt) = :year')
                  ->setParameter('year', date('Y'));
          }
          dump($test);
          dump($state->getGlobalSearch());
      }
  ])

If you can help me thx a lot


来源: stackexchange

问:
Would this .htaccess double index in google?
Would this htaccess double index? It's working fine for making urls pretty (removing .html, removing / and just having example.com/subdomain) but I don't know if google or any other search engines would have problems with it, since I read it might double index some times. Thanks.</p>
```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [QSA,L]

RewriteEngine on

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Would this htaccess double index? It's working fine for making urls pretty (removing .html, removing / and just having example.com/subdomain) but I don't know if google or any other search engines would have problems with it, since I read it might double index some times. Thanks.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [QSA,L]

RewriteEngine on

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]


问:
SQL Server Expand JSON to Columns - THIS IS NOT about Pivoting Table
I have a use case where I want to convert json stored in a table to be expanded as columns. Now the issue is that Json contains object + arrays + nested array e.g.

{prop1: "Hi", prop2Arr: [{aP1: "Bye", aP2: "Bye2", aP3: "Bye3" }, {aP1: "Bye", aP2: "Bye2", aP3: "Bye3" }], prop3: "", prop4Arr: []}

above is just a sample; actual json is longer; I'm finding a way to dynamically extract the keys and bring them into results as columns along with other Non-json columns

Non-Json-Col
Prop1
Prop2Arr_0_aP1
Prop2Arr_0_aP2
Prop2Arr_0_aP3
Prop2Arr_1_aP1

Cell 1
Cell 2
Bye
Bye 2
Bye 3

That array length is not fixed. It can be 0, 1 to nth.

I tried OPENJSON, but I have to define the json properties manually, and the array is not being handled the way I mentioned above.

Looking for someone with a similar use case and how did you resolve or, I will say, how that can be achievable?

I was thinking of generating the SQL statement via stored proc and executing it dynamically. Still, I cannot find a way to extract keys, handle the array, and make them flatten.


问:
Extract dataframes from activity_log object
I have the code below

```<code>library(bupar)
library(daqapo)
hospital<-hospital
hospital %>%
  rename(start = start_ts,
         complete = complete_ts) -> hospital
hospital %>%
  convert_timestamps(c("start","complete"), format = dmy_hms) -> hospital
hospital %>%
  activitylog(case_id = "patient_visit_nr",
              activity_id = "activity",
              resource_id = "originator",
              timestamps = c("start", "complete")) -> hospital
hospital %>%
  detect_missing_values()
</code>```

which gives

```<code>Absolute number of missing values per column:

patient_visit_nr 0
activity         0
originator       2
start            1
complete         0
triagecode       1
specialization   0
.order           0
Relative number of missing values per column (expressed as percentage):

patient_visit_nr 0.000000
activity         0.000000
originator       3.773585
start            1.886792
complete         0.000000
triagecode       1.886792
specialization   0.000000
.order           0.000000
</code>```

how can I extract those two dataframes merged as one?

Body:
I have the code below

library(bupar)
library(daqapo)
hospital<-hospital
hospital %>%
  rename(start = start_ts,
         complete = complete_ts) -> hospital
hospital %>%
  convert_timestamps(c("start","complete"), format = dmy_hms) -> hospital
hospital %>%
  activitylog(case_id = "patient_visit_nr",
              activity_id = "activity",
              resource_id = "originator",
              timestamps = c("start", "complete")) -> hospital
hospital %>%
  detect_missing_values()

which gives

Absolute number of missing values per column:

patient_visit_nr 0
activity         0
originator       2
start            1
complete         0
triagecode       1
specialization   0
.order           0
Relative number of missing values per column (expressed as percentage):

patient_visit_nr 0.000000
activity         0.000000
originator       3.773585
start            1.886792
complete         0.000000
triagecode       1.886792
specialization   0.000000
.order           0.000000

how can I extract those two dataframes merged as one?


问:
unable to pass data from laravel 9 blade to vue 3 components
when I tried in Vue 2 It worked but Vue 3 not working. Please help me.

```<code><template>
    <p class="text-blue-600">The quick brown fox...</p>

      <div class="inline-flex justify-between w-full">
          <h1>{{ nodeGroups }} Hi</h1>

      </div>

</template>

<script >
export default{
    props:['nodeGroups'],

    mounted () {
      // Do something useful with the data in the template
      console.dir(this.nodeGroups)
    }

}

</script>

</code>```

import { createApp } from "vue";

import Welcome from "./components/test.vue";

createApp(Welcome).mount("#app");

larvel blade

```<code><div id="app">
            {{-- <node-group></node-group> --}}
            <Welcome :nodeGroups="'abc'"></Welcome>
        </div>
</code>```

Body:
when I tried in Vue 2 It worked but Vue 3 not working. Please help me.

<template>

The quick brown fox...

{{ nodeGroups }} Hi

</template>

import { createApp } from "vue";

import Welcome from "./components/test.vue";

createApp(Welcome).mount("#app");

larvel blade

            {{-- <node-group></node-group> --}}
            <Welcome :nodeGroups="'abc'"></Welcome>


问:
Vite Plugin Not Writing Compressed Assets
I've written the following plugin for Vite that should compress SVG assets using SVGO.

onst { crawl } = require('recrawl-sync')
const { normalizePath } = require('vite')
const { optimize } = require('svgo')
const path = require('path')
const fs = require('fs')

const VITE_PLUGIN_NAME = 'vite-plugin-svgo'
let outRoot
const svgExt = /\.svg$/
const options = {
  cleanupAttrs: true,
  removeDoctype: true,
  removeXMLProcInst: true,
  removeComments: true,
  removeMetadata: true,
  removeTitle: true,
  removeDesc: true,
  removeUselessDefs: true,
  removeEditorsNSData: true,
  removeEmptyAttrs: true,
  removeHiddenElems: true,
  removeEmptyText: true,
  removeEmptyContainers: true,
  removeViewBox: false,
  cleanupEnableBackground: true,
  convertStyleToAttrs: true,
  convertColors: true,
  convertPathData: true,
  convertTransform: true,
  removeUnknownsAndDefaults: true,
  removeNonInheritableGroupAttrs: true,
  removeUselessStrokeAndFill: true,
  removeUnusedNS: true,
  cleanupIDs: true,
  cleanupNumericValues: true,
  moveElemsAttrsToGroup: true,
  moveGroupAttrsToElems: true,
  collapseGroups: true,
  removeRasterImages: false,
  mergePaths: true,
  convertShapeToPath: true,
  sortAttrs: true,
  removeDimensions: true,
  removeAttrs: { attrs: '(stroke|fill)' },
}

async function optimizeSvg (unminifiedString) {
  const svg = await optimize(unminifiedString, {
    multipass: true,
    ...options,
  })
  return svg.data
}

const exportFn = () => {
  return {
    name: VITE_PLUGIN_NAME,
    apply: 'build',
    configResolved ({ root, build: { outDir } }) {
      outRoot = normalizePath(path.resolve(root, outDir))
    },
    async buildEnd () {
      const files = crawl(outRoot, {
        skip: ['.DS_Store'],
      })
      await Promise.all(
        files.map(async (name) => {
          const filePath = path.posix.join(outRoot, name)
          if (svgExt.test(name)) {
            const unminifiedString = await fs.promises.readFile(filePath, 'utf8')
            const minifiedString = await optimizeSvg(unminifiedString)

            console.log('File :', filePath)
            console.log('Savings: ', unminifiedString.length - minifiedString.length)
            console.log('Writing to: ', filePath)

            const buffer = Buffer.from(minifiedString)
            if (buffer) {
              await fs.promises.writeFile(filePath, buffer)
            }
          }
        }))
      console.log('Done!')
    },
  }
}

module.exports = exportFn
```
<p>I'm then using it inside of the Vite Configuration file. I'm able to see logs from the plugin that tell me it's working:</p>
```File: /app/dist/images/svg/user-1.svg
Savings: 300
Writing to: /app/dist/images/svg/user-1.svg

...
```
<p>However, after the build completes, I'm inspecting the size of the assets in the <code>dist</code> folder like this:</p>
```$ ls -lahSr /app/dist/images
```

And comparing it to the unminified version of these SVGs from the original public folder in my project. They don't seem to be any different. Why does the buildEnd function here not write the minified files to their location in the dist folder? Are they being overwritten at some point?

Body:
I've written the following plugin for Vite that should compress SVG assets using SVGO.

onst { crawl } = require('recrawl-sync')
const { normalizePath } = require('vite')
const { optimize } = require('svgo')
const path = require('path')
const fs = require('fs')

const VITE_PLUGIN_NAME = 'vite-plugin-svgo'
let outRoot
const svgExt = /\.svg$/
const options = {
  cleanupAttrs: true,
  removeDoctype: true,
  removeXMLProcInst: true,
  removeComments: true,
  removeMetadata: true,
  removeTitle: true,
  removeDesc: true,
  removeUselessDefs: true,
  removeEditorsNSData: true,
  removeEmptyAttrs: true,
  removeHiddenElems: true,
  removeEmptyText: true,
  removeEmptyContainers: true,
  removeViewBox: false,
  cleanupEnableBackground: true,
  convertStyleToAttrs: true,
  convertColors: true,
  convertPathData: true,
  convertTransform: true,
  removeUnknownsAndDefaults: true,
  removeNonInheritableGroupAttrs: true,
  removeUselessStrokeAndFill: true,
  removeUnusedNS: true,
  cleanupIDs: true,
  cleanupNumericValues: true,
  moveElemsAttrsToGroup: true,
  moveGroupAttrsToElems: true,
  collapseGroups: true,
  removeRasterImages: false,
  mergePaths: true,
  convertShapeToPath: true,
  sortAttrs: true,
  removeDimensions: true,
  removeAttrs: { attrs: '(stroke|fill)' },
}

async function optimizeSvg (unminifiedString) {
  const svg = await optimize(unminifiedString, {
    multipass: true,
    ...options,
  })
  return svg.data
}

const exportFn = () => {
  return {
    name: VITE_PLUGIN_NAME,
    apply: 'build',
    configResolved ({ root, build: { outDir } }) {
      outRoot = normalizePath(path.resolve(root, outDir))
    },
    async buildEnd () {
      const files = crawl(outRoot, {
        skip: ['.DS_Store'],
      })
      await Promise.all(
        files.map(async (name) => {
          const filePath = path.posix.join(outRoot, name)
          if (svgExt.test(name)) {
            const unminifiedString = await fs.promises.readFile(filePath, 'utf8')
            const minifiedString = await optimizeSvg(unminifiedString)

            console.log('File :', filePath)
            console.log('Savings: ', unminifiedString.length - minifiedString.length)
            console.log('Writing to: ', filePath)

            const buffer = Buffer.from(minifiedString)
            if (buffer) {
              await fs.promises.writeFile(filePath, buffer)
            }
          }
        }))
      console.log('Done!')
    },
  }
}

module.exports = exportFn

I'm then using it inside of the Vite Configuration file. I'm able to see logs from the plugin that tell me it's working:

File: /app/dist/images/svg/user-1.svg
Savings: 300
Writing to: /app/dist/images/svg/user-1.svg

...

However, after the build completes, I'm inspecting the size of the assets in the dist folder like this:

$ ls -lahSr /app/dist/images

And comparing it to the unminified version of these SVGs from the original public folder in my project. They don't seem to be any different. Why does the buildEnd function here not write the minified files to their location in the dist folder? Are they being overwritten at some point?


问:
Replace NaN values in dataframe column with values from another data frame when column values match
I have a dataframe "df" that has many thousands of rows and NaN values in "Waist":

Dataframe "df"

```<code>Height  Weight  Bust  Cup     Waist   Sales    Returns
64      130     34    4       NaN     10       1
65      130     34    3       27      11       4
66      130     34    3       26      9        5
65      130     34    3       NaN     3        2
64      130     34    3       28      5        1
64      130     34    3       NaN     6        1
67      129     33    4       26      7        4
68      130     33    3       27      6        3
66      130     33    3       27      4        3
</code>```

I have a second dataframe "dfwaist" which is smaller in both number of rows and columns. 'dfwaist' only contains Height, Weight, Bust, Cup, Waist, and Count.

I'd like to return the value of "Waist" from 'dfwaist' where the values for Height, Weight, Bust, and Cup match 'df' and replace the NaN values in 'df' with the returned values. If there is no match, leave the NaN in place.

Dataframe 'dfwaist'

```<code>Height  Weight  Bust  Cup     Waist   Count
64      130     34    4       27      79
65      130     34    3       27      76
66      130     34    3       26      72
65      130     34    3       26      63
64      130     34    3       28      55
64      130     34    3       28      46
67      129     33    4       26      47
68      130     33    3       27      36
66      130     33    3       27      24
</code>```

Desired output for 'df'

```<code>Height  Weight  Bust  Cup     Waist   Sales    Returns
64      130     34    4       27      10       1
65      130     34    3       27      11       4
66      130     34    3       26      9        5
65      130     34    3       26      3        2
64      130     34    3       28      5        1
64      130     34    3       28      6        1
67      129     33    4       26      7        4
68      130     33    3       27      6        3
66      130     33    3       27      4        3
</code>```

Is there a way to return and overwrite NaN values in my first data frame with those found in the second conditionally?

I've already tried .combine_first() and .merge() and both fail because both assume the same shape between the data frames as is suggested in Pandas fill missing values in dataframe from another dataframe

.fillna() also assumes the same shape between the dataframes as is suggested in proper way to replace NaN value from another dataframe on column match in pandas
It also requires a common index to be set, but a common index doesn't exist between the two dataframes.

.combine_first() is promising, but it would fill at most one of the rows in "df" and wouldn't respect the combination of Height, Weight, Bust, and Cup required before combining "df" and "dfwaist". This was suggested in how can I replace NaN value with data from another dataframe in python?

replacing values in a pandas dataframe with values from another dataframe based common columns will not preserve the order of the data, and requires the creation of a third dataframe.

Lastly, I've tried disregarding the second data frame entirely and filling NaN values with the .mode() of the Waist column when the combination of Height, Weight, Bust, and Cup is grouped in a .groupby(). The first V1 fails because of a key error: 0. The second fails to run. The third runs, but imputes NaN values over previously "good" values.

```<code># For every Height, Weight, Bust, Cup combination, populate the 'Waist' feature with the mode of the combination.
# V1
#df['Waist'] = df.groupby(['Height', 'Weight', 'Bust', 'Cup','Waist']).Waist.apply(lambda x: x.fillna(x.mode()[]))
# V2
#df['Waist'] = df.groupby(['Height', 'Weight', 'Bust', 'Cup','Waist'])['Waist'].apply(lambda x: x.fillna(x.mode([0])))
# V3
#df['Waist'] = df.groupby(['Height','Weight','Bust','Cup','Waist']).agg(pd.Series.mode).apply(lambda x: x.fillna(x.mode([4])))
</code>```

Body:
I have a dataframe "df" that has many thousands of rows and NaN values in "Waist":

Dataframe "df"

Height  Weight  Bust  Cup     Waist   Sales    Returns
64      130     34    4       NaN     10       1
65      130     34    3       27      11       4
66      130     34    3       26      9        5
65      130     34    3       NaN     3        2
64      130     34    3       28      5        1
64      130     34    3       NaN     6        1
67      129     33    4       26      7        4
68      130     33    3       27      6        3
66      130     33    3       27      4        3

I have a second dataframe "dfwaist" which is smaller in both number of rows and columns. 'dfwaist' only contains Height, Weight, Bust, Cup, Waist, and Count.

I'd like to return the value of "Waist" from 'dfwaist' where the values for Height, Weight, Bust, and Cup match 'df' and replace the NaN values in 'df' with the returned values. If there is no match, leave the NaN in place.

Dataframe 'dfwaist'

Height  Weight  Bust  Cup     Waist   Count
64      130     34    4       27      79
65      130     34    3       27      76
66      130     34    3       26      72
65      130     34    3       26      63
64      130     34    3       28      55
64      130     34    3       28      46
67      129     33    4       26      47
68      130     33    3       27      36
66      130     33    3       27      24

Desired output for 'df'

Height  Weight  Bust  Cup     Waist   Sales    Returns
64      130     34    4       27      10       1
65      130     34    3       27      11       4
66      130     34    3       26      9        5
65      130     34    3       26      3        2
64      130     34    3       28      5        1
64      130     34    3       28      6        1
67      129     33    4       26      7        4
68      130     33    3       27      6        3
66      130     33    3       27      4        3

Is there a way to return and overwrite NaN values in my first data frame with those found in the second conditionally?

I've already tried .combine_first() and .merge() and both fail because both assume the same shape between the data frames as is suggested in Pandas fill missing values in dataframe from another dataframe

.fillna() also assumes the same shape between the dataframes as is suggested in proper way to replace NaN value from another dataframe on column match in pandas
It also requires a common index to be set, but a common index doesn't exist between the two dataframes.

.combine_first() is promising, but it would fill at most one of the rows in "df" and wouldn't respect the combination of Height, Weight, Bust, and Cup required before combining "df" and "dfwaist". This was suggested in how can I replace NaN value with data from another dataframe in python?

replacing values in a pandas dataframe with values from another dataframe based common columns will not preserve the order of the data, and requires the creation of a third dataframe.

Lastly, I've tried disregarding the second data frame entirely and filling NaN values with the .mode() of the Waist column when the combination of Height, Weight, Bust, and Cup is grouped in a .groupby(). The first V1 fails because of a key error: 0. The second fails to run. The third runs, but imputes NaN values over previously "good" values.

# For every Height, Weight, Bust, Cup combination, populate the 'Waist' feature with the mode of the combination.
# V1
#df['Waist'] = df.groupby(['Height', 'Weight', 'Bust', 'Cup','Waist']).Waist.apply(lambda x: x.fillna(x.mode()[]))
# V2
#df['Waist'] = df.groupby(['Height', 'Weight', 'Bust', 'Cup','Waist'])['Waist'].apply(lambda x: x.fillna(x.mode([0])))
# V3
#df['Waist'] = df.groupby(['Height','Weight','Bust','Cup','Waist']).agg(pd.Series.mode).apply(lambda x: x.fillna(x.mode([4])))


问:
Getting the exact amount of bits needed for a type in c++
I have an array with bytes : ByteSource byteSource and I have a function

```<code>template<class target_t>
target_t BitReader<max_bytes>::readBits(size_t bitCount) {
</code>```

In this function, I take bits out of the array (bitCount amount of bits) and put them into a T value.

After I am done with that, I have to check how many bits the target_t needs, if my bitcount is below that, I have to fill the value with 0's.

I am using const size_t bits = sizeof(target_t) * 8; but was wondering if this would be correct since in case I need for example 4 bits (instead a whole byte). Wouldn't I just be filling my value with 0's that aren't need?

Body:
I have an array with bytes : ByteSource byteSource and I have a function

template<class target_t>
target_t BitReader<max_bytes>::readBits(size_t bitCount) {

In this function, I take bits out of the array (bitCount amount of bits) and put them into a T value.

After I am done with that, I have to check how many bits the target_t needs, if my bitcount is below that, I have to fill the value with 0's.

I am using const size_t bits = sizeof(target_t) * 8; but was wondering if this would be correct since in case I need for example 4 bits (instead a whole byte). Wouldn't I just be filling my value with 0's that aren't need?


问:
PHP bind_param Uncaught Error: Call to a member function bind_param()
I've basically been researching this Uncaught Error: Call to a member function bind_param() on bool error I've been getting for the last 2 hours with nothing.

```<code>$post_data = json_decode(file_get_contents("php://input"));
$encoded_publisher = base64_encode($post_data->publisher);
$encoded_notes = base64_encode($post_data->notes);
$rellevel = $post_data->releaselevel;
$uid = $post_data->uid;

$request = $db->prepare('UPDATE release_history SET author = ?, notes = ?, release_state = ? WHERE uid = ?');
                                                $request->bind_param('ssss', $encoded_publisher, $encoded_notes, $rellevel, $uid);
</code>```

All these fields are checked at the start of the script if they're empty and they all have data, I've also checked if the data is valid and it is

I've tried changing the MySQL statement, changed the variable names, changed the parameter values like ssss -> ssssssss, I've tagged out every line except the prepare and bind_param lines and its the same error, I've also run the code on the MySQL server and it works perfectly fine

The script should simply update the database entry but it just gives an error

Body:
I've basically been researching this Uncaught Error: Call to a member function bind_param() on bool error I've been getting for the last 2 hours with nothing.

$post_data = json_decode(file_get_contents("php://input"));
$encoded_publisher = base64_encode($post_data->publisher);
$encoded_notes = base64_encode($post_data->notes);
$rellevel = $post_data->releaselevel;
$uid = $post_data->uid;

$request = $db->prepare('UPDATE release_history SET author = ?, notes = ?, release_state = ? WHERE uid = ?');
                                                $request->bind_param('ssss', $encoded_publisher, $encoded_notes, $rellevel, $uid);

All these fields are checked at the start of the script if they're empty and they all have data, I've also checked if the data is valid and it is

I've tried changing the MySQL statement, changed the variable names, changed the parameter values like ssss -> ssssssss, I've tagged out every line except the prepare and bind_param lines and its the same error, I've also run the code on the MySQL server and it works perfectly fine

The script should simply update the database entry but it just gives an error


问:
When I load .mtl to .obj textures goes opaque
I use pre-made 3d objects for my projects but sometimes when I load the .mtl textures goes opaque.

For ex. this 3D mask

how should look like

red color outside

face cutouts inside

files:

```<code>obj.rf.gd/obj.obj

obj.rf.gd/mtl.mtl

obj.rf.gd/56cb773b81b2db955cf6a62a6dc3d0e7.png
</code>```

I found that.. if I convert .obj to .glb the 3D object load correctly:
.glb file

.obj file (via windows 3D viewer):
.obj file
.obj file

I just cannot work with .glb files. Any ideas how to load 3D file correctly?

Body:
I use pre-made 3d objects for my projects but sometimes when I load the .mtl textures goes opaque.

For ex. this 3D mask

how should look like

red color outside

face cutouts inside

files:

obj.rf.gd/obj.obj

obj.rf.gd/mtl.mtl

obj.rf.gd/56cb773b81b2db955cf6a62a6dc3d0e7.png

I found that.. if I convert .obj to .glb the 3D object load correctly:
.glb file

.obj file (via windows 3D viewer):
.obj file
.obj file

I just cannot work with .glb files. Any ideas how to load 3D file correctly?


问:
Svelte layout reset
I'm trying to reset the navbar and forward an active link to it. I read the advanced routing, and I think it's supposed to work like this.

```<code>src/routes/
│ test/
│ ├ **+page@test.svelte** //The whole point is to add@tags to svelte files for resetting
│ └ +layout.svelte
│
├ +page.svelte
└ +layout.svelte
</code>```

The expected output is only one navbar with an active link working. Instead, I get 2 navbars, with the lower one doing what I want.

I'm following this guy from youtube .From 5:00 to 5:18, he gets 2 different navbars, which is what I want.

Title: Svelte layout reset

Body:
I'm trying to reset the navbar and forward an active link to it. I read the advanced routing, and I think it's supposed to work like this.

src/routes/
│ test/
│ ├ **+page@test.svelte** //The whole point is to add@tags to svelte files for resetting
│ └ +layout.svelte
│
├ +page.svelte
└ +layout.svelte

The expected output is only one navbar with an active link working. Instead, I get 2 navbars, with the lower one doing what I want.

I'm following this guy from youtube .From 5:00 to 5:18, he gets 2 different navbars, which is what I want.


问:
is not assignable to parameter of type never
I have the following line of code:

```<code>if (!target.unit.subTypes.includes(effectAmount.multiplicator.subType)) continue
</code>```

The line throws the error:

```<code>TS2345: Argument of type 'CreatureSubType | StructureSubType' is not assignable to parameter of type 'never'. Type 'CreatureSubType' is not assignable to type 'never'.
</code>```

target.unit.subTypes is defined as:

```<code>public subTypes: CreatureSubType[] | StructureSubType[]
</code>```

whereas both CreatureSubType and StructureSubType are regular enums.

multiplicator.subType is therefore defined as:

```<code>subType?: CreatureSubType | StructureSubType
</code>```

I dealt with the optional case before.

I don't understand why that error occurs. I also tried rebuilding this case a bit simpler here but it works without problem there. What am I missing?

EDIT:

Ok, I have managed to create a somewhat minimal example. Test class:

```<code>export class Foo {
  constructor(public subTypes: CreatureSubType[] | StructureSubType[]) {}
}
</code>```

If I use this class like that:

```<code>const foo = new Foo([CreatureSubType.HUMAN])
foo.subTypes.push(3)
</code>```

Then it complains about "Argument of type 'number' is not assignable to parameter of type 'never'.", meaning that subTypes somehow has a never type, even though it is clearly specified as CreatureSubType[] | StructureSubType[], and I am even passing in one CreatureSubType.

Why is that?

EDIT 2:

The same thing happens, with arrays of basic types like subTypes: number[] | boolean[]. But it does not happen, if there are no arrays involved. subTypes: number | boolean does not loose its type and will not be resulting in type never.

Body:
I have the following line of code:

if (!target.unit.subTypes.includes(effectAmount.multiplicator.subType)) continue

The line throws the error:

TS2345: Argument of type 'CreatureSubType | StructureSubType' is not assignable to parameter of type 'never'. Type 'CreatureSubType' is not assignable to type 'never'.

target.unit.subTypes is defined as:

public subTypes: CreatureSubType[] | StructureSubType[]

whereas both CreatureSubType and StructureSubType are regular enums.

multiplicator.subType is therefore defined as:

subType?: CreatureSubType | StructureSubType

I dealt with the optional case before.

I don't understand why that error occurs. I also tried rebuilding this case a bit simpler here but it works without problem there. What am I missing?

EDIT:

Ok, I have managed to create a somewhat minimal example. Test class:

export class Foo {
  constructor(public subTypes: CreatureSubType[] | StructureSubType[]) {}
}

If I use this class like that:

const foo = new Foo([CreatureSubType.HUMAN])
foo.subTypes.push(3)

Then it complains about "Argument of type 'number' is not assignable to parameter of type 'never'.", meaning that subTypes somehow has a never type, even though it is clearly specified as CreatureSubType[] | StructureSubType[], and I am even passing in one CreatureSubType.

Why is that?

EDIT 2:

The same thing happens, with arrays of basic types like subTypes: number[] | boolean[]. But it does not happen, if there are no arrays involved. subTypes: number | boolean does not loose its type and will not be resulting in type never.


问:
Docker-compose down
I ran the following command docker-compose down to stop the running docker containers, but besides that I saw that it removes the volumes. I had a volume of a database. Then I lost my volume. Can someone tell me how I can recover this database data?

I haven't tried anything yet

Title: Docker-compose down


问:
Overfitted model after train_test_split
The issue is related to https://github.com/CarterWoolsey/woodentify/blob/master/woodentify.py

How can I avoid overfitting the model when using the Sklearn train_test_split in Python, after the original images have been cropped, rotated and mirrored in order to expand the database?
Because for every image used for the test, a similar (rotated, mirrored) image has already been used for the training.

Many thanks!

I tried the adjusting the different train_test_split parameters. None of them seem to be related to such a problem.

Title: Overfitted model after train_test_split


问:
Create a wordpress page by a json file
I have a json file containing my restaurant menu

```
```
{"id":17135,"name":"Apperò","categories":[{"id":3343680,"name":"APERITIVO","color":"#F6B352","position":0,"type":"PRODUCT","products":[{"id":30510283,"name":"COPERTO","price":100,"position":0,"options":[]},
{"id":27271178,"name":"PETTOLE","price":250,"position":12,"image":{"thumbnail":"https://assets.tiller.systems/17135/products/27271178/thumbnail.png","small":"https://assets.tiller.systems/17135/products/27271178/small.png","medium":"https://assets.tiller.systems/17135/products/27271178/medium.png","large":"https://assets.tiller.systems/17135/products/27271178/large.png"},"options":[{"id":1218380,"category":"CONDIMENTI","products":[{"id":27271185,"name":"FORMAGGIO FUSO","price":100,"position":0},
{"id":27271189,"name":"CAPPERI","price":20,"position":1},
{"id":27271192,"name":"ACCIUGHE","price":50,"position":2},
{"id":27271200,"name":"CREMA DI RICOTTA FORTE","price":100,"position":3},
{"id":27271202,"name":"CREMA PICCANTE","price":100,"position":4},
{"id":27271203,"name":"VIN COTTO","price":50,"position":5},
{"id":27273149,"name":"RICOTTA","price":100,"position":6},
{"id":27273150,"name":"CACIORICOTTA STAGIONATO","price":100,"position":7},
{"id":27273171,"name":"CICORIA RIPASSATA","price":200,"position":8}]},
{"id":1218381,"category":"SALSE","products":[{"id":27264693,"name":"MAIONESE","price":50,"position":0},
{"id":27265590,"name":"KETCHUP","price":50,"position":1},
{"id":27266487,"name":"SENAPE","price":50,"position":2},
{"id":27268050,"name":"SALSA YOGURT","price":80,"position":3},
{"id":27270214,"name":"SALSA DI POMODORO","price":100,"position":4}]}]},
{"id":27271252,"name":"SPIEDINO DI CACIOCAVALLO SILANO","description":"Breaded and fried Caciocavallo skewer","price":250,"position":13,"image":{"thumbnail":"https://assets.tiller.systems/17135/products/27271252/thumbnail.png","small":"https://assets.tiller.systems/17135/products/27271252/small.png","medium":"https://assets.tiller.systems/17135/products/27271252/medium.png","large":"https://assets.tiller.systems/17135/products/27271252/large.png"},"options":[]}]},
{"id":3130810,"name":"POLPETTE","color":"#F68657","position":1,"type":"PRODUCT","products":[{"id":27270115,"name":"POLPETTE DI PANE PUGLIESI","description":"APULIAN BREAD MEATBALLS","price":300,"position":0,"image":{"thumbnail":"https://assets.tiller.systems/17135/products/27270115/thumbnail.png","small":"https://assets.tiller.systems/17135/products/27270115/small.png","medium":"https://assets.tiller.systems/17135/products/27270115/medium.png","large":"https://assets.tiller.systems/17135/products/27270115/large.png"},"options":[]}]}],"meals":[]}
```
```

this file is updated by a script connected to my system .

I have a page in my wordpress site called "menu" and I want it to read this file and get the updated HTML from json.

How can I do that?

thank you

Title: Create a wordpress page by a json file

Body:
I have a json file containing my restaurant menu

```
{"id":17135,"name":"Apperò","categories":[{"id":3343680,"name":"APERITIVO","color":"#F6B352","position":0,"type":"PRODUCT","products":[{"id":30510283,"name":"COPERTO","price":100,"position":0,"options":[]},
{"id":27271178,"name":"PETTOLE","price":250,"position":12,"image":{"thumbnail":"https://assets.tiller.systems/17135/products/27271178/thumbnail.png","small":"https://assets.tiller.systems/17135/products/27271178/small.png","medium":"https://assets.tiller.systems/17135/products/27271178/medium.png","large":"https://assets.tiller.systems/17135/products/27271178/large.png"},"options":[{"id":1218380,"category":"CONDIMENTI","products":[{"id":27271185,"name":"FORMAGGIO FUSO","price":100,"position":0},
{"id":27271189,"name":"CAPPERI","price":20,"position":1},
{"id":27271192,"name":"ACCIUGHE","price":50,"position":2},
{"id":27271200,"name":"CREMA DI RICOTTA FORTE","price":100,"position":3},
{"id":27271202,"name":"CREMA PICCANTE","price":100,"position":4},
{"id":27271203,"name":"VIN COTTO","price":50,"position":5},
{"id":27273149,"name":"RICOTTA","price":100,"position":6},
{"id":27273150,"name":"CACIORICOTTA STAGIONATO","price":100,"position":7},
{"id":27273171,"name":"CICORIA RIPASSATA","price":200,"position":8}]},
{"id":1218381,"category":"SALSE","products":[{"id":27264693,"name":"MAIONESE","price":50,"position":0},
{"id":27265590,"name":"KETCHUP","price":50,"position":1},
{"id":27266487,"name":"SENAPE","price":50,"position":2},
{"id":27268050,"name":"SALSA YOGURT","price":80,"position":3},
{"id":27270214,"name":"SALSA DI POMODORO","price":100,"position":4}]}]},
{"id":27271252,"name":"SPIEDINO DI CACIOCAVALLO SILANO","description":"Breaded and fried Caciocavallo skewer","price":250,"position":13,"image":{"thumbnail":"https://assets.tiller.systems/17135/products/27271252/thumbnail.png","small":"https://assets.tiller.systems/17135/products/27271252/small.png","medium":"https://assets.tiller.systems/17135/products/27271252/medium.png","large":"https://assets.tiller.systems/17135/products/27271252/large.png"},"options":[]}]},
{"id":3130810,"name":"POLPETTE","color":"#F68657","position":1,"type":"PRODUCT","products":[{"id":27270115,"name":"POLPETTE DI PANE PUGLIESI","description":"APULIAN BREAD MEATBALLS","price":300,"position":0,"image":{"thumbnail":"https://assets.tiller.systems/17135/products/27270115/thumbnail.png","small":"https://assets.tiller.systems/17135/products/27270115/small.png","medium":"https://assets.tiller.systems/17135/products/27270115/medium.png","large":"https://assets.tiller.systems/17135/products/27270115/large.png"},"options":[]}]}],"meals":[]}
```

this file is updated by a script connected to my system .

I have a page in my wordpress site called "menu" and I want it to read this file and get the updated HTML from json.

How can I do that?

thank you


问:
How can I deploy my full stack project to vercel?
How can I deploy my full stack project to vercel ?

my project done with reactjs nodejs express mysql

How to deploy all project.


问:
Unable to use list comprehension with class-variable function
```<code>class A:
    func = lambda x: x+4
    added_values = [func(45)]

if __name__=="__main__":
    print(A.added_values)
</code>```

The above code outputs [49], that is expected. Then why this code

```<code>class A:
    func = lambda x: x+4
    added_values = [func(45) for _ in range(1)]

if __name__=="__main__":
    print(A.added_values)
</code>```

gives undefined error, what is happening here?

```<code>Traceback (most recent call last):
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 1, in <module>
    class A:
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in A
    added_values = [func(45) for _ in range(1)]
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in <listcomp>
    added_values = [func(45) for _ in range(1)]
NameError: name 'func' is not defined
</code>```

I do not know what is happening under the hood, looks very strange to me.

Body:
class A:
    func = lambda x: x+4
    added_values = [func(45)]

if __name__=="__main__":
    print(A.added_values)

The above code outputs [49], that is expected. Then why this code

class A:
    func = lambda x: x+4
    added_values = [func(45) for _ in range(1)]

if __name__=="__main__":
    print(A.added_values)

gives undefined error, what is happening here?

Traceback (most recent call last):
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 1, in <module>
    class A:
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in A
    added_values = [func(45) for _ in range(1)]
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in <listcomp>
    added_values = [func(45) for _ in range(1)]
NameError: name 'func' is not defined

I do not know what is happening under the hood, looks very strange to me.


问:
Probabilistic Bounds for a Strictly Positive Machine Learning Point Estimate?
I'm trying to create some probabilistic bounds for my machine learning regression predictions. What I'm currently doing is taking the output of the regression algorithm (I'm predicting team points scored), passing it in as the mean to a normal distribution, using the team's historical standard deviation of points scored as the standard deviation for the normal distribution, and then using the CDF to get the probability of them scoring any given range of points.

The problem I'm facing is that depending on the regression prediction and the standard deviation, I could be accidentally giving 10% probability that the team will score negative points.

Does anyone have any suggestions for how I can take the output of a regression algorithm, use it as a parameter to a distribution (along with some sort of variance parameter), and get a probability that a team scores over N points, while keeping it to strictly positive values? AKA the probability of scoring less than 0 points should always be 0.

Everything else about my current approach works well - I'm able to combine machine learning with traditional statistics for probabilistic bounds. The problem is these negative values.

Here's a concrete example:

```<code>from scipy.stats import norm

#model predicts team will score 5 points
model_points_prediction = 5

#teams historical standard deviation of points scored is 3
team_points_standard_deviation = 3

#pass it parameters to normal distribution
dist = norm(model_points_prediction, team_points_standard_deviation)

#probability of scoring less than 0 points
print(dist.cdf(0))

</code>```

And it print's out 4.7% chance of points being less than zero. What's a better solution to this that keeps it strictly positive?

Body:
I'm trying to create some probabilistic bounds for my machine learning regression predictions. What I'm currently doing is taking the output of the regression algorithm (I'm predicting team points scored), passing it in as the mean to a normal distribution, using the team's historical standard deviation of points scored as the standard deviation for the normal distribution, and then using the CDF to get the probability of them scoring any given range of points.

The problem I'm facing is that depending on the regression prediction and the standard deviation, I could be accidentally giving 10% probability that the team will score negative points.

Does anyone have any suggestions for how I can take the output of a regression algorithm, use it as a parameter to a distribution (along with some sort of variance parameter), and get a probability that a team scores over N points, while keeping it to strictly positive values? AKA the probability of scoring less than 0 points should always be 0.

Everything else about my current approach works well - I'm able to combine machine learning with traditional statistics for probabilistic bounds. The problem is these negative values.

Here's a concrete example:

from scipy.stats import norm

#model predicts team will score 5 points
model_points_prediction = 5

#teams historical standard deviation of points scored is 3
team_points_standard_deviation = 3

#pass it parameters to normal distribution
dist = norm(model_points_prediction, team_points_standard_deviation)

#probability of scoring less than 0 points
print(dist.cdf(0))

And it print's out 4.7% chance of points being less than zero. What's a better solution to this that keeps it strictly positive?


问:
SQL statement to find woocommerce variable products that are marked "outofstock" but have child products instock or with a stock quantity > 0
We keep having an issue where WooCommerce variable/parent products get set to Out Of Stock status, even though they have children/variations that are in stock and we are not sure why. We've attempted everything found online.

As a fix, I would like to create an SQL statement that checks for such products i.e. one that finds parent products that are marked out of stock but whos children are marked in stock.

This is the code I've written to get the parent products that are out of stock:

```<code>SELECT p.ID, p.post_title, pm.meta_value
    FROM wp_posts as p
    INNER JOIN wp_postmeta as pm ON p.ID = pm.post_id
    INNER JOIN wp_term_relationships AS term_relationships ON p.ID = term_relationships.object_id
    INNER JOIN wp_term_taxonomy AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
    INNER JOIN wp_terms AS terms ON term_taxonomy.term_id = terms.term_id
    WHERE p.post_type LIKE 'product'
    AND p.post_status LIKE 'publish'
    AND p.post_parent = '0'
    AND pm.meta_key LIKE '_stock_status'
    AND pm.meta_value LIKE 'outofstock'
    AND terms.slug = 'variable'
    GROUP BY p.ID;
</code>```

This is the code I've written to get the children products that are in stock:

```<code>SELECT p.ID, p.post_title, pm.meta_value
    FROM wp_posts as p
    INNER JOIN wp_postmeta as pm ON p.ID = pm.post_id
    WHERE p.post_type LIKE 'product_variation'
    AND p.post_status LIKE 'publish'
    AND p.post_parent = '***THE_ID_OF_THE_PARENT***'
    AND (
        (pm.meta_key LIKE '_stock_status' AND pm.meta_value LIKE 'instock')
        OR
        (pm.meta_key LIKE '_stock' AND pm.meta_value > 0)
     )
</code>```

I need the result of the first code (the parent product that is set to out of stock) ONLY when one or more of its children products are marked in stock (the second code). It's been a very long time since I studied SQL, so I am not sure how to combine these two statements like that.  I'm hoping someone here can help

EDIT:
I think I got it (below), but it seems cumbersome. Is there a better way?

```<code>SELECT p.ID, p.post_title, pm.meta_value
FROM wp_posts as p
INNER JOIN wp_postmeta as pm ON p.ID = pm.post_id
INNER JOIN wp_term_relationships AS term_relationships ON p.ID = term_relationships.object_id
INNER JOIN wp_term_taxonomy AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
INNER JOIN wp_terms AS terms ON term_taxonomy.term_id = terms.term_id
WHERE p.post_type LIKE 'product'
AND p.post_status LIKE 'publish'
AND terms.slug = 'variable'
AND p.post_parent = '0'
AND pm.meta_key LIKE '_stock_status'
AND pm.meta_value LIKE 'outofstock'
AND terms.slug = 'variable'
AND p.ID IN (
    SELECT pc.post_parent
    FROM wp_posts as pc
    INNER JOIN wp_postmeta as pmc ON pc.ID = pmc.post_id
    WHERE pc.post_type LIKE 'product_variation'
    AND pc.post_status LIKE 'publish'
    AND (
        (pmc.meta_key LIKE '_stock_status' AND pmc.meta_value LIKE 'instock')
        OR
        (pmc.meta_key LIKE '_stock' AND pmc.meta_value > 0)
     )
);
</code>```

Body:
We keep having an issue where WooCommerce variable/parent products get set to Out Of Stock status, even though they have children/variations that are in stock and we are not sure why. We've attempted everything found online.

As a fix, I would like to create an SQL statement that checks for such products i.e. one that finds parent products that are marked out of stock but whos children are marked in stock.

This is the code I've written to get the parent products that are out of stock:

SELECT p.ID, p.post_title, pm.meta_value
    FROM wp_posts as p
    INNER JOIN wp_postmeta as pm ON p.ID = pm.post_id
    INNER JOIN wp_term_relationships AS term_relationships ON p.ID = term_relationships.object_id
    INNER JOIN wp_term_taxonomy AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
    INNER JOIN wp_terms AS terms ON term_taxonomy.term_id = terms.term_id
    WHERE p.post_type LIKE 'product'
    AND p.post_status LIKE 'publish'
    AND p.post_parent = '0'
    AND pm.meta_key LIKE '_stock_status'
    AND pm.meta_value LIKE 'outofstock'
    AND terms.slug = 'variable'
    GROUP BY p.ID;

This is the code I've written to get the children products that are in stock:

SELECT p.ID, p.post_title, pm.meta_value
    FROM wp_posts as p
    INNER JOIN wp_postmeta as pm ON p.ID = pm.post_id
    WHERE p.post_type LIKE 'product_variation'
    AND p.post_status LIKE 'publish'
    AND p.post_parent = '***THE_ID_OF_THE_PARENT***'
    AND (
        (pm.meta_key LIKE '_stock_status' AND pm.meta_value LIKE 'instock')
        OR
        (pm.meta_key LIKE '_stock' AND pm.meta_value > 0)
     )

I need the result of the first code (the parent product that is set to out of stock) ONLY when one or more of its children products are marked in stock (the second code). It's been a very long time since I studied SQL, so I am not sure how to combine these two statements like that.  I'm hoping someone here can help

EDIT:
I think I got it (below), but it seems cumbersome. Is there a better way?

SELECT p.ID, p.post_title, pm.meta_value
FROM wp_posts as p
INNER JOIN wp_postmeta as pm ON p.ID = pm.post_id
INNER JOIN wp_term_relationships AS term_relationships ON p.ID = term_relationships.object_id
INNER JOIN wp_term_taxonomy AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
INNER JOIN wp_terms AS terms ON term_taxonomy.term_id = terms.term_id
WHERE p.post_type LIKE 'product'
AND p.post_status LIKE 'publish'
AND terms.slug = 'variable'
AND p.post_parent = '0'
AND pm.meta_key LIKE '_stock_status'
AND pm.meta_value LIKE 'outofstock'
AND terms.slug = 'variable'
AND p.ID IN (
    SELECT pc.post_parent
    FROM wp_posts as pc
    INNER JOIN wp_postmeta as pmc ON pc.ID = pmc.post_id
    WHERE pc.post_type LIKE 'product_variation'
    AND pc.post_status LIKE 'publish'
    AND (
        (pmc.meta_key LIKE '_stock_status' AND pmc.meta_value LIKE 'instock')
        OR
        (pmc.meta_key LIKE '_stock' AND pmc.meta_value > 0)
     )
);


问:
Invalid XML for POST_FLAT_FILE_FULFILLMENT_DATA feed
I am using the Other Carrier option and added the tracking number myself, so when the customer receives the order it shows late on the customer panel.
So, I am trying to update the order status from shipped to delivered. I haven't found any API endpoint for this task but when reading the API I noticed POST_FLAT_FILE_FULFILLMENT_DATA in feeds data so thought maybe it can update the order status still not sure though.

I am at step 7 Download the feed processing report

And I am getting

Warning The XML field heading is invalid, so values in this field were
ignored. To correct this error, download the template again and use
the new copy, or fix the field heading in your existing file.

Here's the XML:

```<code><?xml version="1.0" encoding="iso-8859-1" ?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>MERCHAnT_TOKEN</MerchantIdentifier> </Header> <MessageType>OrderFulfillment</MessageType> <PurgeAndReplace>true</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OrderFulfillment> <AmazonOrderID>123-1234567-1234567</AmazonOrderID> <FulfillmentDate>2022-12-13 23:20:00</FulfillmentDate> <FulfillmentData> <CarrierName>XYZ</CarrierName> <ShipperTrackingNumber>TRACKING_NUMBER</ShipperTrackingNumber> </FulfillmentData> </OrderFulfillment> </Message> </AmazonEnvelope>
</code>```

How can I fix this also am I in the right direction

Body:
I am using the Other Carrier option and added the tracking number myself, so when the customer receives the order it shows late on the customer panel.
So, I am trying to update the order status from shipped to delivered. I haven't found any API endpoint for this task but when reading the API I noticed POST_FLAT_FILE_FULFILLMENT_DATA in feeds data so thought maybe it can update the order status still not sure though.

I am at step 7 Download the feed processing report

And I am getting

Warning The XML field heading is invalid, so values in this field were
ignored. To correct this error, download the template again and use
the new copy, or fix the field heading in your existing file.

Here's the XML:

<?xml version="1.0" encoding="iso-8859-1" ?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">  <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>MERCHAnT_TOKEN</MerchantIdentifier>  <MessageType>OrderFulfillment</MessageType> <PurgeAndReplace>true</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OrderFulfillment> <AmazonOrderID>123-1234567-1234567</AmazonOrderID> <FulfillmentDate>2022-12-13 23:20:00</FulfillmentDate> <FulfillmentData> <CarrierName>XYZ</CarrierName> <ShipperTrackingNumber>TRACKING_NUMBER</ShipperTrackingNumber> </FulfillmentData> </OrderFulfillment> </Message> </AmazonEnvelope>

How can I fix this also am I in the right direction


问:
React can & Angular can't? Filesystem write operation
Is anyone able to explain, why is this React face detection example able to write to filesystem?

https://codesandbox.io/s/opencv-js-face-detection-i1i3u?file=/src/App.jsx:515-516

using

https://github.com/TechStark/opencv-js

Script file cvDataFile.js calls an OpenCV method, that writes a file on filesystem cv.FS_createDataFile(...).

As far as I know, apps runing in browser are not able to do that, or are they?

I'm trying to create something very similar in Angular and failing on this exact line with nothing more in console.log than FS error. So before digging deeper into my bug, why is that code able to do that?


问:
How to prevent Tab Navigator header from rerendering every time I open a new tab in react navigation v6?
I am using react navigation v6 with react native. I have a custom header component that I want at the top of all of my screens in my Tab.Navigator. This custom header includes a reanimated animation when you press on the search icon which is at the top right. I think it's not working because every time a new tab is opened, the header is rendered as many times as there are tabs opened in the history. The first render begins the animation but then it's disrupted by the new render. I'm not 100% sure though. How do I prevent my header component from rerendering? Here is the wrapper for my Tab.Navigator:

```<code><Tab.Navigator
    tabBar={(props) => <TabBar {...props} />}
    backBehavior="history"
    screenOptions={{
    header: (props) => <Header green={true} />,
        }}
    initialRouteName="HomeStack">
</code>```

My prop green={true} also never changes.

Body:
I am using react navigation v6 with react native. I have a custom header component that I want at the top of all of my screens in my Tab.Navigator. This custom header includes a reanimated animation when you press on the search icon which is at the top right. I think it's not working because every time a new tab is opened, the header is rendered as many times as there are tabs opened in the history. The first render begins the animation but then it's disrupted by the new render. I'm not 100% sure though. How do I prevent my header component from rerendering? Here is the wrapper for my Tab.Navigator:

<Tab.Navigator
    tabBar={(props) => <TabBar {...props} />}
    backBehavior="history"
    screenOptions={{
    header: (props) => ,
        }}
    initialRouteName="HomeStack">

My prop green={true} also never changes.


问:
python syntax error "keyword can't be an expression"
I ran the following script and got the error message at the bottom.  I can't figure out why I am getting the error message.

```<code>def vp(ds_final_revised):
    df=ds_final_revised
    df = df.filter(df._type_ = 8)
    return df
</code>```

error message:

Syntax Error.

File "vp", line 3
SyntaxError: keyword can't be an expression
```

Body:
I ran the following script and got the error message at the bottom.  I can't figure out why I am getting the error message.

def vp(ds_final_revised):
    df=ds_final_revised
    df = df.filter(df._type_ = 8)
    return df

error message:

Syntax Error.

File "vp", line 3
SyntaxError: keyword can't be an expression


问:
Is it possible to only consume onSingleTapConfirmed event in Android?
I have 2 touch listeners attached to the child and parent views. The child view would handle onSingleTapConfirmed while parent view would handle all other events like scroll, fling, double tap, etc. The problem is, if the child view returns true in onDown, its onSingleTapConfirmed will be be called. but no events are propagated up to the gesture detector attached to parent. If I return false in onDown, gestures in parent view are working but child is not receiving onSingleTapConfirmed anymore.


问:
GEOquery does not work for larger RAW files
In R studio, I am unable to use getGEOSuppFiles("") to work when the RAW.tar file is > 500mb (it stops after ~100mb download). here is the snippet.

```<code>> getGEOSuppFiles("GSE31210")
trying URL 'https://ftp.ncbi.nlm.nih.gov/geo/series/GSE31nnn/GSE31210/suppl//GSE31210_RAW.tar?tool=geoquery'
Content type 'application/x-tar' length 1320140800 bytes (1259.0 MB)
====
downloaded 110.6 MB

Error in getGEOSuppFiles("GSE31210") :
  Failed to download /Users/db/Desktop/pracR/1213/GSE31210/GSE31210_RAW.tar!
</code>```

Smaller files work fine when I use this command. Could anyone help? Is it the storage problem, timing out problem, memory problem or anything else. I am using getGEOSuppFiles("GSE31210") command in the Rstudio

do not know what to do next as I am stuck.

Body:
In R studio, I am unable to use getGEOSuppFiles("") to work when the RAW.tar file is > 500mb (it stops after ~100mb download). here is the snippet.

> getGEOSuppFiles("GSE31210")
trying URL 'https://ftp.ncbi.nlm.nih.gov/geo/series/GSE31nnn/GSE31210/suppl//GSE31210_RAW.tar?tool=geoquery'
Content type 'application/x-tar' length 1320140800 bytes (1259.0 MB)
====
downloaded 110.6 MB

Error in getGEOSuppFiles("GSE31210") :
  Failed to download /Users/db/Desktop/pracR/1213/GSE31210/GSE31210_RAW.tar!

Smaller files work fine when I use this command. Could anyone help? Is it the storage problem, timing out problem, memory problem or anything else. I am using getGEOSuppFiles("GSE31210") command in the Rstudio

do not know what to do next as I am stuck.


问:
I'm modeling in 3ds max, but the scale is strange
Reset XForm is applied, and when Imported to Unity
scale has changed
For example, if you exported with a size of 10 10 10
There is a bug in Unity that imports in the size of 15 15 15.

How can i fix this bug?
And can you tell me what causes this bug?
Due to this issue, scale within Unity is constantly
You have to do it by hand.
I hope you can resolve this question as soon as possible.
I tried searching through google, but couldn't find the problem.


问:
Python: Querying lineage file but script keeps running
I have a file with cells, their self ID and their parent ID. I need to complete two methods to build a suitable datastructure and one to look into that datastructure to find all the parents of the query cell. (So the parent, the parent of that parent, etc). I have code that I think should work, but my code just keeps running and never gives an output, so I think it's stuck somewhere? The file looks like this

```<code>cell    time    x   y   z   radius  self    parent  child1  child2
ABa 1   84  68  61  10  2   -1  2   -1
ABp 1   58  139 61  10  2795    -1  2795    -1
EMS 1   133 121 55  10  5543    -1  5543    -1
P2  1   93  201 63  10  6591    -1  6591    -1
ABa 2   96  65  69  10  2   2   3   1608
ABp 2   65  146 67  10  2795    2795    3931    2796
</code>```

The first method reads in the lineage file and composes a python datastructure you can use to query the lineage tree. I have chosen to make a dictionary of dictionaries. I checked it with printing the cell and this works.

```<code>`from collections import defaultdict
def build_datastructure_lineage_query(lineage_file):
    # create a dictionary of dictionaries to store the cell names, self IDs, and parent IDs
    cells = defaultdict(dict)

    # open the lineage file
    with open(lineage_file, 'r') as f:
        # skip the first line (header)
        f.readline()

        # read in each line of the file
        for line in f:
            # split the line into columns
            cols = line.split()

            # store the cell name, self ID, and parent ID in the dictionary of dictionaries
            cells[cols[0]]["self"] = int(cols[6])
            cells[cols[0]]["parent"] = int(cols[7])

    # return the dictionary of dictionaries
    return cells`
</code>```

The second method looks like this:

```<code>`def get_parents_for_cell(query_cell, ds_lineage_query):
    # Initialize empty list to store the parent cells
    parents = []

    # Loop until we reach a cell with no parent
    while query_cell in ds_lineage_query:
        # Get the parent ID of the query cell
        parent_id = ds_lineage_query[query_cell]["parent"]

        # Loop through the cells in the dictionary of dictionaries
        for cell_name, cell_info in ds_lineage_query.items():
            # Check if the cell has the same self ID as the parent ID of the query cell
            if cell_info["self"] == parent_id:
                # This is the parent cell, add its name to the list of parents
                parents.append(cell_name)

                # Set the parent cell as the new query cell for the next iteration
                query_cell = cell_name
                break

    # Return the list of parent cells
    return parents`
</code>```

And to get the output:

```<code>`ds_lineage_query = build_datastructure_lineage_query(lineage_file)
    query_cell = "ABalapaaa"
    parents = get_parents_for_cell(query_cell, ds_lineage_query)
    print(f"The parents for cell {query_cell} are {parents}")`
</code>```

So the output I hope to become is something like
`> parents = get_parents_for_cell(’ABalapaaa’, ds_lineage_query)

parents
[’ABalapaa’, ’ABalapa’, ’ABalap’, ’ABala’, ’ABal’, ’ABa’]

But right now it just keeps loading infinitely, I have been trying and retrying a lot to no avail. If anyone has any advice or knows what to do, I would be very grateful!

Body:
I have a file with cells, their self ID and their parent ID. I need to complete two methods to build a suitable datastructure and one to look into that datastructure to find all the parents of the query cell. (So the parent, the parent of that parent, etc). I have code that I think should work, but my code just keeps running and never gives an output, so I think it's stuck somewhere? The file looks like this

cell    time    x   y   z   radius  self    parent  child1  child2
ABa 1   84  68  61  10  2   -1  2   -1
ABp 1   58  139 61  10  2795    -1  2795    -1
EMS 1   133 121 55  10  5543    -1  5543    -1
P2  1   93  201 63  10  6591    -1  6591    -1
ABa 2   96  65  69  10  2   2   3   1608
ABp 2   65  146 67  10  2795    2795    3931    2796

The first method reads in the lineage file and composes a python datastructure you can use to query the lineage tree. I have chosen to make a dictionary of dictionaries. I checked it with printing the cell and this works.

`from collections import defaultdict
def build_datastructure_lineage_query(lineage_file):
    # create a dictionary of dictionaries to store the cell names, self IDs, and parent IDs
    cells = defaultdict(dict)

    # open the lineage file
    with open(lineage_file, 'r') as f:
        # skip the first line (header)
        f.readline()

        # read in each line of the file
        for line in f:
            # split the line into columns
            cols = line.split()

            # store the cell name, self ID, and parent ID in the dictionary of dictionaries
            cells[cols[0]]["self"] = int(cols[6])
            cells[cols[0]]["parent"] = int(cols[7])

    # return the dictionary of dictionaries
    return cells`

The second method looks like this:

`def get_parents_for_cell(query_cell, ds_lineage_query):
    # Initialize empty list to store the parent cells
    parents = []

    # Loop until we reach a cell with no parent
    while query_cell in ds_lineage_query:
        # Get the parent ID of the query cell
        parent_id = ds_lineage_query[query_cell]["parent"]

        # Loop through the cells in the dictionary of dictionaries
        for cell_name, cell_info in ds_lineage_query.items():
            # Check if the cell has the same self ID as the parent ID of the query cell
            if cell_info["self"] == parent_id:
                # This is the parent cell, add its name to the list of parents
                parents.append(cell_name)

                # Set the parent cell as the new query cell for the next iteration
                query_cell = cell_name
                break

    # Return the list of parent cells
    return parents`

And to get the output:

`ds_lineage_query = build_datastructure_lineage_query(lineage_file)
    query_cell = "ABalapaaa"
    parents = get_parents_for_cell(query_cell, ds_lineage_query)
    print(f"The parents for cell {query_cell} are {parents}")`

So the output I hope to become is something like
`> parents = get_parents_for_cell(’ABalapaaa’, ds_lineage_query)

parents
[’ABalapaa’, ’ABalapa’, ’ABalap’, ’ABala’, ’ABal’, ’ABa’]

But right now it just keeps loading infinitely, I have been trying and retrying a lot to no avail. If anyone has any advice or knows what to do, I would be very grateful!


问:
How to navigate from activity to fragment with JetPack Compose and navigation?
I want to navigate from @Composable in onClick () function

OutlinedButton(onClick = { onClick() }) to new fragment but when I call onClick() a get error : ID does not reference a View inside this Activity

I create navigation graph nav_graph.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph"
    app:startDestination="@id/newMainActivity">

    <fragment
        android:id="@+id/anyFragment"
        android:name="AnyFragment"
        android:label="AnyFragmentLabel">
    </fragment>

</navigation>
</code>```

This is MainActivity() :

```<code>class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AnyApp(::onClick)
        }
    }

    private fun onClick() {
        val navController = findNavController(R.id.nav_graph)
        navController.navigateUp() // to clear previous navigation history
        navController.navigate(R.id.anyFragment)
    }
}

@Composable
fun AnyApp(onClick:() -> Unit) {
    AnyTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colors.background
        ) {
            Column(modifier = Modifier.padding(vertical = 4.dp)) {
                val list = listOf(
                    Pair("StartAnyFragment", {}))                )
                LazyColumn {
                    items(items = list){ name ->
                        OutlinedButton(onClick = {onClick()}) {
                            Text(name.first)

                        }
                    }
                }
            }

        }

    }
}

</code>```

Body:
I want to navigate from @Composable in onClick () function

OutlinedButton(onClick = { onClick() }) to new fragment but when I call onClick() a get error : ID does not reference a View inside this Activity

I create navigation graph nav_graph.xml:

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph"
    app:startDestination="@id/newMainActivity">

    <fragment
        android:id="@+id/anyFragment"
        android:name="AnyFragment"
        android:label="AnyFragmentLabel">
    </fragment>

</navigation>

This is MainActivity() :

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AnyApp(::onClick)
        }
    }

    private fun onClick() {
        val navController = findNavController(R.id.nav_graph)
        navController.navigateUp() // to clear previous navigation history
        navController.navigate(R.id.anyFragment)
    }
}

@Composable
fun AnyApp(onClick:() -> Unit) {
    AnyTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colors.background
        ) {
            Column(modifier = Modifier.padding(vertical = 4.dp)) {
                val list = listOf(
                    Pair("StartAnyFragment", {}))                )
                LazyColumn {
                    items(items = list){ name ->
                        OutlinedButton(onClick = {onClick()}) {
                            Text(name.first)

                        }
                    }
                }
            }

        }

    }
}


问:
Allow IP CIDR range OR api gateway(A) to invoke API Gateway(B)
I have API Gateway(A) which needs to invoke API Gateway(B). These will be in the same account, however I would also like to whitelist a set of IP CIDRs such that this CIDR range can invoke API(B).

I understand that You can enable an API key on the second API (say API B) and pass the API Key from the first API (say API A) using mapping template. And this will allow only requests to the API when the x-api-key header is present in the request.

In the API A's mapping template on the integration request, you will need to hard code the API Key as a header.So any request which goes through the first API will have the x-api-key added to the integration back-end.

However this would solve 50% of the problem.

Is it possible to also whitelist certain IPs such that a certain IP Range can invoke API-B directly. If not, are there possible workarounds to this?

I've tried creating resource policy for API(B) which whitelists an EC2 instance IP address. This works fine, however when I create the API key, the request fails because both conditions are not met.


问:
Adding ModelState.IsValid breaks my page in c# MVC
I am working on a db that allows a user to add courses, then add books to those courses, while having a many to many relationship with students. I got a page set up that shows a selected course, a list of its books, and a few of its student.

I managed to get the ability to add books on that same page, however, whenever I add a ModelState.IsValid check, it completely breaks when I press the submit button. I've tried googling and different methods but I seem to not be able to get around this... I'm probably missing something obvious, but I don't know what it is...

Here is my course DB object

```<code>using System.ComponentModel.DataAnnotations;

namespace SchoolPracticeDB.Entities
{
    public class Course
    {

        public int CourseId { get; set; }

        [Required(ErrorMessage = "Please enter a course name.")]
        public string? CourseName { get; set; }

        [Required(ErrorMessage = "Please enter credits worth.")]
        public int? Credits { get; set; }

        //nav to students
        public ICollection<Enrollment>? Enrollments { get; set; }

        //nav to all of its books (zero to many)
        public ICollection<Book>? Books { get; set; }

    }
}
</code>```

Here is my CourseDetailsViewModel

```<code>using SchoolPracticeDB.Entities;

namespace SchoolPracticeDB.Models
{
    public class CourseDetailsViewModel
    {

        public Course? ActiveCourse { get; set; }

        public Book? NewBook { get; set; }

        public double? AverageMark { get; set; }

    }
}
</code>```

This is my controller method that works without the check:

```<code>[HttpPost("/courses/{id}/books")]
public IActionResult AddBookToCourseById(int id, CourseDetailsViewModel courseDetailsViewModel)
{

    var course = _courseDbContext.Courses
        .Include(c => c.Books)
        .Include(c => c.Enrollments)
        .ThenInclude(e => e.Student).Where(c => c.CourseId == id)
        .FirstOrDefault();

    course.Books.Add(courseDetailsViewModel.NewBook);
    _courseDbContext.SaveChanges();
    return RedirectToAction("GetCourseById", "Course", new { id = id });

}
</code>```

But when I add any check it crashes and gives me null errors
Here's the code with the check

```<code>[HttpPost("/courses/{id}/books")]
public IActionResult AddBookToCourseById(int id, CourseDetailsViewModel courseDetailsViewModel)
{

    var course = _courseDbContext.Courses
        .Include(c => c.Books)
        .Include(c => c.Enrollments).ThenInclude(e => e.Student)
        .Where(c => c.CourseId == id)
        .FirstOrDefault();

    if (ModelState.IsValid)
    {
        course.Books.Add(courseDetailsViewModel.NewBook);
        _courseDbContext.SaveChanges();
        return RedirectToAction("GetCourseById", "Course", new { id = id });
    }
    else
    {

        courseDetailsViewModel.ActiveCourse = _courseDbContext.Courses
                .Include(c => c.Books)
                .Include(c => c.Enrollments).ThenInclude(e => e.Student)
                .Where(c => c.CourseId == id)
                .FirstOrDefault();

        courseDetailsViewModel.NewBook.Course = courseDetailsViewModel.ActiveCourse;

        return View("CourseDetails", courseDetailsViewModel);
    }

}
</code>```

And here's the error:
enter image description here

The only way I have been able to get it to work is by adding hidden inputs for the course's required values in the form itself: in this case id (which seems normal) and then CourseName and Credits (which doesn't seem right), since I'm trying to add a book not a course as well. I'm hoping to get this working through the controller.

Here is my form with the ActiveCourse.CourseName and Credits added as hidden values:

```<code><div asp-validation-summary="All" class="text-danger"></div>
<form class="row" asp-controller="Course"
        asp-action="AddBookToCourseById" asp-route-id="@Model.ActiveCourse.CourseId"
        method="post" enctype="application/x-www-form-urlencoded">
    <div class="col-sm-4">
        <label class="visually-hidden" asp-for="NewBook.Title">Title</label>
        <div class="input-group">
            <div class="input-group-text">Title</div>
            <input type="text" class="form-control" asp-for="NewBook.Title" />
        </div>
    </div>

    <div class="col-sm-4">
        <label class="visually-hidden" asp-for="NewBook.Author">Author</label>
        <div class="input-group">
            <div class="input-group-text">Author</div>
            <input type="text" class="form-control" asp-for="NewBook.Author" />
        </div>
    </div>

    <div class="col-sm-2">
        <label class="visually-hidden" asp-for="NewBook.YearPublished">Year</label>
        <div class="input-group">
            <div class="input-group-text">Year</div>
            <input type="text" class="form-control" asp-for="NewBook.YearPublished" />
        </div>
    </div>

    <!-- Seems to only work when adding hidden info for activecourse name and credits -->
    <input type="hidden" asp-for="ActiveCourse.CourseName" />
    <input type="hidden" asp-for="ActiveCourse.Credits" />

    <!-- Add th Id (i.e. PK) field as a hidden input element: -->
    <input type="hidden" asp-for="ActiveCourse.CourseId" />

    <div class="col-sm-2">
        <button type="submit" class="btn btn-primary">Add Book</button>
    </div>
</form>
</code>```

Body:
I am working on a db that allows a user to add courses, then add books to those courses, while having a many to many relationship with students. I got a page set up that shows a selected course, a list of its books, and a few of its student.

I managed to get the ability to add books on that same page, however, whenever I add a ModelState.IsValid check, it completely breaks when I press the submit button. I've tried googling and different methods but I seem to not be able to get around this... I'm probably missing something obvious, but I don't know what it is...

Here is my course DB object

using System.ComponentModel.DataAnnotations;

namespace SchoolPracticeDB.Entities
{
    public class Course
    {

        public int CourseId { get; set; }

        [Required(ErrorMessage = "Please enter a course name.")]
        public string? CourseName { get; set; }

        [Required(ErrorMessage = "Please enter credits worth.")]
        public int? Credits { get; set; }

        //nav to students
        public ICollection<Enrollment>? Enrollments { get; set; }

        //nav to all of its books (zero to many)
        public ICollection<Book>? Books { get; set; }

    }
}

Here is my CourseDetailsViewModel

using SchoolPracticeDB.Entities;

namespace SchoolPracticeDB.Models
{
    public class CourseDetailsViewModel
    {

        public Course? ActiveCourse { get; set; }

        public Book? NewBook { get; set; }

        public double? AverageMark { get; set; }

    }
}

This is my controller method that works without the check:

[HttpPost("/courses/{id}/books")]
public IActionResult AddBookToCourseById(int id, CourseDetailsViewModel courseDetailsViewModel)
{

    var course = _courseDbContext.Courses
        .Include(c => c.Books)
        .Include(c => c.Enrollments)
        .ThenInclude(e => e.Student).Where(c => c.CourseId == id)
        .FirstOrDefault();

    course.Books.Add(courseDetailsViewModel.NewBook);
    _courseDbContext.SaveChanges();
    return RedirectToAction("GetCourseById", "Course", new { id = id });

}

But when I add any check it crashes and gives me null errors
Here's the code with the check

[HttpPost("/courses/{id}/books")]
public IActionResult AddBookToCourseById(int id, CourseDetailsViewModel courseDetailsViewModel)
{

    var course = _courseDbContext.Courses
        .Include(c => c.Books)
        .Include(c => c.Enrollments).ThenInclude(e => e.Student)
        .Where(c => c.CourseId == id)
        .FirstOrDefault();

    if (ModelState.IsValid)
    {
        course.Books.Add(courseDetailsViewModel.NewBook);
        _courseDbContext.SaveChanges();
        return RedirectToAction("GetCourseById", "Course", new { id = id });
    }
    else
    {

        courseDetailsViewModel.ActiveCourse = _courseDbContext.Courses
                .Include(c => c.Books)
                .Include(c => c.Enrollments).ThenInclude(e => e.Student)
                .Where(c => c.CourseId == id)
                .FirstOrDefault();

        courseDetailsViewModel.NewBook.Course = courseDetailsViewModel.ActiveCourse;

        return View("CourseDetails", courseDetailsViewModel);
    }

}

And here's the error:
enter image description here

The only way I have been able to get it to work is by adding hidden inputs for the course's required values in the form itself: in this case id (which seems normal) and then CourseName and Credits (which doesn't seem right), since I'm trying to add a book not a course as well. I'm hoping to get this working through the controller.

Here is my form with the ActiveCourse.CourseName and Credits added as hidden values:

<form class="row" asp-controller="Course"
        asp-action="AddBookToCourseById" asp-route-id="@Model.ActiveCourse.CourseId"
        method="post" enctype="application/x-www-form-urlencoded">

        Title

Title

            <input type="text" class="form-control" asp-for="NewBook.Title" />

        Author

Author

            <input type="text" class="form-control" asp-for="NewBook.Author" />

        Year

Year

            <input type="text" class="form-control" asp-for="NewBook.YearPublished" />

    <input type="hidden" asp-for="ActiveCourse.CourseName" />
    <input type="hidden" asp-for="ActiveCourse.Credits" />

    <input type="hidden" asp-for="ActiveCourse.CourseId" />

        <button type="submit" class="btn btn-primary">Add Book</button>

</form>


问:
In react-native-svg, how can I prevent <Text> from being cut-off in a <TextPath>?
I am creating a simple compass with North, East, South, West directions. I created a TextPath so that my Text can curve along the circular compass.

I am facing one major problem: the beginning of the Text is being cut-off. I cannot see the complete "North" label because of the textAnchor being set to middle (which is what I prefer).

How can I make the text fully visible? After it is visible, then I can space the directions accordingly (25%) along the TextPath.

```<code>/* eslint-disable react/jsx-key */
import React, { Fragment, useState } from 'react'
import { Dimensions, View, Text } from 'react-native'
import {
    Line,
    Circle,
    Text as SVGText,
    Defs,
    Path,
    Use,
    Svg,
    G,
    TextPath,
    ForeignObject,
    TSpan,
} from 'react-native-svg'
import { ReactNativeZoomableView } from '@openspacelabs/react-native-zoomable-view'

const getPoint = (R = 0, degree = 0) => {
    // Convert the angle to a value between 0 and 360 degrees
    const angle = ((degree % 360) + 360) % 360
    // Calculate the coordinates using Math.sin and Math.cos
    const x = R * Math.cos(angle * (Math.PI / 180))
    const y = R * Math.sin(angle * (Math.PI / 180))
    return [x, y]
}

const Compass = (props) => {
    const [X, setW] = useState(1000)
    const [Y, setH] = useState(1000)
    const CoreRadius = 100
    const PartRadius = 50

    const [slider, setSlider] = useState(0)
    const [point, setPoint] = useState([0, CoreRadius])

    const rings = [
        {
            offset: -45,
            degree: 90,
            parts: [{ text: 'North' }, { text: 'East' }, { text: 'South' }, { text: 'West' }],
        },
    ]

    return (
        <View style={{ flex: 1 }}>
            <View style={{ position: 'absolute', padding: 12, top: 0, left: 0, right: 0, zIndex: 1 }}></View>
            <ReactNativeZoomableView maxZoom={30} bindToBorders={false}>
                <Svg
                    style={{ backgroundColor: '#141414', width: X, height: Y }}
                    viewBox={`-${X / 2} -${Y / 2} ${X} ${Y}`}
                    onLayout={(event) => {
                        const { layout } = event.nativeEvent
                    }}
                >
                    {/* Inside Ring */}
                    <Circle cx="0" cy="0" r={CoreRadius} fill="none" strokeWidth={2} stroke={'white'} />
                    {rings.map((ring, ringIndex) => {
                        //Begin at [0, 1] (bottom of the circle)
                        let totalDegrees = 0

                        const prevRing = CoreRadius + ringIndex * PartRadius
                        const newRing = prevRing + (ringIndex + 1 * PartRadius)

                        //This is the Path for the Text
                        const pathRadius = prevRing + (newRing - prevRing) / 2
                        const centerX = 0
                        const centerY = 0

                        return (
                            <Fragment>
                                <Circle cx="0" cy="0" r={newRing} fill="none" strokeWidth={2} stroke={'white'} />
                                <Defs>
                                    {/* This path is used for text to be displayed along the circular path. */}
                                    <Path
                                        d={`M ${centerX} ${centerY + pathRadius}
                                           A ${pathRadius} ${pathRadius} 0 0 1 ${centerX} ${centerY - pathRadius}
                                           A ${pathRadius} ${pathRadius} 0 0 1 ${centerX} ${centerY + pathRadius}
                                           `}
                                        fill="none"
                                        stroke="green"
                                        strokeWidth={1}
                                        id={`path-${ringIndex}`}
                                    />
                                </Defs>
                                <Use href={`#path-${ringIndex}`} />
                                {ring.parts.map((part, partIndex) => {
                                    const partDegree = part.degree || ring.degree
                                    totalDegrees = totalDegrees + partDegree
                                    const innerStartPoint = getPoint(prevRing, totalDegrees - ring.offset)
                                    const outerStartPoint = getPoint(newRing, totalDegrees - ring.offset)

                                    return (
                                        <Fragment>
                                            <Line
                                                x1={innerStartPoint[0]}
                                                y1={innerStartPoint[1]}
                                                x2={outerStartPoint[0]}
                                                y2={outerStartPoint[1]}
                                                stroke={'white'}
                                                strokeWidth={2}
                                            />

                                            {/* Fix startOffset so that each Direction begins at a different point. */}
                                            <TextPath href={`#path-${ringIndex}`}>
                                                <TSpan
                                                    fill={'white'}
                                                    textAnchor="middle"
                                                    alignmentBaseline="middle"
                                                    verticalAlign={'middle'}
                                                >
                                                    {part.text}
                                                </TSpan>
                                            </TextPath>
                                        </Fragment>
                                    )
                                })}
                            </Fragment>
                        )
                    })}
                </Svg>
            </ReactNativeZoomableView>
        </View>
    )
}

export default Compass
</code>```

Body:
I am creating a simple compass with North, East, South, West directions. I created a TextPath so that my Text can curve along the circular compass.

I am facing one major problem: the beginning of the Text is being cut-off. I cannot see the complete "North" label because of the textAnchor being set to middle (which is what I prefer).

How can I make the text fully visible? After it is visible, then I can space the directions accordingly (25%) along the TextPath.

/* eslint-disable react/jsx-key */
import React, { Fragment, useState } from 'react'
import { Dimensions, View, Text } from 'react-native'
import {
    Line,
    Circle,
    Text as SVGText,
    Defs,
    Path,
    Use,
    Svg,
    G,
    TextPath,
    ForeignObject,
    TSpan,
} from 'react-native-svg'
import { ReactNativeZoomableView } from '@openspacelabs/react-native-zoomable-view'

const getPoint = (R = 0, degree = 0) => {
    // Convert the angle to a value between 0 and 360 degrees
    const angle = ((degree % 360) + 360) % 360
    // Calculate the coordinates using Math.sin and Math.cos
    const x = R * Math.cos(angle * (Math.PI / 180))
    const y = R * Math.sin(angle * (Math.PI / 180))
    return [x, y]
}

const Compass = (props) => {
    const [X, setW] = useState(1000)
    const [Y, setH] = useState(1000)
    const CoreRadius = 100
    const PartRadius = 50

    const [slider, setSlider] = useState(0)
    const [point, setPoint] = useState([0, CoreRadius])

    const rings = [
        {
            offset: -45,
            degree: 90,
            parts: [{ text: 'North' }, { text: 'East' }, { text: 'South' }, { text: 'West' }],
        },
    ]

    return (
        <View style={{ flex: 1 }}>
            <View style={{ position: 'absolute', padding: 12, top: 0, left: 0, right: 0, zIndex: 1 }}></View>
            <ReactNativeZoomableView maxZoom={30} bindToBorders={false}>
                <Svg
                    style={{ backgroundColor: '#141414', width: X, height: Y }}
                    viewBox={`-${X / 2} -${Y / 2} ${X} ${Y}`}
                    onLayout={(event) => {
                        const { layout } = event.nativeEvent
                    }}
                >
                    {/* Inside Ring */}
                    <Circle cx="0" cy="0" r={CoreRadius} fill="none" strokeWidth={2} stroke={'white'} />
                    {rings.map((ring, ringIndex) => {
                        //Begin at [0, 1] (bottom of the circle)
                        let totalDegrees = 0

                        const prevRing = CoreRadius + ringIndex * PartRadius
                        const newRing = prevRing + (ringIndex + 1 * PartRadius)

                        //This is the Path for the Text
                        const pathRadius = prevRing + (newRing - prevRing) / 2
                        const centerX = 0
                        const centerY = 0

                        return (
                            <Fragment>
                                <Circle cx="0" cy="0" r={newRing} fill="none" strokeWidth={2} stroke={'white'} />
                                <Defs>
                                    {/* This path is used for text to be displayed along the circular path. */}
                                    <Path
                                        d={`M ${centerX} ${centerY + pathRadius}
                                           A ${pathRadius} ${pathRadius} 0 0 1 ${centerX} ${centerY - pathRadius}
                                           A ${pathRadius} ${pathRadius} 0 0 1 ${centerX} ${centerY + pathRadius}
                                           `}
                                        fill="none"
                                        stroke="green"
                                        strokeWidth={1}
                                        id={`path-${ringIndex}`}
                                    />
                                </Defs>
                                <Use href={`#path-${ringIndex}`} />
                                {ring.parts.map((part, partIndex) => {
                                    const partDegree = part.degree || ring.degree
                                    totalDegrees = totalDegrees + partDegree
                                    const innerStartPoint = getPoint(prevRing, totalDegrees - ring.offset)
                                    const outerStartPoint = getPoint(newRing, totalDegrees - ring.offset)

                                    return (
                                        <Fragment>
                                            <Line
                                                x1={innerStartPoint[0]}
                                                y1={innerStartPoint[1]}
                                                x2={outerStartPoint[0]}
                                                y2={outerStartPoint[1]}
                                                stroke={'white'}
                                                strokeWidth={2}
                                            />

                                            {/* Fix startOffset so that each Direction begins at a different point. */}
                                            <TextPath href={`#path-${ringIndex}`}>
                                                <TSpan
                                                    fill={'white'}
                                                    textAnchor="middle"
                                                    alignmentBaseline="middle"
                                                    verticalAlign={'middle'}
                                                >
                                                    {part.text}
                                                </TSpan>
                                            </TextPath>
                                        </Fragment>
                                    )
                                })}
                            </Fragment>
                        )
                    })}
                </Svg>
            </ReactNativeZoomableView>
        </View>
    )
}

export default Compass


问:
Bad Gateway with nginx and nodejs with large payload
I have a nodejs with expressjs running behind nginx on AWS.

If I send a request with a small payload (and it succeeds) and then I send a request with a large payload 1.2MB, the request also succeeds.

But, if I refresh my browser page, and send only the request with the large payload, the server fails with:

```<code>node /var/wwwjs/sand/backend/api/server.js[27885]: ../src/node_http_parser.cc:738:v8::Local<v8::Value> node::{anonymous}::Parser::Execute(const char*, size_t): Assertion `(execute_depth_) == (0)' failed.
 1: 0xb30950 node::Abort() [node /var/wwwjs/sand/backend/api/server.js]
 2: 0xb309ce  [node /var/wwwjs/sand/backend/api/server.js]
 3: 0xb4b89a  [node /var/wwwjs/sand/backend/api/server.js]
 4: 0xc1c828 node::LibuvStreamWrap::OnUvRead(long, uv_buf_t const*) [node /var/wwwjs/sand/backend/api/server.js]
 5: 0x15af4c7  [node /var/wwwjs/sand/backend/api/server.js]
 6: 0x15afcf0  [node /var/wwwjs/sand/backend/api/server.js]
 7: 0x15b5ed4  [node /var/wwwjs/sand/backend/api/server.js]
 8: 0x15a40f8 uv_run [node /var/wwwjs/sand/backend/api/server.js]
 9: 0x7f37dc2e3c1d Run(Napi::CallbackInfo const&) [/var/wwwjs/sand/node_modules/deasync/bin/linux-x64-node-17/deasync.node]
10: 0x7f37dc2e4a23 Napi::details::CallbackData<Napi::Value (*)(Napi::CallbackInfo const&), Napi::Value>::Wrapper(napi_env__*, napi_callback_info__*) [/var/wwwjs/sand/node_modules/deasync/bin/linux-x64-node-17/deasync.node]
11: 0xad9d9d  [node /var/wwwjs/sand/backend/api/server.js]
12: 0xd7f43e  [node /var/wwwjs/sand/backend/api/server.js]
13: 0xd8085f v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [node /var/wwwjs/sand/backend/api/server.js]
14: 0x1635d39  [node /var/wwwjs/sand/backend/api/server.js]
</code>```

Calling a small payload request, resets the issue and I can call the large payload request again.
Without calling the samll payload request, it will always fail.

I tried adding:

```<code>client_max_body_size 50M;
</code>```

to /etc/nginx/nginx.conf, but no change.

Trying to add

```<code>app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))
</code>```

Results in "InternalServerError: stream is not readable" for every request.

Thanks for any help

Body:
I have a nodejs with expressjs running behind nginx on AWS.

If I send a request with a small payload (and it succeeds) and then I send a request with a large payload 1.2MB, the request also succeeds.

But, if I refresh my browser page, and send only the request with the large payload, the server fails with:

node /var/wwwjs/sand/backend/api/server.js[27885]: ../src/node_http_parser.cc:738:v8::Local<v8::Value> node::{anonymous}::Parser::Execute(const char*, size_t): Assertion `(execute_depth_) == (0)' failed.
 1: 0xb30950 node::Abort() [node /var/wwwjs/sand/backend/api/server.js]
 2: 0xb309ce  [node /var/wwwjs/sand/backend/api/server.js]
 3: 0xb4b89a  [node /var/wwwjs/sand/backend/api/server.js]
 4: 0xc1c828 node::LibuvStreamWrap::OnUvRead(long, uv_buf_t const*) [node /var/wwwjs/sand/backend/api/server.js]
 5: 0x15af4c7  [node /var/wwwjs/sand/backend/api/server.js]
 6: 0x15afcf0  [node /var/wwwjs/sand/backend/api/server.js]
 7: 0x15b5ed4  [node /var/wwwjs/sand/backend/api/server.js]
 8: 0x15a40f8 uv_run [node /var/wwwjs/sand/backend/api/server.js]
 9: 0x7f37dc2e3c1d Run(Napi::CallbackInfo const&) [/var/wwwjs/sand/node_modules/deasync/bin/linux-x64-node-17/deasync.node]
10: 0x7f37dc2e4a23 Napi::details::CallbackData<Napi::Value (*)(Napi::CallbackInfo const&), Napi::Value>::Wrapper(napi_env__*, napi_callback_info__*) [/var/wwwjs/sand/node_modules/deasync/bin/linux-x64-node-17/deasync.node]
11: 0xad9d9d  [node /var/wwwjs/sand/backend/api/server.js]
12: 0xd7f43e  [node /var/wwwjs/sand/backend/api/server.js]
13: 0xd8085f v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [node /var/wwwjs/sand/backend/api/server.js]
14: 0x1635d39  [node /var/wwwjs/sand/backend/api/server.js]

Calling a small payload request, resets the issue and I can call the large payload request again.
Without calling the samll payload request, it will always fail.

I tried adding:

client_max_body_size 50M;

to /etc/nginx/nginx.conf, but no change.

Trying to add

app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))

Results in "InternalServerError: stream is not readable" for every request.

Thanks for any help