问:
Changing the interactor style when hovering an actor in VTK python
I want to use the TrackballCamera InteractorStyle when I don't hover my actor (a cylinder). In the case where the mouse is over the actor, I want to use the TrackballActor InteractorStyle.
I know that it is possible to change the current InteractorStyle with the StyleSwitch Object. I created it like this:

```<code>styleSwitch = vtk.vtkInteractorStyleSwitch()
styleSwitch.SetCurrentStyleToTrackballCamera()
self.interactor.SetInteractorStyle(styleSwitch)
</code>```

I also know that i can change the current style by just calling one of the SetCurrentStyleTo...() functions.

But how do I do this while hovering an Actor?

Body:
I want to use the TrackballCamera InteractorStyle when I don't hover my actor (a cylinder). In the case where the mouse is over the actor, I want to use the TrackballActor InteractorStyle.
I know that it is possible to change the current InteractorStyle with the StyleSwitch Object. I created it like this:

styleSwitch = vtk.vtkInteractorStyleSwitch()
styleSwitch.SetCurrentStyleToTrackballCamera()
self.interactor.SetInteractorStyle(styleSwitch)

I also know that i can change the current style by just calling one of the SetCurrentStyleTo...() functions.

But how do I do this while hovering an Actor?


来源: stackexchange

问:
How to set rollup-plugin-dts for UMD module
My project has the follwing build dependencies -

```<code>  "devDependencies": {
    "@rollup/plugin-json": "^5.0.2",
    "@rollup/plugin-terser": "^0.2.0",
    "@types/node": "^18.11.13",
    "rimraf": "^3.0.2",
    "rollup": "^3.7.2",
    "rollup-plugin-dts": "^5.0.0",
    "rollup-plugin-typescript2": "^0.34.1",
    "tslib": "^2.4.1",
    "typescript": "^4.9.4"
  },
</code>```

Here, the .d.ts file generating is only applicable for ES modules. However I'm creating a UMD module.

My .d.ts file ends with this: export { module as default }.
But I want it to end like this: export = module.
So that it also works in CommonJS.

My Rollup configuration is as follows:

```<code>import json from '@rollup/plugin-json';
import dts from 'rollup-plugin-dts';
import typescript from 'rollup-plugin-typescript2';

export default [
  {
    input: 'src/index.ts',

    plugins: [
      typescript({
        tsconfig: 'tsconfig.json',
      }),
      json(),
    ],
    output: {
      file: `dist/mymodule.js`,
      format: 'umd',
      sourcemap: true,
      name: 'MyModule',
    },
  },
  {
    input: 'src/index.ts',
    plugins: [
      dts(),
    ],
    output: {
      file: `dist/mymodule.d.ts`,
    },
  },
];
</code>```

My TS Config (if needed):

```<code>{
  "compilerOptions": {
    "lib": ["es2015"],
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "target": "ES5",
    "types": ["@types/node"],
    "declaration": false,
    "moduleResolution": "Node16",
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src/**/*"]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My project has the follwing build dependencies -

  "devDependencies": {
    "@rollup/plugin-json": "^5.0.2",
    "@rollup/plugin-terser": "^0.2.0",
    "@types/node": "^18.11.13",
    "rimraf": "^3.0.2",
    "rollup": "^3.7.2",
    "rollup-plugin-dts": "^5.0.0",
    "rollup-plugin-typescript2": "^0.34.1",
    "tslib": "^2.4.1",
    "typescript": "^4.9.4"
  },

Here, the .d.ts file generating is only applicable for ES modules. However I'm creating a UMD module.

My .d.ts file ends with this: export { module as default }.
But I want it to end like this: export = module.
So that it also works in CommonJS.

My Rollup configuration is as follows:

import json from '@rollup/plugin-json';
import dts from 'rollup-plugin-dts';
import typescript from 'rollup-plugin-typescript2';

export default [
  {
    input: 'src/index.ts',

    plugins: [
      typescript({
        tsconfig: 'tsconfig.json',
      }),
      json(),
    ],
    output: {
      file: `dist/mymodule.js`,
      format: 'umd',
      sourcemap: true,
      name: 'MyModule',
    },
  },
  {
    input: 'src/index.ts',
    plugins: [
      dts(),
    ],
    output: {
      file: `dist/mymodule.d.ts`,
    },
  },
];

My TS Config (if needed):

{
  "compilerOptions": {
    "lib": ["es2015"],
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "target": "ES5",
    "types": ["@types/node"],
    "declaration": false,
    "moduleResolution": "Node16",
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src/**/*"]
}


问:
function in a Button in tkinter
How do I store the value you enter in a dict. The output is
{'Player name': 'Enter your player name: '}  1
at the moment and the if statement is just to check if the name is in the dictionary or not, I'll delete it when the problem is fixed. Here is where I'm stuck:

```<code>from tkinter import *

root = Tk()

playerData = {}

p_name = Entry(root, width=50)
p_name.pack()
p_name.insert(0, "Enter your player name: ")

def storeName(x):
    store = x
    playerData.update(Player name=store)

printName = Button(root, text="Confirm", command=storeName(p_name.get()))
printName.pack()

if len(playerData) != 0 or len(playerData):
    print(playerData)
    print(len(playerData))

root.mainloop()
</code>```

I saw it's better to have a function like storeName(x) then using global variables. But I don't know how to use it in a button because you don't have the () after the function or is that no problem?

I also tried this:

```<code>global playerData
playerData = {}
</code>```

and

```<code>def storeName():
    store = p_name.get()
    playerData.update(Playername=store)
    return store, playerData

printName = Button(root, text="Confirm", command=storeName)
printName.pack()

if len(playerData) != 0:
    print(playerData)
</code>```

there is no output
btw I'm new to tkinter and I'm following a tuturial on positioning in grid, buttons and input fields

Title: function in a Button in tkinter

Body:
How do I store the value you enter in a dict. The output is
{'Player name': 'Enter your player name: '}  1
at the moment and the if statement is just to check if the name is in the dictionary or not, I'll delete it when the problem is fixed. Here is where I'm stuck:

from tkinter import *

root = Tk()

playerData = {}

p_name = Entry(root, width=50)
p_name.pack()
p_name.insert(0, "Enter your player name: ")

def storeName(x):
    store = x
    playerData.update(Player name=store)

printName = Button(root, text="Confirm", command=storeName(p_name.get()))
printName.pack()

if len(playerData) != 0 or len(playerData):
    print(playerData)
    print(len(playerData))

root.mainloop()

I saw it's better to have a function like storeName(x) then using global variables. But I don't know how to use it in a button because you don't have the () after the function or is that no problem?

I also tried this:

global playerData
playerData = {}

and

def storeName():
    store = p_name.get()
    playerData.update(Playername=store)
    return store, playerData

printName = Button(root, text="Confirm", command=storeName)
printName.pack()

if len(playerData) != 0:
    print(playerData)

there is no output
btw I'm new to tkinter and I'm following a tuturial on positioning in grid, buttons and input fields


问:
Getting the error message "Error in lolliplot(data) : unused argument (data)"
I tried applying various solutions I found, but they didn't work.

The code I tried to run is an example I found for using the function lolliplot:

```<code>data <- brcaMAF[brcaMAF$Hugo_Symbol == 'TP53',c('Hugo_Symbol', 'amino_acid_change_WU')]
data <- as.data.frame(cbind(data, 'ENST00000269305'))
colnames(data) <- c('gene', 'amino_acid_change', 'transcript_name')
lolliplot(data)
</code>```

This yields the error message:

Error in lolliplot(data) : unused argument (data).

I tried running lolliplot with no arguments and got the following error message:

This function has been removed due to the removal of the FField package on cran, please use Lolliplot() instead.

I tried using Lollipop as suggested: Lolliplot(data), which gave yet another error message:

```<code>This function is part of the new S4 feature and is under active development, did you mean to use lolliplot() with a lowercase l?
Error in .local(object, ...) :
  The following required columns were missing from the input: chromosome, start, stop, reference, variant, sample
