问:
React + Typescript: reactjs doesn't fail compiling on typescript error
starting from some point recently, my React compiling doesn't fail on the obvious typescript error, it has been working for a long time, and I forgot what config matters, does anybody have a clue?

As the screenshot shows, I updated the parameter type with a new field, VS code actually captured the missing field, but ReactJS still let go, I definitely want it fails the build so that I can fix all places accordingly.

```<code>  # yarn start script
  "scripts": {
    "start": "react-scripts start",
</code>```

(note: I didn't upgrade reactjs or typescript versions recently)

Body:
starting from some point recently, my React compiling doesn't fail on the obvious typescript error, it has been working for a long time, and I forgot what config matters, does anybody have a clue?

As the screenshot shows, I updated the parameter type with a new field, VS code actually captured the missing field, but ReactJS still let go, I definitely want it fails the build so that I can fix all places accordingly.

  # yarn start script
  "scripts": {
    "start": "react-scripts start",

(note: I didn't upgrade reactjs or typescript versions recently)


来源: stackexchange

问:
Create ceph-volumes osd. not found:divice not cleared
I have some problem with creating volumes.

I am creating docker-compose ceph.

In monitor docker on bash type

```<code>ceph-volume inventory
</code>```

and get:

```<code>/dev/vdb                  20.00 GB     True    True
/dev/vdc                  20.00 GB     True    True
/dev/vdd                  20.00 GB     True    True
/dev/vda                  100.00 GB    True    False
</code>```

I try create volume with command:

```<code>ceph-volume lvm batch --bluestore /dev/vdb /dev/vdc /dev/vdd
</code>```

get

```<code>--> DEPRECATION NOTICE
--> You are using the legacy automatic disk sorting behavior
--> The Pacific release will change the default to --no-auto
--> passed data devices: 3 physical, 0 LVM
--> relative data size: 1.0

Total OSDs: 3

  Type            Path                                                    LV Size         % of device

  data            /dev/vdb                                                20.00 GB        100.00%

  data            /dev/vdc                                                20.00 GB        100.00%

  data            /dev/vdd                                                20.00 GB        100.00%
--> The above OSDs would be created if the operation continues
--> do you want to proceed? (yes/no) yes
Running command: /usr/bin/ceph-authtool --gen-print-key
Running command: /usr/bin/ceph --cluster ceph --name client.bootstrap-osd --keyring /var/lib/ceph/bootstrap-osd/ceph.keyring -i - osd new ef8b1bb4-71b4-40b3-8476-891fda560ffa
Running command: /usr/sbin/vgcreate --force --yes ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60 /dev/vdb
 stdout: Physical volume "/dev/vdb" successfully created.
 stdout: Volume group "ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60" successfully created
Running command: /usr/sbin/lvcreate --yes -l 5119 -n osd-block-ef8b1bb4-71b4-40b3-8476-891fda560ffa ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60
 stderr: /dev/ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60/osd-block-ef8b1bb4-71b4-40b3-8476-891fda560ffa: not found: device not cleared
  Aborting. Failed to wipe start of new LV.
--> Was unable to complete a new OSD, will rollback changes
Running command: /usr/bin/ceph --cluster ceph --name client.bootstrap-osd --keyring /var/lib/ceph/bootstrap-osd/ceph.keyring osd purge-new osd.0 --yes-i-really-mean-it
 stderr: purged osd.0
-->  RuntimeError: command returned non-zero exit status: 5
</code>```

Someone know how to fix it?

ContentLicense: CC BY-SA 4.0

Body:
I have some problem with creating volumes.

I am creating docker-compose ceph.

In monitor docker on bash type

ceph-volume inventory

and get:

/dev/vdb                  20.00 GB     True    True
/dev/vdc                  20.00 GB     True    True
/dev/vdd                  20.00 GB     True    True
/dev/vda                  100.00 GB    True    False

I try create volume with command:

ceph-volume lvm batch --bluestore /dev/vdb /dev/vdc /dev/vdd

get

--> DEPRECATION NOTICE
--> You are using the legacy automatic disk sorting behavior
--> The Pacific release will change the default to --no-auto
--> passed data devices: 3 physical, 0 LVM
--> relative data size: 1.0

Total OSDs: 3

  Type            Path                                                    LV Size         % of device

  data            /dev/vdb                                                20.00 GB        100.00%

  data            /dev/vdc                                                20.00 GB        100.00%

  data            /dev/vdd                                                20.00 GB        100.00%
--> The above OSDs would be created if the operation continues
--> do you want to proceed? (yes/no) yes
Running command: /usr/bin/ceph-authtool --gen-print-key
Running command: /usr/bin/ceph --cluster ceph --name client.bootstrap-osd --keyring /var/lib/ceph/bootstrap-osd/ceph.keyring -i - osd new ef8b1bb4-71b4-40b3-8476-891fda560ffa
Running command: /usr/sbin/vgcreate --force --yes ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60 /dev/vdb
 stdout: Physical volume "/dev/vdb" successfully created.
 stdout: Volume group "ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60" successfully created
Running command: /usr/sbin/lvcreate --yes -l 5119 -n osd-block-ef8b1bb4-71b4-40b3-8476-891fda560ffa ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60
 stderr: /dev/ceph-42e0a3bb-5c3c-4f99-ab37-a651e23b0a60/osd-block-ef8b1bb4-71b4-40b3-8476-891fda560ffa: not found: device not cleared
  Aborting. Failed to wipe start of new LV.
--> Was unable to complete a new OSD, will rollback changes
Running command: /usr/bin/ceph --cluster ceph --name client.bootstrap-osd --keyring /var/lib/ceph/bootstrap-osd/ceph.keyring osd purge-new osd.0 --yes-i-really-mean-it
 stderr: purged osd.0
-->  RuntimeError: command returned non-zero exit status: 5

Someone know how to fix it?


问:
How to download all folders of folders and files from Share point using python script
I have seen many questions and answers in stackoverflow regarding sharepoint topics, but my requirement is quite different

I need to download all folders of folders and files from in that folders, but this type requirement haven't found

so i'm attaching how my folder structure looks like

in General folder i have other folder so like that i have remaining folders also looks like that
i tried many scripts but didn't useful much
here is site link

https://abchome.sharepoint.com/sites/QualityGSharepoint/Shared%20Documents/Forms/AllItems.aspx

can anyone please advice how can i proceed, it would be very helpful to mee

FYI
I tried many of examples from stackoverfolw but no one is showed example for multiple folders of folder and files at  time download/access
here i'm attaching some links  i tried many but pasting some links FYI
Accessing Microsoft Sharepoint files and data using Python

How to solve directory path problem recursively in Python?

https://github.com/iamlu-coding

https://github.com/JonathanHolvey/sharepy/issues/5


问:
WebSocket over .htaccess failed and do endless http requests
I have a wesite with WebSocket to subdomain.
I used .htaccess to redirect all transportation to another port.

Here is my .htaccess file:

```<code>DirectoryIndex disabled
RewriteEngine On

RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
RewriteCond %{QUERY_STRING} transport=websocket    [NC]
RewriteRule (.*)           ws://localhost:8080/$1 [P,L]

RewriteBase /
RewriteRule ^(.*)?$ http://127.0.0.1:8080/$1 [P,L]
</code>```

While https works fine. wss doesn't.

The error from chrome:

```<code>socket.io.js:1706 WebSocket connection to 'wss://subdomain.domain.com/socket.io/?EIO=4&transport=websocket&sid=f5j9zNNk8-gStdnxAAA8' failed:
</code>```

Without any more information

The weird thing is, my browser do https request every second and get the correct data.
Here is my Network tab:

Please help me figure it out.

Body:
I have a wesite with WebSocket to subdomain.
I used .htaccess to redirect all transportation to another port.

Here is my .htaccess file:

DirectoryIndex disabled
RewriteEngine On

RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
RewriteCond %{QUERY_STRING} transport=websocket    [NC]
RewriteRule (.*)           ws://localhost:8080/$1 [P,L]

RewriteBase /
RewriteRule ^(.*)?$ http://127.0.0.1:8080/$1 [P,L]

While https works fine. wss doesn't.

The error from chrome:

socket.io.js:1706 WebSocket connection to 'wss://subdomain.domain.com/socket.io/?EIO=4&transport=websocket&sid=f5j9zNNk8-gStdnxAAA8' failed:

Without any more information

The weird thing is, my browser do https request every second and get the correct data.
Here is my Network tab:

Please help me figure it out.


问:
Nuxt 'npm run dev' running but the webpage is not responding and won't load
I have been working with nuxt for my personal website. but suddenly the page won't load even though my nuxt dev running perfectly on the console. here is my nuxt-config.js:

```<code>// import { auth } from 'firebase'
import colors from 'vuetify/es5/util/colors'

export default {
  srcDir: 'src/',
  components: {
    // global: true,
    dirs: [
      '~/components',
      '~/components/main',
      '~/components/user',
      '~/components/feedback',
      '~/components/auxiliary',
    ],
  },
  buildDir: 'functions/.nuxt',
  mode: 'universal',
  /*
   ** Headers of the page
   */
  head: {
    custom title page
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: process.env.npm_package_description || '',
      },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },
  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#5f24', size: '30px' },
  /*
   ** Global CSS
   */
  css: [],
  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    '~/plugins/components.js',
    '~/plugins/icons-fa.js',
    '~/plugins/filter.js',
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: ['@nuxtjs/vuetify'],
  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc: https://github.com/nuxt-community/dotenv-module
    '@nuxtjs/dotenv',
    ['vue-scrollto/nuxt', { duration: 1000 }],
    [
      '@nuxtjs/firebase',
      {
        config: {
          serverDev: {
            apiKey: process.env.FIREBASE_API_KEY_DEV,
            authDomain: process.env.FIREBASE_AUTH_DOMAIN_DEV,
            databaseURL: process.env.FIREBASE_DATABASE_URL_DEV,
            projectId: process.env.FIREBASE_PROJECT_ID_DEV,
            storageBucket: process.env.FIREBASE_STORAGE_BUCKET_DEV,
            messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_DEV,
            appId: process.env.FIREBASE_APP_ID_DEV,
            measurementId: process.env.FIREBASE_MEASUREMENT_ID_DEV,
          },
          serverPrd: {
            apiKey: process.env.FIREBASE_API_KEY_PRD,
            authDomain: process.env.FIREBASE_AUTH_DOMAIN_PRD,
            databaseURL: process.env.FIREBASE_DATABASE_URL_PRD,
            projectId: process.env.FIREBASE_PROJECT_ID_PRD,
            storageBucket: process.env.FIREBASE_STORAGE_BUCKET_PRD,
            messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_PRD,
            appId: process.env.FIREBASE_APP_ID_PRD,
            measurementId: process.env.FIREBASE_MEASUREMENT_ID_PRD,
          },
        },
        services: {
          auth: true,
          firestore: true,
          storage: true,
          analytics: true,
          functions: true,
        },
        onFirebaseHosting: true,
        customEnv: true,
      },
    ],
  ],
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {
    baseURL: process.env.BASE_URL,
    credentials: false,
  },
  /*
   ** vuetif module configuration
   ** https://github.com/nuxt-community/vuetify-module
   */
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: false,
      themes: {
        dark: {
          primary: colors.blue.darken2,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3,
        },
      },
    },
    icons: {
      iconfont: ['mdi', 'fa'],
    },
  },
  /*
   ** Build configuration
   */
  build: {
    extractCSS: true,
    extend(config, ctx) {},
    transpile: ['vuetify/lib'],
    babel: {
      plugins: [['@babel/plugin-proposal-private-methods', { loose: true }]],
    },
  },
  env: {
    baseURL: process.env.BASE_URL,
    apiKey: null,
    FIRE_ENV: process.env.FIRE_ENV,
    // Declare another env here
  },
  pageTransition: {
    name: 'fade',
    mode: 'out-in',
  },
  pluginOptions: {
    ssr: {
      nodeExternalsWhitelist: [/^vuetify/],
    },
  },
}
</code>```

and here is my package-lock.json:

```<code>{
  "name": "",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "FIRE_ENV=serverDev nuxt",
    "build": "FIRE_ENV=serverPrd nuxt build",
    "start": "FIRE_ENV=serverPrd nuxt start",
    "generate": "FIRE_ENV=serverPrd nuxt generate",
    "build:firebase": "FIRE_ENV=serverPrd npm run clean && npm run build && npm run copy && cd \"functions\" && npm i",
    "clean": "npm run clean:public && npm run clean:functions && npm run clean:static",
    "clean:functions": "rimraf \"functions/node_modules\" && rimraf \"functions/.nuxt\"",
    "clean:public": "rimraf \"public/**/*.*!(md)\" && rimraf \"public/_nuxt\"",
    "clean:static": "rimraf \"src/static/sw.js\"",
    "copy": "npm run copy:nuxt && npm run copy:static",
    "copy:nuxt": "mkdir public/_nuxt && cp -r functions/.nuxt/dist/* public/_nuxt",
    "copy:static": "cp -r src/static/* public",
    "start:firebase": "FIRE_ENV=serverPrd firebase serve --only functions,hosting",
    "deploy": "FIRE_ENV=serverPrd firebase deploy --only functions,hosting"
  },
  "dependencies": {
    "@loadingio/loading.css": "^2.0.1",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/firebase": "^7.6.1",
    "@vue/compiler-dom": "^3.2.45",
    "core-js": "^3.9.1",
    "express": "^4.18.2",
    "firebase": "^8.10.1",
    "firebase-admin": "^11.4.1",
    "firebase-functions": "^4.1.1",
    "nuxt": "^2.15.3",
    "vue": "^2.7.14",
    "vue-scrollto": "^2.20.0"
  },
  "devDependencies": {
    "@fortawesome/fontawesome-free": "^5.15.3",
    "@mdi/js": "^5.9.55",
    "@nuxtjs/vuetify": "^1.12.3",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "material-design-icons-iconfont": "^6.1.0",
    "prettier": "^2.2.1"
  }
}

</code>```

there are no error or warning, either on the server and client.

I have tried removing the package-lock.json, node_modules folder and .nuxt folder then npm install again but it still not working. I also tried using npm -i --legacy-peer-deps also not helping. any ideas what is wrong with my project? or shall i migrate to nuxt3?

Thank you

Body:
I have been working with nuxt for my personal website. but suddenly the page won't load even though my nuxt dev running perfectly on the console. here is my nuxt-config.js:

// import { auth } from 'firebase'
import colors from 'vuetify/es5/util/colors'

export default {
  srcDir: 'src/',
  components: {
    // global: true,
    dirs: [
      '~/components',
      '~/components/main',
      '~/components/user',
      '~/components/feedback',
      '~/components/auxiliary',
    ],
  },
  buildDir: 'functions/.nuxt',
  mode: 'universal',
  /*
   ** Headers of the page
   */
  head: {
    custom title page
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: process.env.npm_package_description || '',
      },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },
  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#5f24', size: '30px' },
  /*
   ** Global CSS
   */
  css: [],
  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    '~/plugins/components.js',
    '~/plugins/icons-fa.js',
    '~/plugins/filter.js',
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: ['@nuxtjs/vuetify'],
  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc: https://github.com/nuxt-community/dotenv-module
    '@nuxtjs/dotenv',
    ['vue-scrollto/nuxt', { duration: 1000 }],
    [
      '@nuxtjs/firebase',
      {
        config: {
          serverDev: {
            apiKey: process.env.FIREBASE_API_KEY_DEV,
            authDomain: process.env.FIREBASE_AUTH_DOMAIN_DEV,
            databaseURL: process.env.FIREBASE_DATABASE_URL_DEV,
            projectId: process.env.FIREBASE_PROJECT_ID_DEV,
            storageBucket: process.env.FIREBASE_STORAGE_BUCKET_DEV,
            messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_DEV,
            appId: process.env.FIREBASE_APP_ID_DEV,
            measurementId: process.env.FIREBASE_MEASUREMENT_ID_DEV,
          },
          serverPrd: {
            apiKey: process.env.FIREBASE_API_KEY_PRD,
            authDomain: process.env.FIREBASE_AUTH_DOMAIN_PRD,
            databaseURL: process.env.FIREBASE_DATABASE_URL_PRD,
            projectId: process.env.FIREBASE_PROJECT_ID_PRD,
            storageBucket: process.env.FIREBASE_STORAGE_BUCKET_PRD,
            messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_PRD,
            appId: process.env.FIREBASE_APP_ID_PRD,
            measurementId: process.env.FIREBASE_MEASUREMENT_ID_PRD,
          },
        },
        services: {
          auth: true,
          firestore: true,
          storage: true,
          analytics: true,
          functions: true,
        },
        onFirebaseHosting: true,
        customEnv: true,
      },
    ],
  ],
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {
    baseURL: process.env.BASE_URL,
    credentials: false,
  },
  /*
   ** vuetif module configuration
   ** https://github.com/nuxt-community/vuetify-module
   */
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: false,
      themes: {
        dark: {
          primary: colors.blue.darken2,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3,
        },
      },
    },
    icons: {
      iconfont: ['mdi', 'fa'],
    },
  },
  /*
   ** Build configuration
   */
  build: {
    extractCSS: true,
    extend(config, ctx) {},
    transpile: ['vuetify/lib'],
    babel: {
      plugins: [['@babel/plugin-proposal-private-methods', { loose: true }]],
    },
  },
  env: {
    baseURL: process.env.BASE_URL,
    apiKey: null,
    FIRE_ENV: process.env.FIRE_ENV,
    // Declare another env here
  },
  pageTransition: {
    name: 'fade',
    mode: 'out-in',
  },
  pluginOptions: {
    ssr: {
      nodeExternalsWhitelist: [/^vuetify/],
    },
  },
}

