问:
createAsyncThunk is not a function TypeError: __vite_ssr_import_0__.createAsyncThunk is not a function from Vitest
I am having a very similar issue than this post but the solution presented doesn't work for me.

Here is my package.json:

```<code>{
  "name": "tenzies-with-redux",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "uuid": "^9.0.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@types/uuid": "^9.0.0",
    "@vitejs/plugin-react": "^3.0.0",
    "prettier": "2.8.1",
    "typescript": "^4.9.3",
    "vite": "^4.0.0",
    "vitest": "^0.27.1"
  }
}
</code>```

I used yarn upgrade-interactive to be up to date on all packages.

Here is my test:

```<code>import { beforeEach, describe, expect, it } from 'vitest'
import { ReduxStore } from '../../../react-view/main'
import { configureStoreWith } from '../../../app/store'
import { Dependencies } from '../../../app/dependencies'
import { InMemoryIdProvider } from '../../../infrastructure/idProvider/InMemoryIdProvider'
import { InMemoryRandomDiceProvider } from '../../../infrastructure/randomDiceProvider/InMemoryRandomDiceProvider'
import { rollDice } from '../diceSlice'

describe('Generate Random Dice', () => {
  let store: ReduxStore
  let dependencies: Dependencies

  beforeEach(() => {
    dependencies = {
      idProvider: new InMemoryIdProvider(),
      randomDiceProvider: new InMemoryRandomDiceProvider(),
    }
    store = configureStoreWith(dependencies)
  })

  it('should generate 10 random dice', () => {
    store.dispatch(rollDice())
    const state = store.getState()

    expect(state).toBe('something')
  })
})
</code>```

here is the SUT:

```<code>import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { Dependencies } from '../../app/dependencies'
import { Die } from './entities/Die'

type ExtraDependencies = {
  extra: Dependencies
}

export const rollDice = createAsyncThunk<Die, void, ExtraDependencies>(
  `dice/rollDice`,
  async (thunkAPI, { extra: { randomDiceProvider, idProvider } }) => {
    const number = randomDiceProvider.generateRandomDieValue()
    const id = idProvider.getNew()
    return new Die(id, { value: number, isHeld: false })
  },
)

export const initialState = {
  dice: [] as Die[],
  loading: false,
  error: null,
}

export const diceSlice = createSlice({
  name: 'dice',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(rollDice.fulfilled, (state, action) => {
      const payload = action.payload
      state.dice.push(payload)
    })
  },
})
</code>```

Typescript compiles, so that seems fine from that perspective.

Am I missing something?

EDIT: I migrated back to Jest meanwhile, and that works fine, so I am confident it's not a code issue. I still wish to know the solution to make Vitest work though!

Body:
I am having a very similar issue than this post but the solution presented doesn't work for me.

Here is my package.json:

{
  "name": "tenzies-with-redux",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "uuid": "^9.0.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@types/uuid": "^9.0.0",
    "@vitejs/plugin-react": "^3.0.0",
    "prettier": "2.8.1",
    "typescript": "^4.9.3",
    "vite": "^4.0.0",
    "vitest": "^0.27.1"
  }
}

I used yarn upgrade-interactive to be up to date on all packages.

Here is my test:

import { beforeEach, describe, expect, it } from 'vitest'
import { ReduxStore } from '../../../react-view/main'
import { configureStoreWith } from '../../../app/store'
import { Dependencies } from '../../../app/dependencies'
import { InMemoryIdProvider } from '../../../infrastructure/idProvider/InMemoryIdProvider'
import { InMemoryRandomDiceProvider } from '../../../infrastructure/randomDiceProvider/InMemoryRandomDiceProvider'
import { rollDice } from '../diceSlice'

describe('Generate Random Dice', () => {
  let store: ReduxStore
  let dependencies: Dependencies

  beforeEach(() => {
    dependencies = {
      idProvider: new InMemoryIdProvider(),
      randomDiceProvider: new InMemoryRandomDiceProvider(),
    }
    store = configureStoreWith(dependencies)
  })

  it('should generate 10 random dice', () => {
    store.dispatch(rollDice())
    const state = store.getState()

    expect(state).toBe('something')
  })
})

here is the SUT:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { Dependencies } from '../../app/dependencies'
import { Die } from './entities/Die'

type ExtraDependencies = {
  extra: Dependencies
}

export const rollDice = createAsyncThunk<Die, void, ExtraDependencies>(
  `dice/rollDice`,
  async (thunkAPI, { extra: { randomDiceProvider, idProvider } }) => {
    const number = randomDiceProvider.generateRandomDieValue()
    const id = idProvider.getNew()
    return new Die(id, { value: number, isHeld: false })
  },
)

export const initialState = {
  dice: [] as Die[],
  loading: false,
  error: null,
}

export const diceSlice = createSlice({
  name: 'dice',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(rollDice.fulfilled, (state, action) => {
      const payload = action.payload
      state.dice.push(payload)
    })
  },
})

Typescript compiles, so that seems fine from that perspective.

Am I missing something?

EDIT: I migrated back to Jest meanwhile, and that works fine, so I am confident it's not a code issue. I still wish to know the solution to make Vitest work though!


来源: stackexchange

问:
Is there a way to not show rows below a certain value in a table using Kable/KableExtra
I am trying to get a table for my dataset that only shows rows which are above a certain value, but which still uses the numbers in those rows to get the means for the supersets. using the df diamonds, i have the following code. What I want is for all rows with column price less than 3000 to NOT show up, but to still have them figure into the means of price for superset rows of cut and color.

Kind of a separate question, but I'm also trying to figure out how to make it so that if there were to be only one row in any of the subset rows, then they would be on the same line as the superset rows- such as if cut Fair had only one color

```<code>library(knitr)
library(kableExtra)

df <- diamonds

a11<-df%>%
  group_by(cut, color, clarity)%>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(sort = 3)

b11<-df%>%
  group_by(cut, color) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(clarity="", sort = 2) %>%
  select(cut, color, clarity,everything())

c11<-df %>%
  group_by(cut) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(color="", clarity= "", sort = 1) %>%
  select(cut, color,everything())

table3<-rbind(a11,b11,c11)
table3%>%
  arrange(cut, color, clarity) %>%
  select(-sort)%>%
  kbl(
    caption = "Table",
    longtable=T
  ) %>%
  kable_paper(full_width = F) %>%
  column_spec(1, bold = T) %>%
  column_spec(3, italic = T) %>%
  collapse_rows(columns = 1:3, valign = "top")%>%
  add_header_above(header = c("Diamonds" = 4))```
```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get a table for my dataset that only shows rows which are above a certain value, but which still uses the numbers in those rows to get the means for the supersets. using the df diamonds, i have the following code. What I want is for all rows with column price less than 3000 to NOT show up, but to still have them figure into the means of price for superset rows of cut and color.

Kind of a separate question, but I'm also trying to figure out how to make it so that if there were to be only one row in any of the subset rows, then they would be on the same line as the superset rows- such as if cut Fair had only one color

library(knitr)
library(kableExtra)

df <- diamonds

a11<-df%>%
  group_by(cut, color, clarity)%>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(sort = 3)

b11<-df%>%
  group_by(cut, color) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(clarity="", sort = 2) %>%
  select(cut, color, clarity,everything())

c11<-df %>%
  group_by(cut) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(color="", clarity= "", sort = 1) %>%
  select(cut, color,everything())

table3<-rbind(a11,b11,c11)
table3%>%
  arrange(cut, color, clarity) %>%
  select(-sort)%>%
  kbl(
    caption = "Table",
    longtable=T
  ) %>%
  kable_paper(full_width = F) %>%
  column_spec(1, bold = T) %>%
  column_spec(3, italic = T) %>%
  collapse_rows(columns = 1:3, valign = "top")%>%
  add_header_above(header = c("Diamonds" = 4))```


问:
"F compiler.cpp:149" Check failed: onames_left.empty()
When I compile the model, I get the error below. I can't find any information about it online.

```<code>[I util.cpp:23] %110 : (Tensor, Tensor) = prim::TupleConstruct(%108, %e.1)
[I op.cpp:88] [I] 108: 0  Tensor  [16, 32, 512]  Float
[I op.cpp:88] [I] e.1: 0  Tensor  [16]  Int
[I op.cpp:111] [O] 110: 0  (Tensor, Tensor)
[F compiler.cpp:149] Check failed: onames_left.empty()
Aborted
compile failed, exit code=134
<class 'SystemExit'> 134 <traceback object at 0x7f34ef0fd410>
</code>```

I don't know what this error means, and I don't know why? I'm doing everything right in python.

Body:
When I compile the model, I get the error below. I can't find any information about it online.

[I util.cpp:23] %110 : (Tensor, Tensor) = prim::TupleConstruct(%108, %e.1)
[I op.cpp:88] [I] 108: 0  Tensor  [16, 32, 512]  Float
[I op.cpp:88] [I] e.1: 0  Tensor  [16]  Int
[I op.cpp:111] [O] 110: 0  (Tensor, Tensor)
[F compiler.cpp:149] Check failed: onames_left.empty()
Aborted
compile failed, exit code=134
<class 'SystemExit'> 134 <traceback object at 0x7f34ef0fd410>

I don't know what this error means, and I don't know why? I'm doing everything right in python.


问:
Variable that's being passed with an empty string and causing an undefined index issue in my logs
I know this is quite a common question but hopefully someone can provide some help for me.

/**

 * @param $optionid

 * @return mixed

 */