</code>```

which seems to have different requirements than lolliplot, so it doesn't seem to fit.

Could it be the result of using improper packages versions?

Body:
I tried applying various solutions I found, but they didn't work.

The code I tried to run is an example I found for using the function lolliplot:

data <- brcaMAF[brcaMAF$Hugo_Symbol == 'TP53',c('Hugo_Symbol', 'amino_acid_change_WU')]
data <- as.data.frame(cbind(data, 'ENST00000269305'))
colnames(data) <- c('gene', 'amino_acid_change', 'transcript_name')
lolliplot(data)

This yields the error message:

Error in lolliplot(data) : unused argument (data).

I tried running lolliplot with no arguments and got the following error message:

This function has been removed due to the removal of the FField package on cran, please use Lolliplot() instead.

I tried using Lollipop as suggested: Lolliplot(data), which gave yet another error message:

This function is part of the new S4 feature and is under active development, did you mean to use lolliplot() with a lowercase l?
Error in .local(object, ...) :
  The following required columns were missing from the input: chromosome, start, stop, reference, variant, sample

which seems to have different requirements than lolliplot, so it doesn't seem to fit.

Could it be the result of using improper packages versions?


问:
python setup.py bdist_wheel did not run successfully - when installing magenta
I am facing an issue while installing the "magenta" package in my python 3.9.12 architecture while using the command pip install magenta.

It retrieves an error when getting to the point

```<code>Building wheels for collected packages: llvmlite
  Created temporary directory: C:\Users\ricar\AppData\Local\Temp\pip-wheel-2h8aaubh
  Building wheel for llvmlite (setup.py) ...   Destination directory: C:\Users\ricar\AppData\Local\Temp\pip-wheel-2h8aaubh
  Running command python setup.py bdist_wheel
  running bdist_wheel
  C:\Users\ricar\anaconda3\python.exe C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py
  -- Selecting Windows SDK version  to target Windows 10.0.19044.
  CMake Error at CMakeLists.txt:3 (project):
    Failed to run MSBuild command:

      MSBuild.exe

    to get the value of VCTargetsPath:

      Das System kann die angegebene Datei nicht finden

  -- Configuring incomplete, errors occurred!
  See also "C:/Users/ricar/AppData/Local/Temp/tmp0f_7kimx/CMakeFiles/CMakeOutput.log".
  CMake Error at CMakeLists.txt:3 (project):
    Generator

      Visual Studio 15 2017 Win64

    could not find any instance of Visual Studio.

  -- Configuring incomplete, errors occurred!
  See also "C:/Users/ricar/AppData/Local/Temp/tmp1bsukddp/CMakeFiles/CMakeOutput.log".
  Trying generator 'Visual Studio 14 2015 Win64'
  Trying generator 'Visual Studio 15 2017 Win64'
  Traceback (most recent call last):
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 192, in <module>
      main()
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 180, in main
      main_win32()
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 89, in main_win32
      generator = find_win32_generator()
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 85, in find_win32_generator
      raise RuntimeError("No compatible cmake generator installed on this machine")
  RuntimeError: No compatible cmake generator installed on this machine
  error: command 'C:\\Users\\ricar\\anaconda3\\python.exe' failed with exit code 1
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> See above for output.
</code>```

I've tried to check the compatibility of the llvm lite package 0.38.1 to the numba version 0.55.1. Further I've tried to check the latest "cmake" package.

I have no other clues right now and would appreciate if anyone got a solution for that or faced a similar problem.

Body:
I am facing an issue while installing the "magenta" package in my python 3.9.12 architecture while using the command pip install magenta.

It retrieves an error when getting to the point

Building wheels for collected packages: llvmlite
  Created temporary directory: C:\Users\ricar\AppData\Local\Temp\pip-wheel-2h8aaubh
  Building wheel for llvmlite (setup.py) ...   Destination directory: C:\Users\ricar\AppData\Local\Temp\pip-wheel-2h8aaubh
  Running command python setup.py bdist_wheel
  running bdist_wheel
  C:\Users\ricar\anaconda3\python.exe C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py
  -- Selecting Windows SDK version  to target Windows 10.0.19044.
  CMake Error at CMakeLists.txt:3 (project):
    Failed to run MSBuild command:

      MSBuild.exe

    to get the value of VCTargetsPath:

      Das System kann die angegebene Datei nicht finden

  -- Configuring incomplete, errors occurred!
  See also "C:/Users/ricar/AppData/Local/Temp/tmp0f_7kimx/CMakeFiles/CMakeOutput.log".
  CMake Error at CMakeLists.txt:3 (project):
    Generator

      Visual Studio 15 2017 Win64

    could not find any instance of Visual Studio.

  -- Configuring incomplete, errors occurred!
  See also "C:/Users/ricar/AppData/Local/Temp/tmp1bsukddp/CMakeFiles/CMakeOutput.log".
  Trying generator 'Visual Studio 14 2015 Win64'
  Trying generator 'Visual Studio 15 2017 Win64'
  Traceback (most recent call last):
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 192, in <module>
      main()
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 180, in main
      main_win32()
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 89, in main_win32
      generator = find_win32_generator()
    File "C:\Users\ricar\AppData\Local\Temp\pip-install-9fq4zbfc\llvmlite_66cdc9c78f06483abf4ae29b277713c0\ffi\build.py", line 85, in find_win32_generator
      raise RuntimeError("No compatible cmake generator installed on this machine")
  RuntimeError: No compatible cmake generator installed on this machine
  error: command 'C:\\Users\\ricar\\anaconda3\\python.exe' failed with exit code 1
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> See above for output.

I've tried to check the compatibility of the llvm lite package 0.38.1 to the numba version 0.55.1. Further I've tried to check the latest "cmake" package.

I have no other clues right now and would appreciate if anyone got a solution for that or faced a similar problem.


问:
Spark pods in INIT. Reason - FailedMount. Detailed error - MountVolume.SetUp failed for volume "trust-store-secret" : failed to sync secret cache:
Spark task pods fail to run, stucking in initialization stage for some time, then terminated.

This issue is not always happening.

[2022-11-24 20:17:00,367] {subprocess.py:92} INFO -     Could not complete the request. Reason - FailedMount. Detailed error - MountVolume.SetUp failed for volume "icp4d-trust-store-secret" : failed to sync secret cache: timed out waiting for the condition

Openshift Container Platform
OCP 4.10
Cloud Platform
IBM Cloud

What could cause this? How to fix it?


问:
TypeOrmModule Unable to connect to the database on localhost
Cannot able connect to local postgresql database on server. It's able to connect from my device using DbVisualizer with globalhost.

Following code in ormconfig.ts:

```<code>const config: ConnectionOptions = {
   type: 'postgres',
   port: 5432,
   host: 'localhost',
   username: 'username',
   password: 'password',
   database: 'database',
   synchronize: false,
   entities: [__dirname + '/../**/*.entity{.ts,.js}'],
   migrations: [__dirname + '/../migrations/**/*{.ts,.js}'],
   cli: {
      migrationsDir: 'src/migrations',
   },
   namingStrategy: new SnakeNamingStrategy(),
};
</code>```

Error details: 'Error: connect ETIMEDOUT localhost:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)'

I found out localhost using ifconfig and changed it to:

```<code>const config: ConnectionOptions = {
   type: 'postgres',
   port: 5432,
   host: '192.168.31.93',
   username: 'username',
   password: 'password',
   database: 'database',
   synchronize: false,
   entities: [__dirname + '/../**/*.entity{.ts,.js}'],
   migrations: [__dirname + '/../migrations/**/*{.ts,.js}'],
   cli: {
      migrationsDir: 'src/migrations',
   },
   namingStrategy: new SnakeNamingStrategy(),
};
</code>```

Error changed to following: 'Error: connect ETIMEDOUT 192.168.31.93:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)'

Also tried to change the host in the config to '127.0.0.1', the same error occurs.

Body:
Cannot able connect to local postgresql database on server. It's able to connect from my device using DbVisualizer with globalhost.

Following code in ormconfig.ts:

const config: ConnectionOptions = {
   type: 'postgres',
   port: 5432,
   host: 'localhost',
   username: 'username',
   password: 'password',
   database: 'database',
   synchronize: false,
   entities: [__dirname + '/../**/*.entity{.ts,.js}'],
   migrations: [__dirname + '/../migrations/**/*{.ts,.js}'],
   cli: {
      migrationsDir: 'src/migrations',
   },
   namingStrategy: new SnakeNamingStrategy(),
};

Error details: 'Error: connect ETIMEDOUT localhost:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)'

I found out localhost using ifconfig and changed it to:

const config: ConnectionOptions = {
   type: 'postgres',
   port: 5432,
   host: '192.168.31.93',
   username: 'username',
   password: 'password',
   database: 'database',
   synchronize: false,
   entities: [__dirname + '/../**/*.entity{.ts,.js}'],
   migrations: [__dirname + '/../migrations/**/*{.ts,.js}'],
   cli: {
      migrationsDir: 'src/migrations',
   },
   namingStrategy: new SnakeNamingStrategy(),
};

Error changed to following: 'Error: connect ETIMEDOUT 192.168.31.93:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)'

Also tried to change the host in the config to '127.0.0.1', the same error occurs.


问:
Property X does not exist in v-for loop
I am currently using Nuxt 3 and i facing this error.

in the v-if it says that option does not exist but it clearly does. How can i fix this bug, or can i ignore this bug with TS?

```<code><template>
    <div ref="opt_el" tabindex="-1" @blur="isOpen = false" class="flex flex-col">
        <i @click="isOpen = !isOpen"
            class="text-gray-700  flex mx-auto ml-auto text-xl cursor-pointer fa-solid px-4 py-2 active:bg-gray-100 rounded hover:bg-gray-50 fa-ellipsis-vertical"></i>
        <div class=" relative">
            <transition name="fadeDropdown" mode="out-in">
                <div v-if="isOpen" class=" right-0  top-1 w-52 bg-white z-50 absolute border border-b-0 rounded">

                    <div v-for="option in options" :key="option.value" v-if="option.show(param)"
                        @click="exec(option.event)"
                        class="bg-white cursor-pointer select-none hover:bg-gray-50 active:bg-gray-100 w-full border-b p-2 text-gray-700">
                        {{ option.name }}
                    </div>
                </div>
            </transition>
        </div>
    </div>
</template>

<script setup lang="ts">
import { DropdownDotOptionT } from "types"
let isOpen = ref(false)
let opt_el = ref<HTMLElement>()
let { param, options } = defineProps({
    options: {
        default: [] as DropdownDotOptionT[]
    },
    param: {
        default: null
    }
})

function exec(event: DropdownDotOptionT["event"]) {
    isOpen.value = false
    event(param)
}

watch(isOpen, (newValue) => {
    if (newValue) {
        nextTick(() => {

            opt_el.value?.focus()

        })

    }
})