and here is my package-lock.json:

{
  "name": "",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "FIRE_ENV=serverDev nuxt",
    "build": "FIRE_ENV=serverPrd nuxt build",
    "start": "FIRE_ENV=serverPrd nuxt start",
    "generate": "FIRE_ENV=serverPrd nuxt generate",
    "build:firebase": "FIRE_ENV=serverPrd npm run clean && npm run build && npm run copy && cd \"functions\" && npm i",
    "clean": "npm run clean:public && npm run clean:functions && npm run clean:static",
    "clean:functions": "rimraf \"functions/node_modules\" && rimraf \"functions/.nuxt\"",
    "clean:public": "rimraf \"public/**/*.*!(md)\" && rimraf \"public/_nuxt\"",
    "clean:static": "rimraf \"src/static/sw.js\"",
    "copy": "npm run copy:nuxt && npm run copy:static",
    "copy:nuxt": "mkdir public/_nuxt && cp -r functions/.nuxt/dist/* public/_nuxt",
    "copy:static": "cp -r src/static/* public",
    "start:firebase": "FIRE_ENV=serverPrd firebase serve --only functions,hosting",
    "deploy": "FIRE_ENV=serverPrd firebase deploy --only functions,hosting"
  },
  "dependencies": {
    "@loadingio/loading.css": "^2.0.1",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/firebase": "^7.6.1",
    "@vue/compiler-dom": "^3.2.45",
    "core-js": "^3.9.1",
    "express": "^4.18.2",
    "firebase": "^8.10.1",
    "firebase-admin": "^11.4.1",
    "firebase-functions": "^4.1.1",
    "nuxt": "^2.15.3",
    "vue": "^2.7.14",
    "vue-scrollto": "^2.20.0"
  },
  "devDependencies": {
    "@fortawesome/fontawesome-free": "^5.15.3",
    "@mdi/js": "^5.9.55",
    "@nuxtjs/vuetify": "^1.12.3",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "material-design-icons-iconfont": "^6.1.0",
    "prettier": "^2.2.1"
  }
}

there are no error or warning, either on the server and client.

I have tried removing the package-lock.json, node_modules folder and .nuxt folder then npm install again but it still not working. I also tried using npm -i --legacy-peer-deps also not helping. any ideas what is wrong with my project? or shall i migrate to nuxt3?

Thank you


