问:
react-sidebar-pro FOUC in Next.JS
I using Sidebar Pro in Next.JS but like JS run before style is ready and then show the unstyled at first like this

i also had try to add

```<code>compiler: { styledComponents: true, }
</code>```

on next.config.js and add getInitialProps in _document like this
https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.tsx
but still not working.
please help me how to handle this, thanks before

btw i also submit the issue: https://github.com/azouaoui-med/react-pro-sidebar/issues/139

Title: react-sidebar-pro FOUC in Next.JS

Body:
I using Sidebar Pro in Next.JS but like JS run before style is ready and then show the unstyled at first like this

i also had try to add

compiler: { styledComponents: true, }

on next.config.js and add getInitialProps in _document like this
https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.tsx
but still not working.
please help me how to handle this, thanks before

btw i also submit the issue: https://github.com/azouaoui-med/react-pro-sidebar/issues/139


来源: stackexchange

问:
Canva like image placement using CSS/JavaScript (next level to masonry layout)

Why this question?

I have been doing research for ~2 months for this but couldn't find anything relevant so finally asking a question here.

Problem Statement

I'm looking to place a set of images with different sizes in a fixed-width container just like Canva does-

This is for sure not a masonry layout because here, Canva is bifurcating images into different rows based on some (?) calculation. What I was able to achieve is this-

This I achieved using https://masonry.desandro.com/ JS library, but it has its own limitations.

My Research

Based on my ~2 months of research, what Google has been telling me is that it's a masonry layout or it's 2D Bin Packing problem but I feel, it's not.

