问:
Laravel + SQLite = SQLSTATE[HY000]General Error: 8 attempt to write a readonly database
I'm trying to delete a db.sqlite file, create it again and then insert some info into this DB all in the same method. This is the method I'm using:

```<code>public function destroy()
{
    // Store all contents and delete the first one since this is created via seeder
    $contents = $this->contents->all()->toArray();
    array_shift($contents);

    // Delete db file, creates it from an example file and changes permissions
    system('rm -rf ../database/database.sqlite');
    system('cp ../database/database.sqlite.example ../database/database.sqlite');
    system('chmod 0777 ../database/');
    system('chmod 0777 ../database/database.sqlite');

    // Insert data
    foreach ($contents as $content) {
        $this->contents->create($content);
    }

    return response()->json(['message' => 'Data has been destroyed!']);
}
</code>```

However when I try to run it i get the error described in the title:

SQLSTATE[HY000]General Error: 8 attempt to write a readonly database

I'm setting 777 permissions on the file and the folder as recommended by others questions' answers, so I have no idea why it isn't working.

答:
If you are on Fedora or Redhat with Selinux rememebr to switch off Selinux (or configure it correctly):</p>

```<code>setenforce 0
</code>```

Body:
I'm trying to delete a db.sqlite file, create it again and then insert some info into this DB all in the same method. This is the method I'm using:

public function destroy()
{
    // Store all contents and delete the first one since this is created via seeder
    $contents = $this->contents->all()->toArray();
    array_shift($contents);

    // Delete db file, creates it from an example file and changes permissions
    system('rm -rf ../database/database.sqlite');
    system('cp ../database/database.sqlite.example ../database/database.sqlite');
    system('chmod 0777 ../database/');
    system('chmod 0777 ../database/database.sqlite');

    // Insert data
    foreach ($contents as $content) {
        $this->contents->create($content);
    }

    return response()->json(['message' => 'Data has been destroyed!']);
}

However when I try to run it i get the error described in the title:

SQLSTATE[HY000]General Error: 8 attempt to write a readonly database

I'm setting 777 permissions on the file and the folder as recommended by others questions' answers, so I have no idea why it isn't working.

Body:
If you are on Fedora or Redhat with Selinux rememebr to switch off Selinux (or configure it correctly):

setenforce 0


来源: stackexchange

问:
androidx.appcompat.appcompat.R does not exist
After upgrading/refactoring into AndroidX i am getting this error
androidx.appcompat.appcompat.R does not exist
in the code it is showing appcompat symbol cannot resolve

答:
Remove extra appcompact from here.

from -
androidx.appcompat.appcompat.R

to -
androidx.appcompat.R

ContentLicense: CC BY-SA 4.0


问:
Managing subviews in Cocoa Touch
I'm developing an iPhone app. I need to create a Quiz application that has different Question views embedded in it (see my similar question).

Different types of Question will have different behavior, so I plan to create a controller class for each type of Question. The MultipleChoiceQuestionController would set up a question and 3-4 buttons for the user to select an answer. Similarly, the IdentifyPictureQuestionController would load an image and present a text box to the user.

However, the docs say that a UIViewController should only be used for views that take up the entire application window. How else can I create a class to manage events in my subviews?

Thanks,

答:
This is a very nice little solution, gives you all of the advantages of a view controller without breaking apples rules.

From the page:

This is a generic controller class
  that can be used to handle a subarea.
  It is modelled after UIViewController,
  but conforms to Apple's
  recommendation.

Your view controller creates the
  instances and is responsible for
  managing the subview controllers.
  Alternatively you can further
  subdivided your view hierachy and
  create subview controllers inside
  other subview controllers. In both
  cases the controller instantiating the
  object is responsible for managing the
  subview controller. The responsible
  controller is referred to as 'parent
  controller.' Subclasses can use the
  view controller when they for example
  need to show a modal dialog.

https://github.com/Koolistov/Subview-Controller

ContentLicense: CC BY-SA 2.5

Title: Managing subviews in Cocoa Touch

ContentLicense: CC BY-SA 3.0


问:
How to check for the existence of values after splitting in object, and then assign them if only the last one does not exist
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

```<code>for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/
</code>```

that is, each scroll is added as long as i is less than the length of the array
it should work like this

```<code>obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};
</code>```

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5

答:
Use reduceRight will simplify as one line

const obj = "a1/a2/a3/a4"
  .split("/")
  .reduceRight((acc, curr) => ({ [curr]: acc }), {});

console.log(obj);```

Body:
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/

that is, each scroll is added as long as i is less than the length of the array
it should work like this

obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5


问:
AWS EC2 Performance explanation
I have a REST API web server, built in .NetCore, that has data heavy APIs.

This is hosted on AWS EC2, I have noticed that the average response time for certain APIs are ~4 seconds and if I turn up the AWS-EC2 specs, the response time goes down to a few milliseconds. I guess this is expected, what I don't understand is that even when I load test the APIs on a lower end CPU, the server never crosses 50% utilization of memory/CPU. So what is the correct technical explanation that makes the APIs perform faster if the lower end CPU never reaches a 100% utilization of memory/CPU?

答:
There is no simple answer, there are so many ec2 variations you need to first figure out what is slowing down your API.

When you 'turn up' your ec2 instance, you are getting some combination of more memory, faster cpu, faster disk and more network bandwidth - and we can't tell which one of those 'more' features are improving your performance. Different instance classes ar optimized for different problems.

It could be as simple as the better network bandwidth, or it could be that your application is disk-bound and the better instance you chose is optimized for i/O performance.

Depending on what feature your instance is lacking, it would help you decide which type of instance to upgrade to - or as you have found out, just upgrade to something 'bigger' and be happy with the performance (at the tradeoff of being more expensive).

Title: AWS EC2 Performance explanation


问:
Deployment Angular Project error type MIME (text/html)
I try to deploy an Angular/CLI 6.12.0 project.

When I put "dist" folder content on a server, there is a console error
"type MIME".

Le chargement du module à l’adresse « http://www.sylvainallain.fr/polyfills-es2015.fd917e7c3ed57f282ee5.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
Le chargement du module à l’adresse « http://www.sylvainallain.fr/main-es2015.2fcd6517edb1de962f8a.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
Le chargement du module à l’adresse « http://www.sylvainallain.fr/runtime-es2015.24b02acc1f369d9b9f37.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
```

<p>https://imgur.com/fQKnWAg.jpg</p>

<p>This in French for me ^^.
You can see it in console here http://biblio.sylvainallain.fr</p>

<p>It's a simply application like a library.
Back-end (logs and data) is manage with Firebase.</p>

<p>In local, all is OK.</p>

<p>I make the build with "ng build --prod", it create a "dist" folder.</p>

<p>My index.html after prod:</p>

<pre class="lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Bibliothèque Angular</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.735ba4029395bfd97371.css"></head>
<body>
  <app-root></app-root>
    <script src="polyfills-es5.f9fad3ad3c84e6dbdd72.js" nomodule defer></script>
    <script src="polyfills-es2015.fd917e7c3ed57f282ee5.js" type="module"></script>
    <script src="runtime-es2015.24b02acc1f369d9b9f37.js" type="module"></script>
    <script src="main-es2015.2fcd6517edb1de962f8a.js" type="module"></script>
    <script src="runtime-es5.24b02acc1f369d9b9f37.js" nomodule defer></script>
    <script src="main-es5.2fcd6517edb1de962f8a.js" nomodule defer></script></body>
</html>

</code>```

I find this GitHub post: https://github.com/angular/angular-cli/issues/10325
.This is the same issue, I try some solutions but nothing work.

The issue is only with es2015.*.js files. So I think there is an issue with type="module" which is not recognize like a Javascript file.
I don't understand why Angular don't manage it.

Edit 25 October :

try to replace type="module" with type="application/javascript". Don't work. Source

try to update Angular/CLI & Angular/core with ng update @angular/cli @angular/core --allow-dirty and ng build --prod again. Don't work

try to host it with Firebase. Same issue: https://bibliang.firebaseapp.com/

Thanks for help ! :)

答:
```<code> <script src="polyfills-es2015.fd917e7c3ed57f282ee5.js" type="module"></script>
    <script src="runtime-es2015.24b02acc1f369d9b9f37.js" type="module"></script>
    <script src="main-es2015.2fcd6517edb1de962f8a.js" type="module"></script>

keep all above file in another folder and give path here like

<script src="../../js/polyfills-es2015.fd917e7c3ed57f282ee5.js" type="text/javascript"></script>
</code>```

it will work

Body:
I try to deploy an Angular/CLI 6.12.0 project.

When I put "dist" folder content on a server, there is a console error
"type MIME".

Le chargement du module à l’adresse « http://www.sylvainallain.fr/polyfills-es2015.fd917e7c3ed57f282ee5.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
Le chargement du module à l’adresse « http://www.sylvainallain.fr/main-es2015.2fcd6517edb1de962f8a.js » a été bloqué en raison d’un type MIME interdit (« text/html »).
Le chargement du module à l’adresse « http://www.sylvainallain.fr/runtime-es2015.24b02acc1f369d9b9f37.js » a été bloqué en raison d’un type MIME interdit (« text/html »).

https://imgur.com/fQKnWAg.jpg

This in French for me ^^.
You can see it in console here http://biblio.sylvainallain.fr

It's a simply application like a library.
Back-end (logs and data) is manage with Firebase.

In local, all is OK.

I make the build with "ng build --prod", it create a "dist" folder.

My index.html after prod:

<!doctype html>

  <meta charset="utf-8">
  <title>Bibliothèque Angular</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.735ba4029395bfd97371.css">

  <app-root></app-root>

I find this GitHub post: https://github.com/angular/angular-cli/issues/10325
.This is the same issue, I try some solutions but nothing work.

The issue is only with es2015.*.js files. So I think there is an issue with type="module" which is not recognize like a Javascript file.
I don't understand why Angular don't manage it.

Edit 25 October :

try to replace type="module" with type="application/javascript". Don't work. Source

try to update Angular/CLI & Angular/core with ng update @angular/cli @angular/core --allow-dirty and ng build --prod again. Don't work

try to host it with Firebase. Same issue: https://bibliang.firebaseapp.com/

Thanks for help ! :)

Body:
 <script src="polyfills-es2015.fd917e7c3ed57f282ee5.js" type="module"></script>
    <script src="runtime-es2015.24b02acc1f369d9b9f37.js" type="module"></script>
    <script src="main-es2015.2fcd6517edb1de962f8a.js" type="module"></script>

keep all above file in another folder and give path here like

<script src="../../js/polyfills-es2015.fd917e7c3ed57f282ee5.js" type="text/javascript"></script>

it will work


问:
Using Selenium WebDriver with Java
My web application is a banking application. After entering application URL in IE browser, it checks for browser configuration/resolution in that browser and immediately opens another browser which has the actual application without any Address Bar. I'm trying to switchTo window and identify elements in browser two (where application is loaded).

switchTo window is not working in my case. How to identify elements from this new window? Please help.

EDIT: I even tried switching to 2nd browser based on title of the browser. Still its not working.

public class Test {

    public static void main(String[] args) throws Exception {

        System.setProperty("webdriver.ie.driver", "C://Apps//IEDriverServernew.exe");
        WebDriver driver = new InternetExplorerDriver();

        driver.get("https://argoqa.snv.net");
        Thread.sleep(8000);

        String winHandleBefore = driver.getWindowHandle();
        for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
        }
        //the above for loop iterates only once. shows only one window handle.

        driver.switchTo().frame("iframeContent"); // 2nd Browser has frame.

        Select bank = new Select(driver.findElement(By.name("selectRegionID"))); //trying to select bank
        bank.selectByVisibleText("TEST BANK");

        System.out.println("Selenium Webdriver Script");
        driver.quit();
        Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe");
    }
}
```