问:
How to add local dependency to project
I have a project "A" in IntelliJ that has a Gradle dependency "B" (defined in "A"'s gradle.build). Both "A" and "B" source codes are in Bitbucket. I need to change some codes in "A" and "B". I had cloned both "A" and "B" repositories to my local. In IntelliJ, I want to remove "B" from "A"'s gradle.build, and then add "B"'s local directory as dependency of "A". How do I do that? Thanks in advance.</p>

Title: How to add local dependency to project


问:
C# source generators: Generate different code for calls to the same method
I'll introduce my question using a concrete example. The actual question is at the bottom of this text.

Introduction

I'd like to extract some unaligned data from byte arrays where given are

the start bit position

the number of bits

whether the data is MSB-first (big endian) or LSB-first (little endian) format

For that I created a Bitpacker class that offers a static method

```<code>  ulong ReadRaw(byte[] src, int startBit, int bitLength, Endianness endianness = Endianness.LSB_FIRST)
</code>```

This method of course has to do some computation to get the desired bits out of the bytes using loops etc. which is slow. I need to evaluate the data on the order of multiple thousand times per second.

Because the arguments are compile-time known constants I could hard-code a fast variant by manually finding what bits to extract and how to shift them.

E.g. the following two assigments to raw do the same:

```<code>ulong raw;

// Manually extract bits
raw = ((ulong)(src[5] & 0xFC) >> 2) + ((ulong)(src[6] & 0x3) << 6);

// Use the slow generic implementation
raw = Bitpacker.ReadRaw(src,42,8, Endianness.LSB_FIRST);
</code>```

Hard-coding of course makes it difficult to write correct code and significantly decreases code-maintainability. That's where I thought that source-generators could come into play.

The actual question

Is it possible to use the source generator feature to somehow generate different code for each call to ReadRaw based on the constant arguments or is it possible to replace the calls to ReadRaw altogether using source generators?

Body:
I'll introduce my question using a concrete example. The actual question is at the bottom of this text.

Introduction

I'd like to extract some unaligned data from byte arrays where given are

the start bit position

the number of bits

whether the data is MSB-first (big endian) or LSB-first (little endian) format

For that I created a Bitpacker class that offers a static method

  ulong ReadRaw(byte[] src, int startBit, int bitLength, Endianness endianness = Endianness.LSB_FIRST)

This method of course has to do some computation to get the desired bits out of the bytes using loops etc. which is slow. I need to evaluate the data on the order of multiple thousand times per second.

Because the arguments are compile-time known constants I could hard-code a fast variant by manually finding what bits to extract and how to shift them.

E.g. the following two assigments to raw do the same:

ulong raw;

// Manually extract bits
raw = ((ulong)(src[5] & 0xFC) >> 2) + ((ulong)(src[6] & 0x3) << 6);

// Use the slow generic implementation
raw = Bitpacker.ReadRaw(src,42,8, Endianness.LSB_FIRST);

Hard-coding of course makes it difficult to write correct code and significantly decreases code-maintainability. That's where I thought that source-generators could come into play.

The actual question

Is it possible to use the source generator feature to somehow generate different code for each call to ReadRaw based on the constant arguments or is it possible to replace the calls to ReadRaw altogether using source generators?


问:
How can I manage the same microservice in API-gateway for a different port? nestjs application
In my nestjs application, the is microservice architecture on the server side which is written in the nestjs framework

I running a single microservice in a multi-port. want to manage a single microservice in the API-gateway for multi ports in nestjs framework.

example

localhost:3000 localhost:3001

A single service running on two different ports. how can I manage the same microservice in API-gateway for a different port?


问:
my vscode run super slow . what should I do
my "hello world" program in python and C/C++ take about 7 seconds to run . what should i do

```<code>python
print("Hello world!")
</code>```

and

```<code>C++
#include<iostream>

using namespace std;

int main() {
    cout << "Hello world!";
    return 0;
}
</code>```

Body:
my "hello world" program in python and C/C++ take about 7 seconds to run . what should i do

python
print("Hello world!")

and

C++
#include<iostream>

using namespace std;

int main() {
    cout << "Hello world!";
    return 0;
}


问:
Calling a shared library in C++ from Chromium results in ld.lld: error: undefined symbol:
Using C++, my goal is to call a function from my own shared library from within Chromium.

When I compile, I get ld.lld: error: undefined symbol: my_class::print_a_dot()

Can anyone suggest why I am getting undefined symbol? thanks!

```<code>ubuntu:~/chromium/src> autoninja -C out/Default chrome
ninja: Entering directory `out/Default'
[16888/17733] SOLINK ./libcontent.so
FAILED: libcontent.so libcontent.so.TOC
python3 "../../build/toolchain/gcc_solink_wrapper.py" --readelf="../../third_party/llvm-build/Release+Asserts/bin/llvm-readelf" --nm="../../third_party/llvm-build/Release+Asserts/bin/llvm-nm"  --sofile="./libcontent.so" --tocfile="./libcontent.so.TOC" --output="./libcontent.so" -- ../../third_party/llvm-build/Release+Asserts/bin/clang++ -shared -Wl,-soname="libcontent.so" -Werror -fuse-ld=lld -Wl,--fatal-warnings -Wl,--build-id -fPIC -Wl,-z,noexecstack -Wl,-z,relro -Wl,--color-diagnostics -Wl,--undefined-version -Wl,--no-call-graph-profile-sort -m64 -no-canonical-prefixes -Wl,--gdb-index -rdynamic -Wl,-z,defs -Wl,--as-needed -nostdlib++ --sysroot=../../build/linux/debian_bullseye_amd64-sysroot -Wl,-rpath=\$ORIGIN -o "./libcontent.so" @"./libcontent.so.rsp"
ld.lld: error: undefined symbol: my_class::print_a_dot()
>>> referenced by delegated_frame_host.cc:457 (../../content/browser/renderer_host/delegated_frame_host.cc:457)
>>>               obj/content/browser/browser/delegated_frame_host.o:(content::DelegatedFrameHost::DidCopyStaleContent(std::Cr::unique_ptr<viz::CopyOutputResult, std::Cr::default_delete<viz::CopyOutputResult>>))
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[16913/17733] CXX irt_x64/obj/ipc/mojom/ipc.mojom.o
ninja: build stopped: subcommand failed.
</code>```

:ubuntu:~/chromium/src>

For my shared library, outside Chroimium I created a C++ source file my_class.cpp

```<code>ubuntu:~/learn> cat my_class.cpp
#include <stdio.h>
#include <iostream>
#include <memory>
#include <stdint.h>
#include "my_class.h"

extern void my_class::print_a_dot()
{
    std::cout << ".";
}
</code>```

For my shared library, outside Chromium I created a C++ header file my_class.h

```<code>:ubuntu:~/learn> cat my_class.h
#ifndef MY_CLASS_H    // To make sure you don't declare the function more than once by including the header multiple times.
#define MY_CLASS_H

class my_class {

  public:
      static int some_number;
      static bool initialised;
      void print_a_dot();
      int init_encoder();
  };

#endif
</code>```

For my shared library, outside Chromium I created a CMakeLists.txt

```<code>:ubuntu:~/learn> cat CMakeLists.txt
cmake_minimum_required(VERSION 3.15)

project(MyProject)

add_library(myexample SHARED my_class.cpp)

:ubuntu:~/learn>
</code>```

In the Chromium third_party directory named "dude4" I created a directory so Chromium can access my shared library:

```<code>third_party % find dude4
dude4
dude4/BUILD.gn
dude4/include
dude4/include/my_class.h
third_party %
</code>```

The BUILD.gn contains:

```<code>config("my_class_import") {
  include_dirs = ["include"]
  libs = ["/home/ubuntu/learn/build/libmyexample.so"]
}

group("my_class") {
  public_configs = [":my_class_import"]
}
</code>```

I want to call my shared library from within Chromium, so I add the following lines at the bottom of the header lines in delegated_frame_host.cc

```<code>#include "third_party/dude4/include/my_class.h"

//using namespace N;
bool my_class::initialised = false;
int my_class::some_number = 999;
</code>```

And also in delegated_frame_host.cc I add some code to call my shared library:

```<code>void DelegatedFrameHost::DidCopyStaleContent(
    std::unique_ptr<viz::CopyOutputResult> result) {
  // host may have become visible by the time the request to capture surface is
  // completed.

    my_class mc;
    mc.initialised = false;
    std::cout << "my_class::some_number: ";
    std::cout << my_class::some_number << std::endl;
    my_class::some_number = 888;
    std::cout << "mc.some_number: ";
    std::cout << mc.some_number << std::endl;
    my_class nc;
    std::cout << "nc.some_number: ";
    std::cout << nc.some_number << std::endl;

    if (mc.initialised == false) {
        std::cout << "initialising encoder" << std::endl;
        mc.initialised = true;
    }
    mc.print_a_dot();
(code of this function continues.......)
</code>```

Body:
Using C++, my goal is to call a function from my own shared library from within Chromium.

When I compile, I get ld.lld: error: undefined symbol: my_class::print_a_dot()

Can anyone suggest why I am getting undefined symbol? thanks!

ubuntu:~/chromium/src> autoninja -C out/Default chrome
ninja: Entering directory `out/Default'
[16888/17733] SOLINK ./libcontent.so
FAILED: libcontent.so libcontent.so.TOC
python3 "../../build/toolchain/gcc_solink_wrapper.py" --readelf="../../third_party/llvm-build/Release+Asserts/bin/llvm-readelf" --nm="../../third_party/llvm-build/Release+Asserts/bin/llvm-nm"  --sofile="./libcontent.so" --tocfile="./libcontent.so.TOC" --output="./libcontent.so" -- ../../third_party/llvm-build/Release+Asserts/bin/clang++ -shared -Wl,-soname="libcontent.so" -Werror -fuse-ld=lld -Wl,--fatal-warnings -Wl,--build-id -fPIC -Wl,-z,noexecstack -Wl,-z,relro -Wl,--color-diagnostics -Wl,--undefined-version -Wl,--no-call-graph-profile-sort -m64 -no-canonical-prefixes -Wl,--gdb-index -rdynamic -Wl,-z,defs -Wl,--as-needed -nostdlib++ --sysroot=../../build/linux/debian_bullseye_amd64-sysroot -Wl,-rpath=\$ORIGIN -o "./libcontent.so" @"./libcontent.so.rsp"
ld.lld: error: undefined symbol: my_class::print_a_dot()
>>> referenced by delegated_frame_host.cc:457 (../../content/browser/renderer_host/delegated_frame_host.cc:457)
>>>               obj/content/browser/browser/delegated_frame_host.o:(content::DelegatedFrameHost::DidCopyStaleContent(std::Cr::unique_ptr<viz::CopyOutputResult, std::Cr::default_delete<viz::CopyOutputResult>>))
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[16913/17733] CXX irt_x64/obj/ipc/mojom/ipc.mojom.o
ninja: build stopped: subcommand failed.

:ubuntu:~/chromium/src>

For my shared library, outside Chroimium I created a C++ source file my_class.cpp

ubuntu:~/learn> cat my_class.cpp
#include <stdio.h>
#include <iostream>
#include <memory>
#include <stdint.h>
#include "my_class.h"

extern void my_class::print_a_dot()
{
    std::cout << ".";
}

For my shared library, outside Chromium I created a C++ header file my_class.h

:ubuntu:~/learn> cat my_class.h
#ifndef MY_CLASS_H    // To make sure you don't declare the function more than once by including the header multiple times.
#define MY_CLASS_H

class my_class {

  public:
      static int some_number;
      static bool initialised;
      void print_a_dot();
      int init_encoder();
  };

#endif

For my shared library, outside Chromium I created a CMakeLists.txt

:ubuntu:~/learn> cat CMakeLists.txt
cmake_minimum_required(VERSION 3.15)

project(MyProject)

add_library(myexample SHARED my_class.cpp)

:ubuntu:~/learn>

In the Chromium third_party directory named "dude4" I created a directory so Chromium can access my shared library:

third_party % find dude4
dude4
dude4/BUILD.gn
dude4/include
dude4/include/my_class.h
third_party %

The BUILD.gn contains:

config("my_class_import") {
  include_dirs = ["include"]
  libs = ["/home/ubuntu/learn/build/libmyexample.so"]
}

group("my_class") {
  public_configs = [":my_class_import"]
}

I want to call my shared library from within Chromium, so I add the following lines at the bottom of the header lines in delegated_frame_host.cc

#include "third_party/dude4/include/my_class.h"

//using namespace N;
bool my_class::initialised = false;
int my_class::some_number = 999;

And also in delegated_frame_host.cc I add some code to call my shared library:

void DelegatedFrameHost::DidCopyStaleContent(
    std::unique_ptr<viz::CopyOutputResult> result) {
  // host may have become visible by the time the request to capture surface is
  // completed.

    my_class mc;
    mc.initialised = false;
    std::cout << "my_class::some_number: ";
    std::cout << my_class::some_number << std::endl;
    my_class::some_number = 888;
    std::cout << "mc.some_number: ";
    std::cout << mc.some_number << std::endl;
    my_class nc;
    std::cout << "nc.some_number: ";
    std::cout << nc.some_number << std::endl;

    if (mc.initialised == false) {
        std::cout << "initialising encoder" << std::endl;
        mc.initialised = true;
    }
    mc.print_a_dot();
(code of this function continues.......)


问:
Trigger a job when a branch is deleted or merged (GITLAB-CI)
For each merge-request or for some branches, our CI deploys a test environment, using terrafrom (hosted on another repository).

The problem is that we end up with a lot of useless environments once the branch is merged or deleted.

I would like that when a branch is merged or deleted execute a trigger (on the terraform repository) with a variable that contains the name of the deleted branch.

If this doesn't exist I would like to know how it is possible to delete these environments automatically when a branch is deleted.

I have already tried this solution and it only works manually, I need an AUTOMATIC solution.


问:
pyqt5 QWebEngineView turns black screen after long time running?
To test the stability of my program, I open the program for a night. I opened the desktop to find QWebengineView area turns black. How come?

I get some possible solutions after searching.

```<code>    QGuiApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    QCoreApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
</code>```

I place the code as top as possible.
But everytime I start the program, the cmdline reads:

```<code>ARB::createContext: wglCreateContextAttribsARB() failed (GL error code: 0x0) for format: QSurfaceFormat(version 2.0, options QFlags<QSurfaceFormat::FormatOption>(), depthBufferSize -1, redBufferSize -1, greenBufferSize -1, blueBufferSize -1, alphaBufferSize -1, stencilBufferSize -1, samples -1, swapBehavior QSurfaceFormat::DefaultSwapBehavior, swapInterval 1, colorSpace QSurfaceFormat::DefaultColorSpace, profile  QSurfaceFormat::NoProfile), shared context: 0x2 (operation done.)
GDI::createContext: wglCreateContext failed. (operation done.)
Unable to create a GL Context.
qt.qpa.backingstore: composeAndFlush: QOpenGLContext creation failed
qt.qpa.backingstore: composeAndFlush: makeCurrent() failed
</code>```

what should I do ?

Body:
To test the stability of my program, I open the program for a night. I opened the desktop to find QWebengineView area turns black. How come?

I get some possible solutions after searching.

    QGuiApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    QCoreApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)

I place the code as top as possible.
But everytime I start the program, the cmdline reads:

ARB::createContext: wglCreateContextAttribsARB() failed (GL error code: 0x0) for format: QSurfaceFormat(version 2.0, options QFlags<QSurfaceFormat::FormatOption>(), depthBufferSize -1, redBufferSize -1, greenBufferSize -1, blueBufferSize -1, alphaBufferSize -1, stencilBufferSize -1, samples -1, swapBehavior QSurfaceFormat::DefaultSwapBehavior, swapInterval 1, colorSpace QSurfaceFormat::DefaultColorSpace, profile  QSurfaceFormat::NoProfile), shared context: 0x2 (operation done.)
GDI::createContext: wglCreateContext failed. (operation done.)
Unable to create a GL Context.
qt.qpa.backingstore: composeAndFlush: QOpenGLContext creation failed
qt.qpa.backingstore: composeAndFlush: makeCurrent() failed

what should I do ?


问:
is it possible to store the arrow function or anonymous function into a variable that is in the class?
I was curious when I first tried PHP, I just heard the term variable function, when I wanted to try it in class, the code was like this:

```<code><?php

class example{
    var $func = function () {
            return 1 + 2;
        };
    var $fn = fn() => 1+2;
}
</code>```

its give error : PHP Fatal error:  Constant expression contains invalid operations in /var/www/html/phpmvc/latihan.php on line 4

is arrow function or anonymous function actually cant declare in class?

iam New btw

Body:
I was curious when I first tried PHP, I just heard the term variable function, when I wanted to try it in class, the code was like this:

<?php

class example{
    var $func = function () {
            return 1 + 2;
        };
    var $fn = fn() => 1+2;
}

its give error : PHP Fatal error:  Constant expression contains invalid operations in /var/www/html/phpmvc/latihan.php on line 4

is arrow function or anonymous function actually cant declare in class?

iam New btw


问:
Webpack - css - extract to multiple files?
I'm on Webpack 5, compiling mostly Vue sfc sass styles, and currently I achieved to extract all the css styles to a single css bundle using mini-css-extract-plugin.

Obviously this bundle has grown in size and consequently the download stars taking s bit too much time, so I'm trying to split it in smaller chunks to parallelize the download.

Found this SO question, but the user managed to solve the problem using multiple entry points (which I want to avoid since the project is a spa (am I wrong?)) and this answer which suggest to configure mini-css-extract-plugin filename property to use a function instead of a string, but it seems not working since every chunk passed to the function seems having the same name/id, maybe due starting from a single entry point?

new MiniCssExtractPlugin({
    // example
    filename: (x) => {
        console.log(x.chunk.name);
        console.log("=====");
        return "css/main.[contenthash].css";
    }
}),
```
```> webpack-demo@1.0.0 build
> webpack

main
=====
main
=====
main
=====
main
=====

...
```

How can I split the outputted css bundle to multiple files?

Body:
I'm on Webpack 5, compiling mostly Vue sfc sass styles, and currently I achieved to extract all the css styles to a single css bundle using mini-css-extract-plugin.

Obviously this bundle has grown in size and consequently the download stars taking s bit too much time, so I'm trying to split it in smaller chunks to parallelize the download.

Found this SO question, but the user managed to solve the problem using multiple entry points (which I want to avoid since the project is a spa (am I wrong?)) and this answer which suggest to configure mini-css-extract-plugin filename property to use a function instead of a string, but it seems not working since every chunk passed to the function seems having the same name/id, maybe due starting from a single entry point?

new MiniCssExtractPlugin({
    // example
    filename: (x) => {
        console.log(x.chunk.name);
        console.log("=====");
        return "css/main.[contenthash].css";
    }
}),

> webpack-demo@1.0.0 build
> webpack

main
=====
main
=====
main
=====
main
=====

...

How can I split the outputted css bundle to multiple files?


问:
X-Ray enabled app sync does not link lambda authoriser trace with api request trace
I am currently playing around with some AWS architectures and I have an AppSync API which uses a lambda authoriser.

The lambda authoriser is very simply tooled with Lambda Power Tools Tracer just following the example on the GitHub page.

After I got the Lambda to properly add Traces to X-Ray I enabled the X-Ray feature on the AppSync API and I assumed that since the lambda was called from AppSync X-Ray would link the traces, but it doesn't. When I go to my X-Ray dashboard it shows both the AppSync trace and the Lambda Authoriser trace, but it does not link them and after some trying around and reading documentation I can't seem to figure out how to achieve this.


问:
memory allocation from heap in windows kernel mode
I'm working on Windows kernel mode driver development.

I believe the way we allocate dynamic memory on the heap in the user space is not applicable in the kernel mode.
I would like to know what is the kernel mode equivalent code for following piece of code(from user space).

MsgAttriPtr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulMessageAttributeBufSize);
HeapFree(GetProcessHeap(), 0, MsgAttriPtr);
```

In the code above I'm trying to allocate memory on the heap of size ulMessageAttributeBufSize and initialize it with zeros. Then I'm using HeapFree() to try and de-allocate/free the above memory.

Thanks,

Also please let me know what are the Windows native API headers to include for the functions we are going to use for kernel mode memory allocation on the heap.

Body:
I'm working on Windows kernel mode driver development.

I believe the way we allocate dynamic memory on the heap in the user space is not applicable in the kernel mode.
I would like to know what is the kernel mode equivalent code for following piece of code(from user space).

MsgAttriPtr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulMessageAttributeBufSize);
HeapFree(GetProcessHeap(), 0, MsgAttriPtr);

In the code above I'm trying to allocate memory on the heap of size ulMessageAttributeBufSize and initialize it with zeros. Then I'm using HeapFree() to try and de-allocate/free the above memory.

Thanks,

Also please let me know what are the Windows native API headers to include for the functions we are going to use for kernel mode memory allocation on the heap.


问:
How to add download conversion on Firebase?
I am getting this notification on Google App Install campaign and I have no idea how to fix it.

This app doesn't have any associated download conversion actions, which could impact campaign performance. Add a download conversion action before continuing

I did my research on Firebase download conversions and found that there is an automatically added conversion called first_open which is automatically triggered when the user first opens the app, so not when the user downloads the app per se.

There are no other automatically added conversions that track raw app downloads which is impossible as the documentation redirects us to either Play Store stats or iTunes Connect stats, as shown here.

And I am confused because I cannot add a conversion for app downloads myself in the code as it would be the same as first_open.

Am I missing something?


问:
How to find average of the column
Thanks in advance.
How to find avg when the column datatype is character varying in PostgreSQL.

here growth and literacy are character-varying.

Select avg(cast(GROWTH as float)) from census2;
```
<p><img src="https://i.stack.imgur.com/QYLpb.png" alt="[1]: https://i.stack.imgur.com/gMKhL.png" /></p>
<p>I have created a table name called <code>census2</code></p>
<pre class="lang-sql prettyprint-override"><code>create table census2
(
    District      VARCHAR(200)
  , STATE          VARCHAR(250)
  , Growth         NUMERIC
  , Sex_Ratio       NUMERIC
  , Literacy        NUMERIC
);
</code>```

After successful creation while adding CSV file it is displaying errors as
ERROR: invalid input syntax for type numeric: "Growth"
CONTEXT: COPY census2, line 503, column growth: "Growth"

Title: How to find average of the column

Body:
Thanks in advance.
How to find avg when the column datatype is character varying in PostgreSQL.

here growth and literacy are character-varying.

Select avg(cast(GROWTH as float)) from census2;

I have created a table name called census2

create table census2
(
    District      VARCHAR(200)
  , STATE          VARCHAR(250)
  , Growth         NUMERIC
  , Sex_Ratio       NUMERIC
  , Literacy        NUMERIC
);

After successful creation while adding CSV file it is displaying errors as
ERROR: invalid input syntax for type numeric: "Growth"
CONTEXT: COPY census2, line 503, column growth: "Growth"


问:
React native container subpages navigation
I am creating a React native application with the following scenario:

There is a navigation bar at the bottom of the screen, allowing the user to navigate between three main pages. On one of these pages, there is a backdrop with a container overlayed on it with two buttons. Each of these buttons should show open different "pages" in that container, and the navigation bar will be hidden when the user opens one of those "pages". An image is included below.

App layout example

My question is: how is this best implemented in react native?

My original idea was to implement a custom Stack Navigator with createStackNavigator. While this does work, I was wondering if this is a good way to go about it.

One result from using a custom navigator is that the navigation state in the container is also bound to the back button of the device (on Android). However, this is a welcome feature in this case as it makes sense in the navigation flow.


问:
mvc: filter table by multiple checkboxes
I have a table and company_type is one of its columns. Let's say cells look like this:

I want to filter this table by multiple checkboxes and they have a,b,c... values.

```<code> #else if
        {
            if (checkedBoxes.Length == 1)
            {
                var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) select new Joincco { Companies = check };
            }
            else if (checkedBoxes.Length == 2)
            {
                var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) select new Joincco { Companies = check };
            }
            else if (checkedBoxes.Length == 3)
            {
                var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) || check.company_type.Contains(checkedBoxes[2]) select new Joincco { Companies = check };
            }
</code>```

This code works but is there an easier way?

Body:
I have a table and company_type is one of its columns. Let's say cells look like this:

I want to filter this table by multiple checkboxes and they have a,b,c... values.

 #else if
        {
            if (checkedBoxes.Length == 1)
            {
                var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) select new Joincco { Companies = check };
            }
            else if (checkedBoxes.Length == 2)
            {
                var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) select new Joincco { Companies = check };
            }
            else if (checkedBoxes.Length == 3)
            {
                var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) || check.company_type.Contains(checkedBoxes[2]) select new Joincco { Companies = check };
            }