</script>
</code>```

Title: Property X does not exist in v-for loop

Body:
I am currently using Nuxt 3 and i facing this error.

in the v-if it says that option does not exist but it clearly does. How can i fix this bug, or can i ignore this bug with TS?

<template>

            <transition name="fadeDropdown" mode="out-in">

                        {{ option.name }}

            </transition>

</template>


问:
How do I get all plots inline in jupyter notebook with hvplot?
I am new to machine learning and I was going through this topic I found this happening. Could you please helpful?

```<code>df_market_data.hvplot.line(
    width=1200,
    height=600,
    rot=90,
    title='Cryptocurrency Market Data: Returns for Several Holding Periods (%)',
    ylabel= 'Return (%)',
    xlabel='Cryptocurrency Name',
    value_label='Return in the Period (%)'
)
</code>```

I looked through document and I tried above code but still not sure how this works.

Body:
I am new to machine learning and I was going through this topic I found this happening. Could you please helpful?

df_market_data.hvplot.line(
    width=1200,
    height=600,
    rot=90,
    title='Cryptocurrency Market Data: Returns for Several Holding Periods (%)',
    ylabel= 'Return (%)',
    xlabel='Cryptocurrency Name',
    value_label='Return in the Period (%)'
)

I looked through document and I tried above code but still not sure how this works.


问:
prevent Next Js from Caching and preFretching specific page
I am working on e-commerce website and I am using Next Js and everything was working ok till I Started to work on Cart Page cause its always changing - I am using ssr with it cause I need to do some checks on the server - I found that due to prefetching and caching it show old data on soft Navigation and even when I set cache-control header to no-store Next js keeps storing the cart Page data</p>


问:
RefreshIndicator triggers InkWell onTap()
I have a list in my app. The items in this list should be clickable. To achieve this, I wrapped the items in an InkWell and implemented the onTap event.

I need pull-to-refresh to update the list, so I wrapped the entire list in a RefreshIndicator. However, when I pull to refresh, the onTap event is triggered on the item that I finish the pull gesture on.

How can I prevent this from happening? I want to receive the onTap event only if I actually tap an item, not if I release the pull-to-refresh gesture.

The code looks like this:

```<code>return Scaffold(
  body: RefreshIndicator(
    child: CustomScrollView(
      slivers: [
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              final item = listData.elementAt(index);
              return InkWell(
                onTap: () { print("Tapped"); },
                child: SpecializedListItemWidget(forItem: item),
              );
            },
            childCount: listData.length,
          ),
        )
      ],
    ),
    onRefresh: () async => await _updateList(),
  ),
);
</code>```

Body:
I have a list in my app. The items in this list should be clickable. To achieve this, I wrapped the items in an InkWell and implemented the onTap event.

I need pull-to-refresh to update the list, so I wrapped the entire list in a RefreshIndicator. However, when I pull to refresh, the onTap event is triggered on the item that I finish the pull gesture on.

How can I prevent this from happening? I want to receive the onTap event only if I actually tap an item, not if I release the pull-to-refresh gesture.

The code looks like this:

return Scaffold(
  body: RefreshIndicator(
    child: CustomScrollView(
      slivers: [
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              final item = listData.elementAt(index);
              return InkWell(
                onTap: () { print("Tapped"); },
                child: SpecializedListItemWidget(forItem: item),
              );
            },
            childCount: listData.length,
          ),
        )
      ],
    ),
    onRefresh: () async => await _updateList(),
  ),
);


问:
building wheels for various packages not working
I receive various error when trying to install magenta with pip

i get an error for building wheels for numba, llvmlite and python-rtmidi
example for numba:

```<code>  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [13 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-39
      creating build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiconstants.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiutil.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\release.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\__init__.py -> build\lib.win-amd64-cpython-39\rtmidi
      running build_ext
      building 'rtmidi._rtmidi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for python-rtmidi
  Running setup.py clean for python-rtmidi
  Building wheel for llvmlite (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [40 lines of output]
      running bdist_wheel
      C:\Users\Dell\anaconda3\python.exe C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py
      -- Selecting Windows SDK version  to target Windows 10.0.19044.
      CMake Error at CMakeLists.txt:3 (project):
        Failed to run MSBuild command:

          MSBuild.exe

        to get the value of VCTargetsPath:

          Das System kann die angegebene Datei nicht finden

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpjza6m78t/CMakeFiles/CMakeOutput.log".
      CMake Error at CMakeLists.txt:3 (project):
        Generator

          Visual Studio 15 2017 Win64

        could not find any instance of Visual Studio.

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmp0ap85972/CMakeFiles/CMakeOutput.log".
      Trying generator 'Visual Studio 14 2015 Win64'
      Trying generator 'Visual Studio 15 2017 Win64'
      Traceback (most recent call last):
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 192, in <module>
          main()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 180, in main
          main_win32()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 89, in main_win32
          generator = find_win32_generator()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 85, in find_win32_generator
          raise RuntimeError("No compatible cmake generator installed on this machine")
      RuntimeError: No compatible cmake generator installed on this machine
      error: command 'C:\\Users\\Dell\\anaconda3\\python.exe' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for llvmlite
  Running setup.py clean for llvmlite
Failed to build numba python-rtmidi llvmlite
Installing collected packages: python-rtmidi, pygtrie, mido, llvmlite, keras, flatbuffers, tensorflow-estimator, sox, scipy, protobuf, promise, numba, keras-preprocessing, importlib_resources, imageio, etils, absl-py, tf-slim, tensorflow-probability, sk-video, resampy, mir-eval, matplotlib, googleapis-common-protos, dm-sonnet, tensorflow-metadata, librosa, tensorflow-datasets, tensorboard, note-seq, tensorflow, magenta
  Running setup.py install for python-rtmidi ... error
  error: subprocess-exited-with-error

  × Running setup.py install for python-rtmidi did not run successfully.
  │ exit code: 1
  ╰─> [15 lines of output]
      running install
      C:\Users\Dell\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-39
      creating build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiconstants.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiutil.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\release.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\__init__.py -> build\lib.win-amd64-cpython-39\rtmidi
      running build_ext
      building 'rtmidi._rtmidi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> python-rtmidi

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
</code>```

what I already tried:

reinstall all 3 packages

downgrade versions of those packages

the same with cmake and wheel package

install windows sdk

test it on another device

I have no idea how to continue. Do you have a solution for this?

my python version is 3.9.13

Thank you very much!

tried to install magenta but receive errors

Body:
I receive various error when trying to install magenta with pip

i get an error for building wheels for numba, llvmlite and python-rtmidi
example for numba:

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [13 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-39
      creating build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiconstants.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiutil.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\release.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\__init__.py -> build\lib.win-amd64-cpython-39\rtmidi
      running build_ext
      building 'rtmidi._rtmidi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for python-rtmidi
  Running setup.py clean for python-rtmidi
  Building wheel for llvmlite (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [40 lines of output]
      running bdist_wheel
      C:\Users\Dell\anaconda3\python.exe C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py
      -- Selecting Windows SDK version  to target Windows 10.0.19044.
      CMake Error at CMakeLists.txt:3 (project):
        Failed to run MSBuild command:

          MSBuild.exe

        to get the value of VCTargetsPath:

          Das System kann die angegebene Datei nicht finden

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmpjza6m78t/CMakeFiles/CMakeOutput.log".
      CMake Error at CMakeLists.txt:3 (project):
        Generator

          Visual Studio 15 2017 Win64

        could not find any instance of Visual Studio.

      -- Configuring incomplete, errors occurred!
      See also "C:/Users/Dell/AppData/Local/Temp/tmp0ap85972/CMakeFiles/CMakeOutput.log".
      Trying generator 'Visual Studio 14 2015 Win64'
      Trying generator 'Visual Studio 15 2017 Win64'
      Traceback (most recent call last):
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 192, in <module>
          main()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 180, in main
          main_win32()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 89, in main_win32
          generator = find_win32_generator()
        File "C:\Users\Dell\AppData\Local\Temp\pip-install-f301n_gf\llvmlite_52e74a978a1540339621403e230729a1\ffi\build.py", line 85, in find_win32_generator
          raise RuntimeError("No compatible cmake generator installed on this machine")
      RuntimeError: No compatible cmake generator installed on this machine
      error: command 'C:\\Users\\Dell\\anaconda3\\python.exe' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for llvmlite
  Running setup.py clean for llvmlite
Failed to build numba python-rtmidi llvmlite
Installing collected packages: python-rtmidi, pygtrie, mido, llvmlite, keras, flatbuffers, tensorflow-estimator, sox, scipy, protobuf, promise, numba, keras-preprocessing, importlib_resources, imageio, etils, absl-py, tf-slim, tensorflow-probability, sk-video, resampy, mir-eval, matplotlib, googleapis-common-protos, dm-sonnet, tensorflow-metadata, librosa, tensorflow-datasets, tensorboard, note-seq, tensorflow, magenta
  Running setup.py install for python-rtmidi ... error
  error: subprocess-exited-with-error

  × Running setup.py install for python-rtmidi did not run successfully.
  │ exit code: 1
  ╰─> [15 lines of output]
      running install
      C:\Users\Dell\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-39
      creating build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiconstants.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\midiutil.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\release.py -> build\lib.win-amd64-cpython-39\rtmidi
      copying rtmidi\__init__.py -> build\lib.win-amd64-cpython-39\rtmidi
      running build_ext
      building 'rtmidi._rtmidi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> python-rtmidi

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

what I already tried:

reinstall all 3 packages

downgrade versions of those packages

the same with cmake and wheel package

install windows sdk

test it on another device

I have no idea how to continue. Do you have a solution for this?

my python version is 3.9.13

Thank you very much!

tried to install magenta but receive errors


问:
Trying to disable a wall when th enemy is killed
just finishing off my demo scene but im faced with an issue, when the enemy boss is killed (disabled) i need the wall behind him to be disabled too automatically. However i cant figure it out, im horrible with script and intend to do a crashcourse youtube tutorial over my december break lol.

But right now i dont understand how thi sis supposed to work, ive done something similar where an item is destroyed upon coming into contact with the player which disables a wall further along in the game:

```<code>public class potionpickup : MonoBehaviour
{
    public Collider2D _FF;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            _FF.enabled = false;
            //this will immediately change the color to the transparent.. and only for that specific object
            Renderer renderer = _FF.GetComponent<Renderer>();
            renderer.material.color = Color.clear;
            Destroy(gameObject);
        }
    }

</code>```

And that works, but i cant seem to use the same method for this and googling it is getting me nowhere. Any help would be appreciated :D

for reference, the enemy is just called Enemy and the wall is called PassageWay

What i tried:
about 30 formats of script were tried each with about 2-6 errors i couldnt understand how to fix like "have you misused an assebly reference?" and im like "yeah, probably, got a solution or you just gonna tell me im wrong?"

Body:
just finishing off my demo scene but im faced with an issue, when the enemy boss is killed (disabled) i need the wall behind him to be disabled too automatically. However i cant figure it out, im horrible with script and intend to do a crashcourse youtube tutorial over my december break lol.

But right now i dont understand how thi sis supposed to work, ive done something similar where an item is destroyed upon coming into contact with the player which disables a wall further along in the game:

public class potionpickup : MonoBehaviour
{
    public Collider2D _FF;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            _FF.enabled = false;
            //this will immediately change the color to the transparent.. and only for that specific object
            Renderer renderer = _FF.GetComponent<Renderer>();
            renderer.material.color = Color.clear;
            Destroy(gameObject);
        }
    }

And that works, but i cant seem to use the same method for this and googling it is getting me nowhere. Any help would be appreciated :D

for reference, the enemy is just called Enemy and the wall is called PassageWay

What i tried:
about 30 formats of script were tried each with about 2-6 errors i couldnt understand how to fix like "have you misused an assebly reference?" and im like "yeah, probably, got a solution or you just gonna tell me im wrong?"


问:
object is null error while using validators
I added validators for mat-form field but in HTML it is showing object is null error.enter image description hereenter image description here

I added both typescript code image and HTML image. please help.

```<code>typescript:
 this.skillMappingForm =this.formBuilder.group({
      skillId: [null,[Validators.required]],
      skillLevelId: [null,[Validators.required]],
      targetSkillLevelId:[null,[Validators.required]],
      allocationPercentage: [null,[Validators.required]],
HTML:
<div class="col-md-3" style="height: 80%;">
  <mat-form-field style="width: 100%;" appearance="fill">
  <mat-label>Select Skill</mat-label>
  <mat-select formControlName="skillId">
  <mat-option *ngFor="let skill of getSkillsForTab(tab)"
  [value]="skill.skillId">
  {{skill.name}}
  </mat-option>
  </mat-select>
  </mat-form-field>
  <mat-error *ngIf="skillMappingForm.get('skillId').hasError('required')">
    skill type cant be null.
   </mat-error>
       </div>

// .haserror showing object is null error
</code>```

Body:
I added validators for mat-form field but in HTML it is showing object is null error.enter image description hereenter image description here

I added both typescript code image and HTML image. please help.

typescript:
 this.skillMappingForm =this.formBuilder.group({
      skillId: [null,[Validators.required]],
      skillLevelId: [null,[Validators.required]],
      targetSkillLevelId:[null,[Validators.required]],
      allocationPercentage: [null,[Validators.required]],
HTML:

  <mat-form-field style="width: 100%;" appearance="fill">
  <mat-label>Select Skill</mat-label>
  <mat-select formControlName="skillId">
  <mat-option *ngFor="let skill of getSkillsForTab(tab)"
  [value]="skill.skillId">
  {{skill.name}}
  </mat-option>
  </mat-select>
  </mat-form-field>
  <mat-error *ngIf="skillMappingForm.get('skillId').hasError('required')">
    skill type cant be null.
   </mat-error>

// .haserror showing object is null error


问:
How react container runs vuejs code in micro frontends architecture

summarize

vue js code not running in container app

to be specific, the main.js code in vue js is not running...

description

i am currently developing MFA (Micro Frontends Architecture) with reference here.

architecture configuration is as follows.

container app(react):

container apps have common components such as header and footer.
request asset-manifest.json from the remote app. and load the built js into the script. then, execute the render function of each app.

react app (remote app)

micro frontend

vue app (remote app)

micro frontend

to explain the operation process, each app declares a render function on the window object. afterwards, the container app receives the asset-manifest.json from the app that needs it, receives the built-in js file, and executes the render function declared above.

So what's the problem?

react works fine, but in case of vue, there is no render function declared in the window object.

code

container app

import { useEffect } from 'react';

function MicroFrontend({ name, host, history }) {
  useEffect(() => {
    const scriptId = `micro-frontend-script-${name}`;

    const renderMicroFrontend = () => {
      window[`render${name}`](`${name}-container`, history);
    };

    if (document.getElementById(scriptId)) {
      renderMicroFrontend();
      return;
    }

    fetch(`${host}/asset-manifest.json`)
      .then((res) => res.json())
      .then((manifest) => {
        const script = document.createElement('script');
        script.id = scriptId;
        script.crossOrigin = '';
        script.src = `${host}${manifest.files['main.js']}`;
        script.onload = () => {
          renderMicroFrontend();
        };
        document.head.appendChild(script);
      });

    return () => {
      window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`);
    };
  });

  return <main id={`${name}-container`} />;
}