答:
Change the registry for IE as shown below, and verify if the new window is detected.

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main

Right-click → New → String Value → Value name: TabProcGrowth (create if not exist)

TabProcGrowth (right-click) → Modify... → Value data: 0

Title: Using Selenium WebDriver with Java


问:
How to solve the Gulp error: imagemin.jpegtran is not a function
I am getting this error whenever I try to make imagemin work for any kind of image:

21:54:49] Starting 'imgmin'...

[21:54:49] 'imgmin' errored after 47 ms

[21:54:49] TypeError: imagemin.jpegtran is not a function

```<code>at imgmin (D:\Dropbox\Side Projects\JS learning\dev-gulp\gulpfile.js:92:26)

at bound (domain.js:419:14)

at runBound (domain.js:432:12)

at asyncRunner (D:\Dropbox\Side Projects\JS learning\dev-gulp\node_modules\async-done\index.js:55:18)

at processTicksAndRejections (internal/process/task_queues.js:75:11)
</code>```

I am currently using:

node version 12.13.1

npm version 6.12.1

gullp cli version: 2.2.0

gulp local version: 4.0.2

Here is my gulpfile.js:

```<code>let mainDir = 'gulp project test';

let gulp = require('gulp'),
    browserSync = require('browser-sync').create(),
    reload = browserSync.reload,
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    cleansCSS = require('gulp-clean-css'),
    sourcemaps = require('gulp-sourcemaps'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    changed = require('gulp-changed'),
    uglyfi = require('gulp-uglify'),
    lineec = require('gulp-line-ending-corrector');

//set directories variables
let root = `../${mainDir}/`,
    scss = root + 'sass',
    js = root + 'src/js',
    cssDist = root + 'dist/css'
jsDist = root + 'dist/js',
    imgSRC = root + 'src/images/*',
    imgDest = root + 'dist/images/*';

//set watch files
let phpWatcher = root + '**/*php', //glob pattern
    styleWatcher = scss + '**/*.scss';

//set the order I want Gulp to concat JS files
let jsSRC = [
    js + 'file1.js',
    js + 'file2.js',
    js + 'file3.js',
    js + 'file4.js',
    js + 'file5.js',
    js + 'file6.js',
];

//set the order I want Gulp to concat CSS files
let cssSRC = [
    root + 'src/css/file1.css',
    root + 'src/css/file2.css',
    root + 'src/css/file3.css',
    root + 'src/css/file4.css',
    cssDist + 'style.css'
];

function css() {
    return gulp.src(scss + 'style.scss')
        .pipe(sourcemaps.init({
            loadMaps: true
        }))
        .pipe(sass({
            outputStyle: 'expanded'
        }).on('error', sass.logError))
        .pipe(autoprefixer('last 2 versions'))
        .pipe(sourcemaps.write())
        .pipe(lineec())
        .pipe(gulp.dest(cssDist))
}

function concatCSS() {
    return gulp.src(cssSRC)
        .pipe(sourcemaps.init({
            loadMaps: true,
            largefile: true
        }))
        .pipe(concat('style.min.css'))
        .pipe(cleansCSS())
        .pipe(sourcemaps.write('./maps/'))
        .pipe(lineec())
        .pipe(gulp.dest(cssDist));
}

function javascript() {
    return gulp.src(jsSRC)
        .pipe(concat('project.js'))
        .pipe(uglyfi())
        .pipe(lineec)
        .pipe(gulp.dest(jsDist));
}

function imgmin() {
    return gulp.src(imgSRC)
        .pipe(changed(imgDest))
        .pipe(imagemin([
            imagemin.gifsicle({
                interlaced: true
            }),
            imagemin.jpegtran({
                progressive: true
            }),
            imagemin.optipng({
                optimizationLevel: 5
            })
        ]))
        .pipe(gulp.dest(imgDest));
}

function watch() {
    browserSync.init({
        open: 'external',
        proxy: 'http://localhost/dev',
        port: 8080,
    });
    gulp.watch(styleWatcher, gulp.series([css, concatCSS]));
    gulp.watch(jsSRC, javascript);
    gulp.watch(imgSRC, imgmin);
    gulp.watch([phpWatcher, jsDist + 'project.js', cssDist + 'style.min.css'])
}

exports.css = css;
exports.concatCSS = concatCSS;
exports.javascript = javascript;
exports.imgmin = imgmin;
exports.watch = watch;

let build = gulp.parallel(watch);
gulp.task('default', build);
</code>```

I found someone had the same error with gifsicle and fixed it by reinstalling the plugins but it didn't work for me.

答:
I found the answer and I write it here in case someone will have the same issue.
imagemin.jpegtran has been substitute by imagemin.mozjpeg. Also, I had to install mozjpeg (npm install --save-dev imagemin-mozjpeg) as, for the time I am writing, it seems it is not installed together with imagemin.</p>

Body:
I am getting this error whenever I try to make imagemin work for any kind of image:

21:54:49] Starting 'imgmin'...

[21:54:49] 'imgmin' errored after 47 ms

[21:54:49] TypeError: imagemin.jpegtran is not a function

at imgmin (D:\Dropbox\Side Projects\JS learning\dev-gulp\gulpfile.js:92:26)

at bound (domain.js:419:14)

at runBound (domain.js:432:12)

at asyncRunner (D:\Dropbox\Side Projects\JS learning\dev-gulp\node_modules\async-done\index.js:55:18)

at processTicksAndRejections (internal/process/task_queues.js:75:11)

I am currently using:

node version 12.13.1

npm version 6.12.1

gullp cli version: 2.2.0

gulp local version: 4.0.2

Here is my gulpfile.js:

let mainDir = 'gulp project test';