This code works but is there an easier way?


问:
Why a tensorflow model with Spatial Pyramid Pooling layers is slower than a sequential, vanilla model?
I'm training a U-net type model with a minor variation in the architecture which is the Atrous Spatial Pyramid pooling (ASPP) layer at the bottleneck after the encoder. I profiled the model during one forward pass and used tensorboard to check the tracer_view to see which part of the model has the highest latency.
Profiler Tracer View with ASPP layer
This revealed that there's a lot of idle GPU time at ASPP computation. I double checked it by removing the ASPP layer and the just connected the encoder to the decoder. In this experiment, the idle time that was previously there disappeared.
Profiler Tracer View without ASPP layer
I understand that the second model example would be a bit smaller than the former.

This is how my model looks like with ASPP layer. And to I just commented those ASPP layers out to profile the model without ASPP layers.

With ASPP

```<code>def get_custom_deeplab(image_size: tuple, num_classes: int):
    """
    This model uses a vanilla CNN backbone. This model also uses upsampling2d in place of conv2d transpose
    """
    input_layer = keras.Input(shape=(image_size[0], image_size[1], 3))
    conv1 = Conv2D(128, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(input_layer)
    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

    conv2 = Conv2D(128, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(pool1)
    conv2 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(conv2)
    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

    conv3 = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(pool2)
    conv3 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(conv3)
    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)

    conv4 = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(pool3)
    conv4 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(conv4)
    pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)
#######ASPP layers
    out_1 = Conv2D(256, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=1, padding='same')(pool4)
    out_6 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=6, padding='same')(pool4)
    out_12 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=10, padding='same')(pool4)
    out_14 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=14, padding='same')(pool4)
    x = layers.Concatenate(axis=-1)([out_1, out_6, out_12, out_14])
########ASPP's output
    x = Conv2D(256, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=1, padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)

    skip_connection_1 = pool3
    x = layers.Concatenate(axis=-1)([x,skip_connection_1])
    x = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)
    skip_connection_2 = pool2
    x = layers.Concatenate(axis=-1)([x,skip_connection_2])
    x = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)
    x = Conv2D(64, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)
    x = Conv2D(
        num_classes,
        kernel_size=1,
        padding="same",
        use_bias=True,
        kernel_initializer=keras.initializers.HeNormal(),
        )(x)
    return tf.keras.Model(inputs=input_layer,outputs=x)
</code>```