MicroFrontend.defaultProps = {
  document,
  window,
};

export default MicroFrontend;

```
<p><em><strong>react app</strong></em>
almost identical to the vue project.</p>
<p><em><strong>vue app</strong></em></p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

window.renderVueApp = (containerId) => {
  new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount(containerId);
};

window.unmountVueApp = (containerId) => {
  const root = document.getElementById(containerId);

  if (root) {
    root.remove();
  }
};

if (!document.getElementById('VueApp-container')) {
  new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount('#root');
}

</code>```

vue.config.js

const WebpackAssetsManifest = require('webpack-assets-manifest');

const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: (config) => {
    config.entry = './src/main.js';
    config.plugins = config.plugins.concat(
      new WebpackAssetsManifest({
        output: 'asset-manifest.json',
        customize(entry) {
          return {
            key: `${entry.key.replace('app', 'main')}`,
            value: `/${entry.value}`,
          };
        },
        transform(assets) {
          return {
            files: assets,
          };
        },
      }),
    );
  },
  chainWebpack: (config) => {
    config.merge({
      externals:
        process.env.NODE_ENV === 'development'
          ? []
          : {
              vue: 'Vue',
              'vue-router': 'VueRouter',
            },
    });
  },
});

```

it's so hard because i can't find a way....
any help would be appreciated.

Body:
summarize

vue js code not running in container app

to be specific, the main.js code in vue js is not running...

description

i am currently developing MFA (Micro Frontends Architecture) with reference here.

architecture configuration is as follows.

container app(react):

container apps have common components such as header and footer.
request asset-manifest.json from the remote app. and load the built js into the script. then, execute the render function of each app.

react app (remote app)

micro frontend

vue app (remote app)

micro frontend

to explain the operation process, each app declares a render function on the window object. afterwards, the container app receives the asset-manifest.json from the app that needs it, receives the built-in js file, and executes the render function declared above.

So what's the problem?

react works fine, but in case of vue, there is no render function declared in the window object.

code

container app

import { useEffect } from 'react';

function MicroFrontend({ name, host, history }) {
  useEffect(() => {
    const scriptId = `micro-frontend-script-${name}`;

    const renderMicroFrontend = () => {
      window[`render${name}`](`${name}-container`, history);
    };

    if (document.getElementById(scriptId)) {
      renderMicroFrontend();
      return;
    }

    fetch(`${host}/asset-manifest.json`)
      .then((res) => res.json())
      .then((manifest) => {
        const script = document.createElement('script');
        script.id = scriptId;
        script.crossOrigin = '';
        script.src = `${host}${manifest.files['main.js']}`;
        script.onload = () => {
          renderMicroFrontend();
        };
        document.head.appendChild(script);
      });

    return () => {
      window[`unmount${name}`] && window[`unmount${name}`](`${name}-container`);
    };
  });

  return <main id={`${name}-container`} />;
}

MicroFrontend.defaultProps = {
  document,
  window,
};

export default MicroFrontend;

react app
almost identical to the vue project.

vue app

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

window.renderVueApp = (containerId) => {
  new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount(containerId);
};

window.unmountVueApp = (containerId) => {
  const root = document.getElementById(containerId);

  if (root) {
    root.remove();
  }
};

if (!document.getElementById('VueApp-container')) {
  new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount('#root');
}

vue.config.js

const WebpackAssetsManifest = require('webpack-assets-manifest');

const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: (config) => {
    config.entry = './src/main.js';
    config.plugins = config.plugins.concat(
      new WebpackAssetsManifest({
        output: 'asset-manifest.json',
        customize(entry) {
          return {
            key: `${entry.key.replace('app', 'main')}`,
            value: `/${entry.value}`,
          };
        },
        transform(assets) {
          return {
            files: assets,
          };
        },
      }),
    );
  },
  chainWebpack: (config) => {
    config.merge({
      externals:
        process.env.NODE_ENV === 'development'
          ? []
          : {
              vue: 'Vue',
              'vue-router': 'VueRouter',
            },
    });
  },
});

it's so hard because i can't find a way....
any help would be appreciated.


问:
TypeError: 'PySide2.QtWidgets.QTableView.setModel' called with wrong argument types
here's my starting position:

I've created an interface file using QtDesigner.

In the interface file I have a model-based QTableView.

I'm trying to build a model for that view, following the structure of the official PyQt documentation at https://doc.qt.io/qt-5/qsqltablemodel.html#details
The model will be accessing a database.

Am getting the following error:

Traceback (most recent call last):

File "D:**\main.py", line> 89, in
window = MainWindow()

File "D:**\main.py", line 28, in init
self.set_individual_clients_model()

File "D:**\main.py", line 48, in set_individual_clients_model
self.ui.tableView.setModel(self.model)

TypeError: 'PySide2.QtWidgets.QTableView.setModel' called with wrong argument types:
PySide2.QtWidgets.QTableView.setModel(QSqlTableModel)

Supported signatures:

PySide2.QtWidgets.QTableView.setModel(PySide2.QtCore.QAbstractItemModel)

When I try to run, I get the above error.

Here's my code:

```<code>from ui_interface import *
from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QMessageBox