public function getAttributeSwatchHashcode($optionid) {
    $hashcodeData = $this->swatchHelper>getSwatchesByOptionsId([$optionid]);

    return $hashcodeData[$optionid]['value'];
}
```
<p>It looks like <code>$optionid</code> has been passed with an empty string. So I believe I need to trace it back to <code>getAttributeSwatchHashcode()</code> and figure out why it's being called with no Option ID.</p>
<p>This is where I get a bit confused. I located it in another file.</p>
<pre class="lang-html prettyprint-override"><code><div class="icon" style="background-color:<?= $_helper44->getAttributeSwatchHashcode($bgColor) ?>"></div>
</code>```

From what I've been reading adding a check isset($array[$index]) would be a quick fix? I'm not sure if that works in this case. Do I need to trace it back more or would that be a quick fix to get the logs to stop firing off so much?

Not sure how to include this isset condition or if it's the right place.

Body:
I know this is quite a common question but hopefully someone can provide some help for me.

/**

 * @param $optionid

 * @return mixed

 */

public function getAttributeSwatchHashcode($optionid) {
    $hashcodeData = $this->swatchHelper>getSwatchesByOptionsId([$optionid]);

    return $hashcodeData[$optionid]['value'];
}

It looks like $optionid has been passed with an empty string. So I believe I need to trace it back to getAttributeSwatchHashcode() and figure out why it's being called with no Option ID.

This is where I get a bit confused. I located it in another file.

<div class="icon" style="background-color:<?= $_helper44->getAttributeSwatchHashcode($bgColor) ?>">

From what I've been reading adding a check isset($array[$index]) would be a quick fix? I'm not sure if that works in this case. Do I need to trace it back more or would that be a quick fix to get the logs to stop firing off so much?

Not sure how to include this isset condition or if it's the right place.


问:
CORS issue with Strapi running on nginx server
I'm trying to create a mock e-commerce site using React and my backend is built with Strapi. I have my backend on an nginx VPS. When I view my website online, no products are being populated and my console is showing this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://.../api/categories?populate=.
(Reason: CORS request did not succeed). Status code: (null).

I have added code to my Nginx configuration file

/etc/nginx/sites-available/default

The code I added was:

```<code>location /api {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
}
</code>```

I'm still getting the same error message.

Any ideas on what could resolve this for me?

I'm really new to setting up a VPS (first time trying it) and I would also appreciate any advice on how to best learn how to work with servers - any online resources or teachers would be great.

Thanks!

Body:
I'm trying to create a mock e-commerce site using React and my backend is built with Strapi. I have my backend on an nginx VPS. When I view my website online, no products are being populated and my console is showing this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://.../api/categories?populate=.
(Reason: CORS request did not succeed). Status code: (null).

I have added code to my Nginx configuration file

/etc/nginx/sites-available/default

The code I added was:

location /api {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
}

I'm still getting the same error message.

Any ideas on what could resolve this for me?

I'm really new to setting up a VPS (first time trying it) and I would also appreciate any advice on how to best learn how to work with servers - any online resources or teachers would be great.

Thanks!


问:
Grid of Textareas Does Not Display
I have been trying to make a wordle copy where the amount of guesses and word length can be controlled. So I used a nested for loop to display the grid. My school has banned inspect on my computer so I cannot use console.log. The error might be coming from the fetch request. I hope I get an answer soon.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <title>Unlimited Wordle</title>
</head>
<body>
    <center><h1>Unlimited Wordle</h1><br><br>
    <h4>Start out by tying in word length and amount of guesses. (Defaults are 5 and 6)</h4>
    <h3>Word Length:</h3>
    <input id="length"/>
    <h3>Guesses:</h3>
    <input id="width"/><br><br>
    <button id="start" onclick="play()">Start!</button>
    <div id="grid"></div><br><br>
    <button id="new" onclick="location.refresh()"><h4>Get A New Word!</h4></button><br><br>
    <h3 id="answer"></h3></center>
    <script>
    function play(){
        grid=document.getElementById("grid");
        var line=1;
        if(document.getElementById("width").length==0){
            var width=5;
        }else{
            var width=parseInt(document.getElementById("width").value);
        }
        if(document.getElementById("length").length==0){
            var length=6;
        }else{
            var length=parseInt(document.getElementById("length").value);
        }
        var length=parseInt(document.getElementById("length").value);
        var word="";
        while(length(word)!=width){
            word=fetch("https://random-word-api.herokuapp.com/word");
        }
        for (i=0; i<length; i++){
            for(j=0; j<width; j++){
                grid.innerHTML+=`<textarea id="${i} ${j}" rows="1", cols="1" maxlength="1" style="resize: none;" onkeyup="this.value = this.value.toUpperCase(); "></textarea>`
            }
            grid.innerHTML+="<br>"
        }
        window.addEventListener(onkeydown, function(event){
            var typed="";
            if(event.keyCode==13){
                var filled=true;
                var colors="";
                for(k=1; k<width; k++){
                    typed+=document.getElementById(`${line} ${k}`).value
                    if(document.getElementById(`${line} ${k}`).value.length==0){
                        var filled=false;
                    }
                }
                if(filled==true){
                    for(k=1; k<width; k++){
                        if(word[i]==typed[i]){
                            document.getElementById(`${line} ${k}`).style.color="green";
                        }
                        if(word.includes(typed[i])){
                            document.getElementById(`${line} ${k}`).style.color="yellow";
                        }
                        if(!word.includes(typed[i])){
                            document.getElementById(`${line} ${k}`).style.color="gray";
                        }
                        document.getElementById(`${line} ${k}`).readOnly=true;
                    }
                    line++;
                    if(line>6){
                        document.getElementById("answer").innerHTML=`The word was: ${word}.`;
                    }
                }
                }
            }
        )
    }
    </script>