But, I would like to know if there's any workaround to mitigate the problem of GPU idle time when the model has layers like ASPP?

Body:
I'm training a U-net type model with a minor variation in the architecture which is the Atrous Spatial Pyramid pooling (ASPP) layer at the bottleneck after the encoder. I profiled the model during one forward pass and used tensorboard to check the tracer_view to see which part of the model has the highest latency.
Profiler Tracer View with ASPP layer
This revealed that there's a lot of idle GPU time at ASPP computation. I double checked it by removing the ASPP layer and the just connected the encoder to the decoder. In this experiment, the idle time that was previously there disappeared.
Profiler Tracer View without ASPP layer
I understand that the second model example would be a bit smaller than the former.

This is how my model looks like with ASPP layer. And to I just commented those ASPP layers out to profile the model without ASPP layers.

With ASPP

def get_custom_deeplab(image_size: tuple, num_classes: int):
    """
    This model uses a vanilla CNN backbone. This model also uses upsampling2d in place of conv2d transpose
    """
    input_layer = keras.Input(shape=(image_size[0], image_size[1], 3))
    conv1 = Conv2D(128, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(input_layer)
    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

    conv2 = Conv2D(128, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(pool1)
    conv2 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(conv2)
    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

    conv3 = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(pool2)
    conv3 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(conv3)
    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)

    conv4 = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(pool3)
    conv4 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(conv4)
    pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)
#######ASPP layers
    out_1 = Conv2D(256, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=1, padding='same')(pool4)
    out_6 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=6, padding='same')(pool4)
    out_12 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=10, padding='same')(pool4)
    out_14 = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=14, padding='same')(pool4)
    x = layers.Concatenate(axis=-1)([out_1, out_6, out_12, out_14])