settings = QSettings()

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.model = QSqlTableModel()

        loadJsonStyle(self, self.ui)

        self.show()

        QAppSettings.updateAppSettings(self)

        self.set_individual_clients_model()

    # INDIVIDUAL CLIENTS PAGE
    def set_individual_clients_model(self):

        # set up the model
        self.model.setTable("ind_clients")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.model.setHeaderData(0, Qt.Horizontal, "ID")
        self.model.setHeaderData(1, Qt.Horizontal, "First Name")
        self.model.setHeaderData(2, Qt.Horizontal, "Last Name")
        self.model.setHeaderData(3, Qt.Horizontal, "Date of Birth")
        self.model.setHeaderData(4, Qt.Horizontal, "Doc Number")
        self.model.setHeaderData(5, Qt.Horizontal, "Doc Type")
        self.model.setHeaderData(6, Qt.Horizontal, "Doc Text")
        self.model.setHeaderData(7, Qt.Horizontal, "Country")

        # set the view
        self.ui.tableView.setModel(self.model)
        self.ui.tableView.resizeColumnsToContents()
        self.ui.tableView.view()

        return

def create_connection():
    conn = QSqlDatabase.addDatabase("QPSQL")
    conn.setDatabaseName("alaric")
    user = os.environ.get("DB_USER")
    password = os.environ.get("DB_PASSWORD")
    if not conn.open(user, password):
        QMessageBox.critical(
            None,
            "Database Error!",
            "Database Error: %s" % conn.lastError().databaseText()
        )
        return False

    return True

if __name__ == "__main__":

    app = QApplication(sys.argv)

    create_connection()

    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

</code>```

Any help with in successfully connecting the view and the model would be greatly appreciated.

Body:
here's my starting position:

I've created an interface file using QtDesigner.

In the interface file I have a model-based QTableView.

I'm trying to build a model for that view, following the structure of the official PyQt documentation at https://doc.qt.io/qt-5/qsqltablemodel.html#details
The model will be accessing a database.

Am getting the following error:

Traceback (most recent call last):

File "D:**\main.py", line> 89, in
window = MainWindow()

File "D:**\main.py", line 28, in init
self.set_individual_clients_model()

File "D:**\main.py", line 48, in set_individual_clients_model
self.ui.tableView.setModel(self.model)

TypeError: 'PySide2.QtWidgets.QTableView.setModel' called with wrong argument types:
PySide2.QtWidgets.QTableView.setModel(QSqlTableModel)

Supported signatures:

PySide2.QtWidgets.QTableView.setModel(PySide2.QtCore.QAbstractItemModel)

When I try to run, I get the above error.

Here's my code:

from ui_interface import *
from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QMessageBox

settings = QSettings()

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.model = QSqlTableModel()

        loadJsonStyle(self, self.ui)

        self.show()

        QAppSettings.updateAppSettings(self)

        self.set_individual_clients_model()

    # INDIVIDUAL CLIENTS PAGE
    def set_individual_clients_model(self):

        # set up the model
        self.model.setTable("ind_clients")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.model.setHeaderData(0, Qt.Horizontal, "ID")
        self.model.setHeaderData(1, Qt.Horizontal, "First Name")
        self.model.setHeaderData(2, Qt.Horizontal, "Last Name")
        self.model.setHeaderData(3, Qt.Horizontal, "Date of Birth")
        self.model.setHeaderData(4, Qt.Horizontal, "Doc Number")
        self.model.setHeaderData(5, Qt.Horizontal, "Doc Type")
        self.model.setHeaderData(6, Qt.Horizontal, "Doc Text")
        self.model.setHeaderData(7, Qt.Horizontal, "Country")

        # set the view
        self.ui.tableView.setModel(self.model)
        self.ui.tableView.resizeColumnsToContents()
        self.ui.tableView.view()

        return

def create_connection():
    conn = QSqlDatabase.addDatabase("QPSQL")
    conn.setDatabaseName("alaric")
    user = os.environ.get("DB_USER")
    password = os.environ.get("DB_PASSWORD")
    if not conn.open(user, password):
        QMessageBox.critical(
            None,
            "Database Error!",
            "Database Error: %s" % conn.lastError().databaseText()
        )
        return False

    return True

if __name__ == "__main__":

    app = QApplication(sys.argv)

    create_connection()

    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Any help with in successfully connecting the view and the model would be greatly appreciated.


问:
Having issues with how to use ' or " in sql statement and query using concatrelated function
I have the following code using the ConcatRelated function. the current sql works with 1 where condition but I can't figure out how to get the sql to work with 2 conditions. It works when use it in a query. I get issues and the code does not debug.

```<code>            ItemsShpdInvSQL = "SELECT InvoiceAllShippedItems.ShipmentID, InvoiceAllShippedItems.ShipType, " _
                            & "InvoiceAllShippedItems.BillTo, InvoiceAllShippedItems.CustID AS Consignee, " _
                            & "InvoiceAllShippedItems.PayMethod, InvoiceAllShippedItems.PaidInFull, " _
                            & "First(InvoiceAllShippedItems.Units) AS Units, " _
                            & "'Freight Charges - Ref. WR: ' & (ConcatRelated('[WR]'," _
                            & "'[InvoiceAllShippedItems]','[BillTo] =' & [BillTo])) & " _
                            & "' - (' & Sum([Chargeable]) & ' ' & [Units] & ' " _
                            & ") - Number of Pieces: ' & [NoPieces] AS InvDetails, " _
                            & "Sum(InvoiceAllShippedItems.[# of Pieces]) AS NoPieces, " _
                            & "Sum(InvoiceAllShippedItems.Chargeable) AS Charge, " _
                            & "CustRate([custid],[ShipType]) AS CustomerRate, " _
                            & "IIf(([Charge])<6.1,20/[Charge],[CustomerRate]) AS RateMin " _
                            & "FROM InvoiceAllShippedItems " _
                            & "GROUP BY InvoiceAllShippedItems.ShipmentID, " _
                            & "InvoiceAllShippedItems.ShipType, InvoiceAllShippedItems.BillTo, " _
                            & "InvoiceAllShippedItems.CustID, InvoiceAllShippedItems.PayMethod, " _
                            & "InvoiceAllShippedItems.PaidInFull, InvoiceAllShippedItems.Units, " _
                            & "CustRate([custid],[ShipType]) " _
                            & "ORDER BY InvoiceAllShippedItems.BillTo;"
                            '& "CustRate([custid],[ShipType]);"