Canva is doing probably something very simple & intuitive (like explained here https://stackoverflow.com/a/14551767/2405040).

Libraries I found and tried

https://masonry.desandro.com/

https://spope.github.io/MiniMasonry.js/

https://github.com/desandro/masonry

https://isotope.metafizzy.co/

https://isotope.metafizzy.co/layout-modes/masonry.html

https://github.com/bigbite/macy.js

Links & blog posts

https://codeincomplete.com/articles/bin-packing/demo/

https://github.com/jakesgordon/bin-packing/

https://github.com/olragon/binpackingjs

How is 2D bin packing achieved programmatically?

Final Question

Is that something very unique, or is it some calculation? How can I achieve this Canva like layout programmatically?

ContentLicense: CC BY-SA 4.0


问:
Adding JEST custom reporter causes compilation error: Class extends value undefined is not a constructor or null
I'm trying to add a custom reporter for jest and I succeeded to make it work, but when import some of the project files it fails with this error

An error occurred while adding the reporter at path "...path/test-reporter/index.js".Class extends value undefined is not a constructor or null
at Object. (...path/country.model.ts:21:43)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (...path/node_modules/.pnpm/ts-node@8.10.2_typescript@3.9.10/node_modules/ts-node/src/index.ts:858:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions. [as .ts] (...path/node_modules/.pnpm/ts-node@8.10.2_typescript@3.9.10/node_modules/ts-node/src/index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:101:18)
at Object. (...path)

Here is the different config files:

test-reporter/index.js

```<code>require('reflect-metadata');
const tsNode = require('ts-node');
const tsConfigPaths = require("tsconfig-paths");
const path = require('path');

const tsconfigPath = path.join(__dirname, '../../tsconfig.json');
const tsconfig = require(tsconfigPath);

tsNode.register({
    compilerOptions: tsconfig.compilerOptions,
    transpileOnly: true,
});

tsConfigPaths.register({
    baseUrl: path.dirname(tsconfigPath),
    paths: tsconfig.compilerOptions.paths
});

module.exports = require('./test-reporter');
</code>```

test-reporter/test-reporter.ts

```<code>import { Reporter, TestContext } from '@jest/reporters';
import { AggregatedResult } from '@jest/test-result';
import { Config } from '@jest/types';
import config from '../config/config';
import { buildSchema } from 'type-graphql';
import {
    FundMutationResolver,
    FundQueryResolver,
} from '@src/investorPortal/funds/resolvers/app/fund.resolver';
type CustomReporter = Pick<Reporter, 'onRunComplete'>;

interface Options {
    useReporter: boolean;
}

export default class TestReporter implements CustomReporter {
    constructor(private config: Config.InitialOptions, private options: Options) {}

    async onRunComplete(context: Set<TestContext>, results: AggregatedResult) {
        console.log('Your report is available!');

        const schema = await buildSchema({
            resolvers: [FundMutationResolver, FundQueryResolver],
            authChecker: () => true,
        }); <-- Issue is when I add those lines
    }
}
</code>```

jest.config.js

```<code>module.exports = {
    globals: {
        'ts-jest': {
            tsconfig: 'tsconfig.json',
        },
    },
    preset: 'ts-jest',
    testEnvironment: 'node',
    resetModules: true,
    globalSetup: '<rootDir>/e2e/config/globalSetup.ts',
    setupFilesAfterEnv: ['<rootDir>/e2e/config/setupFile.ts'],
    reporters: ['default', '<rootDir>/e2e/test-reporter/index.js'],
    testMatch: ['**/e2e/**/*.test.ts'],
    rootDir: '.',
    transform: {
        '^.+\\.(t|j)s$': 'ts-jest',
    },
    moduleFileExtensions: ['js', 'json', 'ts'],
    moduleNameMapper: {
        '^@config/(.*)$': '<rootDir>/config/$1',
        '^@common/(.*)$': '<rootDir>/src/common/$1',
        '^@seed/(.*)$': '<rootDir>/lib/seed/$1',
        '^@src/(.*)$': '<rootDir>/src/$1',
        '^@services/(.*)$': '<rootDir>/services/$1',
        '^@lib/(.*)$': '<rootDir>/lib/$1',
        '^@tests-app/(.*)$': '<rootDir>/__tests/app/$1',
        '^@tests-admin/(.*)$': '<rootDir>/__tests/admin/$1',
        '^package.json$': '<rootDir>/package.json',
    },
    testTimeout: 100000,
};
</code>```

tsconfig.json

```<code>{
    "compilerOptions": {
        "preserveConstEnums": true,
        "strictNullChecks": true,
        "inlineSources": true,
        "inlineSourceMap": true,
        "sourceRoot": "/",
        "target": "ES6",
        "outDir": ".build",
        "module": "commonjs",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "lib": ["es2020", "DOM", "DOM.Iterable"],
        "rootDir": "./",
        "baseUrl": "./",
        "resolveJsonModule": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "skipLibCheck": true,
        "paths": {
            "@config/*": ["config/*"],
            "@common/*": ["src/common/*"],
            "@seed/*": ["lib/seed/*"],
            "@src/*": ["src/*"],
            "@services/*": ["services/*"],
            "@lib/*": ["lib/*"],
            "@tests-app/*": ["__tests/app/*"],
            "@tests-admin/*": ["__tests/admin/*"]
        }
    },
   ...
}
</code>```

I'm thinking the issue is related to relative paths, but no idea how to solve it.

Body:
I'm trying to add a custom reporter for jest and I succeeded to make it work, but when import some of the project files it fails with this error

An error occurred while adding the reporter at path "...path/test-reporter/index.js".Class extends value undefined is not a constructor or null
at Object. (...path/country.model.ts:21:43)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (...path/node_modules/.pnpm/ts-node@8.10.2_typescript@3.9.10/node_modules/ts-node/src/index.ts:858:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions. [as .ts] (...path/node_modules/.pnpm/ts-node@8.10.2_typescript@3.9.10/node_modules/ts-node/src/index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:101:18)
at Object. (...path)

Here is the different config files:

test-reporter/index.js

require('reflect-metadata');
const tsNode = require('ts-node');
const tsConfigPaths = require("tsconfig-paths");
const path = require('path');

const tsconfigPath = path.join(__dirname, '../../tsconfig.json');
const tsconfig = require(tsconfigPath);

tsNode.register({
    compilerOptions: tsconfig.compilerOptions,
    transpileOnly: true,
});

tsConfigPaths.register({
    baseUrl: path.dirname(tsconfigPath),
    paths: tsconfig.compilerOptions.paths
});

module.exports = require('./test-reporter');

test-reporter/test-reporter.ts

import { Reporter, TestContext } from '@jest/reporters';
import { AggregatedResult } from '@jest/test-result';
import { Config } from '@jest/types';
import config from '../config/config';
import { buildSchema } from 'type-graphql';
import {
    FundMutationResolver,
    FundQueryResolver,
} from '@src/investorPortal/funds/resolvers/app/fund.resolver';
type CustomReporter = Pick<Reporter, 'onRunComplete'>;

interface Options {
    useReporter: boolean;
}

export default class TestReporter implements CustomReporter {
    constructor(private config: Config.InitialOptions, private options: Options) {}

    async onRunComplete(context: Set<TestContext>, results: AggregatedResult) {
        console.log('Your report is available!');

        const schema = await buildSchema({
            resolvers: [FundMutationResolver, FundQueryResolver],
            authChecker: () => true,
        }); <-- Issue is when I add those lines
    }
}

jest.config.js

module.exports = {
    globals: {
        'ts-jest': {
            tsconfig: 'tsconfig.json',
        },
    },
    preset: 'ts-jest',
    testEnvironment: 'node',
    resetModules: true,
    globalSetup: '<rootDir>/e2e/config/globalSetup.ts',
    setupFilesAfterEnv: ['<rootDir>/e2e/config/setupFile.ts'],
    reporters: ['default', '<rootDir>/e2e/test-reporter/index.js'],
    testMatch: ['**/e2e/**/*.test.ts'],
    rootDir: '.',
    transform: {
        '^.+\\.(t|j)s$': 'ts-jest',
    },
    moduleFileExtensions: ['js', 'json', 'ts'],
    moduleNameMapper: {
        '^@config/(.*)$': '<rootDir>/config/$1',
        '^@common/(.*)$': '<rootDir>/src/common/$1',
        '^@seed/(.*)$': '<rootDir>/lib/seed/$1',
        '^@src/(.*)$': '<rootDir>/src/$1',
        '^@services/(.*)$': '<rootDir>/services/$1',
        '^@lib/(.*)$': '<rootDir>/lib/$1',
        '^@tests-app/(.*)$': '<rootDir>/__tests/app/$1',
        '^@tests-admin/(.*)$': '<rootDir>/__tests/admin/$1',
        '^package.json$': '<rootDir>/package.json',
    },
    testTimeout: 100000,
};

tsconfig.json

{
    "compilerOptions": {
        "preserveConstEnums": true,
        "strictNullChecks": true,
        "inlineSources": true,
        "inlineSourceMap": true,
        "sourceRoot": "/",
        "target": "ES6",
        "outDir": ".build",
        "module": "commonjs",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "lib": ["es2020", "DOM", "DOM.Iterable"],
        "rootDir": "./",
        "baseUrl": "./",
        "resolveJsonModule": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "skipLibCheck": true,
        "paths": {
            "@config/*": ["config/*"],
            "@common/*": ["src/common/*"],
            "@seed/*": ["lib/seed/*"],
            "@src/*": ["src/*"],
            "@services/*": ["services/*"],
            "@lib/*": ["lib/*"],
            "@tests-app/*": ["__tests/app/*"],
            "@tests-admin/*": ["__tests/admin/*"]
        }
    },
   ...
}

I'm thinking the issue is related to relative paths, but no idea how to solve it.


问:
Invalid argument error when using f string in path of DataFrame.to_csv()
I want to write pandas dataframe to a csv file every 10 secs. The csv file name includes the current timestamp. Here is part of the code:

```<code>import pandas as pd
import time

while True:
    df = pd.read_sql_query('select * from dbo.tbl_tag_values', cnxn)
    t = time.localtime()
    current_time = time.strftime('%Y-%m-%dT%H:%M:%S',t)
    csv_path =f'C:/Users/00_Projects/App/data-{current_time}.csv'
    df.to_csv(csv_path)
    time.sleep(10)
</code>```

Without using f-string and a static file name, the script works fine but with the f-string I get the error:

```<code>Traceback (most recent call last):
  File "c:\Users\00_Projects\App\script.py", line 24, in <module>
    df.to_csv(csv_path)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 3466, in to_csv
    return DataFrameRenderer(formatter).to_csv(
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\format.py", line 1105, in to_csv
    csv_formatter.save()
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py", line 237, in save
    with get_handle(
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\common.py", line 702, in get_handle
    handle = open(
OSError: [Errno 22] Invalid argument: 'C:/Users/00_Projects/App/data-2023-01-02T15:33:19.csv'
</code>```

I read this post How to use f string in a path location and tried Path from pathlib but got the same error.
My OS is windows.

Thanks for any help!

Body:
I want to write pandas dataframe to a csv file every 10 secs. The csv file name includes the current timestamp. Here is part of the code:

import pandas as pd
import time

while True:
    df = pd.read_sql_query('select * from dbo.tbl_tag_values', cnxn)
    t = time.localtime()
    current_time = time.strftime('%Y-%m-%dT%H:%M:%S',t)
    csv_path =f'C:/Users/00_Projects/App/data-{current_time}.csv'
    df.to_csv(csv_path)
    time.sleep(10)

Without using f-string and a static file name, the script works fine but with the f-string I get the error:

Traceback (most recent call last):
  File "c:\Users\00_Projects\App\script.py", line 24, in <module>
    df.to_csv(csv_path)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 3466, in to_csv
    return DataFrameRenderer(formatter).to_csv(
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\format.py", line 1105, in to_csv
    csv_formatter.save()
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py", line 237, in save
    with get_handle(
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\common.py", line 702, in get_handle
    handle = open(
OSError: [Errno 22] Invalid argument: 'C:/Users/00_Projects/App/data-2023-01-02T15:33:19.csv'

I read this post How to use f string in a path location and tried Path from pathlib but got the same error.
My OS is windows.

Thanks for any help!


问:
Why my progress bar disappears after printing on Mozilla Firefox
I've this CV online, and when I want to print it on Chrome, everything is fine, but in mozilla, some colours disappear and mainly the progress bars.

I'm using this tool:

```<code>import { ProgressBar } from 'react-bootstrap';
</code>```

The css

```<code>/* skills */
.progress {
    width: 60%;
    background-color:var(--progressbar-background-color) !important;
}

@media(width < 450px) {
    .progress {
        width: 70%;
    }
}

.progress-bar, ::-webkit-progress-bar, ::-moz-progress-bar {
    background-color:var(--highlight-color) !important;
}
</code>```

Can somebody help me ?
Thank u

Body:
I've this CV online, and when I want to print it on Chrome, everything is fine, but in mozilla, some colours disappear and mainly the progress bars.

I'm using this tool:

import { ProgressBar } from 'react-bootstrap';

The css

/* skills */
.progress {
    width: 60%;
    background-color:var(--progressbar-background-color) !important;
}

@media(width < 450px) {
    .progress {
        width: 70%;
    }
}

.progress-bar, ::-webkit-progress-bar, ::-moz-progress-bar {
    background-color:var(--highlight-color) !important;
}

Can somebody help me ?
Thank u


问:
pdfkit - firebase functions - node 16
I have currently 10 working functions in my firebase:functions. Now I try to create a pdf inside a rtdb-trigger-function. The problem is, as soon as I require pdfkit:

```<code>const pdfkit = require('pdfkit');
</code>```

All of my functions can not be updated:
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.

I installed pdfkit via npm: npm install pdfkit
This is the output:

```<code>npm WARN old lockfile
npm WARN old lockfile The package-lock.json file was created with an old version of npm,
npm WARN old lockfile so supplemental metadata must be fetched from the registry.
npm WARN old lockfile
npm WARN old lockfile This is a one-time fix-up, please be patient...
npm WARN old lockfile

up to date, audited 465 packages in 2s

52 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

</code>```

This is my package.json:

```<code>{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "dependencies": {
    "busboy-firebase": "^1.0.7",
    "check-node-version": "^4.2.1",
    "firebase-admin": "^11.4.1",
    "firebase-functions": "^4.1.1",
    "mailgun": "^0.5.0",
    "node": "^16.1.0",
    "node-fetch": "^2.6.1",
    "nodemailer": "^6.6.1"
  },
  "devDependencies": {
    "@google-cloud/tasks": "^2.1.2",
    "@types/pdfkit": "^0.12.8",
    "busboy": "^1.6.0",
    "cors": "^2.8.5",
    "eslint": "^5.12.0",
    "eslint-plugin-promise": "^4.0.1",
    "firebase-functions-test": "^0.1.6",
    "pdfkit": "^0.13.0"
  },
  "private": true
}
</code>```

What is wrong?

Thank you!

This is what I did:

Try node version 10,12,14,16

Installed node 16.4.0

npm install pdfkit

Title: pdfkit - firebase functions - node 16

Body:
I have currently 10 working functions in my firebase:functions. Now I try to create a pdf inside a rtdb-trigger-function. The problem is, as soon as I require pdfkit:

const pdfkit = require('pdfkit');

All of my functions can not be updated:
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.

I installed pdfkit via npm: npm install pdfkit
This is the output:

npm WARN old lockfile
npm WARN old lockfile The package-lock.json file was created with an old version of npm,
npm WARN old lockfile so supplemental metadata must be fetched from the registry.
npm WARN old lockfile
npm WARN old lockfile This is a one-time fix-up, please be patient...
npm WARN old lockfile

up to date, audited 465 packages in 2s

52 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

This is my package.json:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "dependencies": {
    "busboy-firebase": "^1.0.7",
    "check-node-version": "^4.2.1",
    "firebase-admin": "^11.4.1",
    "firebase-functions": "^4.1.1",
    "mailgun": "^0.5.0",
    "node": "^16.1.0",
    "node-fetch": "^2.6.1",
    "nodemailer": "^6.6.1"
  },
  "devDependencies": {
    "@google-cloud/tasks": "^2.1.2",
    "@types/pdfkit": "^0.12.8",
    "busboy": "^1.6.0",
    "cors": "^2.8.5",
    "eslint": "^5.12.0",
    "eslint-plugin-promise": "^4.0.1",
    "firebase-functions-test": "^0.1.6",
    "pdfkit": "^0.13.0"
  },
  "private": true
}

What is wrong?

Thank you!

This is what I did:

Try node version 10,12,14,16

Installed node 16.4.0

npm install pdfkit


问:
Need help finding the best time performing lines of code to replace existing-working code
The question is very straight forward. Content here is information collected during the run of an interconnected system. I simplified functions to emphasise the bottlenecks from line_profiler into three dependend functions objectively similar to real code.

As of now it seems all lines are mandatory, but I refuse to believe this. I did try simplifying logical parts with .all() and .any() but either I am not proficient in Python, or I keep running into a bizarre limitation; just keep giving me a different result than expected.

If you are unable to gather full use case of the 3 functions, try to comprehend on a purely syntactic manner (while at least preserving same number of variables) and provide a usable solution to achieve the same functionality.

```<code>Total time: 419.632 s
File: switch_array_logic.py
Function: func_A at line 336

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   336                                           @profile
   337                                           def func_A(_switch,_loc,_prev_state=None,_cur_state=None,bulb_on=True):
   338  43048749   27529633.0      0.6      6.6      if bulb_on:
   339  43048651   43186202.0      1.0     10.3          _p_cur_state = _switch[_loc][2]
   340  43048651   42282929.0      1.0     10.1          _p_prev_state = _switch[_loc-1][2]
   341                                               else:
   342        98         80.0      0.8      0.0          _p_prev_state = _prev_state
   343        98         54.0      0.6      0.0          _p_cur_state = _cur_state
   348  43048749   38735332.0      0.9      9.2      cond_11 = (_p_cur_state >= 0)
   349  43048749   35887392.0      0.8      8.6      cond_10 = (_p_cur_state < 0)
   350  43048749   34747819.0      0.8      8.3      cond_00 = (_p_prev_state < 0)
   351  43048749   34685101.0      0.8      8.3      cond_01 = (_p_prev_state > 0)
   352
   353  43048749   24860540.0      0.6      5.9      cond_x = cond_00 and cond_11
   354  43048749   24083554.0      0.6      5.7      cond_y = cond_10 and cond_01
   355  43048749   24902602.0      0.6      5.9      condition = cond_x or cond_y
   356
   357  43048749   23279349.0      0.5      5.5      _brighness = 0
   358  43048749   23704315.0      0.6      5.6      if condition:
   359  21573867   18852346.0      0.9      4.5          _brighness = _p_prev_state/2
   360  43048749   22894531.0      0.5      5.5      return _brighness

Total time: 66.9593 s
File: switch_array_logic.py
Function: func_B at line 362

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   362                                           @profile
   363                                           def func_B(_switch,_pos,_loc,_brighness):
   364  43638012   66959275.0      1.5    100.0      return _switch[_pos][3] - _switch[_loc][3] - _brighness

Total time: 9.59384 s
File: switch_array_logic.py
Function: func_C at line 378

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   378                                           @profile
   379                                           def func_C(_switchs_slice,_valid,_PH_LEVEL):
   380    114012      82093.0      0.7      0.9      _idx = 0
   381    114012    2403035.0     21.1     25.0      _brighness = func_A(_switchs_slice,_idx+1)
   382    809223     583712.0      0.7      6.1      for _pos in range(1, _switchs_slice.shape[0]):
   383    808216     831149.0      1.0      8.7          if _valid and _switchs_slice[_idx][0] < _switchs_slice[_pos][0]:
   385     57307      44704.0      0.8      0.5              return False,_pos
   386    750909    1686519.0      2.2     17.6          elif ~_valid and _switchs_slice[_idx][1] > _switchs_slice[_pos][1]:
   388     47536      41899.0      0.9      0.4              return False,_pos
   389    703373    3320805.0      4.7     34.6          _ph_out = func_B(_switchs_slice,_pos,_idx,_brighness)
   391    703373     592597.0      0.8      6.2          if abs(_ph_out)  > _PH_LEVEL[1] :
   393      8162       6334.0      0.8      0.1              return True, _pos #Successful Case
   395      1007        990.0      1.0      0.0      return False,_switchs_slice.shape[0]

</code>```

Additionally, as I am not familiar with Cython, but can someone try to provide an optimised version of this in Cython in answers really appreciate it. Not sure we will use it in the code. But I would very much like to see performance disparity.

Thanks in advance!

Body:
The question is very straight forward. Content here is information collected during the run of an interconnected system. I simplified functions to emphasise the bottlenecks from line_profiler into three dependend functions objectively similar to real code.

As of now it seems all lines are mandatory, but I refuse to believe this. I did try simplifying logical parts with .all() and .any() but either I am not proficient in Python, or I keep running into a bizarre limitation; just keep giving me a different result than expected.

If you are unable to gather full use case of the 3 functions, try to comprehend on a purely syntactic manner (while at least preserving same number of variables) and provide a usable solution to achieve the same functionality.

Total time: 419.632 s
File: switch_array_logic.py
Function: func_A at line 336

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   336                                           @profile
   337                                           def func_A(_switch,_loc,_prev_state=None,_cur_state=None,bulb_on=True):
   338  43048749   27529633.0      0.6      6.6      if bulb_on:
   339  43048651   43186202.0      1.0     10.3          _p_cur_state = _switch[_loc][2]
   340  43048651   42282929.0      1.0     10.1          _p_prev_state = _switch[_loc-1][2]
   341                                               else:
   342        98         80.0      0.8      0.0          _p_prev_state = _prev_state
   343        98         54.0      0.6      0.0          _p_cur_state = _cur_state
   348  43048749   38735332.0      0.9      9.2      cond_11 = (_p_cur_state >= 0)
   349  43048749   35887392.0      0.8      8.6      cond_10 = (_p_cur_state < 0)
   350  43048749   34747819.0      0.8      8.3      cond_00 = (_p_prev_state < 0)
   351  43048749   34685101.0      0.8      8.3      cond_01 = (_p_prev_state > 0)
   352
   353  43048749   24860540.0      0.6      5.9      cond_x = cond_00 and cond_11
   354  43048749   24083554.0      0.6      5.7      cond_y = cond_10 and cond_01
   355  43048749   24902602.0      0.6      5.9      condition = cond_x or cond_y
   356
   357  43048749   23279349.0      0.5      5.5      _brighness = 0
   358  43048749   23704315.0      0.6      5.6      if condition:
   359  21573867   18852346.0      0.9      4.5          _brighness = _p_prev_state/2
   360  43048749   22894531.0      0.5      5.5      return _brighness

Total time: 66.9593 s
File: switch_array_logic.py
Function: func_B at line 362

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   362                                           @profile
   363                                           def func_B(_switch,_pos,_loc,_brighness):
   364  43638012   66959275.0      1.5    100.0      return _switch[_pos][3] - _switch[_loc][3] - _brighness

Total time: 9.59384 s
File: switch_array_logic.py
Function: func_C at line 378

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
   378                                           @profile
   379                                           def func_C(_switchs_slice,_valid,_PH_LEVEL):
   380    114012      82093.0      0.7      0.9      _idx = 0
   381    114012    2403035.0     21.1     25.0      _brighness = func_A(_switchs_slice,_idx+1)
   382    809223     583712.0      0.7      6.1      for _pos in range(1, _switchs_slice.shape[0]):
   383    808216     831149.0      1.0      8.7          if _valid and _switchs_slice[_idx][0] < _switchs_slice[_pos][0]:
   385     57307      44704.0      0.8      0.5              return False,_pos
   386    750909    1686519.0      2.2     17.6          elif ~_valid and _switchs_slice[_idx][1] > _switchs_slice[_pos][1]:
   388     47536      41899.0      0.9      0.4              return False,_pos
   389    703373    3320805.0      4.7     34.6          _ph_out = func_B(_switchs_slice,_pos,_idx,_brighness)
   391    703373     592597.0      0.8      6.2          if abs(_ph_out)  > _PH_LEVEL[1] :
   393      8162       6334.0      0.8      0.1              return True, _pos #Successful Case
   395      1007        990.0      1.0      0.0      return False,_switchs_slice.shape[0]

Additionally, as I am not familiar with Cython, but can someone try to provide an optimised version of this in Cython in answers really appreciate it. Not sure we will use it in the code. But I would very much like to see performance disparity.

Thanks in advance!


问:
Cloud SQL Server on GCP is recreating if I am changing the root password in teraform
I'm using Terraform to create a cloud SQL Server and specify its root password. When I use Terraform to change the root password for the same instance, it initially deletes the instance and then creates a new one with the new root password, which is not how it should work.

However, whether I use the console or the gcloud api to perform the same action. It enables me to modify the server's existing password.


问:
Docker on windows generates different image layer id for COPY command
Environment:
Docker on windows
Code in questions:  COPY configure_my_app.bat .

Expected:  If I run docker build multiple times, I expect the image id to be same from various runs on docker build, given that there is no change in the Dockerfile

What happens: The image id after the above command changes for each run of docker build

I read it somewhere a while ago that this might have something to do with file attributes/permissions. I wonder, how can I get around this ? I want to use layers from cache if Dockerfile is not changed.


问:
Xamarin forms SignalR Notifications background service when app is closed
I'm building a Xamarin Forms App that uses SignalR to notify a user when there's a new post. I am currently using the LocalNotication Plugin, It works great when the App is in the background using a simulator. However, when  I kill the App(Swipe up) on the simulator, the SignalR disconnects, and I don't get Notifications anymore. How can I achieve something similar to WhatsApp and Instagram, basically being able to receive notifications even when the App is dead? I was thinking of Shiny 2.0 but not sure if I can receive notifications when App is not running.</p>


问:
I'm trying to reset the admin password I'm the admin panel
I'm using the django admin panel with jazzmin theme,  I have created a link to reset the admin password after the reset is complete and trying to login in again.
I got redirect to this  path
/account/profile/
There is no current url with this path

I,m expecting to be redirect to the admin panel


问:
Wcnf dimacs how to get the value with highest weight
Let's say i have this problem and wanted to solve it using dimacs and maxsat solvers

There's 10 police patrols and i want solver to pick the best police patrol to go to intervention, each patrol is described by 3 variables (status, distance, districts)
so there will be 3 group of clauses

for example first patrol will be PP1 = x1,x11,x21, PP2 = x2,x12,x22 PP3 = x3,x13,x23 .. PP10 = x10,x20,x30

group 1 describing police patrol status, (300 means weight)

```<code>300 C1 - (x1 v x2 v x3)
50 C2 - (x4 v x5)
10 C3 - (x6 v x7 v x8 v x9 v x10)
</code>```

C1 means their status is the best and C3 means it's the worst

group 2 describing police patrol distance to some incident or crime happening

```<code>300 C4 -  (x11 v x12 v x13)
50 C5 - (x14 v x15)
10 C6 - (x16 v x17 v x18 v x19 v x20 )
</code>```

C4 means they are the closest to incident, in C6 they are farthest

group 3 describing in what district they are

```<code>300 C7 - (x21 v x22 v x23)
50 C8 - (x24 v x25)
10 C9 - (x26 v x27 v x28 v x29 v x30)
</code>```

C7 will be the safest etc.

So this is my wcnf file in dimacs, i don't know if it's good but will be pleased if you correct me what's wrong with it

```<code>p wcnf 30 9
300 1 2 3 0
50 4 5 0
10 6 7 8 9 10 0
300 20 11 14 0
50 15 16 17 0
10 12 13 18 19 0
300 29 21 27 0
50 22 23 24 25 0
10 26 28 30 0
</code>```

I tested it in 2 solvers, rc2 maxsat solver and EvalMaxSAT and output was like this:

```<code>EvalMaxSAT
s OPTIMUM FOUND
o 0
v -1 2 -3 4 -5 6 -7 -8 -9 -10 11 12 -13 -14 15 -16 -17 -18 -19 -20 21 22 -23 -24 -25 26 -27 -28 -29 -30
c Total time: 335 µs
-

rc2
c formula: 30 vars, 0 hard, 9 soft
s OPTIMUM FOUND
o 0
v 1 -2 -3 4 -5 6 -7 -8 -9 -10 11 12 -13 -14 15 -16 -17 -18 -19 -20 21 22 -23 -24 -25 26 -27 -28 -29 -30
</code>```

but looking at my wcnf file, I think ideal output should get values 1,11,21 as true because they are in the clauses with highest weight

Body:
Let's say i have this problem and wanted to solve it using dimacs and maxsat solvers

There's 10 police patrols and i want solver to pick the best police patrol to go to intervention, each patrol is described by 3 variables (status, distance, districts)
so there will be 3 group of clauses

for example first patrol will be PP1 = x1,x11,x21, PP2 = x2,x12,x22 PP3 = x3,x13,x23 .. PP10 = x10,x20,x30

group 1 describing police patrol status, (300 means weight)

300 C1 - (x1 v x2 v x3)
50 C2 - (x4 v x5)
10 C3 - (x6 v x7 v x8 v x9 v x10)

C1 means their status is the best and C3 means it's the worst

group 2 describing police patrol distance to some incident or crime happening

300 C4 -  (x11 v x12 v x13)
50 C5 - (x14 v x15)
10 C6 - (x16 v x17 v x18 v x19 v x20 )

C4 means they are the closest to incident, in C6 they are farthest

group 3 describing in what district they are

300 C7 - (x21 v x22 v x23)
50 C8 - (x24 v x25)
10 C9 - (x26 v x27 v x28 v x29 v x30)

C7 will be the safest etc.

So this is my wcnf file in dimacs, i don't know if it's good but will be pleased if you correct me what's wrong with it

p wcnf 30 9
300 1 2 3 0
50 4 5 0
10 6 7 8 9 10 0
300 20 11 14 0
50 15 16 17 0
10 12 13 18 19 0
300 29 21 27 0
50 22 23 24 25 0
10 26 28 30 0

I tested it in 2 solvers, rc2 maxsat solver and EvalMaxSAT and output was like this:

EvalMaxSAT
s OPTIMUM FOUND
o 0
v -1 2 -3 4 -5 6 -7 -8 -9 -10 11 12 -13 -14 15 -16 -17 -18 -19 -20 21 22 -23 -24 -25 26 -27 -28 -29 -30
c Total time: 335 µs
-

rc2
c formula: 30 vars, 0 hard, 9 soft
s OPTIMUM FOUND
o 0
v 1 -2 -3 4 -5 6 -7 -8 -9 -10 11 12 -13 -14 15 -16 -17 -18 -19 -20 21 22 -23 -24 -25 26 -27 -28 -29 -30

but looking at my wcnf file, I think ideal output should get values 1,11,21 as true because they are in the clauses with highest weight


问:
VS 2022 - Add multi language code summaries
I'm currently working on a growing shared codebase.

I'd like to add method summaries (XML comments) in multiple languages - the codebase has been used by Italian programmers until today, but it's now becoming international.

I'd like to mantain existing summaries (written in Italian) and adding English ones. Is there a way?

At the moment it has been done as follow:

```<code>    /// <summary>
    /// EN Provides access to database-related methods to simplify connection and data operations.
    /// IT Fornisce accesso a metodi relativi a database per semplificare connessione ed operazioni sui dati.
    /// </summary>

    public class DatabaseHelper
    {
        /// ...
    }
</code>```

I wonder if there's a more professional way - just like base class library members (they are commented by Intellisense in the IDE selected language).

Body:
I'm currently working on a growing shared codebase.

I'd like to add method summaries (XML comments) in multiple languages - the codebase has been used by Italian programmers until today, but it's now becoming international.

I'd like to mantain existing summaries (written in Italian) and adding English ones. Is there a way?

At the moment it has been done as follow:

    ///
    /// EN Provides access to database-related methods to simplify connection and data operations.
    /// IT Fornisce accesso a metodi relativi a database per semplificare connessione ed operazioni sui dati.
    ///

    public class DatabaseHelper
    {
        /// ...
    }

I wonder if there's a more professional way - just like base class library members (they are commented by Intellisense in the IDE selected language).


问:
problem when loading a keras model saved through a wrapper class
I have the following wrapper class:

```<code>from tensorflow.keras.models import Sequential
class NeuralNet(Sequential):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
</code>```

I can fit and save the model without problems, but when I try to load it:

```<code>from tensorflow.keras.models import load_model
model = load_model('model.h5')
</code>```

I get:

```<code>--> 296     raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    297
    298   cls_config = config['config']

ValueError: Unknown layer: NeuralNet
</code>```

I'd like to find a way to solve this error keeping the wrapper class.

Body:
I have the following wrapper class:

from tensorflow.keras.models import Sequential
class NeuralNet(Sequential):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

I can fit and save the model without problems, but when I try to load it:

from tensorflow.keras.models import load_model
model = load_model('model.h5')

I get:

--> 296     raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    297
    298   cls_config = config['config']

ValueError: Unknown layer: NeuralNet

I'd like to find a way to solve this error keeping the wrapper class.


问:
How to set up a mobile webserver with reverse SSH and a reverse proxy?
I’m trying to host an apache webserver on a phone with termux, and the final goal is to make this server mobile by using 4G.To achieve this I thought it was possible to use a reverse SSH connection (to set a connection from the phone, wherever he is on internet) to a proxy in my home. The DNS of my website will redirect to this (reverse) proxy, which will redirect to my phone webserver, by using the reverse SSH connection.
For now, the phone server is on the same wifi network as the proxy, not in 4G.
So this phone connects to a computer which acts as a proxy, by connecting with reverse SSH on port 8082. From this computer, when I search http://localhost:8082 on internet on the computer, it works, I have access to the website.
However I can’t access the website from another device on the local network or from internet (I tried http://IPproxyComputer:8082 and I tried from a device on internet http://MyPublicIP with a port redirection from 80 to IPproxyComputer :8082 on my router). I don’t have any firewall on.
Here is a diagram to clarify

I didn’t find anyone trying to host a webserver with this config but someone explain how to give access to a device with reverse SSH and a squid proxy here.
So I thought this is what I must do, but with a different configuration for Squid because in my case, the request comes from someone on internet or local network to the webserver, so Squid must listen on a port, let say 8081 and redirect to 8082 where the SSH  connection is, but I failed to set this up.

I need help to undersand two things:
-Why is the page accessible from the proxy with http://localhost:8082, but not from a device on the local network with http://IpproxyComputer:8082 ? Is it because of an authorization (and is it possible to change it?). Or is it just impossible to do this kind of connection ?

Is it a solution to use squid ? How to set this up ?

Here is the reverse SSH command I used from the phone webserver :

```<code>ssh -R 8080:localhost:8081 UsrProxyComputer@IPproxyComputer
</code>```

Here is the config I tried for squid (it is the first time I use it and I am really a beginner in networks)

```<code> Define the listening port and default site
# Declare that virtual hosts will be used for allowing the reverse proxy
http_port 8081 accel vhost

# First we will configure the servers in our system
cache_peer 127.0.0.1 parent 8082 0 proxy-only name=InterRedir

# Create an additional ACL for local network access
acl localip src 192.168.0.0/24
http_access allow localip
cache_peer_access InterRedir allow localip

# Next we will map domains to the specific systems
# 1) This is done by creating an ACL for the domain
# 2) Then granting http access to it to allow the connection
# to get through.
# 3) Then mapping an acl to the specific server

# MyWebSite.com
acl MyWebSite_acl dstdomain MyWebSite.Com
http_access allow MyWebSite_acl
cache_peer_access InterRedir allow MyWebSite_acl

# Additional ACL definitions
acl all src all
acl manager proto cache_object
acl localhost src 127.0.0.1/32
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32
acl purge method PURGE
acl CONNECT method CONNECT

# Restrictions
http_access allow manager localhost
http_access deny manager
http_access allow purge localhost
http_access deny purge
http_access deny all

# Disable caching
cache deny all
</code>```

Body:
I’m trying to host an apache webserver on a phone with termux, and the final goal is to make this server mobile by using 4G.To achieve this I thought it was possible to use a reverse SSH connection (to set a connection from the phone, wherever he is on internet) to a proxy in my home. The DNS of my website will redirect to this (reverse) proxy, which will redirect to my phone webserver, by using the reverse SSH connection.
For now, the phone server is on the same wifi network as the proxy, not in 4G.
So this phone connects to a computer which acts as a proxy, by connecting with reverse SSH on port 8082. From this computer, when I search http://localhost:8082 on internet on the computer, it works, I have access to the website.
However I can’t access the website from another device on the local network or from internet (I tried http://IPproxyComputer:8082 and I tried from a device on internet http://MyPublicIP with a port redirection from 80 to IPproxyComputer :8082 on my router). I don’t have any firewall on.
Here is a diagram to clarify

I didn’t find anyone trying to host a webserver with this config but someone explain how to give access to a device with reverse SSH and a squid proxy here.
So I thought this is what I must do, but with a different configuration for Squid because in my case, the request comes from someone on internet or local network to the webserver, so Squid must listen on a port, let say 8081 and redirect to 8082 where the SSH  connection is, but I failed to set this up.

I need help to undersand two things:
-Why is the page accessible from the proxy with http://localhost:8082, but not from a device on the local network with http://IpproxyComputer:8082 ? Is it because of an authorization (and is it possible to change it?). Or is it just impossible to do this kind of connection ?

Is it a solution to use squid ? How to set this up ?

Here is the reverse SSH command I used from the phone webserver :

ssh -R 8080:localhost:8081 UsrProxyComputer@IPproxyComputer

Here is the config I tried for squid (it is the first time I use it and I am really a beginner in networks)

 Define the listening port and default site
# Declare that virtual hosts will be used for allowing the reverse proxy
http_port 8081 accel vhost

# First we will configure the servers in our system
cache_peer 127.0.0.1 parent 8082 0 proxy-only name=InterRedir

# Create an additional ACL for local network access
acl localip src 192.168.0.0/24
http_access allow localip
cache_peer_access InterRedir allow localip

# Next we will map domains to the specific systems
# 1) This is done by creating an ACL for the domain
# 2) Then granting http access to it to allow the connection
# to get through.
# 3) Then mapping an acl to the specific server

# MyWebSite.com
acl MyWebSite_acl dstdomain MyWebSite.Com
http_access allow MyWebSite_acl
cache_peer_access InterRedir allow MyWebSite_acl

# Additional ACL definitions
acl all src all
acl manager proto cache_object
acl localhost src 127.0.0.1/32
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32
acl purge method PURGE
acl CONNECT method CONNECT

# Restrictions
http_access allow manager localhost
http_access deny manager
http_access allow purge localhost
http_access deny purge
http_access deny all

# Disable caching
cache deny all


问:
How to determine the best Lambda to fill in missing values with external data
I have precipitation data from real weather stations. Unfortunately the data has a lot of missing values. I downloaded satellite data and want to fill the missing data. My approach looks as follows:

How would i determine the best lambda? Preferably in R or Python. One way I can think of is using a linear regressive model in the form of  and setting the intercept   to 0.
Are there more sophisticated estimation methods that are still general (there might be some methods specifically designed for precipitation data, but I am more interested in the general mathematical approach)?

I looked for paper on similar cases.


问:
Migrating Kubernetes cluster created by Rancher to a different Rancher instance
I currently have Air-Gapped Docker-installed Rancher v2.4.8 hosting a few clusters created in the Rancher UI.
I created a new Air-Gapped Rancher v2.6.6 instance on RKE Kubernetes cluster and I need to migrate those clusters.
Question is, After I upgrade the Docker instance, Is there any solution to migrate them? I saw an article from 2021 stating it's not possible, But maybe there's a way now or a solid workaround?
Thanks everyone.

I searched online for solutions, But I am planning this migration ahead to avoid problems.


问:
Install templates of Identity server 4
I Install the Identity server 4. But when I run

```<code>dotnet new is4inmem
</code>```

in a command window, I get an error

No templates found matching : 'is4inmem.'

I try to reinstall the templates but the response is "idenitytyserver4.Templates.4.0.1.nupkg already exists."

How can I fix it? I just try to reinstall but it's not ok.

Title: Install templates of Identity server 4

Body:
I Install the Identity server 4. But when I run

dotnet new is4inmem

in a command window, I get an error

No templates found matching : 'is4inmem.'

I try to reinstall the templates but the response is "idenitytyserver4.Templates.4.0.1.nupkg already exists."

How can I fix it? I just try to reinstall but it's not ok.


问:
How to retrieve data from a CSV Collection using ArcGIS and Python
I want to automate the downlaod of a dataset from ArcGIS using Python, but the files I need are in a CSV Collection item type, rather than a Table Layer item type.

Firstly, I can retrieve data from a single Table Layer.

```<code>from arcgis import GIS
from arcgis.features import FeatureLayerCollection, Table

gisClient=GIS()
item = gisClient.content.get("3a7e23cc7c2f49a7953838a2e9a4ed1a")

item
<Item title:"LAD (Dec 2020) Names and Codes in the United Kingdom" type:Table Layer owner:ONSGeography_data>
</code>```

I can get the URL which in this case allows me to query the data.

```<code>table_ref = Table.fromitem(item)
<Table url:"https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/LAD_Dec_2020_Names_and_Codes_in_the_United_Kingdom_2022/FeatureServer/0">
</code>```

But some datasets are of type CSV Collection.  The dataset I actually want is the august 2022 postcode to output area classifications

```<code>res = gisClient.content.search(query="title:Postcode to Output Area Hierarchy* AND owner:ONSGeography_data", max_items=10)

for i in res:
     print(i)
<Item title:"Postcode to Output Area Hierarchy with Classifications (May 2020) Multi-CSV Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2018) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2020) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (November 2021) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (November 2018) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (February 2021) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (May 2022) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2019) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2022) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (May 2020) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
</code>```

Retrieving a reference is Ok, but once I have this, I do not know how to obtain the URL that will allow me to download or access the zipped file.

```<code>for i in res:
     i_txt = str(i)
     if "(August 2022)" in i_txt:
             item = i
item
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2022) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>

table_ref = Table.fromitem(item)

Traceback (most recent call last):
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/gis/__init__.py", line 11448, in __getitem__
    return dict.__getitem__(self, k)
KeyError: 'tables'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/features/layer.py", line 3362, in fromitem
    return item.tables[table_id]
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/gis/__init__.py", line 11422, in __getattribute__
    if self["tables"] == None or self["tables"] == []:
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/gis/__init__.py", line 11452, in __getitem__
    return dict.__getitem__(self, k)
KeyError: 'tables'
</code>```

What do I need to do, to access the data within the CSV Collection?

Body:
I want to automate the downlaod of a dataset from ArcGIS using Python, but the files I need are in a CSV Collection item type, rather than a Table Layer item type.

Firstly, I can retrieve data from a single Table Layer.

from arcgis import GIS
from arcgis.features import FeatureLayerCollection, Table

gisClient=GIS()
item = gisClient.content.get("3a7e23cc7c2f49a7953838a2e9a4ed1a")

item
<Item title:"LAD (Dec 2020) Names and Codes in the United Kingdom" type:Table Layer owner:ONSGeography_data>

I can get the URL which in this case allows me to query the data.

table_ref = Table.fromitem(item)

But some datasets are of type CSV Collection.  The dataset I actually want is the august 2022 postcode to output area classifications

res = gisClient.content.search(query="title:Postcode to Output Area Hierarchy* AND owner:ONSGeography_data", max_items=10)

for i in res:
     print(i)
<Item title:"Postcode to Output Area Hierarchy with Classifications (May 2020) Multi-CSV Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2018) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2020) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (November 2021) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (November 2018) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (February 2021) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (May 2022) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2019) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2022) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>
<Item title:"Postcode to Output Area Hierarchy with Classifications (May 2020) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>

Retrieving a reference is Ok, but once I have this, I do not know how to obtain the URL that will allow me to download or access the zipped file.

for i in res:
     i_txt = str(i)
     if "(August 2022)" in i_txt:
             item = i
item
<Item title:"Postcode to Output Area Hierarchy with Classifications (August 2022) Lookup in the UK" type:CSV Collection owner:ONSGeography_data>

table_ref = Table.fromitem(item)

Traceback (most recent call last):
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/gis/__init__.py", line 11448, in __getitem__
    return dict.__getitem__(self, k)
KeyError: 'tables'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/features/layer.py", line 3362, in fromitem
    return item.tables[table_id]
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/gis/__init__.py", line 11422, in __getattribute__
    if self["tables"] == None or self["tables"] == []:
  File "/home/avrob/projects/cucumber/.venv/cucumber/lib/python3.9/site-packages/arcgis/gis/__init__.py", line 11452, in __getitem__
    return dict.__getitem__(self, k)
KeyError: 'tables'

What do I need to do, to access the data within the CSV Collection?


问:
Can't retrieve image from web in Xamarin forms
In the viewmodel of my page, I try to get an image to show. This image I get from one of our webservice. The image source is stored in ProductImage

```<code>string path = $@"http://www.MyCompany.be/cdn-cgi/image/width=150,quality=75/images/products/{CurrentProduct.Image}".Replace($"\\", $"/");

ProductImage = ImageSource.FromUri(new Uri(path));
</code>```

I of course make sure when I update the Image source for the view when I change it

```<code>public ImageSource ProductImage
    {

        get
        {
            return _productImage;
        }

        set
        {
            if (_productImage != value)
            {
                _productImage = value;
                OnPropertyChanged();
            }
        }
    }
</code>```

Sadly, for some reason it doesn't work. I checked the URL called and it does lead to an image.
It used to work when I was using streams instead of calling an URL. I know I haven't put the safety checks around yet to make sure the image exist, but other than that nothing has changed. I save the image the exact same way, i just use fromUri rather than fromStream.

```<code>            //Get target's SmbFile.
            var file = new SmbFile(path, auth);
            try
            {
                if (file.Exists())
                {
                    // Get readable stream.
                    var readStream = file.GetInputStream();

                    //Create reading buffer.
                    MemoryStream memStream = new MemoryStream();

                    //Get bytes.
                    ((Stream)readStream).CopyTo(memStream);

                    var stream1 = new MemoryStream(memStream.ToArray());

                    if (stream1.Length < 30000000)
                    {
                        //Save image
                        //ProductImage = ImageSource.FromStream(() => stream1);

                        //Dispose readable stream.
                        readStream.Dispose();

                        InfoColSpan = 1;
                    }
                    else
                    {
                        Common.AlertError("Image trop lourde pour l'affichage");
                    }
                }
            }
            catch (Exception ex)
            {
                Common.AlertError(ex, "Impossible de charger l'image");
            }
</code>```

Since I changed my method, I no longer load anything.

Body:
In the viewmodel of my page, I try to get an image to show. This image I get from one of our webservice. The image source is stored in ProductImage

string path = $@"http://www.MyCompany.be/cdn-cgi/image/width=150,quality=75/images/products/{CurrentProduct.Image}".Replace($"\\", $"/");

ProductImage = ImageSource.FromUri(new Uri(path));

I of course make sure when I update the Image source for the view when I change it

public ImageSource ProductImage
    {

        get
        {
            return _productImage;
        }

        set
        {
            if (_productImage != value)
            {
                _productImage = value;
                OnPropertyChanged();
            }
        }
    }

Sadly, for some reason it doesn't work. I checked the URL called and it does lead to an image.
It used to work when I was using streams instead of calling an URL. I know I haven't put the safety checks around yet to make sure the image exist, but other than that nothing has changed. I save the image the exact same way, i just use fromUri rather than fromStream.

            //Get target's SmbFile.
            var file = new SmbFile(path, auth);
            try
            {
                if (file.Exists())
                {
                    // Get readable stream.
                    var readStream = file.GetInputStream();

                    //Create reading buffer.
                    MemoryStream memStream = new MemoryStream();

                    //Get bytes.
                    ((Stream)readStream).CopyTo(memStream);

                    var stream1 = new MemoryStream(memStream.ToArray());

                    if (stream1.Length < 30000000)
                    {
                        //Save image
                        //ProductImage = ImageSource.FromStream(() => stream1);

                        //Dispose readable stream.
                        readStream.Dispose();

                        InfoColSpan = 1;
                    }
                    else
                    {
                        Common.AlertError("Image trop lourde pour l'affichage");
                    }
                }
            }
            catch (Exception ex)
            {
                Common.AlertError(ex, "Impossible de charger l'image");
            }

Since I changed my method, I no longer load anything.


问:
Get watcher icon in Jira
I'm trying to get the watcher icon that we can see on Jira, to use it in one of my projects.

I could download the icon and just use it, but I'd rather use an URL like I'm already doing for the epics with  https://ctl.atlassian.net/images/icons/issuetypes/epic.svg?format=png

Any ideas? And also, where could I find all the other icons, in case they need them in the future?

Title: Get watcher icon in Jira


问:
GraphX Pregel send Message srcAttr() and dstAttr are not updated
Im using the Java Apache Spark Graphx API and these are my first tries using the pregel conecept in GraphX. I simple just want to pass a Arraylist of Integer to another vertex as a message. In the SendMsg function I have the EdgeTriplet e as a parameter, but e.srcAttr()/e.dstAttr() are always just the initial vertex values at the beginning of my algorithm and don't update.
But this missing update is just in the SendMsg function and not in the vertexProgramm function. There everything updates correctly.

```<code>static class Vprog extends AbstractFunction3<Object, List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>> implements Serializable {

    @Override
    public List<Pair<Integer, Integer>> apply(Object v1, List<Pair<Integer, Integer>> v2, List<Pair<Integer, Integer>> v3) {

        for (Pair<Integer, Integer> i : v3) {
            if (!v2.contains(i)) {
                v2.add(i);
            }
        }

        ArrayList<Pair<Integer, Integer>> ret = new ArrayList<>(v2);
        return ret;
    }
}

</code>```
```<code>static class SendMsg extends AbstractFunction1<EdgeTriplet<List<Pair<Integer, Integer>>, List<Integer>>, Iterator<Tuple2<Object, List<Pair<Integer, Integer>>>>> implements Serializable {

    @Override
    public Iterator<Tuple2<Object, List<Pair<Integer, Integer>>>> apply(EdgeTriplet<List<Pair<Integer, Integer>>, List<Integer>> v1) {
        ArrayList<Tuple2<Object, List<Pair<Integer, Integer>>>> ret = new ArrayList<>();

        ArrayList<Pair<Integer, Integer>> pairList = new ArrayList<>(v1.srcAttr());
        ret.add(new Tuple2<Object, List<Pair<Integer, Integer>>>(v1.dstId(), pairList));

        return JavaConverters.asScalaIteratorConverter(ret.iterator()).asScala();
    }
}
</code>```
```<code>static class MergeMsg extends AbstractFunction2<List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>> implements Serializable {
    @Override
    public List<Pair<Integer, Integer>> apply(List<Pair<Integer, Integer>> a, List<Pair<Integer, Integer>> b) {
        for (Pair<Integer, Integer> i : b) {
            if (!a.contains(i)) {
                a.add(i);
            }
        }
        return new ArrayList<>(a);
    }
}
</code>```

I debugged the whole code and found out, every new Superstep I get a new List in SendMsg for the vertex values each of these new lists just contains the content of the initial vertexvalue (at the beginning of the pregel program)

Also if someone has some good sources or documentation for the apache spark java api(especially the prgel stuff), it would be very nice if you can post this because the official documentation isn't the best

Body:
Im using the Java Apache Spark Graphx API and these are my first tries using the pregel conecept in GraphX. I simple just want to pass a Arraylist of Integer to another vertex as a message. In the SendMsg function I have the EdgeTriplet e as a parameter, but e.srcAttr()/e.dstAttr() are always just the initial vertex values at the beginning of my algorithm and don't update.
But this missing update is just in the SendMsg function and not in the vertexProgramm function. There everything updates correctly.

static class Vprog extends AbstractFunction3<Object, List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>> implements Serializable {

    @Override
    public List<Pair<Integer, Integer>> apply(Object v1, List<Pair<Integer, Integer>> v2, List<Pair<Integer, Integer>> v3) {

        for (Pair<Integer, Integer> i : v3) {
            if (!v2.contains(i)) {
                v2.add(i);
            }
        }

        ArrayList<Pair<Integer, Integer>> ret = new ArrayList<>(v2);
        return ret;
    }
}

static class SendMsg extends AbstractFunction1<EdgeTriplet<List<Pair<Integer, Integer>>, List<Integer>>, Iterator<Tuple2<Object, List<Pair<Integer, Integer>>>>> implements Serializable {

    @Override
    public Iterator<Tuple2<Object, List<Pair<Integer, Integer>>>> apply(EdgeTriplet<List<Pair<Integer, Integer>>, List<Integer>> v1) {
        ArrayList<Tuple2<Object, List<Pair<Integer, Integer>>>> ret = new ArrayList<>();

        ArrayList<Pair<Integer, Integer>> pairList = new ArrayList<>(v1.srcAttr());
        ret.add(new Tuple2<Object, List<Pair<Integer, Integer>>>(v1.dstId(), pairList));

        return JavaConverters.asScalaIteratorConverter(ret.iterator()).asScala();
    }
}

static class MergeMsg extends AbstractFunction2<List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>, List<Pair<Integer, Integer>>> implements Serializable {
    @Override
    public List<Pair<Integer, Integer>> apply(List<Pair<Integer, Integer>> a, List<Pair<Integer, Integer>> b) {
        for (Pair<Integer, Integer> i : b) {
            if (!a.contains(i)) {
                a.add(i);
            }
        }
        return new ArrayList<>(a);
    }
}

I debugged the whole code and found out, every new Superstep I get a new List in SendMsg for the vertex values each of these new lists just contains the content of the initial vertexvalue (at the beginning of the pregel program)

Also if someone has some good sources or documentation for the apache spark java api(especially the prgel stuff), it would be very nice if you can post this because the official documentation isn't the best


问:
Got daDK error on netlify while building react + material ui x data grid project
The project is running successfully on the local machine in dev mode.
but got this error on netlify.

```<code>./node_modules/@mui/x-data-grid/locales/daDK.js
Attempted import error: 'daDK' is not exported from
'@mui/material/locale' (imported as 'daDKCore').
</code>```

Any help would be appreciated.
Thanks in advance
P.S:
local build in production mode is also failed.
but error was different

```<code>Attempted import error: 'useGridApiContext'
 is not exported from '@mui/x-data-grid'
</code>```

I wonder if this useGridApiContext is not for the community version of mui-x-data-grid package.
If so, how it worked in dev mode?

P.S:
after removing that useGridApiContext, still netlify build failed.
but local build is working.

```<code>https://github.com/browserslist/browserslist#browsers-data-updating
Failed to compile.
./node_modules/@mui/x-data-grid/locales/daDK.js
Attempted import error:
'daDK' is not exported from '@mui/material/locale' (imported as 'daDKCore').

</code>```

Body:
The project is running successfully on the local machine in dev mode.
but got this error on netlify.

./node_modules/@mui/x-data-grid/locales/daDK.js
Attempted import error: 'daDK' is not exported from
'@mui/material/locale' (imported as 'daDKCore').

Any help would be appreciated.
Thanks in advance
P.S:
local build in production mode is also failed.
but error was different

Attempted import error: 'useGridApiContext'
 is not exported from '@mui/x-data-grid'

I wonder if this useGridApiContext is not for the community version of mui-x-data-grid package.
If so, how it worked in dev mode?

P.S:
after removing that useGridApiContext, still netlify build failed.
but local build is working.

https://github.com/browserslist/browserslist#browsers-data-updating
Failed to compile.
./node_modules/@mui/x-data-grid/locales/daDK.js
Attempted import error:
'daDK' is not exported from '@mui/material/locale' (imported as 'daDKCore').


问:
I have deployed a flask application on google cloud app engine. After deploying i get 502 Bad Gateway error nginx . How can i solve this error?
I am running my flask application on google cloud that works fine locally and also in cloud editor.I have to deploy the flask application on google cloud so, i need to add app.yaml and requirement.txt file before deployment.I have added those files to my project directory & Once i deploy my flask application and browse to the url i am getting nginx error 502 Bad Gateway.How to solve this error.Error screenshot
Since it works just fine on my local environment, my current workflow to solve this issue involves changing my code locally and deploying it to see if it works afterwards,but each deployment takes over 30min only to figure out it still does not work. I have my app variable set in my main.py file as described below.The flask application which i want to deploy is a simple app where i can upload-process-download the processed image

```<code>          main.py
</code>```
```<code>import os
import cv2
from werkzeug.utils import secure_filename
from flask import Flask,flash,request,redirect,send_file,render_template,send_from_directory
from PIL import Image, ImageDraw, ImageFont
import datetime
UPLOAD_FOLDER = 'uploads/'
#PROCESSED_FOLDER = 'processed/'

app = Flask(__name__)
app.template_folder = 'templates'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Upload API
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            print('no file')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            print('no filename')
            return redirect(request.url)
        else:
            os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print("saved file successfully")
            #send file name as parameter to downlad
            return redirect('/process-file/'+ filename)

    return render_template('upload_file.html')
# Download API
@app.route("/downloadfile/<filename>", methods = ['GET'])
def download_file(filename):
    return render_template('download.html',value = filename)
@app.route('/return-files/<filename>')
def return_files_tut(filename):
    file_path = 'processed/' + filename
    return send_file(file_path, as_attachment=True)

if __name__ == "__main__":
    app.run(debug=False)
</code>```
```<code>app = Flask(__name__, template_folder='templates')
</code>```

requirement.txt

```<code>aniso8601==9.0.1
click==8.1.3
colorama==0.4.6
distlib==0.3.6
filelock==3.8.2
Flask==2.2.2
Flask-RESTful==0.3.9
Flask-Uploads==0.2.1
Flask-WTF==1.0.1
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
numpy==1.24.1
opencv-python==4.7.0.68
Pillow==9.3.0
platformdirs==2.6.0
PyPDF2==3.0.0
python-dotenv==0.21.0
pytz==2022.7
six==1.16.0
virtualenv==20.17.1
Werkzeug==2.2.2
WTForms==3.0.1
</code>```

when i deploy app with the requirement.txt as decribed above i get

```<code>Error:could not find the version that satisfies the requirement
</code>```

I have solved those by editing my requirements with available versions .
Final requirement.txt

```<code>Flask==2.0.2
gunicorn==20.1.0
Jinja2==3.0.2
opencv-python==4.6.0.66
Pillow==8.3.0
python-dotenv==0.20.0
Werkzeug==2.0.2
</code>```

Once deployed i get [Error screenshot][1]
[1]: https://i.stack.imgur.com/MdQMj.png

```<code>app.yaml
runtime: python311
</code>```

this is my app.yaml and when i deploy my app gets deployed and gives 502 error

Body:
I am running my flask application on google cloud that works fine locally and also in cloud editor.I have to deploy the flask application on google cloud so, i need to add app.yaml and requirement.txt file before deployment.I have added those files to my project directory & Once i deploy my flask application and browse to the url i am getting nginx error 502 Bad Gateway.How to solve this error.Error screenshot
Since it works just fine on my local environment, my current workflow to solve this issue involves changing my code locally and deploying it to see if it works afterwards,but each deployment takes over 30min only to figure out it still does not work. I have my app variable set in my main.py file as described below.The flask application which i want to deploy is a simple app where i can upload-process-download the processed image

          main.py

import os
import cv2
from werkzeug.utils import secure_filename
from flask import Flask,flash,request,redirect,send_file,render_template,send_from_directory
from PIL import Image, ImageDraw, ImageFont
import datetime
UPLOAD_FOLDER = 'uploads/'
#PROCESSED_FOLDER = 'processed/'

app = Flask(__name__)
app.template_folder = 'templates'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Upload API
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            print('no file')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            print('no filename')
            return redirect(request.url)
        else:
            os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print("saved file successfully")
            #send file name as parameter to downlad
            return redirect('/process-file/'+ filename)

    return render_template('upload_file.html')
# Download API
@app.route("/downloadfile/<filename>", methods = ['GET'])
def download_file(filename):
    return render_template('download.html',value = filename)
@app.route('/return-files/<filename>')
def return_files_tut(filename):
    file_path = 'processed/' + filename
    return send_file(file_path, as_attachment=True)

if __name__ == "__main__":
    app.run(debug=False)

app = Flask(__name__, template_folder='templates')

requirement.txt

aniso8601==9.0.1
click==8.1.3
colorama==0.4.6
distlib==0.3.6
filelock==3.8.2
Flask==2.2.2
Flask-RESTful==0.3.9
Flask-Uploads==0.2.1
Flask-WTF==1.0.1
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
numpy==1.24.1
opencv-python==4.7.0.68
Pillow==9.3.0
platformdirs==2.6.0
PyPDF2==3.0.0
python-dotenv==0.21.0
pytz==2022.7
six==1.16.0
virtualenv==20.17.1
Werkzeug==2.2.2
WTForms==3.0.1

when i deploy app with the requirement.txt as decribed above i get

Error:could not find the version that satisfies the requirement

I have solved those by editing my requirements with available versions .
Final requirement.txt

Flask==2.0.2
gunicorn==20.1.0
Jinja2==3.0.2
opencv-python==4.6.0.66
Pillow==8.3.0
python-dotenv==0.20.0
Werkzeug==2.0.2

Once deployed i get [Error screenshot][1]
[1]: https://i.stack.imgur.com/MdQMj.png

app.yaml
runtime: python311

this is my app.yaml and when i deploy my app gets deployed and gives 502 error


问:
Foreign Key Specific Date and Date Range
I am trying to set a foreign key between two tables with the following structure:

Table 1

Contract
Beginning
End

V001
01.01.20
01.01.21

V001
02.01.21
31.12.22

and

Table 2

Contract
Date

V001
15.05.20

V002
10.02.21

How can I set a foreign key such that it maps the rows where the date is between the beginning and the end date?

I've tried to add a where clause after the foreign key constraint but that did not work.


问:
How to trace exceptions in a domain context in C++11?
When an exception is thrown, it would be nice to be able to add information about how the error could happen, as the exception propagates up the call stack.
With information i don't mean technical info (e.g. Error in /src/foo.cpp:26), but something in context of the domain (e.g. Failed to load image "foo.png").
So instead of tracing the actual call stack, i want to provide my own information.

What's the best way to implement that in c++11?

I tried using nested exceptions with std::throw_with_nested() but the problem there is that if you want to catch some exceptions by their type only the outermost exception can be caught (I want the innermost).

Like in this example:

#include <iostream>
#include <exception>

void run()
{
    try
    {
        throw 1;
    }
    catch(...)
    {
        std::throw_with_nested(std::runtime_error("run() failed"));
    }
}

int main()
{
    try {
        run();
    } catch(const int& e) {
        // won't handle this error because only outermost exception can be caught
        std::cerr << e << std::endl;
    }
}

```

That is a problem, because the outer exceptions are only there to provid informartion, and only the innermost represents the actual error.

Body:
When an exception is thrown, it would be nice to be able to add information about how the error could happen, as the exception propagates up the call stack.
With information i don't mean technical info (e.g. Error in /src/foo.cpp:26), but something in context of the domain (e.g. Failed to load image "foo.png").
So instead of tracing the actual call stack, i want to provide my own information.

What's the best way to implement that in c++11?

I tried using nested exceptions with std::throw_with_nested() but the problem there is that if you want to catch some exceptions by their type only the outermost exception can be caught (I want the innermost).

Like in this example:

#include <iostream>
#include <exception>

void run()
{
    try
    {
        throw 1;
    }
    catch(...)
    {
        std::throw_with_nested(std::runtime_error("run() failed"));
    }
}

int main()
{
    try {
        run();
    } catch(const int& e) {
        // won't handle this error because only outermost exception can be caught
        std::cerr << e << std::endl;
    }
}

That is a problem, because the outer exceptions are only there to provid informartion, and only the innermost represents the actual error.


问:
The stacking level of relative positioning is higher than that of float?
The stacking level of relative positioning is higher than that of float. Why does the text box2  go to the bottom?

.box1 {
  float: left;
  width: 100px;
  height: 100px;
  background-color: pink;
}

.box2 {
  position: relative;
  width: 100px;
  height: 100px;
  background-color: deeppink;
}

.box3 {
  width: 100px;
  height: 100px;
  background-color: aquamarine;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box1">box1</div>
<div class="box2">box2</div>
<div class="box3"></div></code>```

Body:
The stacking level of relative positioning is higher than that of float. Why does the text box2  go to the bottom?

.box1 {
  float: left;
  width: 100px;
  height: 100px;
  background-color: pink;
}

.box2 {
  position: relative;
  width: 100px;
  height: 100px;
  background-color: deeppink;
}

.box3 {
  width: 100px;
  height: 100px;
  background-color: aquamarine;
}

box1

box2


问:
Solving an error (indices must be of integer)
I faced the following problem with my code :

```<code>lst_patient_array = np.array(lst_patient)
lst_patient_array[2][0][0].shape
print(lst_patient_array.dtype)

</code>```

Test_fold_0 =[]
i = 0
for i in files_patient:
y = lst_patient_array[0][0][i] # HERE SHOW ME AN ERROR
Test_fold_0 = np.concatenate((Test_fold_0,y))

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

The error is:
IndexError: arrays used as indices must be of integer (or boolean) type

solve my problem with IndexError: arrays used as indices must be of integer (or boolean) type

Body:
I faced the following problem with my code :

lst_patient_array = np.array(lst_patient)
lst_patient_array[2][0][0].shape
print(lst_patient_array.dtype)

Test_fold_0 =[]
i = 0
for i in files_patient:
y = lst_patient_array[0][0][i] # HERE SHOW ME AN ERROR
Test_fold_0 = np.concatenate((Test_fold_0,y))

The error is:
IndexError: arrays used as indices must be of integer (or boolean) type

solve my problem with IndexError: arrays used as indices must be of integer (or boolean) type


问:
getting No certificate found with the supplied thumbprint error in Xamarin project
I am creating a pipeline to Build a XAMARIN project.
The project compiles on my desktop but I am having trouble compiling it in classic DevOps. The project is under Team Foundation Version Control Repos.

I have followed the example in this link: https://yanxiaodi.medium.com/using-azure-devops-build-pipeline-for-xamarin-forms-436ddc6bcf97

I added the pfx file (created today, expires in a year) to the library Secure files and the pipeline successfully downloads the file. It seems to copy the file to right place because i do not get an error the file is missing. However, I do get the error shown below.
The thumbprint shown is the one that is in the secure file.
what am i doing wrong?

##[error]C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Microsoft\VisualStudio\v17.0\AppxPackage\Microsoft.AppXPackage.Targets(854,5): Error : No certificate found with the supplied thumbprint: 738D7BBE2C2D55EA43D65CA94224E76296C10F1

C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Microsoft\VisualStudio\v17.0\AppxPackage\Microsoft.AppXPackage.Targets(854,5): error : No certificate found with the supplied thumbprint: 738D7BBE2C2D55EA943D65CA4224E76296C10F1 [D:\a\9\s\App1.UWP\MyProgram.UWP.csproj]


问:
Localization issue with Header and Footer sections of a page in Vue.js
When changing the browser preferred language, main page labels are getting updated as per the preferred language but header and footer section labels are still in older language.

We are using i18n for language related to updates.

Please find below outline of the code I have for i18n

```<code>export default async function getI18n(){
   //fetch all browser languages
   //fetch preferred language
   //fetch related resource files for preferred language.
   return new VueI18n({

   })
}
</code>```

Observations:

Header and Footer labels are getting updated once the session is ended.

When fetching language resources, we are maintaining local storage where we are clearing and adding data to local storage as per the language change or duration of time for which data is cached in local storage.
[getlocalstorage updation is happening only for the main page]

Tried remounting header and footer page but it doesn’t work.

Need help in updating localizations for header and footer section

Please let me know if any other details are required.

Body:
When changing the browser preferred language, main page labels are getting updated as per the preferred language but header and footer section labels are still in older language.

We are using i18n for language related to updates.

Please find below outline of the code I have for i18n

export default async function getI18n(){
   //fetch all browser languages
   //fetch preferred language
   //fetch related resource files for preferred language.
   return new VueI18n({

   })
}

Observations:

Header and Footer labels are getting updated once the session is ended.

When fetching language resources, we are maintaining local storage where we are clearing and adding data to local storage as per the language change or duration of time for which data is cached in local storage.
[getlocalstorage updation is happening only for the main page]

Tried remounting header and footer page but it doesn’t work.

Need help in updating localizations for header and footer section

Please let me know if any other details are required.


问:
Can not access private method declared with "#" but "private" works
As the title says, why i can't call Example.method2()?

Example class:

class Example {
  private method1(): any{
    return "it works"
  }
  #method2(): any {
    return "it works"
  }
}
```
<p>Test that works</p>
<pre class="lang-js prettyprint-override"><code>it('should call method1', () => {
    // @ts-ignore
    const result = Example.method1()

    expect(result === "it works" ).toBeTruthy(); // OK

  });
</code>```

Test that should work

it('should call #method2', () => {
    // @ts-ignore
    const result = Example.#method2()

    expect(result === "it works" ).toBeTruthy(); // NOT OK

  });
```
<p>Error log:</p>
```        const result = Example..call(Example);
                               ^

    SyntaxError: Unexpected token '.'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
```

Body:
As the title says, why i can't call Example.method2()?

Example class:

class Example {
  private method1(): any{
    return "it works"
  }
  #method2(): any {
    return "it works"
  }
}

Test that works

it('should call method1', () => {
    // @ts-ignore
    const result = Example.method1()

    expect(result === "it works" ).toBeTruthy(); // OK

  });

Test that should work

it('should call #method2', () => {
    // @ts-ignore
    const result = Example.#method2()

    expect(result === "it works" ).toBeTruthy(); // NOT OK

  });

Error log:

        const result = Example..call(Example);
                               ^

    SyntaxError: Unexpected token '.'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)


问:
in flyte, is it possible to dynamically control cache usage?
My use case is as follows:

the initial task of the flyte workflow extracts a dataset

in production, I want to always use the latest data (or use cache with short expiration

during development, runtime is more important then data freshness - so I prefer to use cached dataset

is there an option to control somehow the caching when launching a workflow (and not just when defining the workflow)


问:
Is it possible to pass args containing & char in python
I was trying to do something like this

```<code>python something.py ThisIs&TheKindOfThing=4Input

import sys
a = sys.argv[1]
b = sys.argv[2]
</code>```

This throws an exception, and we can inspect the values and see that

```<code>a = 'ThisIs'
</code>```

and it appears the rest is rejected. I had a bit of a google search around that, but didn't find any match. Can anyone explain to me how I can pass in a parameter like this, or just tell me where the relevant documentation is. I can't imagine that there isn't an easy way to handle this.

Body:
I was trying to do something like this

python something.py ThisIs&TheKindOfThing=4Input

import sys
a = sys.argv[1]
b = sys.argv[2]

This throws an exception, and we can inspect the values and see that

a = 'ThisIs'

and it appears the rest is rejected. I had a bit of a google search around that, but didn't find any match. Can anyone explain to me how I can pass in a parameter like this, or just tell me where the relevant documentation is. I can't imagine that there isn't an easy way to handle this.


问:
Implement this query using typeorm createQuerybuilder()
I need to write this query using typeorm query builder. Is there any way to write this? If not, any suggestions?</p>
```<code>SELECT
    message.*,
    advertisement.title AS advertisement_title,
    image.location_url AS image,
    CONCAT(user.first_name, " ", user.last_name) AS user_name
FROM
    message
LEFT JOIN
    image ON image.id = (SELECT MIN(id)
                         FROM image
                         WHERE advertisement_id = message.advertisement_id)
INNER JOIN
    advertisement ON message.advertisement_id = advertisement.id
INNER JOIN
    user ON (CASE
                 WHEN message.sender_id != ${userId} THEN sender_id
                 WHEN message.receiver_id != ${userId} THEN receiver_id
             END) = user.id
WHERE
    message.id IN (SELECT MAX(message.id)
                   FROM message
                   WHERE message.sender_id = ${userId}
                      OR message.receiver_id = ${userId}
                   GROUP BY
                       message.advertisement_id,
                       CONCAT(LEAST(message.sender_id, message.receiver_id), '.',
  GREATEST(message.sender_id, message.receiver_id)))
ORDER BY
    message.id DESC;
</code>```

Body:
I need to write this query using typeorm query builder. Is there any way to write this? If not, any suggestions?

SELECT
    message.*,
    advertisement.title AS advertisement_title,
    image.location_url AS image,
    CONCAT(user.first_name, " ", user.last_name) AS user_name
FROM
    message
LEFT JOIN
    image ON image.id = (SELECT MIN(id)
                         FROM image
                         WHERE advertisement_id = message.advertisement_id)
INNER JOIN
    advertisement ON message.advertisement_id = advertisement.id
INNER JOIN
    user ON (CASE
                 WHEN message.sender_id != ${userId} THEN sender_id
                 WHEN message.receiver_id != ${userId} THEN receiver_id
             END) = user.id
WHERE
    message.id IN (SELECT MAX(message.id)
                   FROM message
                   WHERE message.sender_id = ${userId}
                      OR message.receiver_id = ${userId}
                   GROUP BY
                       message.advertisement_id,
                       CONCAT(LEAST(message.sender_id, message.receiver_id), '.',
  GREATEST(message.sender_id, message.receiver_id)))
ORDER BY
    message.id DESC;


问:
Pydantic generate json-schema enforcing field requirements
I have the following model, where the field b is a list whose length is additionally enforced based on the value of field a.

from pydantic import BaseModel, validator
from enum import Enum

class A(BaseModel):
    a: int
    b: list[int]

    @validator("b")
    def check_b_length(cls, v, values):
        assert len(v) == values["a"]

a = A(a=1, b=[1])

A.schema_json()
```
<p>Generating the following JSON-schema:</p>
<pre class="lang-json prettyprint-override"><code>{
    "title": "A",
    "type": "object",
    "properties": {
        "a": {
            "title": "A",
            "type": "integer"
        },
        "b": {
            "title": "B",
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "required": [
        "a",
        "b"
    ]
}
</code>```

Is there any way to enfore the additional validation being done by pydantic in the check_b_length function in JSON-schema? I.e. this could be done possibly via oneOf, as in this question: JSON Schema - specify field is required based on value of another field ... So its possible to enfore in JSON-schema, and possible to enforce in pydantic, but how can you map them?

Body:
I have the following model, where the field b is a list whose length is additionally enforced based on the value of field a.

from pydantic import BaseModel, validator
from enum import Enum

class A(BaseModel):
    a: int
    b: list[int]

    @validator("b")
    def check_b_length(cls, v, values):
        assert len(v) == values["a"]

a = A(a=1, b=[1])

A.schema_json()

Generating the following JSON-schema:

{
    "title": "A",
    "type": "object",
    "properties": {
        "a": {
            "title": "A",
            "type": "integer"
        },
        "b": {
            "title": "B",
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "required": [
        "a",
        "b"
    ]
}

Is there any way to enfore the additional validation being done by pydantic in the check_b_length function in JSON-schema? I.e. this could be done possibly via oneOf, as in this question: JSON Schema - specify field is required based on value of another field ... So its possible to enfore in JSON-schema, and possible to enforce in pydantic, but how can you map them?


问:
Uncaught (in promise) ReferenceError: storesList is not defined
```<code>
<script>
  import {
    mapGetters,
    mapActions
  } from "vuex";
  export default {
    name: 'Stores',
    data() {
    return {
        selectedCity: {name: 'New York', code: 'NY'},
        cities: storesList
    }
},
    methods: {
      ...mapActions(["fetchStores"])
    },
    computed: mapGetters(["storesList"]),
    created() {
        console.log( this.fetchStores());
      this.fetchStores()
    }
  }
</script>

the cites should be

cities: [
            {name: 'New York', code: 'NY'},
            {name: 'Rome', code: 'RM'},
            {name: 'London', code: 'LDN'},
            {name: 'Istanbul', code: 'IST'},
            {name: 'Paris', code: 'PRS'}
        ]
</code>```

vuex return data in array not working  (cities: storesList)
Uncaught (in promise) ReferenceError: storesList is not defined
its show error .how to solve this?

Body:
the cites should be

cities: [
            {name: 'New York', code: 'NY'},
            {name: 'Rome', code: 'RM'},
            {name: 'London', code: 'LDN'},
            {name: 'Istanbul', code: 'IST'},
            {name: 'Paris', code: 'PRS'}
        ]

vuex return data in array not working  (cities: storesList)
Uncaught (in promise) ReferenceError: storesList is not defined
its show error .how to solve this?


问:
Save jpeg to pdf with iTextSharp
I am trying to save jpeg files to a PDF file.

The commented code works, but the images are unscaled. I would like to use a different way of saving, but it results in a blank PDF file with a message. ERROR: Infinite table loop.

My code:

```<code>using (var img = webp.Decode(array))
{
  img.Save(streamJpeg, ImageFormat.Jpeg);
  streamJpeg.Position = 0;
  iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(streamJpeg);

 //if (pdfImage.Height > pdfImage.Width)
 //{
 //    //Maximum height is 800 pixels.
 //    float percentage = 0.0f;
 //    percentage = 700 / pdfImage.Height;
 //    pdfImage.ScalePercent(percentage * 100);
 //}
 //else
 //{
 //    //Maximum width is 600 pixels.
 //    float percentage = 0.0f;
 //    percentage = 540 / pdfImage.Width;
 //    pdfImage.ScalePercent(percentage * 100);
 //}

 PdfPTable table = new PdfPTable(1);
 table.AddCell(new PdfPCell(pdfImage));
 doc.Add(table);
 //doc.Add(pdfImage);
 //doc.NewPage();
}
</code>```

Thanks, regards.

Title: Save jpeg to pdf with iTextSharp

Body:
I am trying to save jpeg files to a PDF file.

The commented code works, but the images are unscaled. I would like to use a different way of saving, but it results in a blank PDF file with a message. ERROR: Infinite table loop.

My code:

using (var img = webp.Decode(array))
{
  img.Save(streamJpeg, ImageFormat.Jpeg);
  streamJpeg.Position = 0;
  iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(streamJpeg);

 //if (pdfImage.Height > pdfImage.Width)
 //{
 //    //Maximum height is 800 pixels.
 //    float percentage = 0.0f;
 //    percentage = 700 / pdfImage.Height;
 //    pdfImage.ScalePercent(percentage * 100);
 //}
 //else
 //{
 //    //Maximum width is 600 pixels.
 //    float percentage = 0.0f;
 //    percentage = 540 / pdfImage.Width;
 //    pdfImage.ScalePercent(percentage * 100);
 //}

 PdfPTable table = new PdfPTable(1);
 table.AddCell(new PdfPCell(pdfImage));
 doc.Add(table);
 //doc.Add(pdfImage);
 //doc.NewPage();
}

Thanks, regards.


问:
CSS image opacity without affecting border
I have a row of images and I want the first image to have a border, I want to reduce the opacity of the image but I want the border color to appear as the color that I have used for the border in my CSS without reduced opacity, is it possible to do that? I tried putting the border around the div but the images that I have to use have a transparent space at the bottom which makes the border look weird.

.images-div {
    display: flex;
    gap: 14px;
}

.image {
    border-radius: 11px;
}

/* This doesn't work
.image-div {
    border-radius: 11px;
} */

.image-active {
    opacity: .5;
    border: 3px solid rgb(0, 0, 255); /* This should be dark blue and not faded */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body >
    <div class="images-div">
        <div class="image-div">
            <img class="image image-active" src="https://i.imgur.com/EcTLpGs.jpg" "alt="">
        </div>
        <img class="image" src="https://i.imgur.com/EcTLpGs.jpg" "alt="">
        <img class="image" src="https://i.imgur.com/EcTLpGs.jpg" "alt="">
        <img class="image" src="https://i.imgur.com/EcTLpGs.jpg" "alt="">
    </div>
</body>
</html></code>```

Body:
I have a row of images and I want the first image to have a border, I want to reduce the opacity of the image but I want the border color to appear as the color that I have used for the border in my CSS without reduced opacity, is it possible to do that? I tried putting the border around the div but the images that I have to use have a transparent space at the bottom which makes the border look weird.

.images-div {
    display: flex;
    gap: 14px;
}

.image {
    border-radius: 11px;
}

/* This doesn't work
.image-div {
    border-radius: 11px;
} */

.image-active {
    opacity: .5;
    border: 3px solid rgb(0, 0, 255); /* This should be dark blue and not faded */
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">