</body>
</html>
</code>```

My github is https://github.com/ethanreesewagner.

Title: Grid of Textareas Does Not Display

Body:
I have been trying to make a wordle copy where the amount of guesses and word length can be controlled. So I used a nested for loop to display the grid. My school has banned inspect on my computer so I cannot use console.log. The error might be coming from the fetch request. I hope I get an answer soon.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <title>Unlimited Wordle</title>

Unlimited Wordle

Start out by tying in word length and amount of guesses. (Defaults are 5 and 6)

Word Length:

    <input id="length"/>

Guesses:

    <input id="width"/>

    <button id="start" onclick="play()">Start!</button>

    <button id="new" onclick="location.refresh()">
Get A New Word!
</button>

My github is https://github.com/ethanreesewagner.


问:
I cannot pass the right information from API to the component using vuejs
this is the DIV where I am including the component responsible to fetch the data from API:

The component has params for filtering through the data and identifying the user but it doesn't return the specific user even when I use params and I am adding in the params of each div the user_id. The picture of this user isn't loading somehow.

```<code><div class="gold_container_below">
<h4 class="gold_subtitle" v-html="$t('awards_gold_type')"></h4>
<div class="special_container">
<img src="/img/event/cheersupports/2022/appreciation/awards/gold_left.svg" class="gold_left"/>                     <div class="userdata_icon">
<LiverListArea1
ref="liver_list"
page_records="1"
:params="params0"/>
<!-- <img src="/img/event/cheersupports/2022/appreciation/awards/gengoro.png"/> -->                     </div>
</code>```
```<code>export default {
  props: ["lang", "params"],
  i18n,
  components: {
    LiverListArea1,
  },
  data() {
    return {
        params0: {
          user_id: 1616,
        },
        params1: {
          user_id: 5754,
        },
        params2: {
          user_id: 298,
        },
        params3: {
          user_id: 4655,
        },
        params4: {
          user_id: 524,
        },
        params5: {
          liver_id: 1807,
        },
</code>```
```<code><template>
  <div class="loadercontainer1 default_font">
    <ul class="account_list">
      <li
        class="account_list_item finger"
        v-for="(liver, key) in livers"
        :key="key"
        v-on:click="click_item(liver)"
      >
        <div class="account">
          <img :src="liver.icon_path" alt="まごころプロジェクト" />

        </div>
      </li>
    </ul>

    <LiverSearchFunction
      ref="liver_search_function"
      :header="header"
      :params="params"
      :page_records="page_records"
    />
  </div>
</template>
</code>```

The code above is the component in charge of filtering though the data from the component LiverSearchFunction.

I am only getting the user icon image from the loop not from the user_id from params. I am not sure how get that specific information....

Body:
this is the DIV where I am including the component responsible to fetch the data from API:

The component has params for filtering through the data and identifying the user but it doesn't return the specific user even when I use params and I am adding in the params of each div the user_id. The picture of this user isn't loading somehow.

<LiverListArea1
ref="liver_list"
page_records="1"
:params="params0"/>

export default {
  props: ["lang", "params"],
  i18n,
  components: {
    LiverListArea1,
  },
  data() {
    return {
        params0: {
          user_id: 1616,
        },
        params1: {
          user_id: 5754,
        },
        params2: {
          user_id: 298,
        },
        params3: {
          user_id: 4655,
        },
        params4: {
          user_id: 524,
        },
        params5: {
          liver_id: 1807,
        },

<template>

    <LiverSearchFunction
      ref="liver_search_function"
      :header="header"
      :params="params"
      :page_records="page_records"
    />

</template>

The code above is the component in charge of filtering though the data from the component LiverSearchFunction.

I am only getting the user icon image from the loop not from the user_id from params. I am not sure how get that specific information....


问:
nextcloud: uninstall and reinstall with occ
Nextcloud has a command-line tool, "occ".
The command occ maintenance:install will install nextcloud.

After initial install, the maintenance:install command is no longer available.
This is also reflected in the output from occ status which reports installed: true.

What I want to do now is to destroy the existing installation, and start over.
So far I always delete the docker volumes that contain nextcloud and the database, but this seems overkill.
There has to be an option to uninstall or mark the installation as uninstalled, and then reinstall.

What I found so far

I found a file config/CAN_INSTALL file which gets removed on install. But restoring this seemed to have no effect.

Setting occ config:system:set --value=false --type=boolean installed does make the system believe it is not installed, but then the occ maintenance:install will fail because there is existing data and configuration. It is not clear to me how I would wipe this.


问:
Cayley: How to get an `Quad` by subject?
For example:
There are some quads of subject: "bob".

```<code><bob> <follows> <Jack> .
<bob> <age> <12> .
<bob> <college> <MIT> .
...
</code>```

Are there any way to get all quads of <bob> ?

Body:
For example:
There are some quads of subject: "bob".

<bob> <follows> <Jack> .
<bob> <age> <12> .
<bob> <college> <MIT> .
...

Are there any way to get all quads of <bob> ?


问:
Flickering When Drawing Keypoints to Canvas
I am learning the the basics of tensorflow.js. I have been able to load a model successfully and extract keypoints from the webcam using blazepose. However, I am noticing that when I start to draw keypoints to the canvas, there is a lot of flickering. I am assuming this is due to the setInterval that does the rendering, but I'm not sure how to remedy this so that the keypoints are rendered in "real-time". Thanks for the help!</p>
```<code>
import './App.css';
import React, { useEffect, useRef } from 'react';
import * as poseDetection from '@tensorflow-models/pose-detection';
import '@tensorflow/tfjs-backend-webgl';
import Webcam from "react-webcam";
import { drawPoints } from './utils/drawKeyPoints';

function App() {

  const webcamRef = useRef(null);
  const canvasRef = useRef(null);

  async function initPoseDetection() {
    const model = poseDetection.SupportedModels.BlazePose;
    const config = {
      runtime: 'tfjs',
      modelType: 'full',
      maxPoses: 1,
    }
    const detector = await poseDetection.createDetector(model, config)
    return detector;
  }

  async function start(){
    const detector = await initPoseDetection();

    setInterval(() => {
      render(detector)
    }, 100)
  }

  async function render(detector) {
    if (
      typeof webcamRef.current !== "undefined" &&
      webcamRef.current !== null &&
      webcamRef.current.video.readyState === 4
    ) {
      // Get Video Properties
      const video = webcamRef.current.video;
      const videoWidth = webcamRef.current.video.videoWidth;
      const videoHeight = webcamRef.current.video.videoHeight;

      // Set video width
      webcamRef.current.video.width = videoWidth;
      webcamRef.current.video.height = videoHeight;

      // Set canvas height and width
      canvasRef.current.width = videoWidth;
      canvasRef.current.height = videoHeight;
      const ctx = canvasRef.current.getContext("2d");
      const poses = await detector.estimatePoses(video)
      drawPoints(ctx, poses[0]["keypoints"])
  }
}
start()

  return (
    <div className="App">
      <header className="App-header">
      <Webcam
          ref={webcamRef}
          style={{
            position: "absolute",
            marginLeft: "auto",
            marginRight: "auto",
            left: 0,
            right: 0,
            textAlign: "center",
            zindex: 9,
            width: 1280,
            height: 720,
          }}
        >
        </Webcam>
        <canvas
          ref={canvasRef}
          style={{
            position: "absolute",
            marginLeft: "auto",
            marginRight: "auto",
            left: 0,
            right: 0,
            textAlign: "center",
            zindex: 9,
            width: 1280,
            height: 720,
          }}
        />
      </header>
    </div>
  );
}

export default App;

</code>```

Body:
I am learning the the basics of tensorflow.js. I have been able to load a model successfully and extract keypoints from the webcam using blazepose. However, I am noticing that when I start to draw keypoints to the canvas, there is a lot of flickering. I am assuming this is due to the setInterval that does the rendering, but I'm not sure how to remedy this so that the keypoints are rendered in "real-time". Thanks for the help!

import './App.css';
import React, { useEffect, useRef } from 'react';
import * as poseDetection from '@tensorflow-models/pose-detection';
import '@tensorflow/tfjs-backend-webgl';
import Webcam from "react-webcam";
import { drawPoints } from './utils/drawKeyPoints';

function App() {

  const webcamRef = useRef(null);
  const canvasRef = useRef(null);

  async function initPoseDetection() {
    const model = poseDetection.SupportedModels.BlazePose;
    const config = {
      runtime: 'tfjs',
      modelType: 'full',
      maxPoses: 1,
    }
    const detector = await poseDetection.createDetector(model, config)
    return detector;
  }

  async function start(){
    const detector = await initPoseDetection();

    setInterval(() => {
      render(detector)
    }, 100)
  }

  async function render(detector) {
    if (
      typeof webcamRef.current !== "undefined" &&
      webcamRef.current !== null &&
      webcamRef.current.video.readyState === 4
    ) {
      // Get Video Properties
      const video = webcamRef.current.video;
      const videoWidth = webcamRef.current.video.videoWidth;
      const videoHeight = webcamRef.current.video.videoHeight;

      // Set video width
      webcamRef.current.video.width = videoWidth;
      webcamRef.current.video.height = videoHeight;

      // Set canvas height and width
      canvasRef.current.width = videoWidth;
      canvasRef.current.height = videoHeight;
      const ctx = canvasRef.current.getContext("2d");
      const poses = await detector.estimatePoses(video)
      drawPoints(ctx, poses[0]["keypoints"])
  }
}
start()

  return (

      <Webcam
          ref={webcamRef}
          style={{
            position: "absolute",
            marginLeft: "auto",
            marginRight: "auto",
            left: 0,
            right: 0,
            textAlign: "center",
            zindex: 9,
            width: 1280,
            height: 720,
          }}
        >
        </Webcam>
        <canvas
          ref={canvasRef}
          style={{
            position: "absolute",
            marginLeft: "auto",
            marginRight: "auto",
            left: 0,
            right: 0,
            textAlign: "center",
            zindex: 9,
            width: 1280,
            height: 720,
          }}
        />

  );
}

export default App;


问:
Using IDurableOrchestrationContext.CurrentUtcDateTime.Ticks as a RowKey - how to prevent duplicate values? (Azure SDK)
I have a queue-triggered Durable Function/orchestrator client that calls an Orchestrator function
SomeWorkflow (simplified code):

public class SomeWorkflow
{
  public Task SomeWorkflow([OrchestrationTrigger] IDurableOrchestrationContext context)
  {
    /* Create many requestsForBacklog items to add into a table - code omitted */
    if (requestsForBacklog.Any())
    {
        long startRowKey = context.CurrentUtcDateTime.Ticks;
        await context.CallActivityAsync(FunctionNames.ADD_TO_BACKLOG_ACTIVITY,
          startRowKey, requestsForBacklog);
    }
  }
}
```
<p><code>ADD_TO_BACKLOG_ACTIVITY</code> takes the <code>requestsForBacklog</code> collection and saves each item in an Azure
Storage Table.<br />
For each entity to be added, it increments the <code>startRowKey</code> argument by 1 and it
becomes a new entity's Rowkey.<br />
This approach guarantees me <strong>FIFO order</strong> for all added entities having the same PartitionKey (<code>Guid</code> type).</p>
<p>Question: could it be possible that when my Azure Function app scales, it will cause the Orchestrator function<br />
<code>SomeWorkflow</code> to run on <strong>different instances</strong>?<br />
If yes, is it then possible for the call to <code>context.CurrentUtcDateTime</code> to happen on multiple instances<br />
at <strong>exactly the same time</strong> (up to a second, millisecond)?</p>
<p>If the answer is YES, it will create duplicate RowKey values. I need to prevent that.</p>
<p>Update: it seems that <code>ADD_TO_BACKLOG_ACTIVITY</code> could create a Guid suffix once for each new <code>requestsForBacklog</code> argument and then add the suffix to each derived Rowkey:</p>
<pre class="lang-cs prettyprint-override"><code>var suffix = Guid.NewGuid().ToString("N");
var itemsBatch = requestsForBacklog.Data.Select(x => new BacklogItem
{
  PartitionKey = x.OrgId.ToString(),
  RowKey = string.Format("{0:d19}+{1}", startRowKey++, suffix)
</code>```

Found this solution here:

What's the probability of repeating a rowkey that depends on datetime in Azure

Thoughts?

Body:
I have a queue-triggered Durable Function/orchestrator client that calls an Orchestrator function
SomeWorkflow (simplified code):

public class SomeWorkflow
{
  public Task SomeWorkflow([OrchestrationTrigger] IDurableOrchestrationContext context)
  {
    /* Create many requestsForBacklog items to add into a table - code omitted */
    if (requestsForBacklog.Any())
    {
        long startRowKey = context.CurrentUtcDateTime.Ticks;
        await context.CallActivityAsync(FunctionNames.ADD_TO_BACKLOG_ACTIVITY,
          startRowKey, requestsForBacklog);
    }
  }
}

ADD_TO_BACKLOG_ACTIVITY takes the requestsForBacklog collection and saves each item in an Azure
Storage Table.

For each entity to be added, it increments the startRowKey argument by 1 and it
becomes a new entity's Rowkey.

This approach guarantees me FIFO order for all added entities having the same PartitionKey (Guid type).

Question: could it be possible that when my Azure Function app scales, it will cause the Orchestrator function

SomeWorkflow to run on different instances?

If yes, is it then possible for the call to context.CurrentUtcDateTime to happen on multiple instances

at exactly the same time (up to a second, millisecond)?

If the answer is YES, it will create duplicate RowKey values. I need to prevent that.

Update: it seems that ADD_TO_BACKLOG_ACTIVITY could create a Guid suffix once for each new requestsForBacklog argument and then add the suffix to each derived Rowkey:

var suffix = Guid.NewGuid().ToString("N");
var itemsBatch = requestsForBacklog.Data.Select(x => new BacklogItem
{
  PartitionKey = x.OrgId.ToString(),
  RowKey = string.Format("{0:d19}+{1}", startRowKey++, suffix)

Found this solution here:

What's the probability of repeating a rowkey that depends on datetime in Azure

Thoughts?


问:
Azure functions CosmosDB Trigger using User assigned managed identity
I'm trying to use "User assigned managed identity" among all my Azure functions and consume change feed. The cosmosDB trigger function is not using the identity. I provided connectionPrefix__clientId in the app settings as well. Does the trigger support User assigned managed identity ?</p>


问:
Trying to understand incrementing a counter in Array.reduce() in Javascript
In the following Javascript Array.reduce() example, why does 'count' increment in the second reducer but not the first one?

I know I can just use the second example, but there was a case where I wanted to give a user name to some of the properties in the initial object.

const data = [1,2,3,4];

data.reduce((accumulator) => {

    let { count } = accumulator;
    count++;
    console.log(accumulator);
    return accumulator;

}, { count: 0 });

/*
Returns:
{ count: 0 }
{ count: 0 }
{ count: 0 }
{ count: 0 }
*/
```
<pre class="lang-js prettyprint-override"><code>data.reduce((accumulator) => {

    accumulator.count++;
    console.log(accumulator);
    return accumulator;

}, { count: 0 });

/*
Returns
{ count: 1 }
{ count: 2 }
{ count: 3 }
{ count: 4 }
*/
</code>```

Body:
In the following Javascript Array.reduce() example, why does 'count' increment in the second reducer but not the first one?

I know I can just use the second example, but there was a case where I wanted to give a user name to some of the properties in the initial object.

const data = [1,2,3,4];

data.reduce((accumulator) => {

    let { count } = accumulator;
    count++;
    console.log(accumulator);
    return accumulator;

}, { count: 0 });

/*
Returns:
{ count: 0 }
{ count: 0 }
{ count: 0 }
{ count: 0 }
*/

data.reduce((accumulator) => {

    accumulator.count++;
    console.log(accumulator);
    return accumulator;

}, { count: 0 });

/*
Returns
{ count: 1 }
{ count: 2 }
{ count: 3 }
{ count: 4 }
*/


问:
Logged events not showing up in Ganache or in Transaction log
So I am triggering this contract's fallback(from another contract) which emits an event, This event shows up in remix but not in ganache or while test.

Target Contract

```<code>contract ContractA {
    event logMsgData (bytes, uint);

    fallback() external payable {
        console.log("here");
        emit logMsgData(msg.data, msg.value);
    }
}
</code>```

Caller

```<code>contract ContractB {
    BookTicket public targetContract;

    constructor(address _targetContract) {
        targetContract = ContractA(payable(_targetContract));
    }

    function callFallbackUsingSignature() public {
        (bool success,) = address(targetContract).call(abi.encodeWithSignature("nonExistingFunction()"));
        require(success);
    }
}
</code>```

now when I run callFallbackUsingSignature() it does trigger the fallback (as indicated by remix and console.log) but it does not show up on ganache

or in transaction log

```<code>{
  to: '0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9',
  from: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
  contractAddress: null,
  transactionIndex: 0,
  gasUsed: BigNumber { value: "31630" },
  logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040200000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000',
  blockHash: '0x28544824c41f6791ca1b0c9abec71d867e14e571598f795fb23385c4ceaabda8',
  transactionHash: '0x6f1ae658afe454af1173c3cce8a3ce152c91a5fcb6ea3af6e31b3b72f04d6527',
  logs: [
    {
      transactionIndex: 0,
      blockNumber: 6,
      transactionHash: '0x6f1ae658afe454af1173c3cce8a3ce152c91a5fcb6ea3af6e31b3b72f04d6527',
      address: '0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0',
      topics: [Array],
      data: '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004f85396d700000000000000000000000000000000000000000000000000000000',
      logIndex: 0,
      blockHash: '0x28544824c41f6791ca1b0c9abec71d867e14e571598f795fb23385c4ceaabda8'
    }
  ],
  blockNumber: 6,
  confirmations: 1,
  cumulativeGasUsed: BigNumber { value: "31630" },
  effectiveGasPrice: BigNumber { value: "1458563173" },
  status: 1,
  type: 2,
  byzantium: true,
  events: [
    {
      transactionIndex: 0,
      blockNumber: 6,
      transactionHash: '0x6f1ae658afe454af1173c3cce8a3ce152c91a5fcb6ea3af6e31b3b72f04d6527',
      address: '0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0',
      topics: [Array],
      data: '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004f85396d700000000000000000000000000000000000000000000000000000000',
      logIndex: 0,
      blockHash: '0x28544824c41f6791ca1b0c9abec71d867e14e571598f795fb23385c4ceaabda8',
      removeListener: [Function (anonymous)],
      getBlock: [Function (anonymous)],
      getTransaction: [Function (anonymous)],
      getTransactionReceipt: [Function (anonymous)]
    }
  ]
}
</code>```

And when i test it, no matter which args i give the test always passes

```<code>expect(await contractB.callFallbackUsingSignature()).to.emit(contractA, "logMsgData").withArgs("0xf853", 0);
</code>```

So how do I test event emission? What am I doing wrong.

Body:
So I am triggering this contract's fallback(from another contract) which emits an event, This event shows up in remix but not in ganache or while test.

Target Contract

contract ContractA {
    event logMsgData (bytes, uint);

    fallback() external payable {
        console.log("here");
        emit logMsgData(msg.data, msg.value);
    }
}

Caller

contract ContractB {
    BookTicket public targetContract;

    constructor(address _targetContract) {
        targetContract = ContractA(payable(_targetContract));
    }

    function callFallbackUsingSignature() public {
        (bool success,) = address(targetContract).call(abi.encodeWithSignature("nonExistingFunction()"));
        require(success);
    }
}

now when I run callFallbackUsingSignature() it does trigger the fallback (as indicated by remix and console.log) but it does not show up on ganache

or in transaction log

{
  to: '0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9',
  from: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
  contractAddress: null,
  transactionIndex: 0,
  gasUsed: BigNumber { value: "31630" },
  logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040200000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000',
  blockHash: '0x28544824c41f6791ca1b0c9abec71d867e14e571598f795fb23385c4ceaabda8',
  transactionHash: '0x6f1ae658afe454af1173c3cce8a3ce152c91a5fcb6ea3af6e31b3b72f04d6527',
  logs: [
    {
      transactionIndex: 0,
      blockNumber: 6,
      transactionHash: '0x6f1ae658afe454af1173c3cce8a3ce152c91a5fcb6ea3af6e31b3b72f04d6527',
      address: '0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0',
      topics: [Array],
      data: '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004f85396d700000000000000000000000000000000000000000000000000000000',
      logIndex: 0,
      blockHash: '0x28544824c41f6791ca1b0c9abec71d867e14e571598f795fb23385c4ceaabda8'
    }
  ],
  blockNumber: 6,
  confirmations: 1,
  cumulativeGasUsed: BigNumber { value: "31630" },
  effectiveGasPrice: BigNumber { value: "1458563173" },
  status: 1,
  type: 2,
  byzantium: true,
  events: [
    {
      transactionIndex: 0,
      blockNumber: 6,
      transactionHash: '0x6f1ae658afe454af1173c3cce8a3ce152c91a5fcb6ea3af6e31b3b72f04d6527',
      address: '0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0',
      topics: [Array],
      data: '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004f85396d700000000000000000000000000000000000000000000000000000000',
      logIndex: 0,
      blockHash: '0x28544824c41f6791ca1b0c9abec71d867e14e571598f795fb23385c4ceaabda8',
      removeListener: [Function (anonymous)],
      getBlock: [Function (anonymous)],
      getTransaction: [Function (anonymous)],
      getTransactionReceipt: [Function (anonymous)]
    }
  ]
}

And when i test it, no matter which args i give the test always passes

expect(await contractB.callFallbackUsingSignature()).to.emit(contractA, "logMsgData").withArgs("0xf853", 0);

So how do I test event emission? What am I doing wrong.


问:
Can we update DOM using GuideBridge object in Adaptive Form?
On AEM Adaptive Form, I have a scenario to format the "Table component" on the review Section dynamically(including changes to no. of column & column names etc.). Though this can be achieved using Jquery, I would like to explore if this can be done using only guideBridge object ? I am able to update the properties of guideBridge object using setProperty fn.; they won't reflect the changes on the Web Page.

I tried to update the properties of guideBridge object using setProperty fn.; they won't reflect the changes on the Web Page.


问:
Is there a way to force TypeScript not to accept `any` as a parameter
Is there a way to erase, forbid, omit the bottom type any from being passed into a function or in other contexts? I know there's the analysis like listing avoiding implicit anys that can be done but there's times where that can still fail in a mixed code base.

```<code>// suppose this `any` comes from somewhere else and lints ok
const someValue: any = 27;

// now I have this function
function superFunction(x: number) {
  // magic
}

// now with `any` I can call it because `any` spoils the type system.
superFunction(someValue);

// this still works from a type-checking scenario
const someValue2: any = {};
superFunction(someValue2); // Runtime error!
</code>```

I would expect there's some sort of generic helper like Pick, Omit, etc. that would force the caller to do its own assertions. Something like this

```<code>type NeverAny<T> = // erase `any`ness

function superFunction(x: NeverAny<number>) {
  // magic
}

const someValue: any = 27;
const someValue2: any = {};

superFunction(someValue); // Type-checking time: "Any is forbidden here"
superFunction(someValue2); // Type-checking time: "Any is forbidden here"
</code>```

Body:
Is there a way to erase, forbid, omit the bottom type any from being passed into a function or in other contexts? I know there's the analysis like listing avoiding implicit anys that can be done but there's times where that can still fail in a mixed code base.

// suppose this `any` comes from somewhere else and lints ok
const someValue: any = 27;

// now I have this function
function superFunction(x: number) {
  // magic
}

// now with `any` I can call it because `any` spoils the type system.
superFunction(someValue);

// this still works from a type-checking scenario
const someValue2: any = {};
superFunction(someValue2); // Runtime error!

I would expect there's some sort of generic helper like Pick, Omit, etc. that would force the caller to do its own assertions. Something like this

type NeverAny<T> = // erase `any`ness

function superFunction(x: NeverAny<number>) {
  // magic
}

const someValue: any = 27;
const someValue2: any = {};

superFunction(someValue); // Type-checking time: "Any is forbidden here"
superFunction(someValue2); // Type-checking time: "Any is forbidden here"


问:
How to check if python user input is a valid character
Im trying to get user input for my script. And the User input can only be 2 characters a dot(".") or a dash("-") I got it to check if its either of the characters the first time and it works. But If you for example put in a "b" itll then say invalid character and retry the input. Only problem is that if u put in a invalid character twice in a row it somehow thinks its a valid character a valid Character being a "." or "-" only.

Current Code:

```<code>character_a = input('Enter First Dot or Dash (. / -): ')

if not character_a == ".":
    if not character_a == "-":
        print('Invalid Character.. Try Again')
        character_a = input('Enter First Dot or Dash (. / -): ')

if character_a == "." or "-":
    print('Valid Character')
</code>```

Body:
Im trying to get user input for my script. And the User input can only be 2 characters a dot(".") or a dash("-") I got it to check if its either of the characters the first time and it works. But If you for example put in a "b" itll then say invalid character and retry the input. Only problem is that if u put in a invalid character twice in a row it somehow thinks its a valid character a valid Character being a "." or "-" only.

Current Code:

character_a = input('Enter First Dot or Dash (. / -): ')

if not character_a == ".":
    if not character_a == "-":
        print('Invalid Character.. Try Again')
        character_a = input('Enter First Dot or Dash (. / -): ')

if character_a == "." or "-":
    print('Valid Character')


问:
as I configurate rtems on redhat9.0 there is somthing wrong with it
I have succssfully complie the former file, but as i complie the enviroment of rtems the error is coming

and I had install gcc .How can I solve it?

I am looking forward to someone could help me solve it.


问:
How to receive Google ChannelPresence in an ActionBean?
I am trying to receive the disconnect google ChannelPresence in a Stripes ActionBean. I am currently using DynamicMappingFilter to dynamically map my ActionBean URLs. The disconnect presence was working perfectly when I was using a servlet that was mapped to "/_ah/channel/disconnected/".

The custom mapping is working with my other ActionBean that uses UrlBinding("/testing/"). However, the ChannelPresence does not seem to be sent to my ActionBean that handles a ChannelPresence disconnect :

```<code>@UrlBinding("/_ah/channel/disconnected/")
public class LogoutActionBean implements ActionBean {

    private ActionBeanContext context;
    public void setContext(ActionBeanContext abc) {
        context = abc;
    }

    public ActionBeanContext getContext() {
        return context;
    }

    @DefaultHandler
    public Resolution logout() {
        UserStore userStore = UserStore.getInstance();
        ChannelService channelService = ChannelServiceFactory.getChannelService();
        ChannelPresence presence = null;
        String clientID = null;
        try {
            presence = channelService.parsePresence(context.getRequest());
        } catch (IOException e) {
        }
        if (presence != null) {
            clientID = presence.clientId();
            userStore.removeUser(clientID);
        }
        UserStoreUtility.updateAllUserList();
        return new ForwardResolution("UserList.jsp");
    }
}
</code>```

This is my web.xml:

```<code><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
        <display-name>Stripes Filter</display-name>
        <filter-name>StripesFilter</filter-name>
        <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
        <init-param>
            <param-name>ActionResolver.Packages</param-name>
            <param-value>net.sourceforge.stripes.examples, com.channel</param-value>
        </init-param>
    </filter>
    <filter>
        <description>Dynamically maps URLs to ActionBeans.</description>
        <display-name>Stripes Dynamic Mapping Filter</display-name>
        <filter-name>DynamicMappingFilter</filter-name>
        <filter-class>
            net.sourceforge.stripes.controller.DynamicMappingFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>DynamicMappingFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to receive the disconnect google ChannelPresence in a Stripes ActionBean. I am currently using DynamicMappingFilter to dynamically map my ActionBean URLs. The disconnect presence was working perfectly when I was using a servlet that was mapped to "/_ah/channel/disconnected/".

The custom mapping is working with my other ActionBean that uses UrlBinding("/testing/"). However, the ChannelPresence does not seem to be sent to my ActionBean that handles a ChannelPresence disconnect :

@UrlBinding("/_ah/channel/disconnected/")
public class LogoutActionBean implements ActionBean {

    private ActionBeanContext context;
    public void setContext(ActionBeanContext abc) {
        context = abc;
    }

    public ActionBeanContext getContext() {
        return context;
    }

    @DefaultHandler
    public Resolution logout() {
        UserStore userStore = UserStore.getInstance();
        ChannelService channelService = ChannelServiceFactory.getChannelService();
        ChannelPresence presence = null;
        String clientID = null;
        try {
            presence = channelService.parsePresence(context.getRequest());
        } catch (IOException e) {
        }
        if (presence != null) {
            clientID = presence.clientId();
            userStore.removeUser(clientID);
        }
        UserStoreUtility.updateAllUserList();
        return new ForwardResolution("UserList.jsp");
    }
}

This is my web.xml:

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
        <display-name>Stripes Filter</display-name>
        <filter-name>StripesFilter</filter-name>
        <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
        <init-param>
            <param-name>ActionResolver.Packages</param-name>
            <param-value>net.sourceforge.stripes.examples, com.channel</param-value>
        </init-param>
    </filter>
    <filter>
        <description>Dynamically maps URLs to ActionBeans.</description>
        <display-name>Stripes Dynamic Mapping Filter</display-name>
        <filter-name>DynamicMappingFilter</filter-name>
        <filter-class>
            net.sourceforge.stripes.controller.DynamicMappingFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>DynamicMappingFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


问:
Laravel 9 & Bulma

Illuminate\Foundation\ComposerScripts::postAutoloadDump
@php artisan package:discover --ansi
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255

Using Laravel 9 & Bulma, this project previously worked on windows and setting it up again with the same settings it doesnt work when running composer update.

Ive checked all my updates that are used in the Handlers to Laravel 9, Ive deleted the files and started over and it doesn't work still.

Title: Laravel 9 & Bulma


问:
Get all services of base type nest.js
I would like to get all services of base type in nest js module. I have module, which contains all my services in provider. I import him to my module, where i would like to get services. How can i do this?</p>

Title: Get all services of base type nest.js


问:
Grid Computing in Azure
An on-premises System/Solution uses IBM Spectrum Symphony for its Grid Computing needs.
This solution will need to migrate to Azure.
What services are available in Azure for solving Grid Computing needs?

Thanks in advance for your help!

Title: Grid Computing in Azure


问:
How to break down a mesh distance minimization problem?
I'm having trouble solving a problem using "Ceres" and I could use some help!

To simplify the problem:

Imagine I have a mesh "A" that I want to scale and rotate (with scale + rotation represented as variables!) to be as
close to a mesh "B" as possible.

"Closeness" is defined as the sum of....

For each vertex in A, find the distance to the nearest vertex in B

For each vertex in B, find the distance to the nearest vertex in A

Now that first clause is super easy to model.

We can add a residual block for each vertex in "A", deform the vertex within the Cost Function using our variables, and work out their nearest neighbour in "B" - great.

But what about that second clause?

Do we have to do it in a single residual block? Deform every vertex in "A" in the residual block and compare to every vertex in "B"?

Do we create a residual block for every vertex in "B", and then have to re-deform every vertex in "A" within each residual block?

Is there something better that we can do to break down the problem??

Any help would be truly appreciated - I've spent hours thinking about it and I feel kinda stuck!


问:
Laravel Shorten Url Package
Hi i will build referral website. So every user will have their unique link. the unique id store in User table.

example: domainname.com/referral/A12CDKDDF

so the route

```<code> Route::get('/referral/{id}', 'IndexController@referral');
</code>```

but i want to make it the link more shorter like using bit.ly/ABCD or firebase ref.page.link/ABCD

i need advice which URL Shorteners api which suitable with my case? if let say currently have 1000 users and this can continue to grow up.

i read in firebase, the max request/day is 200.000/day for free plan. so its mean, i can have my short url unlimited in my table. but only 200000 click/open allow. is it my understanding correct?

thannk you for advice

Title: Laravel Shorten Url Package

Body:
Hi i will build referral website. So every user will have their unique link. the unique id store in User table.

example: domainname.com/referral/A12CDKDDF

so the route

 Route::get('/referral/{id}', 'IndexController@referral');

but i want to make it the link more shorter like using bit.ly/ABCD or firebase ref.page.link/ABCD

i need advice which URL Shorteners api which suitable with my case? if let say currently have 1000 users and this can continue to grow up.

i read in firebase, the max request/day is 200.000/day for free plan. so its mean, i can have my short url unlimited in my table. but only 200000 click/open allow. is it my understanding correct?

thannk you for advice


问:
I have to validate the user agreement content for a mobile application using selenium java
I am new to Appium and i have to validate End user agreement content to make sure its typo free.

below is the logic to get the list of element text from current view

List listOfElements = driver.findElements(AppiumBy.className("android.widget.xxx"));
{

```<code>        for (WebElement element : listOfElements) {
            String ActualContent = element.getText();
            System.out.println(ActualContent);

        }
</code>```

after getting the actual content for each element one by one, i want to validate the content whether is type free or not

what is the best way to approach it.

Body:
I am new to Appium and i have to validate End user agreement content to make sure its typo free.

below is the logic to get the list of element text from current view

List listOfElements = driver.findElements(AppiumBy.className("android.widget.xxx"));
{

        for (WebElement element : listOfElements) {
            String ActualContent = element.getText();
            System.out.println(ActualContent);

        }

after getting the actual content for each element one by one, i want to validate the content whether is type free or not

what is the best way to approach it.


问:
How To Make Responsive positioned inside a Stack in flutter and how to control the space between elements inside the row and the row inside coulmn

This is The Result in tablet and phone the different is show

this is main design i build it

**How To Solve It **

this is my code in this design

```<code>import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../../../../core/app_color.dart';
import '../../../../core/app_style.dart';
import '../../../../models/product_model.dart';

class ProductView extends StatelessWidget {
  ProductView({Key? key, required this.productModel}) : super(key: key);
  final ProductModel productModel;
  final ScrollController scrollController = ScrollController();
  final double _height = 100;

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    final double percent = (productModel.disPrice - productModel.price) /
        productModel.disPrice *
        100;
    return Container(
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(20),
      ),
      margin: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
      padding: const EdgeInsets.symmetric(
        horizontal: 8,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Stack(children: [
            Container(
              width: width * 0.42,
              height: height * 0.21,
              decoration: BoxDecoration(
                color: Colors.transparent,
                image: DecorationImage(
                  image: AssetImage(productModel.imageUrl),
                ),
              ),
            ),
            Positioned(
              bottom: height * 0.01,
              right: 0.0,
              child: Container(
                width: 48.31,
                height: 19,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: AppColor.lightBlue,
                  // border: Border.all(color: AppColor.white)),
                ),
                child: Text(
                  productModel.productNameType,
                  style: bodyStyle1.copyWith(
                      fontSize: 7.sp, color: AppColor.white),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
            //height * 0.026
            //width * 0.04
            Align(
              widthFactor: width * 0.42 / width * 12,
              child: Container(
                decoration: BoxDecoration(
                    color: AppColor.lightBlue,
                    borderRadius: BorderRadius.circular(30)),
                child: const FaIcon(
                  Icons.favorite_outline_rounded,
                  color: AppColor.white,
                ),
              ),
            ),
          ]),
          Text(
            productModel.productName,
            style: bodyStyle1.copyWith(color: AppColor.lightBlue),
          ),
          Text(
            productModel.productType,
            style: bodyStyle2.copyWith(fontSize: 11.sp, color: AppColor.grey),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${productModel.price}',
                style: bodyStyle1.copyWith(
                    fontSize: 12.sp,
                    color: AppColor.lightGreyHeader,
                    decoration: TextDecoration.lineThrough),
              ),
              Text(
                '${productModel.disPrice}',
                style: bodyStyle1.copyWith(
                  fontSize: 12.sp,
                  color: AppColor.black,
                ),
              ),
              percent != 0
                  ? Container(
                      width: 48.31,
                      height: 19,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20),
                          color: Colors.transparent,
                          border: Border.all(color: AppColor.lightBlue)),
                      child: Text(
                        '${percent.toStringAsFixed(0)}%',
                        style: bodyStyle2.copyWith(
                            fontSize: 9.sp, color: AppColor.lightBlue),
                        textAlign: TextAlign.center,
                      ),
                    )
                  : Container(),
            ],
          )
        ],
      ),
    );
  }
}
</code>```

how to solve the responsive positioned
and how to control the space between elements inside the row
i tired of try and try and can  not any soloution of that issue

Body:
This is The Result in tablet and phone the different is show

this is main design i build it

**How To Solve It **

this is my code in this design

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../../../../core/app_color.dart';
import '../../../../core/app_style.dart';
import '../../../../models/product_model.dart';

class ProductView extends StatelessWidget {
  ProductView({Key? key, required this.productModel}) : super(key: key);
  final ProductModel productModel;
  final ScrollController scrollController = ScrollController();
  final double _height = 100;

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    final double percent = (productModel.disPrice - productModel.price) /
        productModel.disPrice *
        100;
    return Container(
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(20),
      ),
      margin: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
      padding: const EdgeInsets.symmetric(
        horizontal: 8,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Stack(children: [
            Container(
              width: width * 0.42,
              height: height * 0.21,
              decoration: BoxDecoration(
                color: Colors.transparent,
                image: DecorationImage(
                  image: AssetImage(productModel.imageUrl),
                ),
              ),
            ),
            Positioned(
              bottom: height * 0.01,
              right: 0.0,
              child: Container(
                width: 48.31,
                height: 19,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: AppColor.lightBlue,
                  // border: Border.all(color: AppColor.white)),
                ),
                child: Text(
                  productModel.productNameType,
                  style: bodyStyle1.copyWith(
                      fontSize: 7.sp, color: AppColor.white),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
            //height * 0.026
            //width * 0.04
            Align(
              widthFactor: width * 0.42 / width * 12,
              child: Container(
                decoration: BoxDecoration(
                    color: AppColor.lightBlue,
                    borderRadius: BorderRadius.circular(30)),
                child: const FaIcon(
                  Icons.favorite_outline_rounded,
                  color: AppColor.white,
                ),
              ),
            ),
          ]),
          Text(
            productModel.productName,
            style: bodyStyle1.copyWith(color: AppColor.lightBlue),
          ),
          Text(
            productModel.productType,
            style: bodyStyle2.copyWith(fontSize: 11.sp, color: AppColor.grey),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${productModel.price}',
                style: bodyStyle1.copyWith(
                    fontSize: 12.sp,
                    color: AppColor.lightGreyHeader,
                    decoration: TextDecoration.lineThrough),
              ),
              Text(
                '${productModel.disPrice}',
                style: bodyStyle1.copyWith(
                  fontSize: 12.sp,
                  color: AppColor.black,
                ),
              ),
              percent != 0
                  ? Container(
                      width: 48.31,
                      height: 19,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20),
                          color: Colors.transparent,
                          border: Border.all(color: AppColor.lightBlue)),
                      child: Text(
                        '${percent.toStringAsFixed(0)}%',
                        style: bodyStyle2.copyWith(
                            fontSize: 9.sp, color: AppColor.lightBlue),
                        textAlign: TextAlign.center,
                      ),
                    )
                  : Container(),
            ],
          )
        ],
      ),
    );
  }
}

how to solve the responsive positioned
and how to control the space between elements inside the row
i tired of try and try and can  not any soloution of that issue


问:
Error when user enters time from keyboard
User enters time from keyboard. I have limited the keyboard so that the user can only type in the correct time. But still jumps into the else case from time to time (although when checking the input times are still correct). My app has users from many countries so I think there is a problem here.

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hhmma"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"

var AMorPMStart = ""
if startTimeAMPMSegment.selectedSegmentIndex == 1 {
    AMorPMStart = "PM"
}else {
    AMorPMStart = "AM"
}

var startDate = Date()

if let _ = dateFormatter.date(from: startDateHourString + startDateMinuteString + AMorPMStart) {
    startDate = dateFormatter.date(from: startDateHourString + startDateMinuteString + AMorPMStart)!
}else {
    AlertService.showInfoAlert(in: self, title: StringForLocal.error, message: StringForLocal.invalidStartTime)
    return
}
</code>```

I have tested a lot of time input cases but it seems to be wrong only for certain set of users. On my device everything is fine.

Body:
User enters time from keyboard. I have limited the keyboard so that the user can only type in the correct time. But still jumps into the else case from time to time (although when checking the input times are still correct). My app has users from many countries so I think there is a problem here.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hhmma"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"

var AMorPMStart = ""
if startTimeAMPMSegment.selectedSegmentIndex == 1 {
    AMorPMStart = "PM"
}else {
    AMorPMStart = "AM"
}

var startDate = Date()

if let _ = dateFormatter.date(from: startDateHourString + startDateMinuteString + AMorPMStart) {
    startDate = dateFormatter.date(from: startDateHourString + startDateMinuteString + AMorPMStart)!
}else {
    AlertService.showInfoAlert(in: self, title: StringForLocal.error, message: StringForLocal.invalidStartTime)
    return
}

I have tested a lot of time input cases but it seems to be wrong only for certain set of users. On my device everything is fine.


问:
How do you create a "Hello World" program with CMU_Graphics?
It starts with from cmu_graphics import * and ends with cmu_graphics.run(). I want it to display "Hello, World!" on the screen.

I've tried

```<code>from cmu_graphics import *
win = GraphWin("Hello, World", 300, 300)
text = Text(Point(150, 150), "Hello, World")
text.draw(win)
cmu_graphics.run()
</code>```

I got it from Google and I was expecting it to display "Hello, World"
Instead it gave the error

NameError: name 'GraphWin' is not defined
```

Body:
It starts with from cmu_graphics import * and ends with cmu_graphics.run(). I want it to display "Hello, World!" on the screen.

I've tried

from cmu_graphics import *
win = GraphWin("Hello, World", 300, 300)
text = Text(Point(150, 150), "Hello, World")
text.draw(win)
cmu_graphics.run()

I got it from Google and I was expecting it to display "Hello, World"
Instead it gave the error

NameError: name 'GraphWin' is not defined


问:
How to display the value that are caculated from two other metrics in GA4 in an explore report?
I can see the count of users with the explore report like this:

However, if I want to check out how much % of users are on mobile or desktop. There is no way to show that.

The current report might have very small and huge values because the visitor of the website is very unstable. But the % of the visitors should be a stable value.

Is it possible to create a metric, that the values in it equals mobile/total?


问:
Using delegates in Swift
I know that this may be tagged as a repeat question, but the ones that exist have not helped me implement delegates in Swift with SwiftUI. My issue can be see in the code below. I have a View and VM, TodaysVM. In here, I do a network request, that downloads movie data from an API, and saves the data to CoreData. In order to show graphs, the HabitVM needs to fetch the data from CoreData, and then do some long processing on it.

For this, I was looking into a way for one class to send a message notification to another class. So I stumbled onto using delegates (not sure if this is correct?). But essentially the idea would be that the TodayVM refreshes its data (which the user can do a pull to refresh on this page), it also sends a message to HabitsVM to start processing (so the data can be done by the time the user navigates to this page. I am not sure if there is a better way to do this, and I was trying to stay away from a singleton approach, passing one class into class, or creating a new instance of one of the classes.

In the code below, I have the delegates set up but 'print("Data update required!")' is never executed. From my research I understand this to be because I never set a value to the delegate? So the delegate value is nil, and therefore the

```<code>        delegate?.requireUpdate(status: true)
</code>```

Is never actually executed. Which makes sense, since delegate is an optional, but never assigned a value. So I was curious how I would assign it a value in SwiftUI? And if using delegates is even the best method to have to separate classes send updateRequired status updates.

```<code>import SwiftUI
import Foundation

// protocol
protocol MovieNotifierDelagate: AnyObject {
    func requireUpdate(status: Bool)
}

struct HabitView {
    @StateObject var habitVM = HabitsVM()

    var body: some View {
        Text("Hello")
    }
}

struct TodaysView {
    @StateObject var todayVM = TodayVM()
    var body: some View {
        Text("Hi!")
    }
}

class HabitsVM: ObservableObject, MovieNotifierDelagate {
    init() {

    }

    func requireUpdate(status: Bool) {
        print("Data update required!")
        reprocessData()
    }

    func reprocessData() {
        print("Processing")
    }
}

class TodayVM: ObservableObject {

    weak var delegate: MovieNotifierDelagate?

    init() {
        //Does some network call and downloads data, and saves to CoreData
        sendUpdate(status: true)
    }

    func sendUpdate(status: Bool) {
        guard status else {
            print ("No update")
            return
        }
        delegate?.requireUpdate(status: true)
    }
}

// Controlling Page
struct HomeView: View {
    //Default the user to the today view
    @State private var selection = 1

    var body: some View {
        TabView(selection: $selection) {
            HabitView()
                .tag(0)
                .tabItem {
                    VStack {
                        Image(systemName: "books.vertical")
                        Text("Habits")
                    }
                }
            TodaysView()
                .tag(1)
                .tabItem {
                    VStack {
                        Image(systemName: "backward.end.alt")
                        Text("Rewind")
                    }
                }
        }
    }
}
</code>```

Title: Using delegates in Swift

Body:
I know that this may be tagged as a repeat question, but the ones that exist have not helped me implement delegates in Swift with SwiftUI. My issue can be see in the code below. I have a View and VM, TodaysVM. In here, I do a network request, that downloads movie data from an API, and saves the data to CoreData. In order to show graphs, the HabitVM needs to fetch the data from CoreData, and then do some long processing on it.

For this, I was looking into a way for one class to send a message notification to another class. So I stumbled onto using delegates (not sure if this is correct?). But essentially the idea would be that the TodayVM refreshes its data (which the user can do a pull to refresh on this page), it also sends a message to HabitsVM to start processing (so the data can be done by the time the user navigates to this page. I am not sure if there is a better way to do this, and I was trying to stay away from a singleton approach, passing one class into class, or creating a new instance of one of the classes.

In the code below, I have the delegates set up but 'print("Data update required!")' is never executed. From my research I understand this to be because I never set a value to the delegate? So the delegate value is nil, and therefore the

        delegate?.requireUpdate(status: true)

Is never actually executed. Which makes sense, since delegate is an optional, but never assigned a value. So I was curious how I would assign it a value in SwiftUI? And if using delegates is even the best method to have to separate classes send updateRequired status updates.

import SwiftUI
import Foundation

// protocol
protocol MovieNotifierDelagate: AnyObject {
    func requireUpdate(status: Bool)
}

struct HabitView {
    @StateObject var habitVM = HabitsVM()

    var body: some View {
        Text("Hello")
    }
}

struct TodaysView {
    @StateObject var todayVM = TodayVM()
    var body: some View {
        Text("Hi!")
    }
}

class HabitsVM: ObservableObject, MovieNotifierDelagate {
    init() {

    }

    func requireUpdate(status: Bool) {
        print("Data update required!")
        reprocessData()
    }

    func reprocessData() {
        print("Processing")
    }
}

class TodayVM: ObservableObject {

    weak var delegate: MovieNotifierDelagate?

    init() {
        //Does some network call and downloads data, and saves to CoreData
        sendUpdate(status: true)
    }

    func sendUpdate(status: Bool) {
        guard status else {
            print ("No update")
            return
        }
        delegate?.requireUpdate(status: true)
    }
}

// Controlling Page
struct HomeView: View {
    //Default the user to the today view
    @State private var selection = 1

    var body: some View {
        TabView(selection: $selection) {
            HabitView()
                .tag(0)
                .tabItem {
                    VStack {
                        Image(systemName: "books.vertical")
                        Text("Habits")
                    }
                }
            TodaysView()
                .tag(1)
                .tabItem {
                    VStack {
                        Image(systemName: "backward.end.alt")
                        Text("Rewind")
                    }
                }
        }
    }
}


问:
MAT Histogram Objects count is not equal to Android Studio Profiler
I use Android Studio Profiler dump heap
the use hprof-conv to  convert the heap file into a standard format

$ANDROID_HOME/platform-tools/hprof-conv memory-20230112T162214.hprof memory-20230112T162214.conv.hprof

but the MAT Histogram Objects count is not equal Android Studio Profiler
for example
In Android Studio Profiler

byte[] count is 112915 = 82773 + 24578 + 5564

MAT  Histogram  display byte[] count 106251

Eclipse Memory Analyzer Version 1.13.0

Android Studio Profiler byte[] count is 112915

Android Studio Profiler parse conv hprof byte[] count 112915

MAT parse conv hprof Histogram  display byte[] count 106251

Android Studio version

but java.lang.Class count is euqal to 16661

I used OQL
select * from "byte[]"

result is 106251

how to fix the problem make Android Studio Profiler and MAT has same result, same Object count


问:
Disposed RSACng when using signing credential in a singleton
I'm trying to use pem certificate for signing tokens in the IdentityServer (where they are being passed into a singleton service).

public void ConfigureServices(IServiceCollection services)
{
    string rsaPrivateKeyString = @"-----BEGIN RSA PRIVATE KEY-----
... certificate content ...
-----END RSA PRIVATE KEY-----";

    using var rsa = RSA.Create();

    rsa.ImportFromPem(rsaPrivateKeyString);
    var rsaSecurityKey = new RsaSecurityKey(rsa);

    var signingCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
    {
        CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
    };

    services.AddIdentityServer()
        .identityServerBuilder.AddSigningCredential(signingCredentials);
}
```
<p>Whenever I try this approach, it throws an exception</p>
```System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'RSACng'.
at System.Security.Cryptography.CngAlgorithmCore.ThrowIfDisposed()
   at System.Security.Cryptography.CngAlgorithmCore.GetOrGenerateKey(Int32 keySize, CngAlgorithm algorithm)
   at System.Security.Cryptography.RSACng.get_Key()
   at System.Security.Cryptography.RSACng.SignHash(Byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
   at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.SignWithRsa(Byte[] bytes)
   at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.Sign(Byte[] bytes)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.Sign(Byte[] input)
   at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
...
```

I can get rid of the exception and things seem to work well when I remove the using clause from the rsa variable. I suppose it is then added to the singleton and will live for the lifetime of the service.

Is there any problem with this approach or is there any better solution how to avoid the disposed object exception or even other way to load the key?

Note: I'm reading the key from a secure store, it is pasted into the code for demonstration purposes only.

Body:
I'm trying to use pem certificate for signing tokens in the IdentityServer (where they are being passed into a singleton service).

public void ConfigureServices(IServiceCollection services)
{
    string rsaPrivateKeyString = @"-----BEGIN RSA PRIVATE KEY-----
... certificate content ...
-----END RSA PRIVATE KEY-----";

    using var rsa = RSA.Create();

    rsa.ImportFromPem(rsaPrivateKeyString);
    var rsaSecurityKey = new RsaSecurityKey(rsa);

    var signingCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
    {
        CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
    };

    services.AddIdentityServer()
        .identityServerBuilder.AddSigningCredential(signingCredentials);
}

Whenever I try this approach, it throws an exception

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'RSACng'.
at System.Security.Cryptography.CngAlgorithmCore.ThrowIfDisposed()
   at System.Security.Cryptography.CngAlgorithmCore.GetOrGenerateKey(Int32 keySize, CngAlgorithm algorithm)
   at System.Security.Cryptography.RSACng.get_Key()
   at System.Security.Cryptography.RSACng.SignHash(Byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
   at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.SignWithRsa(Byte[] bytes)
   at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.Sign(Byte[] bytes)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.Sign(Byte[] input)
   at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
...

I can get rid of the exception and things seem to work well when I remove the using clause from the rsa variable. I suppose it is then added to the singleton and will live for the lifetime of the service.

Is there any problem with this approach or is there any better solution how to avoid the disposed object exception or even other way to load the key?

Note: I'm reading the key from a secure store, it is pasted into the code for demonstration purposes only.


问:
Is there any way to console warning user when user imported a variable from my npm package?
In my package, one src file exported a variable for interal use, but user can access it from dist files  like import {xxx} from 'package/dist/xxx.js'

How to console a warning in browser devtool when user use it by the way like above?

Now my idea is use jsdoc '@deprecated' word to warn in code editor but can't warn in browser devtool.


问:
Cannot convert from method group to System.EventHandler. Changing handler signature shows error when dealing with appdomain
I have the following two programs
(1) Windows forms application
(2) ClassLibrary1.dll

In the winform, the dll is loaded using appdomain. The winform subscribes to the action('TestAction') in the dll. I am trying to access the value returned by the dll action and use it in the event handler('HandleAction'). To do this I created a child class that inherits EventArgs. I changed the input arguments of the event handler(HandleAction) accordingly. But I am seeing a compiler error at  Loader.Call( "RaiseAct", HandleAction, DateTime.Now.ToShortDateString()); . The error is:Cannot convert from method group to System.EventHandler

I have referred to other duplicates to this question, but they are not the same case. Any help will be very much appreciated. Thank you.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using ClassLibrary1;

namespace WindowsFormsApplication2
{
    [Serializable]
    public class IntEventArgs : EventArgs
    {
        public int data;
    }

    [Serializable]
    public partial class Form1 : Form
    {
        void HandleEvent(object sender, EventArgs e)
        {
            Debug.WriteLine("HandleEvent called");
        }
        void HandleAction(object sender, IntEventArgs e)
        {
            Debug.WriteLine("HandleAction called");
            Debug.WriteLine("the value of index is " + e.data);
        }
        public Form1()
        {
            InitializeComponent();
            Loader.Call(  "RaiseEvent", HandleEvent, DateTime.Now.ToShortDateString());
            Loader.Call( "RaiseAct", HandleAction, DateTime.Now.ToShortDateString()); // Cannot convert from method group to System.EventHandler
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Restart();
            Application.Run(new Form1());
            this.Close();
        }
    }

    public class Loader : MarshalByRefObject
    {
        static string dll = @"..\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
        static AppDomain ad = AppDomain.CreateDomain("Test");
        static Assembly a = Assembly.LoadFile(dll);
        static object o = a.CreateInstance("ClassLibrary1.Class1");
        static Type t = o.GetType();

        object CallInternal1( string method, EventHandler handler, object[] parameters)
        {
            // Subscribe to the event
            EventInfo eventInfo1 = t.GetEvent("TestEvent");
            eventInfo1.AddEventHandler(o, handler);

            MethodInfo m = t.GetMethod(method);
            return m.Invoke(o, parameters);
        }

        object CallInternal2( string method, EventHandler handler, object[] parameters)
        {

            // Subscribe to the event
            EventInfo eventInfo2 = t.GetEvent("TestAction");
            eventInfo2.AddEventHandler(o, new Action<int>((index) => handler(null, new IntEventArgs { data = index })));
            MethodInfo m = t.GetMethod(method);
            return m.Invoke(o, parameters);
        }

        public static object Call( string method, EventHandler handler, params object[] parameters)
        {
            Loader ld = (Loader)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Loader).FullName);
            object result = 0;
            switch (method)
            {
                case "RaiseEvent":
                    {
                        result = ld.CallInternal1( method, handler, parameters);
                        break;
                    }

                case "RaiseAct":
                    {
                        result = ld.CallInternal2( method, handler, parameters);
                        break;
                    }
            }
            return result;
        }
    }
}
</code>```

This ClassLibrary1.dll code

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    [Serializable]
    public class Class1
    {
        public event EventHandler TestEvent;

        public int RaiseEvent(string msg)
        {
            try
            {
                TestEvent(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                Console.WriteLine("the exception is: " + ex.ToString());
                if (ex.InnerException != null)
                {
                    Console.WriteLine("the inner exception is: " + ex.InnerException.Message.ToString());
                }
            }
            return 2;
        }

       public event Action<int> TestAction = Func;
        public int RaiseAct(string msg)
        {
            TestAction(3);
            return 5;
        }

        public static void Func(int a)
        {
            int g = 2;
        }

    }
}
</code>```

Body:
I have the following two programs
(1) Windows forms application
(2) ClassLibrary1.dll

In the winform, the dll is loaded using appdomain. The winform subscribes to the action('TestAction') in the dll. I am trying to access the value returned by the dll action and use it in the event handler('HandleAction'). To do this I created a child class that inherits EventArgs. I changed the input arguments of the event handler(HandleAction) accordingly. But I am seeing a compiler error at  Loader.Call( "RaiseAct", HandleAction, DateTime.Now.ToShortDateString()); . The error is:Cannot convert from method group to System.EventHandler

I have referred to other duplicates to this question, but they are not the same case. Any help will be very much appreciated. Thank you.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using ClassLibrary1;

namespace WindowsFormsApplication2
{
    [Serializable]
    public class IntEventArgs : EventArgs
    {
        public int data;
    }

    [Serializable]
    public partial class Form1 : Form
    {
        void HandleEvent(object sender, EventArgs e)
        {
            Debug.WriteLine("HandleEvent called");
        }
        void HandleAction(object sender, IntEventArgs e)
        {
            Debug.WriteLine("HandleAction called");
            Debug.WriteLine("the value of index is " + e.data);
        }
        public Form1()
        {
            InitializeComponent();
            Loader.Call(  "RaiseEvent", HandleEvent, DateTime.Now.ToShortDateString());
            Loader.Call( "RaiseAct", HandleAction, DateTime.Now.ToShortDateString()); // Cannot convert from method group to System.EventHandler
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Restart();
            Application.Run(new Form1());
            this.Close();
        }
    }

    public class Loader : MarshalByRefObject
    {
        static string dll = @"..\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
        static AppDomain ad = AppDomain.CreateDomain("Test");
        static Assembly a = Assembly.LoadFile(dll);
        static object o = a.CreateInstance("ClassLibrary1.Class1");
        static Type t = o.GetType();

        object CallInternal1( string method, EventHandler handler, object[] parameters)
        {
            // Subscribe to the event
            EventInfo eventInfo1 = t.GetEvent("TestEvent");
            eventInfo1.AddEventHandler(o, handler);

            MethodInfo m = t.GetMethod(method);
            return m.Invoke(o, parameters);
        }

        object CallInternal2( string method, EventHandler handler, object[] parameters)
        {

            // Subscribe to the event
            EventInfo eventInfo2 = t.GetEvent("TestAction");
            eventInfo2.AddEventHandler(o, new Action<int>((index) => handler(null, new IntEventArgs { data = index })));
            MethodInfo m = t.GetMethod(method);
            return m.Invoke(o, parameters);
        }

        public static object Call( string method, EventHandler handler, params object[] parameters)
        {
            Loader ld = (Loader)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Loader).FullName);
            object result = 0;
            switch (method)
            {
                case "RaiseEvent":
                    {
                        result = ld.CallInternal1( method, handler, parameters);
                        break;
                    }

                case "RaiseAct":
                    {
                        result = ld.CallInternal2( method, handler, parameters);
                        break;
                    }
            }
            return result;
        }
    }
}

This ClassLibrary1.dll code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    [Serializable]
    public class Class1
    {
        public event EventHandler TestEvent;

        public int RaiseEvent(string msg)
        {
            try
            {
                TestEvent(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                Console.WriteLine("the exception is: " + ex.ToString());
                if (ex.InnerException != null)
                {
                    Console.WriteLine("the inner exception is: " + ex.InnerException.Message.ToString());
                }
            }
            return 2;
        }

       public event Action<int> TestAction = Func;
        public int RaiseAct(string msg)
        {
            TestAction(3);
            return 5;
        }

        public static void Func(int a)
        {
            int g = 2;
        }

    }
}