</code>```

with this it works in a query but not in the code above:

```<code>'concatrelated("[WR]","InvoiceAllShippedItems","[BillTo]&[PayMethod] ='" & [BillTo] & [PayMethod] & "'")
</code>```

Body:
I have the following code using the ConcatRelated function. the current sql works with 1 where condition but I can't figure out how to get the sql to work with 2 conditions. It works when use it in a query. I get issues and the code does not debug.

            ItemsShpdInvSQL = "SELECT InvoiceAllShippedItems.ShipmentID, InvoiceAllShippedItems.ShipType, " _
                            & "InvoiceAllShippedItems.BillTo, InvoiceAllShippedItems.CustID AS Consignee, " _
                            & "InvoiceAllShippedItems.PayMethod, InvoiceAllShippedItems.PaidInFull, " _
                            & "First(InvoiceAllShippedItems.Units) AS Units, " _
                            & "'Freight Charges - Ref. WR: ' & (ConcatRelated('[WR]'," _
                            & "'[InvoiceAllShippedItems]','[BillTo] =' & [BillTo])) & " _
                            & "' - (' & Sum([Chargeable]) & ' ' & [Units] & ' " _
                            & ") - Number of Pieces: ' & [NoPieces] AS InvDetails, " _
                            & "Sum(InvoiceAllShippedItems.[# of Pieces]) AS NoPieces, " _
                            & "Sum(InvoiceAllShippedItems.Chargeable) AS Charge, " _
                            & "CustRate([custid],[ShipType]) AS CustomerRate, " _
                            & "IIf(([Charge])<6.1,20/[Charge],[CustomerRate]) AS RateMin " _
                            & "FROM InvoiceAllShippedItems " _
                            & "GROUP BY InvoiceAllShippedItems.ShipmentID, " _
                            & "InvoiceAllShippedItems.ShipType, InvoiceAllShippedItems.BillTo, " _
                            & "InvoiceAllShippedItems.CustID, InvoiceAllShippedItems.PayMethod, " _
                            & "InvoiceAllShippedItems.PaidInFull, InvoiceAllShippedItems.Units, " _
                            & "CustRate([custid],[ShipType]) " _
                            & "ORDER BY InvoiceAllShippedItems.BillTo;"
                            '& "CustRate([custid],[ShipType]);"

with this it works in a query but not in the code above:

'concatrelated("[WR]","InvoiceAllShippedItems","[BillTo]&[PayMethod] ='" & [BillTo] & [PayMethod] & "'")


问:
include or configure --module-path --add-modules in javafx jar file
I have a JavaFX application which I can compile and create a jar file with the following maven configuration inside IntelliJ idea:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
            <configuration>
                <source>18</source>
                <target>18</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.8</version>
            <executions>
                <execution>
                    <!-- Default configuration for running with: mvn clean javafx:run -->
                    <id>default-cli</id>
                    <configuration>
                        <mainClass>net.golbarg.nahjolfasahe/net.golbarg.nahjolfasahe.MainApp</mainClass>
                        <launcher>app</launcher>
                        <compress>2</compress>
                        <jlinkZipName>app</jlinkZipName>
                        <jlinkImageName>app</jlinkImageName>
                        <noManPages>true</noManPages>
                        <stripDebug>true</stripDebug>
                        <noHeaderFiles>true</noHeaderFiles>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>
                            ${project.build.directory}/libs
                        </outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.3.0</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>libs/</classpathPrefix>
                        <mainClass>
                            net.golbarg.nahjolfasahe.MainApp
                        </mainClass>
                    </manifest>
                </archive>
                <finalName>setup</finalName>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

more details

But for running this jar file I had to run it as below:

```<code>"C:\Program Files\Java\jdk-18.0.1.1\bin\java.exe" --module-path "C:\Program Files\Java\javafx\javafx-sdk-19\lib" --add-modules javafx.controls,javafx.fxml,javafx.swing -Dfile.encoding=windows-1252 -jar C:\work\system\NahjolFasahe\target\setup.jar
</code>```

adding --module-path and --add-modules parameters before running the jar file.

How can I simplify and add this settings either by editing the maven file or including it in the Manifest file of the builder jar file?

I want to make my jar file openable just by double clicking and include these configuration inside my jar file.

Body:
I have a JavaFX application which I can compile and create a jar file with the following maven configuration inside IntelliJ idea:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
            <configuration>
                <source>18</source>
                <target>18</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.8</version>
            <executions>
                <execution>

                    <id>default-cli</id>
                    <configuration>
                        <mainClass>net.golbarg.nahjolfasahe/net.golbarg.nahjolfasahe.MainApp</mainClass>
                        <launcher>app</launcher>
                        <compress>2</compress>
                        <jlinkZipName>app</jlinkZipName>
                        <jlinkImageName>app</jlinkImageName>
                        <noManPages>true</noManPages>
                        <stripDebug>true</stripDebug>
                        <noHeaderFiles>true</noHeaderFiles>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>
                            ${project.build.directory}/libs
                        </outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.3.0</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>libs/</classpathPrefix>
                        <mainClass>
                            net.golbarg.nahjolfasahe.MainApp
                        </mainClass>
                    </manifest>
                </archive>
                <finalName>setup</finalName>
            </configuration>
        </plugin>
    </plugins>
</build>

more details

But for running this jar file I had to run it as below:

"C:\Program Files\Java\jdk-18.0.1.1\bin\java.exe" --module-path "C:\Program Files\Java\javafx\javafx-sdk-19\lib" --add-modules javafx.controls,javafx.fxml,javafx.swing -Dfile.encoding=windows-1252 -jar C:\work\system\NahjolFasahe\target\setup.jar

adding --module-path and --add-modules parameters before running the jar file.

How can I simplify and add this settings either by editing the maven file or including it in the Manifest file of the builder jar file?

I want to make my jar file openable just by double clicking and include these configuration inside my jar file.


问:
Error: userdata validation failed: messages.0.name: Path `name` is required

Here are the details of my code. Thanks in advance.

/////////////////////////////////////////////////Client-side////////////////////////////////////////////

```<code>const submitContact = async(e)=>{
  e.preventDefault();
  const {name,email,message} = contact;
  const response = await fetch('http://localhost:4000/sent',{
    method:'POST',
    credentials: 'include',
    headers:{
      "Accept":"application/json",
      "ContentType":"application/json"
    },
    body:JSON.stringify({name,email,message})
  })
//const data = await res.json();
  if(response.status===201){
    window.alert('sent!')
    console.log('Message not sent!!')
  }else{
    window.alert('Server errro..')
    //setContact({...contact,message:""})
  }
  console.log(contact);
}
</code>```

////////////////////////////////////MongoDb////////////////////////////////////

```<code>const mongooseSchema = new mongoose.Schema({
  name:{
    type:String,
    required:true
  },
  email:{
    type:String,
    required:true
  },
  password:{
    type:String,
    required:true
  },
  confirmpassword:{
    type:String,
    required:true
  },

  messages:[
    {
      name:{
        type:String,
        required:true
      },
      email:{
        type:String,
        required:true
      },
      message:{
        type:String,
        required:true
      }
    }
  ],
  tokens:[
    {
        token:{
            type:String,
            required:true
        }
    }
  ]
},{timestamps:true})

</code>```
```<code>mongooseSchema.methods.addMessage = async function(name,email,message){
  try{
    this.messages= this.messages.concat({name,email,message})
    await this.save();
    return this.messages;
  }catch(e){
    console.log(e);
  }
}
const usermodel = new mongoose.model('userdata',mongooseSchema)
module.exports = usermodel;

</code>```

///////////////////////////////////////Route////////////////////////////////////////////////////

```<code>app.post('/sent',auth,async(req,res)=>{
           try{
            const {name,email,message} = req.body;
            // if(!name || !email ||!message){
            //     console.log(`${req.body} is blank.`);
            //     return res.status(401).json({error:"error"})
            // }
            const userif = await usermodel.findOne({_id:req.userid});
            if(userif){
                const umessage = await userif.addMessage(name,email,message)
                await userif.save();
                console.log(userif);
                res.status(201).json({message:"added.."})
            }else{
                console.log("error")
            }
            }catch(e){
            console.log(e);
           }
        })

```//////////////////////////////////////////////////////////////////////////////

```
<p>const express = require('express')
require('dotenv').config();
const dotenv = require('dotenv');
dotenv.config({path: './.env'})
const multer = require('multer');
const mongooseModel = require('./database')
const jwt = require('jsonwebtoken');
const bycrpt = require('bcryptjs')
const cors = require('cors')
const cookieParser = require("cookie-parser")
const bodyParser = require('body-parser');
const path = require('path')
const app = express();
const auth = require('./middle/auth')
const usermodel = require('../server/database2');
const corsOptions = {
origin:true,
credentials:true
};
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(bodyParser.json());
app.use('/pictures',express.static(path.join(__dirname,'pictures')));</p>
```

I'm stuck in this error from past 24hrs.Please help!
```

Body:
Here are the details of my code. Thanks in advance.

/////////////////////////////////////////////////Client-side////////////////////////////////////////////

const submitContact = async(e)=>{
  e.preventDefault();
  const {name,email,message} = contact;
  const response = await fetch('http://localhost:4000/sent',{
    method:'POST',
    credentials: 'include',
    headers:{
      "Accept":"application/json",
      "ContentType":"application/json"
    },
    body:JSON.stringify({name,email,message})
  })
//const data = await res.json();
  if(response.status===201){
    window.alert('sent!')
    console.log('Message not sent!!')
  }else{
    window.alert('Server errro..')
    //setContact({...contact,message:""})
  }
  console.log(contact);
}

////////////////////////////////////MongoDb////////////////////////////////////

const mongooseSchema = new mongoose.Schema({
  name:{
    type:String,
    required:true
  },
  email:{
    type:String,
    required:true
  },
  password:{
    type:String,
    required:true
  },
  confirmpassword:{
    type:String,
    required:true
  },

  messages:[
    {
      name:{
        type:String,
        required:true
      },
      email:{
        type:String,
        required:true
      },
      message:{
        type:String,
        required:true
      }
    }
  ],
  tokens:[
    {
        token:{
            type:String,
            required:true
        }
    }
  ]
},{timestamps:true})

mongooseSchema.methods.addMessage = async function(name,email,message){
  try{
    this.messages= this.messages.concat({name,email,message})
    await this.save();
    return this.messages;
  }catch(e){
    console.log(e);
  }
}
const usermodel = new mongoose.model('userdata',mongooseSchema)
module.exports = usermodel;

///////////////////////////////////////Route////////////////////////////////////////////////////

app.post('/sent',auth,async(req,res)=>{
           try{
            const {name,email,message} = req.body;
            // if(!name || !email ||!message){
            //     console.log(`${req.body} is blank.`);
            //     return res.status(401).json({error:"error"})
            // }
            const userif = await usermodel.findOne({_id:req.userid});
            if(userif){
                const umessage = await userif.addMessage(name,email,message)
                await userif.save();
                console.log(userif);
                res.status(201).json({message:"added.."})
            }else{
                console.log("error")
            }
            }catch(e){
            console.log(e);
           }
        })