########ASPP's output
    x = Conv2D(256, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), dilation_rate=1, padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)

    skip_connection_1 = pool3
    x = layers.Concatenate(axis=-1)([x,skip_connection_1])
    x = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)
    skip_connection_2 = pool2
    x = layers.Concatenate(axis=-1)([x,skip_connection_2])
    x = Conv2D(128, (1, 1), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = Conv2D(256, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)
    x = Conv2D(64, (3, 3), activation='relu', kernel_initializer='lecun_uniform', kernel_constraint=max_norm(3), padding='same')(x)
    x = layers.UpSampling2D(
        (2,2),interpolation="bilinear",
        )(x)
    x = Conv2D(
        num_classes,
        kernel_size=1,
        padding="same",
        use_bias=True,
        kernel_initializer=keras.initializers.HeNormal(),
        )(x)
    return tf.keras.Model(inputs=input_layer,outputs=x)

But, I would like to know if there's any workaround to mitigate the problem of GPU idle time when the model has layers like ASPP?


问:
Validating xp:inputTextArea field not containing Return characters
In my xpages application I have a validation on a inputTextArea control e.g.

```<code><xp:inputTextarea
    id="inpRelPresentation"
    value="#{matterBean.matter.busRelations}"
    validator="#{matterValidators.valBusinessRelation}">
    <xp:this.validators>
        <xp:validateRequired>
            <xp:this.message><![CDATA[#{javascript:xptI18NBean.getValue("matter.msg_valid_business_relation")}]]></xp:this.message>
        </xp:validateRequired>
    </xp:this.validators>
    <xp:this.required><![CDATA[#{javascript:return ( submittedBy('btnSendToCommitee'))}]]></xp:this.required>
</xp:inputTextarea>
</code>```

The validator has a simple check that no spaces are entered. I would to extend the validator so it also removed black lines and return characters but I wonder how to apply this?

```<code>public void valBusinessRelation(FacesContext facesContext, UIComponent component, Object value) {
    try {
        String msg = null;
        if (value.toString().replaceAll("\\s+","").equals("")){
            utils.printToConsole(this.getClass().getSimpleName().toString() + " " + methodName + " -> FAILED. Component: " + component.getId() + ". Value = " + value.toString());
            msg = propStrings.getProperty("msg_valid_business_relation");
            FacesMessage message = new FacesMessage(msg);
            throw new ValidatorException(message);
        }
    } catch (Exception e) {
        XspOpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
    }
}
</code>```

Any suggestions?

Body:
In my xpages application I have a validation on a inputTextArea control e.g.

<xp:inputTextarea
    id="inpRelPresentation"
    value="#{matterBean.matter.busRelations}"
    validator="#{matterValidators.valBusinessRelation}">
    <xp:this.validators>
        <xp:validateRequired>
            <xp:this.message><![CDATA[#{javascript:xptI18NBean.getValue("matter.msg_valid_business_relation")}]]></xp:this.message>
        </xp:validateRequired>
    </xp:this.validators>
    <xp:this.required><![CDATA[#{javascript:return ( submittedBy('btnSendToCommitee'))}]]></xp:this.required>
</xp:inputTextarea>

The validator has a simple check that no spaces are entered. I would to extend the validator so it also removed black lines and return characters but I wonder how to apply this?

public void valBusinessRelation(FacesContext facesContext, UIComponent component, Object value) {
    try {
        String msg = null;
        if (value.toString().replaceAll("\\s+","").equals("")){
            utils.printToConsole(this.getClass().getSimpleName().toString() + " " + methodName + " -> FAILED. Component: " + component.getId() + ". Value = " + value.toString());
            msg = propStrings.getProperty("msg_valid_business_relation");
            FacesMessage message = new FacesMessage(msg);
            throw new ValidatorException(message);
        }
    } catch (Exception e) {
        XspOpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
    }
}

Any suggestions?


问:
Need explaination of a python code - newbiew to Python
I am quite new to Python and there is one assignment that I could not understand even though I have already reviewed similar solutions:

Assignment: Find K numbers in a list that their sum is equal to M ( input K and M). Print these numbers

For example:

```<code>Array= [3,2,4,8,5]
</code>```
```<code>Input:K=2, M=5
Output: [3,2]
Input: K=3, M=13
Output: [3,2,8]
</code>```

Here is a solution of this modified assignment: print all subsequences that their sum is equal to M.

```<code>
def subsetSumToK(arr,k):
    if len(arr)==0:
        if k == 0:
            return [[]]
        else:
            return []

    output=[]
    if arr[0]<=k:
        temp2=subsetSumToK(arr[1:],k-arr[0])  #Including the current element
        if len(temp2)>0:
            for i in range(len(temp2)):
                temp2[i].insert(0,arr[0])
                output.append(temp2[i])

    temp1=subsetSumToK(arr[1:],k)            #Excluding the current element
    if len(temp1)>0:
        for i in range(len(temp1)):
            output.append(temp1[i])
    return output

arr=[int(i) for i in input().split()]
k=int(input())
sub=subsetSumToK(arr,k)
for i in sub:
    for j in range(len(i)):
        if j==len(i)-1:
            print(i[j])
        else:
            print(i[j],end=" ")
</code>```
```<code>Ex: Input:K=2, M=5
Output: [3,2], [5]
</code>```

The problem here is, even though I have already had seen solutions, I tried to do manually by doing iterations by hand, but I could not understand the algorithm, maybe I read it wrong. I really need your help.

Especially starting from these lines:

```<code>if arr[0]<=k:
        temp2=subsetSumToK(arr[1:],k-arr[0])  #Including the current element
        if len(temp2)>0:
            for i in range(len(temp2)):
                temp2[i].insert(0,arr[0])
                output.append(temp2[i])
</code>```

Here were my plain explainations:

```<code>arr=[3,2,4,8,5], K=5
</code>```
```<code>#1st iteration:

if array[0]                                                 #(=3)<=5 :True
   temp2=subsetSumToK(arr[1:],k-arr[0])                     # temp2= ( [2,4,8,5], 2)
   if len(temp2)>0                                          #(2>0: True):
      for i in range (len(temp2)):                          # i=0
          temp2[i].insert(0,arr[0])                         # temp2[0]=[2,4,8,5]
                                                            # => temp2= ( [3,2,4,8,5],2)
          output.append(temp2[i])                           # output= ([3,2,4,8,5])

#2nd iteration:

      for i in range (len(temp2)):                          # i=1
          temp2[i].insert(0,arr[0])                         # temp2[1]= (2)
                                                            #=> temp2= ( [3,2,4,8,5], 2, 2) ????
          output.append(temp2[i])                           # output= ( [3,2,4,8,5], 2)?????

# And then I realised that the length of temp2 goes to infinitive.....
# Far beyond
</code>```

Body:
I am quite new to Python and there is one assignment that I could not understand even though I have already reviewed similar solutions:

Assignment: Find K numbers in a list that their sum is equal to M ( input K and M). Print these numbers

For example:

Array= [3,2,4,8,5]

Input:K=2, M=5
Output: [3,2]
Input: K=3, M=13
Output: [3,2,8]

Here is a solution of this modified assignment: print all subsequences that their sum is equal to M.

def subsetSumToK(arr,k):
    if len(arr)==0:
        if k == 0:
            return [[]]
        else:
            return []

    output=[]
    if arr[0]<=k:
        temp2=subsetSumToK(arr[1:],k-arr[0])  #Including the current element
        if len(temp2)>0:
            for i in range(len(temp2)):
                temp2[i].insert(0,arr[0])
                output.append(temp2[i])

    temp1=subsetSumToK(arr[1:],k)            #Excluding the current element
    if len(temp1)>0:
        for i in range(len(temp1)):
            output.append(temp1[i])
    return output

arr=[int(i) for i in input().split()]
k=int(input())
sub=subsetSumToK(arr,k)
for i in sub:
    for j in range(len(i)):
        if j==len(i)-1:
            print(i[j])
        else:
            print(i[j],end=" ")

Ex: Input:K=2, M=5
Output: [3,2], [5]

The problem here is, even though I have already had seen solutions, I tried to do manually by doing iterations by hand, but I could not understand the algorithm, maybe I read it wrong. I really need your help.

Especially starting from these lines:

if arr[0]<=k:
        temp2=subsetSumToK(arr[1:],k-arr[0])  #Including the current element
        if len(temp2)>0:
            for i in range(len(temp2)):
                temp2[i].insert(0,arr[0])
                output.append(temp2[i])

Here were my plain explainations:

arr=[3,2,4,8,5], K=5

#1st iteration:

if array[0]                                                 #(=3)<=5 :True
   temp2=subsetSumToK(arr[1:],k-arr[0])                     # temp2= ( [2,4,8,5], 2)
   if len(temp2)>0                                          #(2>0: True):
      for i in range (len(temp2)):                          # i=0
          temp2[i].insert(0,arr[0])                         # temp2[0]=[2,4,8,5]
                                                            # => temp2= ( [3,2,4,8,5],2)
          output.append(temp2[i])                           # output= ([3,2,4,8,5])

#2nd iteration:

      for i in range (len(temp2)):                          # i=1
          temp2[i].insert(0,arr[0])                         # temp2[1]= (2)
                                                            #=> temp2= ( [3,2,4,8,5], 2, 2) ????
          output.append(temp2[i])                           # output= ( [3,2,4,8,5], 2)?????

# And then I realised that the length of temp2 goes to infinitive.....
# Far beyond


问:
How to resize the image of kinect with Processing
The output image of using EasyOpenNI with an xbox360 kinect is a small 640 x 480 image, is there anyway to maybe scale it up to fullscreen, or near fullscreen.

I tried using image.resize() but it creates additional images on the top, and the expanded image does not refresh, it gives the initial frame at boot.

Code:

```<code>import SimpleOpenNI.*;

SimpleOpenNI kinect;

PImage depthCam;
PImage result;

void setup()
{
  size(640, 480);
  surface.setResizable(true);
  background(0);

  kinect  = new SimpleOpenNI(this);
  kinect.enableDepth();

  result = createImage(width,height,RGB);
}

void draw()
{

  background(0);
  kinect.update();

  depthCam = kinect.depthImage();
  int[] depthVals = kinect.depthMap();

  result.loadPixels();

  for (int y=0; y<depthCam.height; y=y+5)
  {
    for (int x =0; x<depthCam.width; x=x+5)
    {
      int loc = x+(y*depthCam.width);

      if (depthVals[loc] <= 1200 && depthVals[loc] > 50) {
        result.pixels[loc] = color(250);
      }
      else if (depthVals[loc] > 1200 && depthVals[loc]< 3000 )
      {
        result.pixels[loc] = color(102);
      }
      else  {
      //otherwise let the pixel value in the result image be white
       result.pixels[loc] = color(0);
      }

    }
  }

result.updatePixels();
result.resize(640*2,480*2);
image(result,0,0);

}
</code>```

Here is a screenshot of what appears:

Everything is working correctly, except for the fact that there are two duplicated streams at the top (that do refresh), and the enlarged stream does not refresh.

Body:
The output image of using EasyOpenNI with an xbox360 kinect is a small 640 x 480 image, is there anyway to maybe scale it up to fullscreen, or near fullscreen.

I tried using image.resize() but it creates additional images on the top, and the expanded image does not refresh, it gives the initial frame at boot.

Code:

import SimpleOpenNI.*;

SimpleOpenNI kinect;

PImage depthCam;
PImage result;

void setup()
{
  size(640, 480);
  surface.setResizable(true);
  background(0);

  kinect  = new SimpleOpenNI(this);
  kinect.enableDepth();

  result = createImage(width,height,RGB);
}

void draw()
{

  background(0);
  kinect.update();

  depthCam = kinect.depthImage();
  int[] depthVals = kinect.depthMap();

  result.loadPixels();

  for (int y=0; y<depthCam.height; y=y+5)
  {
    for (int x =0; x<depthCam.width; x=x+5)
    {
      int loc = x+(y*depthCam.width);

      if (depthVals[loc] <= 1200 && depthVals[loc] > 50) {
        result.pixels[loc] = color(250);
      }
      else if (depthVals[loc] > 1200 && depthVals[loc]< 3000 )
      {
        result.pixels[loc] = color(102);
      }
      else  {
      //otherwise let the pixel value in the result image be white
       result.pixels[loc] = color(0);
      }

    }
  }

result.updatePixels();
result.resize(640*2,480*2);
image(result,0,0);

}

Here is a screenshot of what appears:

Everything is working correctly, except for the fact that there are two duplicated streams at the top (that do refresh), and the enlarged stream does not refresh.


问:
follow softlinks when reading file in h5py
I have a hdf5 file where I have a big dataset containing a Nx3 matrix, to store positions in 3D. This dataset is referenced in several groups using softlinks, as shown in the hierarchy below

```<code>/
/POINTS (the big dataset)
/mesh0
/mesh0/POINTS (softlink to /POINTS)
/mesh1
/mesh1/POINTS (softlink to /POINTS)
</code>```

However, to load this using h5py, I iterate on my groups and if I found a mesh (a group with an attribute called mesh), I assume there is a POINTS dataset and parse it. The issue is that this is creating new numpy matrices for each POINTS dataset.

```<code># This creates a new numpy array, which is inefficient is we are dealing with softlinks
points = mesh_group["POINTS"][::]
</code>```

I would like to know how to check if the link to the dataset is a softlink, so I can create the matrix only once.

Body:
I have a hdf5 file where I have a big dataset containing a Nx3 matrix, to store positions in 3D. This dataset is referenced in several groups using softlinks, as shown in the hierarchy below

/
/POINTS (the big dataset)
/mesh0
/mesh0/POINTS (softlink to /POINTS)
/mesh1
/mesh1/POINTS (softlink to /POINTS)

However, to load this using h5py, I iterate on my groups and if I found a mesh (a group with an attribute called mesh), I assume there is a POINTS dataset and parse it. The issue is that this is creating new numpy matrices for each POINTS dataset.

# This creates a new numpy array, which is inefficient is we are dealing with softlinks
points = mesh_group["POINTS"][::]

I would like to know how to check if the link to the dataset is a softlink, so I can create the matrix only once.


问:
Issue with delete multiple orders - codeigniter 3
With this function I can correct delete single record:

```<code>`    //delete order
    public function delete_order($id)
    {
        $id = clean_number($id);
        $order = $this->get_order($id);
        if (!empty($order)) {
            //delete order products
            $order_products = $this->get_order_products($id);
            if (!empty($order_products)) {
                foreach ($order_products as $order_product) {
                    $this->db->where('id', $order_product->id);
                    $this->db->delete('order_products');
                }
            }
            //delete invoice
            $this->db->where('order_id', $order->id)->delete('invoices');
            //delete order
            $this->db->where('id', $id);
            return $this->db->delete('orders');
        }
        return false;
    }`
</code>```

Now I try prepare function for delete multiple records.

In header table I add:

```<code>` <th scope="col" style="width: 25px;">
                                                            <div class="form-check">
                                                              <input class="form-check-input fs-15" type="checkbox" id="checkAll">
                                                            </div>
                                                        </th>`
</code>```

and in foreach:

```<code>      ` <th scope="row">
                                                            <div class="form-check">
                                                                <input class="form-check-input fs-15" name="checkbox-table" type="checkbox" name="checkAll" value="<?php echo $item->id; ?>">
                                                            </div>
                                                        </th>`
</code>```

Now I created action:

```<code>`<a class="dropdown-item" onclick="delete_selected_orders('<?php echo trans("confirm_products"); ?>');"><?php echo trans('delete'); ?></a>`
</code>```

.js script

```<code>`<script>
//delete selected orders
function delete_selected_orders(message) {
    swal({
        text: message,
        icon: "warning",
        buttons: true,
        buttons: [sweetalert_cancel, sweetalert_ok],
        dangerMode: true,
    }).then(function (willDelete) {
        if (willDelete) {
            var order_ids = [];
            $("input[name='checkbox-table']:checked").each(function () {
                order_ids.push(this.value);
            });
            var data = {
                'order_ids': order_ids,
            };
            data[csfr_token_name] = $.cookie(csfr_cookie_name);
            $.ajax({
                type: "POST",
                url: base_url + "order_admin_controller/delete_selected_orders",
                data: data,
                success: function (response) {
                    location.reload();
                }
            });
        }
    });
};
</script>`
</code>```

order_admin_controller/delete_selected_orders

```<code>`    /**
     * Delete Selected Orders
     */
    public function delete_selected_orders()
    {
        $order_ids = $this->input->post('order_ids', true);
        $this->order_admin_model->delete_multi_orders($order_ids);

        //reset cache
        reset_cache_data_on_change();
    }`
</code>```

model

```<code>    //delete multi order
    public function delete_multi_orders($order_ids)
    {
        if (!empty($order_ids)) {
            foreach ($order_ids as $id) {
                $this->delete_order($id);
            }
        }
    }`

</code>```

When I check all and post delete multiple action then I see sweatalert to confirm delete, when I confirm I not see any error in console browser. But When I select multiple records and post then page refresh and  orders not deleted.

I think function controller/model is correct. But im not sure with this in .js order_ids  and in view table if I  post order_ids correct.

Body:
With this function I can correct delete single record:

`    //delete order
    public function delete_order($id)
    {
        $id = clean_number($id);
        $order = $this->get_order($id);
        if (!empty($order)) {
            //delete order products
            $order_products = $this->get_order_products($id);
            if (!empty($order_products)) {
                foreach ($order_products as $order_product) {
                    $this->db->where('id', $order_product->id);
                    $this->db->delete('order_products');
                }
            }
            //delete invoice
            $this->db->where('order_id', $order->id)->delete('invoices');
            //delete order
            $this->db->where('id', $id);
            return $this->db->delete('orders');
        }
        return false;
    }`

Now I try prepare function for delete multiple records.

In header table I add:

`

                                                              <input class="form-check-input fs-15" type="checkbox" id="checkAll">

                                                        	`

and in foreach:

      `

                                                                <input class="form-check-input fs-15" name="checkbox-table" type="checkbox" name="checkAll" value="<?php echo $item->id; ?>">

                                                        	`

Now I created action:

`<a class="dropdown-item" onclick="delete_selected_orders('<?php echo trans("confirm_products"); ?>');"><?php echo trans('delete'); ?></a>`

.js script

``

order_admin_controller/delete_selected_orders

`    /**
     * Delete Selected Orders
     */
    public function delete_selected_orders()
    {
        $order_ids = $this->input->post('order_ids', true);
        $this->order_admin_model->delete_multi_orders($order_ids);

        //reset cache
        reset_cache_data_on_change();
    }`

model

    //delete multi order
    public function delete_multi_orders($order_ids)
    {
        if (!empty($order_ids)) {
            foreach ($order_ids as $id) {
                $this->delete_order($id);
            }
        }
    }`

When I check all and post delete multiple action then I see sweatalert to confirm delete, when I confirm I not see any error in console browser. But When I select multiple records and post then page refresh and  orders not deleted.

I think function controller/model is correct. But im not sure with this in .js order_ids  and in view table if I  post order_ids correct.


问:
phpdocx library
 and
 not working in docx file when
 tag used in

i am using phpdocx library to generate docx file from html content. it not working when
 tag used in
 tag. in generated docx file

 format messed up.

nothing found for this problem

$docx = new CreateDocx();
$docx->setDefaultFont('Arial');
$wordStyles = array('
' => 'LightListAccent3PHPDOCX', '
' => 'Heading1PHPDOCX' , '
' => 'Heading2PHPDOCX' , '
' => 'Heading3PHPDOCX' , '
' => 'Heading4PHPDOCX' , '
' => 'Heading5PHPDOCX' , '
' => 'Heading6PHPDOCX');
$docx->embedHTML($htmlContent, array('strictWordStyles' => false, 'wordStyles' => $wordStyles));
$docx->createDocxAndDownload('/tmp/'.$filename);
```

image attached

Title: phpdocx library <ul> and <li> not working in docx file when <p> tag used in <li>

Body:
i am using phpdocx library to generate docx file from html content. it not working when
 tag used in
 tag. in generated docx file

 format messed up.

nothing found for this problem

$docx = new CreateDocx();
$docx->setDefaultFont('Arial');
$wordStyles = array('
' => 'LightListAccent3PHPDOCX', '
' => 'Heading1PHPDOCX' , '
' => 'Heading2PHPDOCX' , '
' => 'Heading3PHPDOCX' , '
' => 'Heading4PHPDOCX' , '
' => 'Heading5PHPDOCX' , '
' => 'Heading6PHPDOCX');
$docx->embedHTML($htmlContent, array('strictWordStyles' => false, 'wordStyles' => $wordStyles));
$docx->createDocxAndDownload('/tmp/'.$filename);

image attached


问:
Why I can't start a windows CMD from Gitbash with a command?
I try to start a CMD on windows from Gitbash with passing a command to be executed. But it is not working.

Example: cmd /K dir

Why is that not working as it only starts the CMD without any command? The help is working (cmd /?)


问:
How can to remove the default active background color in ReactNative Material Bottom Tabs version 6.2.10
please I Will like to learn how to remove this background color in the image below. I've tried all props in the documentation, nothing worked.


问:
html2canvas - render page during or after element's animation/transition
I made button that capture the whole page using html2canvas
but my page has a loading animation from the start when the page loads.
The problem is that, when I use html2canvas, I was expecting it will render the page when the loading animation finished, but no, instead, it also renders the first frame of the animation.
is there a workaround of this?</p>


问:
Removing all child nodes of a div with a while loop doesn't work within event listener fucntion
So I am using the following code to remove all child nodes of a div.

```<code>    while (colorInputContainer.firstChild) {
        console.log(1);
        console.log(colorInputContainer);
        console.log(colorInputContainer.firstChild)
        colorInputContainer.removeChild(colorInputContainer.firstChild);
    }
</code>```

This code in itself works inside the console. But when I use it in the full context (pastebin) it does not. And I have no idea why.

Body:
So I am using the following code to remove all child nodes of a div.

    while (colorInputContainer.firstChild) {
        console.log(1);
        console.log(colorInputContainer);
        console.log(colorInputContainer.firstChild)
        colorInputContainer.removeChild(colorInputContainer.firstChild);
    }

This code in itself works inside the console. But when I use it in the full context (pastebin) it does not. And I have no idea why.


问:
How to add hyperlink using json-as-xlsx library?
I want to export the json data into an excel data and there is one column (name = Link) and in each data there should be a clickable link . i want to set hyperlink on that link

(Library used => json-as-xlsx    )

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

data = [
           {
             sheet: "Tasks",
             columns: [
             { label: "Status", value: (row) =>row.status_description==="completed"?"Pending                 Approval":"Accepted"},
            { label: "Req Date", value: (row) => moment(row.created_at).format('DD-MM-YYYY hh:mm:ss')},
             { label: "Task Name", value: (row) => row.fields.find(o=>o.label==="Task name")?.value },
             { label: "Title", value: (row) => row.name },
            { label: "Content Type", value: (row) => row.fields.find(o=>o.label==="Content type")?.value },
            { label: "Final word count", value: (row) => row.word_count },
            { label: "Link", value: (row) =>  `https://docs.google.com/document/d/${row.doc}`,type:"hyperlink"}

                                    ],
                                    content: response.items,
                                }
                            ]
</code>```
```<code>let filename = `${reqData.query.project_name}-${moment().format('DD-MMM-YYYY')}`
                        let settings = {
                            fileName: filename, // Name of the resulting spreadsheet
                            extraLength: 1, // A bigger number means that columns will be wider
                            writeMode: 'writeFile', // The available parameters are 'WriteFile' and 'write'. This setting is optional. Useful in such cases https://docs.sheetjs.com/docs/solutions/output#example-remote-file
                            writeOptions: {}, // Style options from https://github.com/SheetJS/sheetjs#writing-options
                            RTL: false, // Display the columns from right-to-left (the default value is false)
                        }

                        let filepath = path.join(__dirname, `../../../${filename}.xlsx`);

                        let callback = function (sheet) {

                            console.log("Download complete:",sheet)
                            resolve({filepath: filepath, filename: `${filename}.xlsx`});
                        }

                        jsonAsXlsx(data, settings, callback)

                    }).catch((err) => reject(err));

</code>```

Body:
I want to export the json data into an excel data and there is one column (name = Link) and in each data there should be a clickable link . i want to set hyperlink on that link

(Library used => json-as-xlsx    )

``````````````````````````````````````````````````````````````````

data = [
           {
             sheet: "Tasks",
             columns: [
             { label: "Status", value: (row) =>row.status_description==="completed"?"Pending                 Approval":"Accepted"},
            { label: "Req Date", value: (row) => moment(row.created_at).format('DD-MM-YYYY hh:mm:ss')},
             { label: "Task Name", value: (row) => row.fields.find(o=>o.label==="Task name")?.value },
             { label: "Title", value: (row) => row.name },
            { label: "Content Type", value: (row) => row.fields.find(o=>o.label==="Content type")?.value },
            { label: "Final word count", value: (row) => row.word_count },
            { label: "Link", value: (row) =>  `https://docs.google.com/document/d/${row.doc}`,type:"hyperlink"}

                                    ],
                                    content: response.items,
                                }
                            ]