let gulp = require('gulp'),
    browserSync = require('browser-sync').create(),
    reload = browserSync.reload,
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    cleansCSS = require('gulp-clean-css'),
    sourcemaps = require('gulp-sourcemaps'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    changed = require('gulp-changed'),
    uglyfi = require('gulp-uglify'),
    lineec = require('gulp-line-ending-corrector');

//set directories variables
let root = `../${mainDir}/`,
    scss = root + 'sass',
    js = root + 'src/js',
    cssDist = root + 'dist/css'
jsDist = root + 'dist/js',
    imgSRC = root + 'src/images/*',
    imgDest = root + 'dist/images/*';

//set watch files
let phpWatcher = root + '**/*php', //glob pattern
    styleWatcher = scss + '**/*.scss';

//set the order I want Gulp to concat JS files
let jsSRC = [
    js + 'file1.js',
    js + 'file2.js',
    js + 'file3.js',
    js + 'file4.js',
    js + 'file5.js',
    js + 'file6.js',
];

//set the order I want Gulp to concat CSS files
let cssSRC = [
    root + 'src/css/file1.css',
    root + 'src/css/file2.css',
    root + 'src/css/file3.css',
    root + 'src/css/file4.css',
    cssDist + 'style.css'
];

function css() {
    return gulp.src(scss + 'style.scss')
        .pipe(sourcemaps.init({
            loadMaps: true
        }))
        .pipe(sass({
            outputStyle: 'expanded'
        }).on('error', sass.logError))
        .pipe(autoprefixer('last 2 versions'))
        .pipe(sourcemaps.write())
        .pipe(lineec())
        .pipe(gulp.dest(cssDist))
}

function concatCSS() {
    return gulp.src(cssSRC)
        .pipe(sourcemaps.init({
            loadMaps: true,
            largefile: true
        }))
        .pipe(concat('style.min.css'))
        .pipe(cleansCSS())
        .pipe(sourcemaps.write('./maps/'))
        .pipe(lineec())
        .pipe(gulp.dest(cssDist));
}

function javascript() {
    return gulp.src(jsSRC)
        .pipe(concat('project.js'))
        .pipe(uglyfi())
        .pipe(lineec)
        .pipe(gulp.dest(jsDist));
}

function imgmin() {
    return gulp.src(imgSRC)
        .pipe(changed(imgDest))
        .pipe(imagemin([
            imagemin.gifsicle({
                interlaced: true
            }),
            imagemin.jpegtran({
                progressive: true
            }),
            imagemin.optipng({
                optimizationLevel: 5
            })
        ]))
        .pipe(gulp.dest(imgDest));
}

function watch() {
    browserSync.init({
        open: 'external',
        proxy: 'http://localhost/dev',
        port: 8080,
    });
    gulp.watch(styleWatcher, gulp.series([css, concatCSS]));
    gulp.watch(jsSRC, javascript);
    gulp.watch(imgSRC, imgmin);
    gulp.watch([phpWatcher, jsDist + 'project.js', cssDist + 'style.min.css'])
}

exports.css = css;
exports.concatCSS = concatCSS;
exports.javascript = javascript;
exports.imgmin = imgmin;
exports.watch = watch;

let build = gulp.parallel(watch);
gulp.task('default', build);

I found someone had the same error with gifsicle and fixed it by reinstalling the plugins but it didn't work for me.


问:
answer incoming phone call from my application
I want to make my application answer the phone calls so I can have the ability to do some processing before allowing the user to answer maybe just display my activity over the InCallScreen but I can't accomplish this.
when I used intentFilter with <action android:name="android.intent.action.ANSWER"></action> when incoming call the InCallScreen start and not my activity and when using broadcastReciever with <action android:name="android.intent.action.PHONE_STATE"></action> I can't use abortBroadcast() method because its non-ordered broadcast.

Any help please

EDIT 1

I managed to display my activity over the InCallScreen by wait 1 second before starting my activity in onReceive of broadcastReceiver method but the InCallScreen is displayed first for portion of time which may allow the user to answer before the processing start and if I reduced the time to wait this may cause InCallScreen to be displayed above my activity. Any other solution will be appreciated.

答: Check out Tedds Droid Tools. It talks about programmatically answering calls. Specifically, you want to look at the Features portion of the Readme.</p>


问:
In TypeScript, can I restrict type of indexer value based on narrow type of indexer key?
Simple example (type of x):

const x = {
    'a': { key: 'a' },
    'b': { key: 'b' },
    'c': { key: 'c' },
    // ...
};
```

If I knew all a/b/c/… in advance, I could do { [TKey in 'a'|'b'|'c']: { key: TKey } }.

But can I define a type so that for any key k value must have { key: k } without having a full list of keys in advance?

答:
You can let the compiler message guide you:

This is what you would like:

```<code>type Foo<K> = { [TKey in K]: { key: TKey } }
</code>```

but it doesn't compile because

```<code>Type 'K' is not assignable to type 'string | number | symbol'.
  Type 'K' is not assignable to type 'symbol'.
</code>```

Assuming (based on your example) you want to work only with string keys:

```<code>type Foo<K extends string> = { [TKey in K]: { key: TKey } }
</code>```

So you can pass your own narrowed type that's based on string:

```<code>type X = Foo<'a' | 'b' | 'c'>
</code>```

```<code>type X = {
    a: {
        key: "a";
    };
    b: {
        key: "b";
    };
    c: {
        key: "c";
    };
}
</code>```

Body:
Simple example (type of x):

const x = {
    'a': { key: 'a' },
    'b': { key: 'b' },
    'c': { key: 'c' },
    // ...
};

If I knew all a/b/c/… in advance, I could do { [TKey in 'a'|'b'|'c']: { key: TKey } }.

But can I define a type so that for any key k value must have { key: k } without having a full list of keys in advance?

Body:
You can let the compiler message guide you:

This is what you would like:

type Foo<K> = { [TKey in K]: { key: TKey } }

but it doesn't compile because

Type 'K' is not assignable to type 'string | number | symbol'.
  Type 'K' is not assignable to type 'symbol'.

Assuming (based on your example) you want to work only with string keys:

type Foo<K extends string> = { [TKey in K]: { key: TKey } }

So you can pass your own narrowed type that's based on string:

type X = Foo<'a' | 'b' | 'c'>

type X = {
    a: {
        key: "a";
    };
    b: {
        key: "b";
    };
    c: {
        key: "c";
    };
}


问:
Mysql command not found in OS X 10.7
I cant get my mysql to start  on os x 10.7.  It is located in /usr/local/mysql/bin/mysql

I get command not found when I type mysql --version in the terminal.

I tried this can't access mysql from command line mac but still get command not found.  I tried installing mysql with the dmg and i have tried to install it through homebrew and I cant get it to work.  When I try to start mysql with homebrew I get MySQL won't start

This is my $PATH:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/Users/Victoria/bin:/usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin

答:
in terminal do:

```<code>vi ~/.bash_profile
</code>```

And add this line:

```<code>export PATH=${PATH}:/usr/local/mysql/bin
</code>```

and the type this in terminal:

```<code>mysql -u [username] -p [password]
</code>```

Title: Mysql command not found in OS X 10.7

Body:
in terminal do:

vi ~/.bash_profile

And add this line:

export PATH=${PATH}:/usr/local/mysql/bin

and the type this in terminal:

mysql -u [username] -p [password]


问:
ExpectUpdate for a submit button
I am checking my shiny app if it is running properly or not. So one method is using expectUpdate.

```<code>app <- ShinyDriver$new(getwd())
expectUpdate(app, n = 5, add = 1, output = "sum", timeout = 3000)
Error: Updating ‘n’, ‘add’ did not update ‘sum’, or it is taking longer than 3000 ms.
</code>```

App below

```<code>shinyApp(
    fluidPage(
        numericInput("n", "Number to add", 5),
        actionButton("add", "Add"),
        verbatimTextOutput("sum", placeholder = TRUE)
    ),
    function(input, output, session) {
        nums <- numeric()

        c_sum <- eventReactive(input$add, {
            nums <<- c(nums, input$n)
            sum(nums)
        })

        output$sum <- renderText({
            c_sum()
        })

    }
)
</code>```

答:
Looks like updating a button does not work with expectUpdate. Here is another way which performs the same test:

```<code>library(shinytest)
library(testthat)

app <- ShinyDriver$new(getwd())
old_sum <- app$getValue("sum")
app$setInputs(add = "click")
new_sum <- app$getValue("sum")
expect_false(old_sum == new_sum)
app$stop()
</code>```

Title: ExpectUpdate for a submit button

Body:
I am checking my shiny app if it is running properly or not. So one method is using expectUpdate.

app <- ShinyDriver$new(getwd())
expectUpdate(app, n = 5, add = 1, output = "sum", timeout = 3000)
Error: Updating ‘n’, ‘add’ did not update ‘sum’, or it is taking longer than 3000 ms.

App below

shinyApp(
    fluidPage(
        numericInput("n", "Number to add", 5),
        actionButton("add", "Add"),
        verbatimTextOutput("sum", placeholder = TRUE)
    ),
    function(input, output, session) {
        nums <- numeric()

        c_sum <- eventReactive(input$add, {
            nums <<- c(nums, input$n)
            sum(nums)
        })

        output$sum <- renderText({
            c_sum()
        })

    }
)

Body:
Looks like updating a button does not work with expectUpdate. Here is another way which performs the same test:

library(shinytest)
library(testthat)

app <- ShinyDriver$new(getwd())
old_sum <- app$getValue("sum")
app$setInputs(add = "click")
new_sum <- app$getValue("sum")
expect_false(old_sum == new_sum)
app$stop()


问:
Could the parameter of macro pass to variable of char array?
The below code has compile error: preprocessor command must start as first nonwhite space

```<code>#define Assert(expr, format, ...)                               \
if(!(!!(expr)))                                                 \
{                                                               \
char message[4096] = #format;                                   \
}
</code>```

Please help me out. I want to get the string passed to 'format'.

答:
For my money, either there is something wrong before this code, or there are spaces after a backslash, or there is some other non-obvious problem.  When I select the macro in the browser, there are three spaces after the third backslash.  Those formally terminate the Assert macro and leave the # on the next line to trigger the error. (Outside of a macro definition, the # symbol has no meaning in C++ other than to start a preprocessor directive.)

I've added a pipe at the end of each line.

```<code>#define Assert(expr, format, ...)                               \|
if(!(!!(expr)))                                                 \|
{                                                               \   |
char message[4096] = #format;                                   \|
}|
</code>```

Remove those blanks and watch the error vanish.  Don't allow trailing blanks in your code.

When I place the code copied from the question into a file pp71.cpp and try to compile it to an object file (which would be empty), I get:

```<code>$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -c pp71.cpp
pp71.cpp:3:65: error: backslash and newline separated by space [-Werror]
    3 | {                                                               \
      |
cc1plus: all warnings being treated as errors
$
</code>```

That's from GCC 9.2.0 on a MacBook Pro running macOS Catalina 10.15.3.

Body:
The below code has compile error: preprocessor command must start as first nonwhite space

#define Assert(expr, format, ...)                               \
if(!(!!(expr)))                                                 \
{                                                               \
char message[4096] = #format;                                   \
}

Please help me out. I want to get the string passed to 'format'.

Body:
For my money, either there is something wrong before this code, or there are spaces after a backslash, or there is some other non-obvious problem.  When I select the macro in the browser, there are three spaces after the third backslash.  Those formally terminate the Assert macro and leave the # on the next line to trigger the error. (Outside of a macro definition, the # symbol has no meaning in C++ other than to start a preprocessor directive.)

I've added a pipe at the end of each line.

#define Assert(expr, format, ...)                               \|
if(!(!!(expr)))                                                 \|
{                                                               \   |
char message[4096] = #format;                                   \|
}|

Remove those blanks and watch the error vanish.  Don't allow trailing blanks in your code.

When I place the code copied from the question into a file pp71.cpp and try to compile it to an object file (which would be empty), I get:

$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -c pp71.cpp
pp71.cpp:3:65: error: backslash and newline separated by space [-Werror]
    3 | {                                                               \
      |
cc1plus: all warnings being treated as errors
$

That's from GCC 9.2.0 on a MacBook Pro running macOS Catalina 10.15.3.


问:
How to create local "copy" of remote Hasura server?
I want to set up a dev environment of Hasura on my local machine, that replicates my existing production (same tables, same schema, same data).

What are the required steps to achieve this task?

答:
Backup the database.

Run Hasura with the database.

Make sure Hasura metadata is synced.


问:
Error exception handling of Java FX input field, ensure that field only accepts positive integers
At the moment my error exception handling returns an error if the field is empty - how can I expand this to include all characters which are not positive integers? </p>

```<code>Button hdButton=new Button();
hdButton.setText("Save");
hdButton.setOnAction(e ->
    {
        if(memoryField.getText().isEmpty())
        {
            dsdisplay2.setText("ERROR: You must enter a positive number in order to set the
            memory\n");
        }
        else
        {
            s1.setHardDisk(Integer.parseInt(hardDisk.getText()));
            dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());

        }
</code>```

答:
Wrap Integer.parseInt() in a try block and catch the NumberFormatException.

```<code>try {
    int size = Integer.parseInt(hardDisk.getText());
    s1.setHardDisk(size);
    dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());
} catch (NumberFormatException e) {
    dsdisplay2.setText("ERROR: You must enter a positive number in order to set the memory\n");
}
</code>```

This way, you won't need to validate the input before setting s1.setHardDisk as the Integer.parseInt will throw an exception if the input is malformed.

Body:
At the moment my error exception handling returns an error if the field is empty - how can I expand this to include all characters which are not positive integers?

Button hdButton=new Button();
hdButton.setText("Save");
hdButton.setOnAction(e ->
    {
        if(memoryField.getText().isEmpty())
        {
            dsdisplay2.setText("ERROR: You must enter a positive number in order to set the
            memory\n");
        }
        else
        {
            s1.setHardDisk(Integer.parseInt(hardDisk.getText()));
            dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());

        }

Body:
Wrap Integer.parseInt() in a try block and catch the NumberFormatException.

try {
    int size = Integer.parseInt(hardDisk.getText());
    s1.setHardDisk(size);
    dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());
} catch (NumberFormatException e) {
    dsdisplay2.setText("ERROR: You must enter a positive number in order to set the memory\n");
}

This way, you won't need to validate the input before setting s1.setHardDisk as the Integer.parseInt will throw an exception if the input is malformed.


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
```<code>SELECT NULL AS ID, Column1, Column2, ..., ColumnN
    FROM my_table
</code>```

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!


问:
VelocityEngineUtils has been removed in Spring 3.2 so what else to use?
Today I have upgraded my entire Spring web application from using Spring 3.1.1 to Spring 3.2.

Most part of my existing app does not break except that in Spring 3.2, the

```<code>org.springframework.ui.velocity.VelocityEngineUtils
</code>```

class seems to be removed completely from the spring-context-3.2.0.RELEASE.jar.

I found the migration guide as in this url.

It stated that org.springframework.ui.velocity.VelocityEngineUtils class has just been deprecated, but in fact it has been removed completely.

Maybe I'm just mistaken, I would like to know if the VelocityEngineUtils class still exist in somewhere or if not, what is the alternative class that I can use.

EDIT: It seems the entire velocity package has been removed from Spring 3.2 so now even
org.springframework.ui.velocity.VelocityEngineFactoryBean does not exist. Are Spring walking away from Velocity?

答:
VelocityEngineUtils is deprecated in spring > 3.2

Below dependency will work perfectly

```<code><dependency>
            <groupId>com.alibaba.spring</groupId>
            <artifactId>spring-webmvc-velocity</artifactId>
            <version>1.4.3.18.RELEASE</version>
 </dependency>
</code>```

It's recommended to deprecate Velocity altogether and replace with thymeleaf

Body:
Today I have upgraded my entire Spring web application from using Spring 3.1.1 to Spring 3.2.

Most part of my existing app does not break except that in Spring 3.2, the

org.springframework.ui.velocity.VelocityEngineUtils

class seems to be removed completely from the spring-context-3.2.0.RELEASE.jar.

I found the migration guide as in this url.

It stated that org.springframework.ui.velocity.VelocityEngineUtils class has just been deprecated, but in fact it has been removed completely.

Maybe I'm just mistaken, I would like to know if the VelocityEngineUtils class still exist in somewhere or if not, what is the alternative class that I can use.

EDIT: It seems the entire velocity package has been removed from Spring 3.2 so now even
org.springframework.ui.velocity.VelocityEngineFactoryBean does not exist. Are Spring walking away from Velocity?

Body:
VelocityEngineUtils is deprecated in spring > 3.2

Below dependency will work perfectly

<dependency>
            <groupId>com.alibaba.spring</groupId>
            <artifactId>spring-webmvc-velocity</artifactId>
            <version>1.4.3.18.RELEASE</version>
 </dependency>

It's recommended to deprecate Velocity altogether and replace with thymeleaf


问:
R replacing words in column by annotation dataframe
I have a dataframe with in 1 column gene IDs (data1). In another dataframe I have the corresponding gene names (data2). Data1 also contains cells with multiple genenames, separated with ':', and also a lot of NAs. Preferably I want to add a column to data1 with the corresponding gene names, also separated by ':' if there are multiple. An alternative would be to replace all the genenames in data1 with the corresponding gene names. Any idea how to go about this? Thanks!</p>

```<code>a <- c("ENSG00000150401:ENSG00000150403", "ENSG00000185294", "NA")
data1 <- data.frame(a)

b <- c("ENSG00000150401", "ENSG00000150403", "ENSG00000185294")
c <- c("GeneA", "GeneB", "GeneC")
data2 <- data.frame(b,c)
</code>```

答:
One option involving stringr could be:

```<code>data1$res <- str_replace_all(data1$a, setNames(data2$c, data2$b))

                                a         res
1 ENSG00000150401:ENSG00000150403 GeneA:GeneB
2                 ENSG00000185294       GeneC
3                              NA          NA
</code>```

Body:
I have a dataframe with in 1 column gene IDs (data1). In another dataframe I have the corresponding gene names (data2). Data1 also contains cells with multiple genenames, separated with ':', and also a lot of NAs. Preferably I want to add a column to data1 with the corresponding gene names, also separated by ':' if there are multiple. An alternative would be to replace all the genenames in data1 with the corresponding gene names. Any idea how to go about this? Thanks!

a <- c("ENSG00000150401:ENSG00000150403", "ENSG00000185294", "NA")
data1 <- data.frame(a)

b <- c("ENSG00000150401", "ENSG00000150403", "ENSG00000185294")
c <- c("GeneA", "GeneB", "GeneC")
data2 <- data.frame(b,c)

Body:
One option involving stringr could be:

data1$res <- str_replace_all(data1$a, setNames(data2$c, data2$b))

                                a         res
1 ENSG00000150401:ENSG00000150403 GeneA:GeneB
2                 ENSG00000185294       GeneC
3                              NA          NA


问:
how do you get window ID for xdotool automatically
I am trying to automate testing forms that selenium would take too long (javascript heavy modern forms), and I want to use xdotool and get window IDs. I see you can call xdotool selectwindow and click it, but then you have to click it each time. I want to tell it "for google chrome windows where the tab title is x, do y"

I got the window ID here:

```<code>cchilders@cchilders-Dell-Precision-M3800:~$ xdotool selectwindow
65011713
</code>```

This is for chrome itself, each tab gets the same value when clicked. So I expected to find that in ps or a window manager, but no:

```<code>cchilders@cchilders-Dell-Precision-M3800:~$ wmctrl -l
0x03a00001  0 cchilders-Dell-Precision-M3800 views.py - /home/cchilders/work_projects - Atom
0x03a00048  0 cchilders-Dell-Precision-M3800 pip_freeze_update.py - /home/cchilders/scripts - Atom
0x03a000bc  0 cchilders-Dell-Precision-M3800 urls.py - /home/cchilders/work_projects - Atom
</code>```

nor does ps work:

```<code>(clientsite)cchilders@cchilders-Dell-Precision-M3800:~$ ps -alx
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
4     0     1     0  20   0 185188  5752 ep_pol Ss   ?          0:06 /sbin/init splash
1     0     2     0  20   0      0     0 kthrea S    ?          0:00 [kthreadd]
1     0     3     2  20   0      0     0 smpboo S    ?          0:02 [ksoftirqd/0]
1     0     5     2   0 -20      0     0 worker S<   ?          0:00 [kworker/0:0H]
1     0     7     2  20   0      0     0 rcu_gp S    ?          1:10 [rcu_sched]
1     0     8     2  20   0      0     0 rcu_gp S    ?          0:00 [rcu_bh]
...etc...
</code>```

nowhere does 65011713 show up. Xdotool is a great tool, but the window manipulation expects you to know a lot about the windows, and from what I remember of using it before, the WINDOW COMMANDS section of https://www.semicomplete.com/projects/xdotool/xdotool.xhtml#window_commands has a lot of ways to find a window you know a lot about, but not much in the way of automating getting that window info. How can I determine the window ID (the format xdotool wants) automatically, say by feeding a script the beginning portion of a URL? Thank you

You can look for Google Chrome in the wmtrl:

```<code>(scripts)cchilders@cchilders-Dell-Precision-M3800:~/scripts/bash$ wmctrl -l
0x03e00001  0 cchilders-Dell-Precision-M3800 Edit - Stack Overflow - Google Chrome
...
</code>```

and grab the first number separated by space to int:

```<code>In [13]: int("0x03e00001", 16)
Out[13]: 65011713
</code>```

The 16 flag in int tells it expect hexadecimal

```<code>In [14]: int("0x03e00001")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-96517b980767> in <module>()
----> 1 int("0x03e00001")

ValueError: invalid literal for int() with base 10: '0x03e00001'
</code>```

答:
If you are running a linux system and are using x-display manager, the command xwininfo to get window information may work for you.

You can run or script the command xwininfo -root -tree and get a detailed and organized output of the xwindows system and the window IDs. You can see how I have used the xwininfo output in a small bot I created for runescape. I store the hexidecimal ID of the window title and then convert it to binary using printf %i and the hex of the window I am interested in. From there, I can script xdotool to do whatever I want in or with the window by making it the active window and moving the mouse to it using xdotool.

So the steps for this method are:

Get the window information using xwininfo -root -tree.

Store the window ID that you are interested in.
(There may be multiple listings of the window name with different
 hex IDs and you will have to know the parent hex ID which is
 usually the first listed and commonly outlines the child processes in

 a sub-tree.)

Convert the window hex ID into binary so xdotool can recognize it.

Use the windowactivate option with xdotool in order to getxdotool
to interact with the correct window.

Perform whatever next steps you wish.

So it's really quite simple, although a bit time-consuming at first, but once you develop your own method for storing the parent window's hex ID, the rest can be easily automated and no worries arise. If you have trouble determining which hex ID belongs to the parent window, there are ways of checking for parent vs child processes but I don't know if you want to go into all of that. Just comment if you want me to include that information.

I hope this was helpful.

Body:
I am trying to automate testing forms that selenium would take too long (javascript heavy modern forms), and I want to use xdotool and get window IDs. I see you can call xdotool selectwindow and click it, but then you have to click it each time. I want to tell it "for google chrome windows where the tab title is x, do y"

I got the window ID here:

cchilders@cchilders-Dell-Precision-M3800:~$ xdotool selectwindow
65011713

This is for chrome itself, each tab gets the same value when clicked. So I expected to find that in ps or a window manager, but no:

cchilders@cchilders-Dell-Precision-M3800:~$ wmctrl -l
0x03a00001  0 cchilders-Dell-Precision-M3800 views.py - /home/cchilders/work_projects - Atom
0x03a00048  0 cchilders-Dell-Precision-M3800 pip_freeze_update.py - /home/cchilders/scripts - Atom
0x03a000bc  0 cchilders-Dell-Precision-M3800 urls.py - /home/cchilders/work_projects - Atom

nor does ps work:

(clientsite)cchilders@cchilders-Dell-Precision-M3800:~$ ps -alx
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
4     0     1     0  20   0 185188  5752 ep_pol Ss   ?          0:06 /sbin/init splash
1     0     2     0  20   0      0     0 kthrea S    ?          0:00 [kthreadd]
1     0     3     2  20   0      0     0 smpboo S    ?          0:02 [ksoftirqd/0]
1     0     5     2   0 -20      0     0 worker S<   ?          0:00 [kworker/0:0H]
1     0     7     2  20   0      0     0 rcu_gp S    ?          1:10 [rcu_sched]
1     0     8     2  20   0      0     0 rcu_gp S    ?          0:00 [rcu_bh]
...etc...

nowhere does 65011713 show up. Xdotool is a great tool, but the window manipulation expects you to know a lot about the windows, and from what I remember of using it before, the WINDOW COMMANDS section of https://www.semicomplete.com/projects/xdotool/xdotool.xhtml#window_commands has a lot of ways to find a window you know a lot about, but not much in the way of automating getting that window info. How can I determine the window ID (the format xdotool wants) automatically, say by feeding a script the beginning portion of a URL? Thank you

You can look for Google Chrome in the wmtrl:

(scripts)cchilders@cchilders-Dell-Precision-M3800:~/scripts/bash$ wmctrl -l
0x03e00001  0 cchilders-Dell-Precision-M3800 Edit - Stack Overflow - Google Chrome
...

and grab the first number separated by space to int:

In [13]: int("0x03e00001", 16)
Out[13]: 65011713

The 16 flag in int tells it expect hexadecimal

In [14]: int("0x03e00001")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-96517b980767> in <module>()
----> 1 int("0x03e00001")

ValueError: invalid literal for int() with base 10: '0x03e00001'


问:
JavaScript Ajax - Prevent Division by Zero Function
I am building a calculator for a class using AJAX. I am having issues with my if else statement not working. It is supposed to display an alert, telling the user that they cannot divide by zero except the alert never shows. I am a beginner to Ajax, if anyone could provide guidance, it'd be greatly appreciated - I know it's probably something simple that I'm overlooking. Below is my function:

...

```<code>    }

    function divFunc() {

        var fn = "divide";
        getResult(fn);
        event.preventDefault();
        return;

        if (frmMain.txtBxSecNum.value == 0) {
            $('#alert').text("You cannot divide by zero!");
        }
        else { (frmMain.txtBxFirstNum.value == 0)
            $('#alert').text("You cannot divide by zero!");

        }
    }
</code>```

...

答:
Please remove 『return;』

This statement does not work because return is added above, so the following statement is not executed

Body:
I am building a calculator for a class using AJAX. I am having issues with my if else statement not working. It is supposed to display an alert, telling the user that they cannot divide by zero except the alert never shows. I am a beginner to Ajax, if anyone could provide guidance, it'd be greatly appreciated - I know it's probably something simple that I'm overlooking. Below is my function:

...

    }

    function divFunc() {

        var fn = "divide";
        getResult(fn);
        event.preventDefault();
        return;

        if (frmMain.txtBxSecNum.value == 0) {
            $('#alert').text("You cannot divide by zero!");
        }
        else { (frmMain.txtBxFirstNum.value == 0)
            $('#alert').text("You cannot divide by zero!");

        }
    }

...


问:
User Control Connection
I have created the kiosk system with several user controls and need to connect the hotdrinks user control using a button which is in the colddrinks user control.

When I use the following code it displays the both user controls together and hotdrinks displays under the colddrinks.I need to hide colddrinks first and display hotdrinks next.
I think need to use child and parent connection here, but didn't know how to do that. Please help me.

```<code>OrderTakingMenu ordertakingmenu;
HotDrinks hotDrinks;

public UserControl currentPanel;

public ColdDrink(OrderTakingMenu ordertakingmenuIn)
{
    InitializeComponent();
    this.Location = new System.Drawing.Point(5, 100);
    ordertakingmenu = ordertakingmenuIn;
}

private void btnHotDrinks_Click(object sender, EventArgs e)
{
    removePreviousPanel();
    currentPanel = new HotDrinks(ordertakingmenu);
    this.Controls.Add(currentPanel);
}

private void removePreviousPanel()
{
    this.Controls.Remove(currentPanel);
}
</code>```

答:
I would use the Visible property.  First add both user controls on the form, and have them overlap each other (both at the same location, same size).</p>

```<code>public ColdDrink(OrderTakingMenu ordertakingmenuIn)
{
    InitializeComponent();
    this.Location = new System.Drawing.Point(5, 100);
    ordertakingmenu = ordertakingmenuIn;
    coldDrinksPanel.Visible = true;
    hotDrinksPanel.Visible = false;
}

private void btnHotDrinks_Click(object sender, EventArgs e)
{
    hotDrinksPanel.Visible = true;
    coldDrinksPanel.Visible = false;
}
</code>```

Title: User Control Connection

Body:
I have created the kiosk system with several user controls and need to connect the hotdrinks user control using a button which is in the colddrinks user control.

When I use the following code it displays the both user controls together and hotdrinks displays under the colddrinks.I need to hide colddrinks first and display hotdrinks next.
I think need to use child and parent connection here, but didn't know how to do that. Please help me.

OrderTakingMenu ordertakingmenu;
HotDrinks hotDrinks;

public UserControl currentPanel;

public ColdDrink(OrderTakingMenu ordertakingmenuIn)
{
    InitializeComponent();
    this.Location = new System.Drawing.Point(5, 100);
    ordertakingmenu = ordertakingmenuIn;
}

private void btnHotDrinks_Click(object sender, EventArgs e)
{
    removePreviousPanel();
    currentPanel = new HotDrinks(ordertakingmenu);
    this.Controls.Add(currentPanel);
}

private void removePreviousPanel()
{
    this.Controls.Remove(currentPanel);
}

Body:
I would use the Visible property.  First add both user controls on the form, and have them overlap each other (both at the same location, same size).

public ColdDrink(OrderTakingMenu ordertakingmenuIn)
{
    InitializeComponent();
    this.Location = new System.Drawing.Point(5, 100);
    ordertakingmenu = ordertakingmenuIn;
    coldDrinksPanel.Visible = true;
    hotDrinksPanel.Visible = false;
}

private void btnHotDrinks_Click(object sender, EventArgs e)
{
    hotDrinksPanel.Visible = true;
    coldDrinksPanel.Visible = false;
}


问:
Custom build step for SAM CLI
When using the AWS SAM CLI to build a serverless application, it located dependencies magically and installs them all as the "build" step. For example, using a NodeJS application:

```<code>$> sam build
Building resource 'HelloWorldFunction'
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

$>
</code>```

Looking at the official documentation they're happy to simply treat it like magic, saying that it:

iterates through the functions in your application, looks for a manifest file (such as requirements.txt) that contains the dependencies, and automatically creates deployment artifacts that you can deploy to Lambda

But what if I have a dependency beyond just those specified in the manifest file? What if my code depends on a compiled binary file, or a static data file?

I would like to add additional build steps so that when I run sam build it compiles these files or copies them appropriately. Is there any way to do this?

答:
You will need to wrap this command into another custom command and add the steps you need to it.

You can create a make file with multiple targets that satisfy your requirements.

I haven't used sam build before, I usually have a make target for that purpose.

you can give it a try with this bootstrap template here https://github.com/healthbridgeltd/nodejs-sam-bootstrap which is more efficient than using sam build.

Title: Custom build step for SAM CLI

Body:
When using the AWS SAM CLI to build a serverless application, it located dependencies magically and installs them all as the "build" step. For example, using a NodeJS application:

$> sam build
Building resource 'HelloWorldFunction'
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

$>

Looking at the official documentation they're happy to simply treat it like magic, saying that it:

iterates through the functions in your application, looks for a manifest file (such as requirements.txt) that contains the dependencies, and automatically creates deployment artifacts that you can deploy to Lambda

But what if I have a dependency beyond just those specified in the manifest file? What if my code depends on a compiled binary file, or a static data file?

I would like to add additional build steps so that when I run sam build it compiles these files or copies them appropriately. Is there any way to do this?


问:
How to know if url is already bookmarked
I am adding bookmark from code. Now in Firefox if user already added the url as bookmark he should not be able to bookmark it again. How can I do it? For now every time a new bookmark is getting created.</p>

答: As an alternative, try setting a cookie whenever the user bookmarks your site using your Javascript.  If the cookie exists, remove the bookmark button (or whatever).</p>

OwnerDisplayName: Tanmoy Rajguru

OwnerDisplayName: strager


问:
How to cherry-pick a range of commits and merge them into another branch?
I have the following repository layout:

master branch (production)

integration

working

What I want to achieve is to cherry-pick a range of commits from the working branch and merge it into the integration branch. I'm pretty new to git and I can't figure out how to exactly do this (the cherry-picking of commit ranges in one operation, not the merging) without messing the repository up. Any pointers or thoughts on this? Thanks!

答:
I have tested that some days ago, after reading the  very clear explanation of Vonc.

My steps

Start

Branch dev : A B C D E F G H I J

Branch target: A B C D

I don't want E nor H

Steps to copy features without the step E and H in the branch dev_feature_wo_E_H

git checkout dev

git checkout -b dev_feature_wo_E_H

git rebase --interactive --rebase-merges --no-ff D where I put drop front of E and H in the rebase editor

resolve conflicts, continue and commit

Steps to copy the branch dev_feature_wo_E_H on target.

git checkout target

git merge --no-ff --no-commit  dev_feature_wo_E_H

resolve conflicts, continue and commit

Some remarks

I've done that because of too much cherry-pick in the days before

git cherry-pick is powerful and simple but

it creates duplicates commits

and when I want to merge I have to resolve conflicts of the initial commits and duplicates commits, so for one or two cherry-pick, it's OK to "cherry-picking" but for more  it's too verbose and the branch will become too complex


问:
How to connect Two Dark Mode buttons on the same Page?
I have been using two dark mode buttons on my Page. One at menu bar and the other on the Footer.

However, the problem is that whenver I switch to dark mode from any one button the other button doesn't toggles itself.

Say, if I switch the night Mode from Menu bar, then the footer button will keep showing that the Day Mode is enabled.

This is my Website Test Page.

Kindly help in solving my problem with code as well.

Thanks

Code for button on Menu Bar

```<code>
    <label class="switch" style="padding: 23px 0;">
        <input type="checkbox" onclick="themeToggle()" class="theme-switcher">
        <div>
            <span></span>
        </div>

</code>```

Code for button on Footer

```<code>
    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label>

</code>```

The js for both the buttons

```<code>
    var tSwitcher = document.getElementsByClassName('theme-switcher');
    let element = document.body;

    let onpageLoad = localStorage.getItem("theme") || "";
    if (onpageLoad != null && onpageLoad == 'dark-mode') {
            for(let i = 0; i<tSwitcher.length; i++){
                    tSwitcher[i].checked = true;
        }

    }

    if(onpageLoad) element.classList.add(onpageLoad);

    function themeToggle() {
        if (event.target.checked) {
          localStorage.setItem('theme', 'dark-mode');
          element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
          element.classList.remove('dark-mode');
        }
      }

</code>```

答:
 var tSwitcher = document.getElementsByClassName('theme-switcher')[0];
var t2 = document.getElementsByClassName('theme-switcher-2')[0];

 function themeToggle() {
  if (event.target.checked) {
    tSwitcher.checked = true;
    t2.checked = true
    localStorage.setItem('theme', 'dark-mode');
    element.classList.add('dark-mode');
  } else {
     tSwitcher.checked = false;
     t2.checked = false
     localStorage.setItem('theme', '');
     element.classList.remove('dark-mode');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <input type="checkbox" onclick="themeToggle()" class="theme-switcher">
 <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2"></code>```

whenever themeToggle is called, change the checked attribute of both the inputs.

Body:
I have been using two dark mode buttons on my Page. One at menu bar and the other on the Footer.

However, the problem is that whenver I switch to dark mode from any one button the other button doesn't toggles itself.

Say, if I switch the night Mode from Menu bar, then the footer button will keep showing that the Day Mode is enabled.

This is my Website Test Page.

Kindly help in solving my problem with code as well.

Thanks

Code for button on Menu Bar

        <input type="checkbox" onclick="themeToggle()" class="theme-switcher">

Code for button on Footer

    <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">

The js for both the buttons

    var tSwitcher = document.getElementsByClassName('theme-switcher');
    let element = document.body;

    let onpageLoad = localStorage.getItem("theme") || "";
    if (onpageLoad != null && onpageLoad == 'dark-mode') {
            for(let i = 0; i<tSwitcher.length; i++){
                    tSwitcher[i].checked = true;
        }

    }

    if(onpageLoad) element.classList.add(onpageLoad);

    function themeToggle() {
        if (event.target.checked) {
          localStorage.setItem('theme', 'dark-mode');
          element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
          element.classList.remove('dark-mode');
        }
      }

Body:
 var tSwitcher = document.getElementsByClassName('theme-switcher')[0];
var t2 = document.getElementsByClassName('theme-switcher-2')[0];

 function themeToggle() {
  if (event.target.checked) {
    tSwitcher.checked = true;
    t2.checked = true
    localStorage.setItem('theme', 'dark-mode');
    element.classList.add('dark-mode');
  } else {
     tSwitcher.checked = false;
     t2.checked = false
     localStorage.setItem('theme', '');
     element.classList.remove('dark-mode');
  }
}

 <input type="checkbox" onclick="themeToggle()" class="theme-switcher">
 <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">

whenever themeToggle is called, change the checked attribute of both the inputs.


问:
How to hide multiple images and show only one image?
I have many buttons and each one must show a different image when that particular button is clicked. The issue is that when a button is clicked, it shows the new image as well as the image from the previous button. How can I hide all the previous images and only show the one that's attached to the button that was most recently clicked?</p>

```<code> <button class="colour-btn colour-btn--3" id="3" onClick="showImage3()"></button>
 <button class="colour-btn colour-btn--8" onClick="showImage8()"></button>
</code>```

```<code>function showImage3() {
    showImage3 = function () {}
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}

function showImage8() {
    showImage8 = function () {}
    var img8 = document.createElement('img')
    img8.setAttribute("src", "")
    img8.setAttribute("width", "600")
    img8.setAttribute("height", "400")
    document.body.appendChild(img8)
}
</code>```

答:
Not clear why do you need separate functions here. You can use data-* attribute and based on that you can set the style property. You can set all the previous images style to none using querySelectorAll() and forEach().

Also you probably do want to append image again if it is already in the DOM, in that case instead of appending again you can simply show that.

Demo:

function showImage(el) {
  var images = document.querySelectorAll('img');
  Array.from(images).forEach(i => i.style.display = 'none');
  var img = document.createElement('img');
  img.setAttribute("src", "");
  var dataId = el.getAttribute('data-id');
  if(dataId == '3'){
    img.setAttribute("width", "700");
    img.setAttribute("height", "400");
  }
  else if(dataId == '8'){
    img.setAttribute("width", "600");
    img.setAttribute("height", "400");
  }
  if(document.querySelector(`img[data-id="${dataId}"]`)){
    document.querySelector(`img[data-id="${dataId}"]`).style.display = 'block';
  }
  else{
    img.setAttribute('data-id', dataId);
    document.body.appendChild(img);
  }
  console.log('current image:', el.getAttribute('data-id'));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="colour-btn colour-btn--3" data-id="3" onClick="showImage(this)">3</button>
<button class="colour-btn colour-btn--8" data-id="8" onClick="showImage(this)">8</button></code>```

Body:
I have many buttons and each one must show a different image when that particular button is clicked. The issue is that when a button is clicked, it shows the new image as well as the image from the previous button. How can I hide all the previous images and only show the one that's attached to the button that was most recently clicked?

 <button class="colour-btn colour-btn--3" id="3" onClick="showImage3()"></button>
 <button class="colour-btn colour-btn--8" onClick="showImage8()"></button>

function showImage3() {
    showImage3 = function () {}
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}

function showImage8() {
    showImage8 = function () {}
    var img8 = document.createElement('img')
    img8.setAttribute("src", "")
    img8.setAttribute("width", "600")
    img8.setAttribute("height", "400")
    document.body.appendChild(img8)
}

Body:
Not clear why do you need separate functions here. You can use data-* attribute and based on that you can set the style property. You can set all the previous images style to none using querySelectorAll() and forEach().

Also you probably do want to append image again if it is already in the DOM, in that case instead of appending again you can simply show that.

Demo:

function showImage(el) {
  var images = document.querySelectorAll('img');
  Array.from(images).forEach(i => i.style.display = 'none');
  var img = document.createElement('img');
  img.setAttribute("src", "");
  var dataId = el.getAttribute('data-id');
  if(dataId == '3'){
    img.setAttribute("width", "700");
    img.setAttribute("height", "400");
  }
  else if(dataId == '8'){
    img.setAttribute("width", "600");
    img.setAttribute("height", "400");
  }
  if(document.querySelector(`img[data-id="${dataId}"]`)){
    document.querySelector(`img[data-id="${dataId}"]`).style.display = 'block';
  }
  else{
    img.setAttribute('data-id', dataId);
    document.body.appendChild(img);
  }
  console.log('current image:', el.getAttribute('data-id'));
}

<button class="colour-btn colour-btn--3" data-id="3" onClick="showImage(this)">3</button>
<button class="colour-btn colour-btn--8" data-id="8" onClick="showImage(this)">8</button>


问:
Saving mysql into a file
I have tried the code suggestions to save MySQL output to a file, but none seem to work. The last one I used is this:

```<code>SELECT price FROM shop INTO OUTFILE 'C:/Users/abu/Desktop/pr.txt'
</code>```

And it produced this:

->

Please tell me what is missing to get it done on Windows

答:
Table name (shop) will be declared at last.

```<code>SELECT price INTO OUTFILE 'C:/Users/abu/Desktop/pr.txt' FROM shop;
</code>```

More options will be available with OUTFILE as mentioned in this link

Title: Saving mysql into a file

Body:
I have tried the code suggestions to save MySQL output to a file, but none seem to work. The last one I used is this:

SELECT price FROM shop INTO OUTFILE 'C:/Users/abu/Desktop/pr.txt'

And it produced this:

->

Please tell me what is missing to get it done on Windows

Body:
Table name (shop) will be declared at last.

SELECT price INTO OUTFILE 'C:/Users/abu/Desktop/pr.txt' FROM shop;

More options will be available with OUTFILE as mentioned in this link


问:
Azure Vnet Private IP Ranges
I've not from a networking background. I'm data platform solution architecture and data/ai engineer. Since distributed data processing and scale out using containers has come into my world I've decided to bite the bullet and learn IP fundamentals so I can build clusters.

I've been doing lots of training but have a simple and relatively dumb question but finding simple answers to simple questions seems quite hard on the topic networking!

I have 2 Azure VNets for example in my subscription on the same domain does it matter if a subnet on 1 vnet overlaps a subnet on other vnet? Presumably that would only be a problem when they're peered together. Does the vnet ring fence it's private ip ranges?

答:
"I have 2 Azure VNets for example in my subscription on the same domain does it matter if a subnet on 1 vnet overlaps a subnet on other vnet? "*Presumably that would only be a problem when they're peered together."

Correct. Your subnet address space can overlap on different networks (VNETS). But if you ever need them to talk to each other with out some pretty complex routing changes or redeploying your resources then creating unique address space per subnet is recommend - deploy unique address space.

Struggling to understand why you require the same address space in different VNETs , there is plenty of address space available to ensure they do not overlap even if using ARM templates i.e use variables to deploy.

"Does the vnet ring fence it's private ip ranges?"

Essentially yes, RFC 1918  “Address Allocation for Private Internets" defines that private address space does not route out of a private network. I am no expert to be fair, but really interesting link here

https://whatis.techtarget.com/definition/RFC-1918

RFC 1918

Request for Comment 1918 (RFC 1918), “Address Allocation for Private Internets,”is the Internet Engineering Task Force (IETF) memorandum on methods of assigning of private IP addresses on TCP/IP networks.

Along with NAT (network address tunneling), RFC 1918 facilitates expansion of the usable number of IP addresses available under IPV4, as a stopgap solution to prevent the exhaustion of public IPs available before the adoption of IPV6. It’s not necessary to register private IPs with a Regional Internet Registry (RIR), which simplifies setting up private networks.

RFC 1918 was used to create the standards by which networking equipment assigns IP addresses in a private network. A private network can use a single public IP address. The RFC reserves the following ranges of IP addresses that cannot be routed on the Internet:

10.0.0.0 - 10.255.255.255 (10/8 prefix)
172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
IP addresses within these ranges can be assigned within a private network; each address will be unique on that network but not outside of it. Private IP addresses can't be communicated with directly by external computers because they are not globally unique and, as such, not addressable on the public Internet.

Computers on the inside of the network can communicate with the Internet through NAT.  NAT translates an IP address used within one network to a different IP address known within another network. Typically, a company maps its local inside network addresses to one or more global outside IP addresses and unmaps the global IP addresses on incoming packets back into local IP addresses.

Title: Azure Vnet Private IP Ranges


问:
Python Curses update_panels() and Panel.move() issues
I'm trying to learn how to use Python Curses (and hopefully build a simple game), but somehow I cannot get curses panels to work.

Specifically, when I try to update_panels(), my script (below) immediately exits directly back to the prompt.

```<code>import curses, curses.panel, time as t

def main(stdscr):
    # Initialize some colors and styles
    curses.start_color()
    curses.init_pair( 1, curses.COLOR_RED, curses.COLOR_BLACK )
    pl_style = curses.color_pair( 1 ) + curses.A_BOLD + curses.A_REVERSE

    # Create a Background window and panel
    bg_W = curses.newwin( 10, 100, 5, 5 )
    bg_W.box();
    bg_W.addstr( 1, 2, "BG Window" )
    bg_P = curses.panel.new_panel( bg_W )
    bg_W.refresh(); t.sleep( 2 )

    # Create a Player window and panel
    pl_W = curses.newwin( 1, 1, 10, 20 )
    pl_W.insch( '+', pl_style )
    pl_P = curses.panel.new_panel( pl_W )
    pl_W.refresh(); t.sleep( 2 )

    # Update panels
    curses.panel.update_panels()
    curses.doupdate()

    # # Move the Player panel and update panels
    # pl_P.move( 10, 30 )
    # curses.panel.update_panels()
    # curses.doupdate()
    # t.sleep( 2 )

    while True:
        if pl_W.getch() == 27: break

if __name__ == "__main__":
    curses.wrapper( main )
</code>```

Alternatively, when I try to just move panels, my script (below), returns an error.

```<code>import curses, curses.panel, time as t

def main(stdscr):
    # Initialize some colors and styles
    curses.start_color()
    curses.init_pair( 1, curses.COLOR_RED, curses.COLOR_BLACK )
    pl_style = curses.color_pair( 1 ) + curses.A_BOLD + curses.A_REVERSE

    # Create a Background window and panel
    bg_W = curses.newwin( 10, 100, 5, 5 )
    bg_W.box();
    bg_W.addstr( 1, 2, "BG Window" )
    bg_P = curses.panel.new_panel( bg_W )
    bg_W.refresh(); t.sleep( 2 )

    # Create a Player window and panel
    pl_W = curses.newwin( 1, 1, 10, 20 )
    pl_W.insch( '+', pl_style )
    pl_P = curses.panel.new_panel( pl_W )
    pl_W.refresh(); t.sleep( 2 )

    # # Update panels
    # curses.panel.update_panels()
    # curses.doupdate()

    # Move the Player panel and update panels
    pl_P.move( 10, 30 )
    curses.panel.update_panels()
    curses.doupdate()
    t.sleep( 2 )

    while True:
        if pl_W.getch() == 27: break

if __name__ == "__main__":
    curses.wrapper( main )
</code>```

The error I get is as follows:

```<code>Traceback (most recent call last):
  File "panl2.py", line 36, in <module>
    curses.wrapper( main )
  File "C:\Program Files\Python38\lib\curses\__init__.py", line 105, in wrapper
    return func(stdscr, *args, **kwds)
  File "panl2.py", line 27, in main
    pl_P.move( 10, 30 )
_curses_panel.error: move_panel() returned ERR
</code>```

I've had a hell of a time trying to figure out what is wrong, but am getting absolutely nowhere, and would be very grateful for any guidance.

I'm using windows-curses (v2.1.0) with Python 3.8 (v3.8.1:1b293b6) in the standard Windows command prompt (v10.0.18362.449) on an x64 Windows 10 Pro (v10.0.18362) machine.

答:
ncurses' move_panel function returns the result from mvwin, which is documented as follows:

Calling mvwin moves the window so that the upper left-hand corner is at
         position  (x,  y).   If  the  move would cause the window to be off the
         screen, it is an error and the window is not moved.  Moving  subwindows
         is allowed, but should be avoided.

In python, you'd have to use a try/except block to avoid simply exiting when there is an error-return from ncurses.

Using "windows-curses", the underlying library is probably PDCurses (which has no documentation aside from comments in the source-code).  However, its panel-support ultimately came from the same (Warren Tucker) implementation.  You can see the error-returns in the source-code.

For what it's worth, the original panel library (author unknown) that one might have encountered in a vendor Unix machine (such as Solaris) did the same thing (see source on Illumos-gate), but the documentation provided could not have been useful when Tucker developed a clone (see "documentation").

Body:
I'm trying to learn how to use Python Curses (and hopefully build a simple game), but somehow I cannot get curses panels to work.

Specifically, when I try to update_panels(), my script (below) immediately exits directly back to the prompt.

import curses, curses.panel, time as t

def main(stdscr):
    # Initialize some colors and styles
    curses.start_color()
    curses.init_pair( 1, curses.COLOR_RED, curses.COLOR_BLACK )
    pl_style = curses.color_pair( 1 ) + curses.A_BOLD + curses.A_REVERSE

    # Create a Background window and panel
    bg_W = curses.newwin( 10, 100, 5, 5 )
    bg_W.box();
    bg_W.addstr( 1, 2, "BG Window" )
    bg_P = curses.panel.new_panel( bg_W )
    bg_W.refresh(); t.sleep( 2 )

    # Create a Player window and panel
    pl_W = curses.newwin( 1, 1, 10, 20 )
    pl_W.insch( '+', pl_style )
    pl_P = curses.panel.new_panel( pl_W )
    pl_W.refresh(); t.sleep( 2 )

    # Update panels
    curses.panel.update_panels()
    curses.doupdate()

    # # Move the Player panel and update panels
    # pl_P.move( 10, 30 )
    # curses.panel.update_panels()
    # curses.doupdate()
    # t.sleep( 2 )

    while True:
        if pl_W.getch() == 27: break

if __name__ == "__main__":
    curses.wrapper( main )

Alternatively, when I try to just move panels, my script (below), returns an error.

import curses, curses.panel, time as t

def main(stdscr):
    # Initialize some colors and styles
    curses.start_color()
    curses.init_pair( 1, curses.COLOR_RED, curses.COLOR_BLACK )
    pl_style = curses.color_pair( 1 ) + curses.A_BOLD + curses.A_REVERSE

    # Create a Background window and panel
    bg_W = curses.newwin( 10, 100, 5, 5 )
    bg_W.box();
    bg_W.addstr( 1, 2, "BG Window" )
    bg_P = curses.panel.new_panel( bg_W )
    bg_W.refresh(); t.sleep( 2 )

    # Create a Player window and panel
    pl_W = curses.newwin( 1, 1, 10, 20 )
    pl_W.insch( '+', pl_style )
    pl_P = curses.panel.new_panel( pl_W )
    pl_W.refresh(); t.sleep( 2 )

    # # Update panels
    # curses.panel.update_panels()
    # curses.doupdate()

    # Move the Player panel and update panels
    pl_P.move( 10, 30 )
    curses.panel.update_panels()
    curses.doupdate()
    t.sleep( 2 )

    while True:
        if pl_W.getch() == 27: break

if __name__ == "__main__":
    curses.wrapper( main )

The error I get is as follows:

Traceback (most recent call last):
  File "panl2.py", line 36, in <module>
    curses.wrapper( main )
  File "C:\Program Files\Python38\lib\curses\__init__.py", line 105, in wrapper
    return func(stdscr, *args, **kwds)
  File "panl2.py", line 27, in main
    pl_P.move( 10, 30 )
_curses_panel.error: move_panel() returned ERR

I've had a hell of a time trying to figure out what is wrong, but am getting absolutely nowhere, and would be very grateful for any guidance.

I'm using windows-curses (v2.1.0) with Python 3.8 (v3.8.1:1b293b6) in the standard Windows command prompt (v10.0.18362.449) on an x64 Windows 10 Pro (v10.0.18362) machine.


问:
Using XSLT to separate XML file but can't get cross tag's value
I have a XML file as below

```<code><Season>
<Activitys>
    <Activity>
        <No>A001</No>
        <Date>2020/1/1</Date>
    </Activity>
    <Activity>
        <No>A002</No>
        <Date>2020/2/1</Date>
    </Activity>
</Activitys>

<Staffs>
    <Staff>
        <Name>Tom</Name>
        <AssignedActivity>A001</AssignedActivity>
    </Staff>
    <Staff>
        <Name>Jason</Name>
        <AssignedActivity>A002</AssignedActivity>
    </Staff>
</Staffs>

<Notice>description</Notice></Season>
</code>```

And want to transform it to 2 XML activity files, each of them will show the corresponding activity<No>, <AssignedStaff> and <Notice> information.

```<code><Activity>
<No>A001</No>
<Date>2020/1/1</Date>
<AssignedStaff>Tom</AssignedStaff>
<Notice>description</Notice></Activity>
</code>```

Now, I'm using below XSLT that can generate to 2 files and get activity information. But don't know how to get the assigned staff and notice tag value. I tried to use apply-template but still can't get the way. Could someone provide any ideas? Thanks a lot.

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output method="xml" indent="yes" name="xml"/>
<xsl:template match="/">
    <xsl:for-each select="Season/Activitys/Activity">
        <xsl:variable name="filename" select="concat('output1/',No,'.xml')" />
        <xsl:value-of select="$filename" />
        <xsl:result-document href="{$filename}" format="xml">
            <Activity>
                <No>
                    <xsl:value-of select="No"/>
                </No>
                <Date>
                    <xsl:value-of select="Date"/>
                </Date>
            </Activity>
        </xsl:result-document>
    </xsl:for-each>
</xsl:template>
</code>```

答:
Well, for the Notice you simply want <xsl:copy-of select="ancestor::Season/Description"/>.

For the reference value declare a key <xsl:key name="staff-act" match="Staff" use="AssignedActivity"/> and use it inside of your for-each with

```<code><AssignedStaff><xsl:value-of select="key('staff-act', No)/Name"/></AssignedStaff>
</code>```

Body:
I have a XML file as below

<Season>
<Activitys>
    <Activity>
        <No>A001</No>
        <Date>2020/1/1</Date>
    </Activity>
    <Activity>
        <No>A002</No>
        <Date>2020/2/1</Date>
    </Activity>
</Activitys>

<Staffs>
    <Staff>
        <Name>Tom</Name>
        <AssignedActivity>A001</AssignedActivity>
    </Staff>
    <Staff>
        <Name>Jason</Name>
        <AssignedActivity>A002</AssignedActivity>
    </Staff>
</Staffs>

<Notice>description</Notice></Season>

And want to transform it to 2 XML activity files, each of them will show the corresponding activity<No>, <AssignedStaff> and <Notice> information.

<Activity>
<No>A001</No>
<Date>2020/1/1</Date>
<AssignedStaff>Tom</AssignedStaff>
<Notice>description</Notice></Activity>

Now, I'm using below XSLT that can generate to 2 files and get activity information. But don't know how to get the assigned staff and notice tag value. I tried to use apply-template but still can't get the way. Could someone provide any ideas? Thanks a lot.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output method="xml" indent="yes" name="xml"/>
<xsl:template match="/">
    <xsl:for-each select="Season/Activitys/Activity">
        <xsl:variable name="filename" select="concat('output1/',No,'.xml')" />
        <xsl:value-of select="$filename" />
        <xsl:result-document href="{$filename}" format="xml">
            <Activity>
                <No>
                    <xsl:value-of select="No"/>
                </No>
                <Date>
                    <xsl:value-of select="Date"/>
                </Date>
            </Activity>
        </xsl:result-document>
    </xsl:for-each>
</xsl:template>

Body:
Well, for the Notice you simply want <xsl:copy-of select="ancestor::Season/Description"/>.

For the reference value declare a key <xsl:key name="staff-act" match="Staff" use="AssignedActivity"/> and use it inside of your for-each with

<AssignedStaff><xsl:value-of select="key('staff-act', No)/Name"/></AssignedStaff>


问:
How to get voronoi edge diagram in python
I want to create a voronoi edge diagram for dot annotations (binary image of nuclei positions ). I used the code from here to create voronoi edge diagram but what I get as a result is shown in an image shown here. I just need voronoi edges. Following is the code

Voronoi edge diagram

```<code>def viro(img):
 label_point=img
 h, w = label_point.shape
 points = np.argwhere(label_point>0)
 vor = Voronoi(points)
 regions, vertices = voronoi_finite_polygons_2d(vor)
 box = Polygon([[0, 0], [0, w], [h, w], [h, 0]])
 region_masks = np.zeros((h, w), dtype=np.int16)
 edges = np.zeros((h, w), dtype=np.bool)
 count = 1
 masks= np.zeros((h, w), dtype=np.bool)
 for region in regions:
            polygon = vertices[region]
            # Clipping polygon
            poly = Polygon(polygon)
            poly = poly.intersection(box)
            polygon = np.array([list(p) for p in poly.exterior.coords])
            mask = poly2mask(polygon[:, 0], polygon[:, 1], (h, w))
            edge = mask * (~morphology.erosion(mask, morphology.disk(1)))
            edges += edge
            region_masks[mask] = count
            count += 1

 # fuse Voronoi edge and dilated points
 label_point_dilated = morphology.dilation(label_point, morphology.disk(1))
 label_vor = np.zeros((h, w, 3), dtype=np.uint8)
 label_vor[:, :, 0] = (edges > 0).astype(np.uint8) * 255
 label_vor[:, :, 1] = (label_point_dilated > 0).astype(np.uint8) * 255

 return label_vor
</code>```

答: I happen to figure out the issue. Actually the problem was with the binary image as it is a ground truth of nuclei position with 3 pixel radius so instead of getting single coordinate for one nuclei(single pixel), it retrieved three coordinate values because of 3 pixel radius for each nuclei position thus giving the resultant image. </p>

Body:
I want to create a voronoi edge diagram for dot annotations (binary image of nuclei positions ). I used the code from here to create voronoi edge diagram but what I get as a result is shown in an image shown here. I just need voronoi edges. Following is the code

Voronoi edge diagram

def viro(img):
 label_point=img
 h, w = label_point.shape
 points = np.argwhere(label_point>0)
 vor = Voronoi(points)
 regions, vertices = voronoi_finite_polygons_2d(vor)
 box = Polygon([[0, 0], [0, w], [h, w], [h, 0]])
 region_masks = np.zeros((h, w), dtype=np.int16)
 edges = np.zeros((h, w), dtype=np.bool)
 count = 1
 masks= np.zeros((h, w), dtype=np.bool)
 for region in regions:
            polygon = vertices[region]
            # Clipping polygon
            poly = Polygon(polygon)
            poly = poly.intersection(box)
            polygon = np.array([list(p) for p in poly.exterior.coords])
            mask = poly2mask(polygon[:, 0], polygon[:, 1], (h, w))
            edge = mask * (~morphology.erosion(mask, morphology.disk(1)))
            edges += edge
            region_masks[mask] = count
            count += 1

 # fuse Voronoi edge and dilated points
 label_point_dilated = morphology.dilation(label_point, morphology.disk(1))
 label_vor = np.zeros((h, w, 3), dtype=np.uint8)
 label_vor[:, :, 0] = (edges > 0).astype(np.uint8) * 255
 label_vor[:, :, 1] = (label_point_dilated > 0).astype(np.uint8) * 255

 return label_vor


问:
padding leading zeros (0 characters) in some string
I have to fill a string (containing numerals) with leading zeros if the content of that string was less than string's size.

example:

```<code>char str[11] = "12345";
</code>```

The expected output should be: 0000012345

I have padded string with leading 0 by using sprintf but with an integer as argument:

```<code>sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters
</code>```

but now I have only two methods left for padding a string (containing numerals) with leading zeros:

1st Method

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);
</code>```

2nd Method

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);
</code>```

If I try using sprintf with string as argument I get leading blanks:

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);
</code>```

OUTPUT:

```<code>     12345   //leading spaces
</code>```

Is there any simple method to accomplish this?

答:
I would personally write function like this</p>

```<code>char *leadingzeroes(char *buff, char *number, size_t size, int mode)
{
    char *saved;
    size_t len = 0;
    const char *wrk;

    if(!buff) buff = number;
    saved = buff;
    while(*number && (!isdigit(*number) || *number == '0')) number++;

    wrk = number;
    while(*wrk++);
    len = wrk - number - 1;
    if(mode)
    {
        size = size - len;
    }
    memmove(buff + size, number, len + 1);
    while(size--) *buff++ = '0';
    return saved;
}
</code>```

Body:
I have to fill a string (containing numerals) with leading zeros if the content of that string was less than string's size.

example:

char str[11] = "12345";

The expected output should be: 0000012345

I have padded string with leading 0 by using sprintf but with an integer as argument:

sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters

but now I have only two methods left for padding a string (containing numerals) with leading zeros:

1st Method

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);

2nd Method

char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);

If I try using sprintf with string as argument I get leading blanks:

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);

OUTPUT:

     12345   //leading spaces

Is there any simple method to accomplish this?

Body:
I would personally write function like this

char *leadingzeroes(char *buff, char *number, size_t size, int mode)
{
    char *saved;
    size_t len = 0;
    const char *wrk;

    if(!buff) buff = number;
    saved = buff;
    while(*number && (!isdigit(*number) || *number == '0')) number++;

    wrk = number;
    while(*wrk++);
    len = wrk - number - 1;
    if(mode)
    {
        size = size - len;
    }
    memmove(buff + size, number, len + 1);
    while(size--) *buff++ = '0';
    return saved;
}


问:
Blocked by CORS policy: Request header field access-control-allow-origin is not allowed
I have a Node JS app which acts as server and processes the data through POST request and running on other port.On the other part i have another jQuery web application which acts as client and sends the post request to Node JS app.

When i try to POST the data from jQuery client, it is throwing error as below

```<code>Access to XMLHttpRequest at 'http://localhost:3000/data' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
</code>```

Below is my Node JS and i have added the any domain to access Node JS app

```<code>// Starting the App Server on Port 3000
app.listen(3000, function() {
console.log("Server running on port http://localhost:3000");
});

// set headers for allowing cross domain access
//Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
</code>```

My client jquery looks like below which post the data to Node JS

```<code>$(document).ready(function(){
      $("button").click(function(){
console.log(" Entered inside click ");

$.ajax({
    contentType: 'application/json',
    data: '{"data":"<div>Some raw data pushed to node url</div>"}',
    dataType: 'json',
    success: function(data){
        console.log(" Data Received ");
        $("#content").append("Data received");
    },
    error: function(){
        console.log(" Error while connecting for data");
    },
    processData: false,
    type: 'POST',
    url: 'http://localhost:3000/data',
    headers: {
        "accept": "application/json",
        "Access-Control-Allow-Origin":"*"
    }
});
</code>```

答:
You can employ CORS library.  It is common place to see the middleware set above
app.use(function (req, res, next) {

```<code>var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
</code>```

https://www.npmjs.com/package/cors

Body:
I have a Node JS app which acts as server and processes the data through POST request and running on other port.On the other part i have another jQuery web application which acts as client and sends the post request to Node JS app.

When i try to POST the data from jQuery client, it is throwing error as below

Access to XMLHttpRequest at 'http://localhost:3000/data' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response

Below is my Node JS and i have added the any domain to access Node JS app

// Starting the App Server on Port 3000
app.listen(3000, function() {
console.log("Server running on port http://localhost:3000");
});

// set headers for allowing cross domain access
//Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

My client jquery looks like below which post the data to Node JS

$(document).ready(function(){
      $("button").click(function(){
console.log(" Entered inside click ");

$.ajax({
    contentType: 'application/json',
    data: '{"data":"
Some raw data pushed to node url
"}',
    dataType: 'json',
    success: function(data){
        console.log(" Data Received ");
        $("#content").append("Data received");
    },
    error: function(){
        console.log(" Error while connecting for data");
    },
    processData: false,
    type: 'POST',
    url: 'http://localhost:3000/data',
    headers: {
        "accept": "application/json",
        "Access-Control-Allow-Origin":"*"
    }
});

Body:
You can employ CORS library.  It is common place to see the middleware set above
app.use(function (req, res, next) {

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

https://www.npmjs.com/package/cors