```//////////////////////////////////////////////////////////////////////////////

const express = require('express')
require('dotenv').config();
const dotenv = require('dotenv');
dotenv.config({path: './.env'})
const multer = require('multer');
const mongooseModel = require('./database')
const jwt = require('jsonwebtoken');
const bycrpt = require('bcryptjs')
const cors = require('cors')
const cookieParser = require("cookie-parser")
const bodyParser = require('body-parser');
const path = require('path')
const app = express();
const auth = require('./middle/auth')
const usermodel = require('../server/database2');
const corsOptions = {
origin:true,
credentials:true
};
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(bodyParser.json());
app.use('/pictures',express.static(path.join(__dirname,'pictures')));

I'm stuck in this error from past 24hrs.Please help!


问:
What is bsPrefix in React-Bootstrap?
I want to change the css design of bootstrap's <Form.Control> component, but I couldn't do it even though I used the css module. I found bsPrefix related to this. I couldn't quite understand when I reviewed the document, can you help?

My code;

enter image description here

*When I use bsPrefix the code works but I don't understand how it works.

thank you very much in advance :)

Title: What is bsPrefix in React-Bootstrap?


问:
Recycler view does not appear when parent view is converted to a bitmap
I am attempting to convert a view constraint layout containing a recycler view into a bitmap to use as a wallpaper. The contents of the recycler view displays in app but the bitmap will either throw an error when i try to create it or be completly white depending on what i try, any advice?

main_content.xml

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

    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/taskRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

MainActivity

```<code>val viewModel:TaskViewModle = ViewModelProvider(this).get(TaskViewModle::class.java)
        //get target view
        val viewContent:View = findViewById(R.id.includedView)
        val wallBtn: Button = findViewById(R.id.wallBTN)
        val wm = WallpaperManager.getInstance(this)

        //on click set wallpaper
        wallBtn.setOnClickListener {
            viewContent.setDrawingCacheEnabled(true)
            val bm = getBitmapFromView(viewContent)
            try {
                wm.setBitmap(bm)
            } catch (e: IOException) {
                Log.e("error :(", "Cannot set image as wallpaper", e)
            }
        }

        val quoteAdapter = TaskAdapter(this)
        val recyclerView: RecyclerView = findViewById(R.id.taskRecycler)
        recyclerView.adapter = quoteAdapter
        viewModel.readAllTask.observe(this, Observer { task -> quoteAdapter.setData(task)
        })

        recyclerView.layoutManager = LinearLayoutManager(this)

    fun getBitmapFromView(view: View): Bitmap? {
        view.measure(MeasureSpec.makeMeasureSpec(view.getLayoutParams().width, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(view.getLayoutParams().height, MeasureSpec.EXACTLY));
        view.layout(0, 0, view.getMeasuredWidth() view.getMeasuredHeight());

        val b:Bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);

        val c:Canvas = Canvas(b);
        view.draw(c)

        return b}
</code>```

This code causes me to get the error java.lang.OutOfMemoryError

When i try the follwing code

```<code> val viewModel:TaskViewModle = ViewModelProvider(this).get(TaskViewModle::class.java)
        val viewContent:View = findViewById(R.id.includedView)

        val wallBtn: Button = findViewById(R.id.wallBTN)
        val wm = WallpaperManager.getInstance(this)
        wallBtn.setOnClickListener {
            viewContent.setDrawingCacheEnabled(true)
            val bm = Bitmap.createBitmap(viewContent.getDrawingCache())
            try {
                wm.setBitmap(bm)
            } catch (e: IOException) {
                Log.e("error :(", "Cannot set image as wallpaper", e)
            }
        }

        val quoteAdapter = TaskAdapter(this)
        val recyclerView: RecyclerView = findViewById(R.id.taskRecycler)
        recyclerView.adapter = quoteAdapter

        viewModel.readAllTask.observe(this, Observer { task -> quoteAdapter.setData(task)

        })

        recyclerView.layoutManager = LinearLayoutManager(this)
</code>```

The bitmap is plain white

Body:
I am attempting to convert a view constraint layout containing a recycler view into a bitmap to use as a wallpaper. The contents of the recycler view displays in app but the bitmap will either throw an error when i try to create it or be completly white depending on what i try, any advice?

main_content.xml

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

    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/taskRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

val viewModel:TaskViewModle = ViewModelProvider(this).get(TaskViewModle::class.java)
        //get target view
        val viewContent:View = findViewById(R.id.includedView)
        val wallBtn: Button = findViewById(R.id.wallBTN)
        val wm = WallpaperManager.getInstance(this)

        //on click set wallpaper
        wallBtn.setOnClickListener {
            viewContent.setDrawingCacheEnabled(true)
            val bm = getBitmapFromView(viewContent)
            try {
                wm.setBitmap(bm)
            } catch (e: IOException) {
                Log.e("error :(", "Cannot set image as wallpaper", e)
            }
        }

        val quoteAdapter = TaskAdapter(this)
        val recyclerView: RecyclerView = findViewById(R.id.taskRecycler)
        recyclerView.adapter = quoteAdapter
        viewModel.readAllTask.observe(this, Observer { task -> quoteAdapter.setData(task)
        })

        recyclerView.layoutManager = LinearLayoutManager(this)

    fun getBitmapFromView(view: View): Bitmap? {
        view.measure(MeasureSpec.makeMeasureSpec(view.getLayoutParams().width, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(view.getLayoutParams().height, MeasureSpec.EXACTLY));
        view.layout(0, 0, view.getMeasuredWidth() view.getMeasuredHeight());

        val b:Bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);

        val c:Canvas = Canvas(b);
        view.draw(c)

        return b}

This code causes me to get the error java.lang.OutOfMemoryError

When i try the follwing code

 val viewModel:TaskViewModle = ViewModelProvider(this).get(TaskViewModle::class.java)
        val viewContent:View = findViewById(R.id.includedView)

        val wallBtn: Button = findViewById(R.id.wallBTN)
        val wm = WallpaperManager.getInstance(this)
        wallBtn.setOnClickListener {
            viewContent.setDrawingCacheEnabled(true)
            val bm = Bitmap.createBitmap(viewContent.getDrawingCache())
            try {
                wm.setBitmap(bm)
            } catch (e: IOException) {
                Log.e("error :(", "Cannot set image as wallpaper", e)
            }
        }

        val quoteAdapter = TaskAdapter(this)
        val recyclerView: RecyclerView = findViewById(R.id.taskRecycler)
        recyclerView.adapter = quoteAdapter

        viewModel.readAllTask.observe(this, Observer { task -> quoteAdapter.setData(task)

        })

        recyclerView.layoutManager = LinearLayoutManager(this)

The bitmap is plain white


问:
How to make a second transition through a fragment
I made the first transition from the fragment to the activity, everything works fine, but I can't make the second transition. I'm a beginner, and I understand that this is a stupid mistake.

```<code>View v = inflater.inflate(R.layout.activity_physics, null);

Button phys35 = (Button) v.findViewById(R.id.phys35);
phys35.setOnClickListener(new View.OnClickListener() {
 Public void onClick(View v) {
  Intent intent = new Intent(getContext(), Phys35.class);
  StartActivity(intent);
}
});
return v;

Button phys36 = (Button) v.findViewById(R.id.phys36);

phys36.setOnClickListener(new View.OnClickListener() {

 Public void onClick(View v) {

  Intent intent = new Intent(getContext(), Phys36.class);

  StartActivity(intent);

}

});

return v;
</code>```

Please help, thank you in advance for your help.

Body:
I made the first transition from the fragment to the activity, everything works fine, but I can't make the second transition. I'm a beginner, and I understand that this is a stupid mistake.

View v = inflater.inflate(R.layout.activity_physics, null);

Button phys35 = (Button) v.findViewById(R.id.phys35);
phys35.setOnClickListener(new View.OnClickListener() {
 Public void onClick(View v) {
  Intent intent = new Intent(getContext(), Phys35.class);
  StartActivity(intent);
}
});
return v;

Button phys36 = (Button) v.findViewById(R.id.phys36);

phys36.setOnClickListener(new View.OnClickListener() {

 Public void onClick(View v) {

  Intent intent = new Intent(getContext(), Phys36.class);

  StartActivity(intent);

}

});

return v;

Please help, thank you in advance for your help.


问:
Why apple splits up struct def and typedef?
I've been looking into the APFS specs, if you go the General-Purpose Types section (page 9), you can see that apple gives structs (like prange_t) as bellow:

```<code>struct prange {
    paddr_t pr_start_paddr;
    uint64_t pr_block_count;
};
typedef struct prange prange_t;
</code>```

But why does apple split up the typedef and struct def? Does this give a better readability or somthing else?

Body:
I've been looking into the APFS specs, if you go the General-Purpose Types section (page 9), you can see that apple gives structs (like prange_t) as bellow:

struct prange {
    paddr_t pr_start_paddr;
    uint64_t pr_block_count;
};
typedef struct prange prange_t;

But why does apple split up the typedef and struct def? Does this give a better readability or somthing else?


问:
To check what values are been assigned to a column using label encoder
How can I check what value is assigned to what label while using sklearns' LabelEncoder()?

How can I check what value is assigned to what label while using sklearns' LabelEncoder()?


问:
Sending a email for all classes with python
My goal is to create a class for each page found in a JSON file.
The sending of emails worked untill i tried doing it with classes.
Does anybody know what im missing here?</p>
```<code>
class Page_Class:
    def __init__(self, email_sender, email_receiver, client, subject, text):
        self.email_sender = email_sender
        self.email_receiver = email_receiver
        self.client = client
        self.subject = subject
        self.text = text

        # Call the send_mail function inside the __init__ method
        self.send_mail()

    def send_mail():
        email_password = "test"
        global subject
        global email_sender
        global email_receiver
        global text
        body = "text"

        em = EmailMessage()
        em['From'] = email_sender
        em['To'] = email_receiver
        em['Subject'] = "subject"
        em.set_content(body)
        context = ssl.create_default_context()

        with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
            smtp.login(email_sender, email_password)
            smtp.sendmail(email_sender, email_sender, em.as_string())

        Read_Database(databaseId, headers)

</code>```

Body:
My goal is to create a class for each page found in a JSON file.
The sending of emails worked untill i tried doing it with classes.
Does anybody know what im missing here?

class Page_Class:
    def __init__(self, email_sender, email_receiver, client, subject, text):
        self.email_sender = email_sender
        self.email_receiver = email_receiver
        self.client = client
        self.subject = subject
        self.text = text

        # Call the send_mail function inside the __init__ method
        self.send_mail()

    def send_mail():
        email_password = "test"
        global subject
        global email_sender
        global email_receiver
        global text
        body = "text"

        em = EmailMessage()
        em['From'] = email_sender
        em['To'] = email_receiver
        em['Subject'] = "subject"
        em.set_content(body)
        context = ssl.create_default_context()

        with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
            smtp.login(email_sender, email_password)
            smtp.sendmail(email_sender, email_sender, em.as_string())

        Read_Database(databaseId, headers)


问:
Is it possible to ECDSA verify hash of the message instead of plain message with nodejs crypto module?
I know I can verify plain message with following code:

const verify = crypto.createVerify('sha256')
verify.write(Buffer.from(message, 'base64'))
verify.end()

const verified = verify.verify(publicKey, signatureToVerify, 'base64')
```