let filename = `${reqData.query.project_name}-${moment().format('DD-MMM-YYYY')}`
                        let settings = {
                            fileName: filename, // Name of the resulting spreadsheet
                            extraLength: 1, // A bigger number means that columns will be wider
                            writeMode: 'writeFile', // The available parameters are 'WriteFile' and 'write'. This setting is optional. Useful in such cases https://docs.sheetjs.com/docs/solutions/output#example-remote-file
                            writeOptions: {}, // Style options from https://github.com/SheetJS/sheetjs#writing-options
                            RTL: false, // Display the columns from right-to-left (the default value is false)
                        }

                        let filepath = path.join(__dirname, `../../../${filename}.xlsx`);

                        let callback = function (sheet) {

                            console.log("Download complete:",sheet)
                            resolve({filepath: filepath, filename: `${filename}.xlsx`});
                        }

                        jsonAsXlsx(data, settings, callback)

                    }).catch((err) => reject(err));


问:
Hi, I have a problem in the data list. After displaying the information, I want to get the product code by clicking on a in the data list
I still couldn't get the output from the program. I put a text in the data list to display the product ID by clicking on it, but it didn't work and only the ID of the first product is displayed.

            <asp:Label ID="Label4" runat="server" Text='<%# Eval("NameKala") %>' />

                <asp:Label ID="Label3" runat="server" Text='<%# Eval("IdKala") %>' />

               open

 test
          <asp:Label ID="Label5" runat="server" Text='<%# Eval("IdKala") %>' />