But I need to verify against the already hashed message, instead of node hashing it for me. Is it possible to do it with node's crypto module?

Body:
I know I can verify plain message with following code:

const verify = crypto.createVerify('sha256')
verify.write(Buffer.from(message, 'base64'))
verify.end()

const verified = verify.verify(publicKey, signatureToVerify, 'base64')

But I need to verify against the already hashed message, instead of node hashing it for me. Is it possible to do it with node's crypto module?


问:
Python User defined exception
Write a program that receives 5 integers and stores them and their cubes in a dictionary. If the number entered is less than 3, raise a user-defined exception NumberTooSmall, and if the number entered is more than 30, then raise a user-defined exception NumberTooBig. Regardless of whether an exception occurs, print the dictionary’s contents at the end.

Sample Input:

4

5

6

7

77

Sample Output:

{'Number too big': 77}

4 : 64

5 : 125

6 : 216

7 : 343

...///////////////////

Title: Python User defined exception


问:
How does the current time update each time a command is executed?
Every time I use the date slash command,
Based on the date at the time of use, I would like to print it out as select for 7 days

However, in the case of the codes currently configured, my expectation is that
The time when the bot runs is set to the current time
If the date changes with the bot running, you can run the date command
A date of 7 days is printed based on the date the bot ran
ex) Run the bot on 12-09 and output 7 days based on 12-09 even after 1 day
Expected: Run the bot on 12-09 and print out 7 days based on 12-10 days if one day has passed

```<code>class date_select(View):
def __init__(self):
    super().__init__()

@discord.ui.select(
    min_values=1,
    max_values=1,
    placeholder='날짜 입력',
    options=ff_option.time_list_option(now = dt.datetime.now)
)
async def select_callback(self, select: discord.ui.Select, interaction):
    df = date_sheet.search_date(now_date=select.values[0], type=False).T
    select.disabled=True
    text = date_sheet.trans_date_str(df)
    await interaction.response.edit_message(view=self)
    await interaction.followup.send(text +'\n X : 신청불가 , O : 신청가능', ephemeral=True,delete_after=300)
</code>```

Body:
Every time I use the date slash command,
Based on the date at the time of use, I would like to print it out as select for 7 days

However, in the case of the codes currently configured, my expectation is that
The time when the bot runs is set to the current time
If the date changes with the bot running, you can run the date command
A date of 7 days is printed based on the date the bot ran
ex) Run the bot on 12-09 and output 7 days based on 12-09 even after 1 day
Expected: Run the bot on 12-09 and print out 7 days based on 12-10 days if one day has passed

class date_select(View):
def __init__(self):
    super().__init__()

@discord.ui.select(
    min_values=1,
    max_values=1,
    placeholder='날짜 입력',
    options=ff_option.time_list_option(now = dt.datetime.now)
)
async def select_callback(self, select: discord.ui.Select, interaction):
    df = date_sheet.search_date(now_date=select.values[0], type=False).T
    select.disabled=True
    text = date_sheet.trans_date_str(df)
    await interaction.response.edit_message(view=self)
    await interaction.followup.send(text +'\n X : 신청불가 , O : 신청가능', ephemeral=True,delete_after=300)


问:
How to get NavigationStack to retain NavigationPath state when switching views?
I modified an app to use the new NavigationSplitView and NavigationStack, but I can't figure out how to have the NavigationPath retain the state when it's not the active view.

Below is some sample code. I run it on an iPad in landscape mode, or on a Mac (Designed for iPad). It starts with View1 selected and displays View1 in the details. I then tap on SubView and it pushes to SubView. If I then tap on View2, View2 is displayed in the details. If I tap on View1 again, View1 is back at it's root, and is no longer pushed to the SubView. How can I fix this so that when I go back to View1 it is still pushed to SubView?

```<code>import SwiftUI

struct ViewType: Identifiable, Hashable {
    let id: String
}

private var viewTypes = [
    ViewType(id: "View1"),
    ViewType(id: "View2"),
]

struct ContentView: View {
    @StateObject private var navigationModel = NavigationModel()
    @State var selection: Set<String> = [viewTypes[0].id]
    var body: some View {
        NavigationSplitView {
            List(viewTypes, selection: $selection) { viewType in
                Text("\(viewType.id)")
            }
        } detail: {
            switch selection.first ?? "Unknown" {
            case "View1":
                View1()
            case "View2":
                View2()
            default:
                Text("Unknown")
            }
        }
        .navigationTitle(selection.first ?? "Unknown")
        .environmentObject(navigationModel)
    }
}

struct View1: View {
    @EnvironmentObject var navigationModel: NavigationModel
    var body: some View {
        NavigationStack(path: $navigationModel.path) {
            Text("View1")
            NavigationLink("SubView", value: "SubView")
                .navigationDestination(for: String.self) { name in
                    Text(name)
                        .onAppear {
                            print((navigationModel.path.count))
                        }
                }
        }
    }
}

struct View2: View {
    var body: some View {
        NavigationStack() {
            Text("View2")
        }
    }
}

final class NavigationModel: ObservableObject {
    @Published var path = NavigationPath() {
        didSet {
            print("path.count: \(path.count)")
        }
    }
}
</code>```

Body:
I modified an app to use the new NavigationSplitView and NavigationStack, but I can't figure out how to have the NavigationPath retain the state when it's not the active view.

Below is some sample code. I run it on an iPad in landscape mode, or on a Mac (Designed for iPad). It starts with View1 selected and displays View1 in the details. I then tap on SubView and it pushes to SubView. If I then tap on View2, View2 is displayed in the details. If I tap on View1 again, View1 is back at it's root, and is no longer pushed to the SubView. How can I fix this so that when I go back to View1 it is still pushed to SubView?

import SwiftUI

struct ViewType: Identifiable, Hashable {
    let id: String
}

private var viewTypes = [
    ViewType(id: "View1"),
    ViewType(id: "View2"),
]

struct ContentView: View {
    @StateObject private var navigationModel = NavigationModel()
    @State var selection: Set<String> = [viewTypes[0].id]
    var body: some View {
        NavigationSplitView {
            List(viewTypes, selection: $selection) { viewType in
                Text("\(viewType.id)")
            }
        } detail: {
            switch selection.first ?? "Unknown" {
            case "View1":
                View1()
            case "View2":
                View2()
            default:
                Text("Unknown")
            }
        }
        .navigationTitle(selection.first ?? "Unknown")
        .environmentObject(navigationModel)
    }
}

struct View1: View {
    @EnvironmentObject var navigationModel: NavigationModel
    var body: some View {
        NavigationStack(path: $navigationModel.path) {
            Text("View1")
            NavigationLink("SubView", value: "SubView")
                .navigationDestination(for: String.self) { name in
                    Text(name)
                        .onAppear {
                            print((navigationModel.path.count))
                        }
                }
        }
    }
}

struct View2: View {
    var body: some View {
        NavigationStack() {
            Text("View2")
        }
    }
}

final class NavigationModel: ObservableObject {
    @Published var path = NavigationPath() {
        didSet {
            print("path.count: \(path.count)")
        }
    }
}


问:
Rotate points around normal to sphere surface
I would like to rotate an array about the axis that is normal to a given location on the surface of a sphere, but unsure how to go about it.

As an example, the below code creates a series of points (a dipole field line), shifts it away from the centre of a sphere and rotates to some angle in the xy plane.

At this location, I would like to rotate the field line to any angle around the axis that is normal to the sphere surface.

```<code>import numpy as np
import matplotlib.pyplot as plt

field=np.linspace(-np.pi/2,np.pi/2,100)
circle=np.linspace(0,2*np.pi,100)
theta=60*np.pi/180

r_shift=0.9
r=1.5*np.sin(field+np.pi/2)**2
x0=r*np.cos(field)+r_shift
y0=r*np.sin(field)
# rotate around y-axis
x=x0*np.cos(theta)
y=y0

fig,ax=plt.subplots()
ax.set_box_aspect(1)
ax.plot(np.cos(circle),np.sin(circle),color='k')
ax.plot(x,y)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)

plt.show()
</code>```

I think it could be done with Euler angles or Rodriguez' formula, but I'm not familiar enough to implement this.

Body:
I would like to rotate an array about the axis that is normal to a given location on the surface of a sphere, but unsure how to go about it.

As an example, the below code creates a series of points (a dipole field line), shifts it away from the centre of a sphere and rotates to some angle in the xy plane.

At this location, I would like to rotate the field line to any angle around the axis that is normal to the sphere surface.

import numpy as np
import matplotlib.pyplot as plt

field=np.linspace(-np.pi/2,np.pi/2,100)
circle=np.linspace(0,2*np.pi,100)
theta=60*np.pi/180

r_shift=0.9
r=1.5*np.sin(field+np.pi/2)**2
x0=r*np.cos(field)+r_shift
y0=r*np.sin(field)
# rotate around y-axis
x=x0*np.cos(theta)
y=y0

fig,ax=plt.subplots()
ax.set_box_aspect(1)
ax.plot(np.cos(circle),np.sin(circle),color='k')
ax.plot(x,y)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)

plt.show()

I think it could be done with Euler angles or Rodriguez' formula, but I'm not familiar enough to implement this.