```

My output should be in such a way that in each line of the data list that is clicked, display the product ID of that line or section.

Body:
I still couldn't get the output from the program. I put a text in the data list to display the product ID by clicking on it, but it didn't work and only the ID of the first product is displayed.

            <asp:Label ID="Label4" runat="server" Text='<%# Eval("NameKala") %>' />

                <asp:Label ID="Label3" runat="server" Text='<%# Eval("IdKala") %>' />

               open

 test
          <asp:Label ID="Label5" runat="server" Text='<%# Eval("IdKala") %>' />

My output should be in such a way that in each line of the data list that is clicked, display the product ID of that line or section.


问:
Google Tag Manager, How to return a class inner text if a parent tag does not have class
I have the following html code:

```<code><li class="ais-RefinementList-item ais-RefinementList-item--selected">
 <div><label class="ais-RefinementList-label">
  <input type="checkbox" class="ais-RefinementList-checkbox" checked="" value="Software">
  <span class="ais-RefinementList-labelText">Software</span>
  <span class="ais-RefinementList-count">264</span></label></div></li
</code>```

I want to do the following: if the class ais-RefinementList-item--selected" exists to not do anything and if it does not exists then to continue to extract the ais-RefinementList-labelText.

I used the following function which worked to always get the labeltText even if the click element was on the count to always get the text value for the analytics and it works fine:

```<code>function () { return {{Click Element}}.parentNode.lastChild.previousSibling.innerText }

</code>```

Therefore i want to have this function run only if ais-RefinementList-item--selected" does not exist in the li as it is added when a checkbox is clicked on the website search filters.

Another thing i noticed was that when the checkbox is not clicked, checked does not appear.

```<code>checked=""
</code>```

I tried doing a DOM ELEMENT trigger variable but it then stopped counting when multiple filters were checked.

Body:
I have the following html code:

  <input type="checkbox" class="ais-RefinementList-checkbox" checked="" value="Software">
  Software
  264
</li

I want to do the following: if the class ais-RefinementList-item--selected" exists to not do anything and if it does not exists then to continue to extract the ais-RefinementList-labelText.

I used the following function which worked to always get the labeltText even if the click element was on the count to always get the text value for the analytics and it works fine:

function () { return {{Click Element}}.parentNode.lastChild.previousSibling.innerText }

Therefore i want to have this function run only if ais-RefinementList-item--selected" does not exist in the li as it is added when a checkbox is clicked on the website search filters.

Another thing i noticed was that when the checkbox is not clicked, checked does not appear.

checked=""

I tried doing a DOM ELEMENT trigger variable but it then stopped counting when multiple filters were checked.


问:
Java if-else statement to print file/directory size; large file size (1 GB<) printing issue
I'd like to print file/directory sizes in Java, however for files larger than 1GB I cannot. For example, when I check a file with ~1.3 GB it writes 0.000 TB, this is shown on the debugging screenshot. The if-else jumps to the else branch. Probably the maximum limit of long type? Please advice me, the code is the following:

```<code>long size;
String notation;
if (file.isDirectory()) {
    // File is a directory, calculate size of all files in the directory
    size = 0;
    for (File f : file.listFiles()) {
        size += f.length();
    }
} else {
    // File is a regular file, use size of file
    size = file.length();
}

// Conversion
long bytes = size;
long kilobytes = (bytes / 1024);
long megabytes = (kilobytes / 1024);
long gigabytes = (megabytes / 1024);
long terabytes = (gigabytes / 1024);
long petabytes = (terabytes / 1024);
long exabytes = (petabytes / 1024);
//long zettabytes = (exabytes / 1024);
//long yottabytes = (zettabytes / 1024);

if (size > 0 && size < kilobytes){
    notation = "B";
    System.out.println(size+notation);
} else if (size > kilobytes && size < megabytes) {
    // file is smaller than 1 MB, return size in KB
    size /= 1024;
    notation = "KB";
    System.out.println(size+notation);
} else if (size > megabytes && size < gigabytes) {
    // file is smaller than 1 GB, return size in MB
    notation = "MB";
    size /= 1024.0 * 1024;
    System.out.println(size+notation);
} else if (size > gigabytes && size < terabytes) {
    // file is larger than 1 GB, return size in GB
    notation = "GB";
    size /= 1024.0 * 1024.0 * 1024.0;
    System.out.println(size+notation);
} else {
    // file is larger than 1 TB, return size in TB
    notation = "TB";
    size /= 1024.0 * 1024.0 * 1024.0 * 1024;
    System.out.println(size+notation);
}

// cast size to double before passing it to String.format
return String.format("[Size: %.3f %s]", (double) size, notation);
</code>```

}

Debugging shows the following:

EDIT:
I have changed to BigDecimal, the values seems correct, but still jumps to TB. Please see the screenshot:

SOLUTION:
Now everything is perfect, thank you for all ;)

```<code>if (bsize.compareTo(BigDecimal.valueOf(1024)) < 0) {
    notation = "B";
    System.out.println(bsize+notation);
} else if (bsize.compareTo(BigDecimal.valueOf(1024*1024)) < 0) {
    // file is smaller than 1 MB, return size in KB
    bsize = bsize.divide(BigDecimal.valueOf(1024));
    notation = "KB";
    System.out.println(bsize+notation);
} else if (bsize.compareTo(BigDecimal.valueOf(1024L*1024L*1024L)) < 0) {
    // file is smaller than 1 GB, return size in MB
    notation = "MB";
    bsize = bsize.divide(BigDecimal.valueOf(1024*1024));
    System.out.println(bsize+notation);
} else if (bsize.compareTo(BigDecimal.valueOf(1024L*1024L*1024L*1024L)) < 0) {
    // file is larger than 1 GB, return size in GB
    notation = "GB";
    System.out.println(bsize+notation);
    bsize = bsize.divide(BigDecimal.valueOf(1024*1024*1024));
    System.out.println(bsize+notation);
} else {
    // file is larger than 1 TB, return size in TB
    notation = "TB";
    bsize = bsize.divide(BigDecimal.valueOf(1024L*1024L*1024L*1024L));
    System.out.println(bsize+notation);
}
</code>```

Body:
I'd like to print file/directory sizes in Java, however for files larger than 1GB I cannot. For example, when I check a file with ~1.3 GB it writes 0.000 TB, this is shown on the debugging screenshot. The if-else jumps to the else branch. Probably the maximum limit of long type? Please advice me, the code is the following:

long size;
String notation;
if (file.isDirectory()) {
    // File is a directory, calculate size of all files in the directory
    size = 0;
    for (File f : file.listFiles()) {
        size += f.length();
    }
} else {
    // File is a regular file, use size of file
    size = file.length();
}

// Conversion
long bytes = size;
long kilobytes = (bytes / 1024);
long megabytes = (kilobytes / 1024);
long gigabytes = (megabytes / 1024);
long terabytes = (gigabytes / 1024);
long petabytes = (terabytes / 1024);
long exabytes = (petabytes / 1024);
//long zettabytes = (exabytes / 1024);
//long yottabytes = (zettabytes / 1024);

if (size > 0 && size < kilobytes){
    notation = "B";
    System.out.println(size+notation);
} else if (size > kilobytes && size < megabytes) {
    // file is smaller than 1 MB, return size in KB
    size /= 1024;
    notation = "KB";
    System.out.println(size+notation);
} else if (size > megabytes && size < gigabytes) {
    // file is smaller than 1 GB, return size in MB
    notation = "MB";
    size /= 1024.0 * 1024;
    System.out.println(size+notation);
} else if (size > gigabytes && size < terabytes) {
    // file is larger than 1 GB, return size in GB
    notation = "GB";
    size /= 1024.0 * 1024.0 * 1024.0;
    System.out.println(size+notation);
} else {
    // file is larger than 1 TB, return size in TB
    notation = "TB";
    size /= 1024.0 * 1024.0 * 1024.0 * 1024;
    System.out.println(size+notation);
}

// cast size to double before passing it to String.format
return String.format("[Size: %.3f %s]", (double) size, notation);

}

Debugging shows the following:

EDIT:
I have changed to BigDecimal, the values seems correct, but still jumps to TB. Please see the screenshot:

SOLUTION:
Now everything is perfect, thank you for all ;)

if (bsize.compareTo(BigDecimal.valueOf(1024)) < 0) {
    notation = "B";
    System.out.println(bsize+notation);
} else if (bsize.compareTo(BigDecimal.valueOf(1024*1024)) < 0) {
    // file is smaller than 1 MB, return size in KB
    bsize = bsize.divide(BigDecimal.valueOf(1024));
    notation = "KB";
    System.out.println(bsize+notation);
} else if (bsize.compareTo(BigDecimal.valueOf(1024L*1024L*1024L)) < 0) {
    // file is smaller than 1 GB, return size in MB
    notation = "MB";
    bsize = bsize.divide(BigDecimal.valueOf(1024*1024));
    System.out.println(bsize+notation);
} else if (bsize.compareTo(BigDecimal.valueOf(1024L*1024L*1024L*1024L)) < 0) {
    // file is larger than 1 GB, return size in GB
    notation = "GB";
    System.out.println(bsize+notation);
    bsize = bsize.divide(BigDecimal.valueOf(1024*1024*1024));
    System.out.println(bsize+notation);
} else {
    // file is larger than 1 TB, return size in TB
    notation = "TB";
    bsize = bsize.divide(BigDecimal.valueOf(1024L*1024L*1024L*1024L));
    System.out.println(bsize+notation);
}