问:
Fixing AutoHotkey function for adding a fixed charge
Full disclosure:  I didn't write this script.  I am improving this after the person who wrote it left the company.

This script is very simple, it adds what we call a "fixed charge" to an account once a ticket number has been entered and then the key combo of "ctrl + alt + insert" is used.

Script works perfectly except when the account already has a "fixed charge".  In that case, the autohotkey won't work.  The solution of the person who wrote this script was to just assign another key combo to add the fixed charge.

I think that there has to be an easier way to do this i.e. force the key combo thru or use an if statement.  I have never written an autohotkeys function before and my understanding of autohotkeys is very limited.

I would like to adapt the script below to work on every account regardless whether another fixed charge is already on the account.

```<code>  ^!Insert::
      Send, !t
      Send, !x
      Send {Tab 3}
      Send, 41025
      Send, {Enter}
      Send, !o
      Sleep, 3000
      Send !{c 3}
  Return
</code>```

答:
One option if you can highlight the text that says 'fixed charge' is to preface your hotkey like so:

```<code>^!Insert::
  click, 711, 431
  clipboard = ; empty your clipboard
  send ^a^c ; select all and copy
  ClipWait, 0.25 ; wait for something to enter your clipboard
  text := clipboard
  If(InStr(text, "fixed charge"))
  {
      Send, !t
      Send, !x
      Send {Tab 3}
      Send, 41025
      Send, {Enter}
      Send, !o
      Sleep, 3000
      Send !{c 3}
  }
Return
</code>```

You can get the X, Y coordinates by using windows spy, which you can run by right-clicking the AutoHotkey icon.

If you cannot highlight text in your system you will have to find something that autohotkey can pickup that has changed. There are many possible ways, like ControlGet, detecting a file change, or even doing the script in another way to modify the output of your in-house software. AutoHotkey is as much art as it is science. The easiest way to figure it out is to throw stuff at the wall and hope it sticks.

Body:
Full disclosure:  I didn't write this script.  I am improving this after the person who wrote it left the company.

This script is very simple, it adds what we call a "fixed charge" to an account once a ticket number has been entered and then the key combo of "ctrl + alt + insert" is used.

Script works perfectly except when the account already has a "fixed charge".  In that case, the autohotkey won't work.  The solution of the person who wrote this script was to just assign another key combo to add the fixed charge.

I think that there has to be an easier way to do this i.e. force the key combo thru or use an if statement.  I have never written an autohotkeys function before and my understanding of autohotkeys is very limited.

I would like to adapt the script below to work on every account regardless whether another fixed charge is already on the account.

  ^!Insert::
      Send, !t
      Send, !x
      Send {Tab 3}
      Send, 41025
      Send, {Enter}
      Send, !o
      Sleep, 3000
      Send !{c 3}
  Return

Body:
One option if you can highlight the text that says 'fixed charge' is to preface your hotkey like so:

^!Insert::
  click, 711, 431
  clipboard = ; empty your clipboard
  send ^a^c ; select all and copy
  ClipWait, 0.25 ; wait for something to enter your clipboard
  text := clipboard
  If(InStr(text, "fixed charge"))
  {
      Send, !t
      Send, !x
      Send {Tab 3}
      Send, 41025
      Send, {Enter}
      Send, !o
      Sleep, 3000
      Send !{c 3}
  }
Return

You can get the X, Y coordinates by using windows spy, which you can run by right-clicking the AutoHotkey icon.

If you cannot highlight text in your system you will have to find something that autohotkey can pickup that has changed. There are many possible ways, like ControlGet, detecting a file change, or even doing the script in another way to modify the output of your in-house software. AutoHotkey is as much art as it is science. The easiest way to figure it out is to throw stuff at the wall and hope it sticks.


来源: stackexchange

问:
Cannot use 'new' with the Function type in TypeScript
I have this code:

```<code>const BlockConstructors: Function[] = [
 OBlock,
 IBlock,
 TBlock
];

function randomFromArray(array: any[]) {
  return array[Math.floor( Math.random() * array.length )];
}

const BlockConstructor: Function = random(BlockConstructors);
const block: Block = new BlockConstructor();
</code>```

I try to draw a some block constructor from array and then create a new object, all my block constructors in array extends Block class. I get error:

Cannot use 'new' with an expression whose type lacks a call or construct signature.

Why this error appears?

答:
Your code isn't self-contained, but here's the boiled down reason.

Function isn't new-able. Only three  things can be new'd in TypeScript:

Types with construct signatures

Types with no construct signatures, but with call signatures that return void

any

You really want the first one.

Try switching from Function to (new () => Block).

ContentLicense: CC BY-SA 3.0

Body:
I have this code:

const BlockConstructors: Function[] = [
 OBlock,
 IBlock,
 TBlock
];

function randomFromArray(array: any[]) {
  return array[Math.floor( Math.random() * array.length )];
}

const BlockConstructor: Function = random(BlockConstructors);
const block: Block = new BlockConstructor();

I try to draw a some block constructor from array and then create a new object, all my block constructors in array extends Block class. I get error:

Cannot use 'new' with an expression whose type lacks a call or construct signature.

Why this error appears?


问:
How can I locally clone opneshift application or clone it to git
Command:

```<code>git clone ssh://56e441dasfasfasfas341d000061@aw2d1164-atpict.rhcloud.com/~/git/age345.git/
</code>```

Error:

```<code>Cloning into 'awsd007'...

Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

What's that and how to fix it?

答:
It seems you didn't create a ssh key, check this website for more information:

https://help.github.com/articles/connecting-to-github-with-ssh/

Also its probably better and easier if you use https intsead of ssh

Body:
Command:

git clone ssh://56e441dasfasfasfas341d000061@aw2d1164-atpict.rhcloud.com/~/git/age345.git/

Error:

Cloning into 'awsd007'...

Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

What's that and how to fix it?


问:
Gulp keeps throwing errors and missing modules
Hi I am working with the web starter kit angular version and am having real issues compiling the code without errors. The main problematic task is the scripts one which keeps giving me random missing modules and uglify/parse problem.

```<code>events.js:85
      throw er; // Unhandled 'error' event
            ^
Error
    at new JS_Parse_Error (C:\Users\Jensten\webkit\node_modules\gulp
-uglify\node_modules\uglify-js\lib\parse.js:196:18)
    at js_error (C:\Users\Jensten\webkit\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:204:11)
    at croak (C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:679:41)
    at token_error (C:\Users\Jensten\webkit\node_modules\gulp-uglify
\node_modules\uglify-js\lib\parse.js:683:9)
    at expect_token (C:\Users\Jensten\webkit\node_modules\gulp-uglif
y\node_modules\uglify-js\lib\parse.js:696:9)
    at expect (C:\Users\Jensten\webkit\node_modules\gulp-uglify\node
_modules\uglify-js\lib\parse.js:699:36)
    at expr_list (C:\Users\Jensten\webkit\node_modules\gulp-uglify\n
ode_modules\uglify-js\lib\parse.js:1202:44)
    at C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_modules
\uglify-js\lib\parse.js:1217:23
    at C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_modules
\uglify-js\lib\parse.js:722:24
    at expr_atom (C:\Users\Jensten\webkit\node_modules\gulp-uglify\n
ode_modules\uglify-js\lib\parse.js:1180:35)

C:\Users\Jensten\webkit\>gulp html
[16:47:01] Using gulpfile ~\pokerstars-webkit\gulpfile.js
[16:47:01] Starting 'html'...
[16:47:02] 'html' errored after 1.54 s
[16:47:02] TypeError: undefined is not a function
    at Gulp.<anonymous> (C:\Users\Jensten\webkit\gulpfile.js:130:18)

    at module.exports (C:\Users\Jensten\webkit\node_modules\gulp\nod
e_modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:\Users\Jensten\webkit\node_modu
les\gulp\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (C:\Users\Jensten\webkit\node_modu
les\gulp\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (C:\Users\Jensten\webkit\node_modules
\gulp\node_modules\orchestrator\index.js:134:8)
    at c:\Users\Coutolil\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
    at process._tickCallback (node.js:355:11)
    at Function.Module.runMain (module.js:503:11)
    at startup (node.js:129:16)
    at node.js:814:3
</code>```

My gulp.js file contains the following:

```<code>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
    'ie >= 10',
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 7',
    'opera >= 23',
    'ios >= 7',
    'android >= 4.0',
    'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function() {
    return gulp.src('app/scripts/**/*.js')
        .pipe(reload({stream: true, once: true}))
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'))
        .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function() {
    return gulp.src('app/assets/images/**/*')
        .pipe($.cache($.imagemin({
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/assets/images'))
        .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
    return gulp.src(['app/*', '!app/*.html', '!app/scss', '!app/scripts'], {dot: true})
        .pipe(gulp.dest('dist'))
        .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function() {
    return gulp.src(['app/assets/fonts/**'])
        .pipe(gulp.dest('dist/assets/fonts'))
        .pipe($.size({title: 'fonts'}));
});

// Automatically Prefix CSS
gulp.task('styles:css', function() {
    return gulp.src('app/styles/css/**/*.css')
        .pipe($.changed('app/styles'))
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe(gulp.dest('app/styles'))
        .pipe($.size({title: 'styles:css'}));
});

// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:scss', function() {
    var path = require('path');
    return gulp.src('app/scss/app.scss')
        .pipe($.sass({
            style: 'expanded',
            precision: 10,
            loadPath: ['app/scss']
        }))
        .on('error', console.error.bind(console))
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe(gulp.dest('app/assets/styles'))
        .pipe(reload({stream:true}))
        .pipe($.size({title: 'styles:scss'}));
});

//Watch sass

//---end Watch sass

// Output Final CSS Styles
gulp.task('styles', ['styles:scss', 'styles:css']);

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {
    return gulp.src('app/**/*.html')
        .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
        // Concatenate And Minify JavaScript
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        // Remove Any Unused CSS
        // commented for now as it doesn't work well with angular (ng-class for example)
        /*.pipe($.if('*.css', $.uncss({
            html: [
                'app/index.html'
            ],
            // CSS Selectors for UnCSS to ignore
            ignore: [
                '.navdrawer-container.open',
                /.app-bar.open/
            ]
        })))*/
        // Concatenate And Minify Styles
        .pipe($.if('*.css', $.csso()))
        .pipe($.useref.restore())
        .pipe($.useref())
        // Update Production Style Guide Paths
        .pipe($.replace('components/components.css', 'components/main.min.css'))
        // Minify Any HTML
        .pipe($.if('*.html', $.minifyHtml({empty: true})))
        // Output Files
        .pipe(gulp.dest('dist'))
        .pipe($.size({title: 'html'}));
});

gulp.task('scripts', function() {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        .pipe($.sourcemaps.init())
        .pipe($.concat('app.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('app/assets/scripts'));
});

gulp.task('vendor', function() {
    var mainBowerFiles = require('main-bower-files');
    return gulp.src(mainBowerFiles(/* options */))
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        .pipe($.sourcemaps.init())
        .pipe($.concat('vendor.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('app/assets/scripts'));
})

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function() {
    browserSync({
        open: false,
        notify: true,
        server: {
            baseDir: ['.tmp', 'app']
        }
    });

    gulp.watch(['app/**/*.html'], reload);
    gulp.watch(['app/scss/**/*.scss'], ['styles:scss']);
//  gulp.watch(['{.tmp,app}/assets/styles/**/*.css'], ['styles:css']);
    gulp.watch(['app/scripts/**/*.js'], [/*'jshint',*/ 'scripts', reload]);
    gulp.watch(['app/assets/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
    browserSync({
        open: false,
        notify: true,
        server: {
            baseDir: 'dist'
        }
    });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
    runSequence('styles', 'vendor', 'scripts', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
    // By default, we use the PageSpeed Insights
    // free (no API key) tier. You can use a Google
    // Developer API key if you have one. See
    // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
    url: 'https://example.com',
    strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try {
    require('require-dir')('tasks');
} catch(err) {
}
</code>```

I am happy to use a different file, all I want is to make sure that: Angular, SASS, compression, and file output to the assets directory are working. I am currently able to run the project but the default task obviously does not run on gulp serve, hence why I was unable to see any errors before.

Could anyone point me in the right direction?

答:
Place your devDependencies at correct place in package.json file as shown below</p>

```<code>{
  "name": "my-project",
  "private": true,
   "devDependencies": {
   //dependencies are place here
   },
  "engines": {
  "node": ">=0.10.0"
  }
}
</code>```

Body:
Hi I am working with the web starter kit angular version and am having real issues compiling the code without errors. The main problematic task is the scripts one which keeps giving me random missing modules and uglify/parse problem.

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error
    at new JS_Parse_Error (C:\Users\Jensten\webkit\node_modules\gulp
-uglify\node_modules\uglify-js\lib\parse.js:196:18)
    at js_error (C:\Users\Jensten\webkit\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:204:11)
    at croak (C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:679:41)
    at token_error (C:\Users\Jensten\webkit\node_modules\gulp-uglify
\node_modules\uglify-js\lib\parse.js:683:9)
    at expect_token (C:\Users\Jensten\webkit\node_modules\gulp-uglif
y\node_modules\uglify-js\lib\parse.js:696:9)
    at expect (C:\Users\Jensten\webkit\node_modules\gulp-uglify\node
_modules\uglify-js\lib\parse.js:699:36)
    at expr_list (C:\Users\Jensten\webkit\node_modules\gulp-uglify\n
ode_modules\uglify-js\lib\parse.js:1202:44)
    at C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_modules
\uglify-js\lib\parse.js:1217:23
    at C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_modules
\uglify-js\lib\parse.js:722:24
    at expr_atom (C:\Users\Jensten\webkit\node_modules\gulp-uglify\n
ode_modules\uglify-js\lib\parse.js:1180:35)

C:\Users\Jensten\webkit\>gulp html
[16:47:01] Using gulpfile ~\pokerstars-webkit\gulpfile.js
[16:47:01] Starting 'html'...
[16:47:02] 'html' errored after 1.54 s
[16:47:02] TypeError: undefined is not a function
    at Gulp.<anonymous> (C:\Users\Jensten\webkit\gulpfile.js:130:18)

    at module.exports (C:\Users\Jensten\webkit\node_modules\gulp\nod
e_modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:\Users\Jensten\webkit\node_modu
les\gulp\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (C:\Users\Jensten\webkit\node_modu
les\gulp\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (C:\Users\Jensten\webkit\node_modules
\gulp\node_modules\orchestrator\index.js:134:8)
    at c:\Users\Coutolil\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
    at process._tickCallback (node.js:355:11)
    at Function.Module.runMain (module.js:503:11)
    at startup (node.js:129:16)
    at node.js:814:3

My gulp.js file contains the following:

/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
    'ie >= 10',
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 7',
    'opera >= 23',
    'ios >= 7',
    'android >= 4.0',
    'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function() {
    return gulp.src('app/scripts/**/*.js')
        .pipe(reload({stream: true, once: true}))
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'))
        .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function() {
    return gulp.src('app/assets/images/**/*')
        .pipe($.cache($.imagemin({
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/assets/images'))
        .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
    return gulp.src(['app/*', '!app/*.html', '!app/scss', '!app/scripts'], {dot: true})
        .pipe(gulp.dest('dist'))
        .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function() {
    return gulp.src(['app/assets/fonts/**'])
        .pipe(gulp.dest('dist/assets/fonts'))
        .pipe($.size({title: 'fonts'}));
});

// Automatically Prefix CSS
gulp.task('styles:css', function() {
    return gulp.src('app/styles/css/**/*.css')
        .pipe($.changed('app/styles'))
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe(gulp.dest('app/styles'))
        .pipe($.size({title: 'styles:css'}));
});

// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:scss', function() {
    var path = require('path');
    return gulp.src('app/scss/app.scss')
        .pipe($.sass({
            style: 'expanded',
            precision: 10,
            loadPath: ['app/scss']
        }))
        .on('error', console.error.bind(console))
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe(gulp.dest('app/assets/styles'))
        .pipe(reload({stream:true}))
        .pipe($.size({title: 'styles:scss'}));
});

//Watch sass

//---end Watch sass

// Output Final CSS Styles
gulp.task('styles', ['styles:scss', 'styles:css']);

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {
    return gulp.src('app/**/*.html')
        .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
        // Concatenate And Minify JavaScript
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        // Remove Any Unused CSS
        // commented for now as it doesn't work well with angular (ng-class for example)
        /*.pipe($.if('*.css', $.uncss({
            html: [
                'app/index.html'
            ],
            // CSS Selectors for UnCSS to ignore
            ignore: [
                '.navdrawer-container.open',
                /.app-bar.open/
            ]
        })))*/
        // Concatenate And Minify Styles
        .pipe($.if('*.css', $.csso()))
        .pipe($.useref.restore())
        .pipe($.useref())
        // Update Production Style Guide Paths
        .pipe($.replace('components/components.css', 'components/main.min.css'))
        // Minify Any HTML
        .pipe($.if('*.html', $.minifyHtml({empty: true})))
        // Output Files
        .pipe(gulp.dest('dist'))
        .pipe($.size({title: 'html'}));
});

gulp.task('scripts', function() {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        .pipe($.sourcemaps.init())
        .pipe($.concat('app.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('app/assets/scripts'));
});

gulp.task('vendor', function() {
    var mainBowerFiles = require('main-bower-files');
    return gulp.src(mainBowerFiles(/* options */))
        .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
        .pipe($.sourcemaps.init())
        .pipe($.concat('vendor.js'))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('app/assets/scripts'));
})

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function() {
    browserSync({
        open: false,
        notify: true,
        server: {
            baseDir: ['.tmp', 'app']
        }
    });

    gulp.watch(['app/**/*.html'], reload);
    gulp.watch(['app/scss/**/*.scss'], ['styles:scss']);
//  gulp.watch(['{.tmp,app}/assets/styles/**/*.css'], ['styles:css']);
    gulp.watch(['app/scripts/**/*.js'], [/*'jshint',*/ 'scripts', reload]);
    gulp.watch(['app/assets/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
    browserSync({
        open: false,
        notify: true,
        server: {
            baseDir: 'dist'
        }
    });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
    runSequence('styles', 'vendor', 'scripts', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
    // By default, we use the PageSpeed Insights
    // free (no API key) tier. You can use a Google
    // Developer API key if you have one. See
    // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
    url: 'https://example.com',
    strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try {
    require('require-dir')('tasks');
} catch(err) {
}

I am happy to use a different file, all I want is to make sure that: Angular, SASS, compression, and file output to the assets directory are working. I am currently able to run the project but the default task obviously does not run on gulp serve, hence why I was unable to see any errors before.

Could anyone point me in the right direction?

Body:
Place your devDependencies at correct place in package.json file as shown below

{
  "name": "my-project",
  "private": true,
   "devDependencies": {
   //dependencies are place here
   },
  "engines": {
  "node": ">=0.10.0"
  }
}


问:
Are there cases where a singleton is the best option?
There is a lot of discussion on this site about why singletons should be avoided but are there any cases where a singleton makes sense and is the best option?

An example where I think that a singleton is the best option is when implementing an Identity Map where you need to keep track of all models that have already been loaded from the database in your mapping layer. In this case it is important that the map is effectively global so that all client code uses the same instance of the map and they are all accessing the same list of loaded models. The simplest solution seems to be to implement the class as a singleton (or as static methods). Is this the best approach or is there another way?

Are there any other cases where it is OK to use a singleton or are they always bad?

答: Think of case where you would like to log different events in the application to a single file. In that case a singleton class Log will be useful. Since different part of the application will be accessing the same instance of the Log class.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: GreenShadow


问:
comma separated regex
I have an email regex I am happy with, lets call it EMAIL.
So my field validator looks like this

```<code>var regex=/^EMAIL$/
</code>```

But now the Captain tells me he wants to allow comma separated emails in the field.

What first comes to mind is something like

```<code>/^(EMAIL)?(, EMAIL)*$/
</code>```

but that repeats EMAIL, which already offends my senses.  Is there a way to write this regex without repeating EMAIL?

答: Split the value by comma, then use the regex on each one.</p>

Title: comma separated regex

Body:
I have an email regex I am happy with, lets call it EMAIL.
So my field validator looks like this

var regex=/^EMAIL$/

But now the Captain tells me he wants to allow comma separated emails in the field.

What first comes to mind is something like

/^(EMAIL)?(, EMAIL)*$/

but that repeats EMAIL, which already offends my senses.  Is there a way to write this regex without repeating EMAIL?


问:
Run JavaScript function on form submit
Trying to get back into Javascript, having a little trouble with this very basic thing.

https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/

var name = document.getElementById("name");
function validate() {
  alert("Your name is " +name);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" method="post" name="myForm">
  <label>Name</label>
  <input type="text" name="name" id="name" />
  <input type="submit" name="submit" onclick="validate()" />
</form></code>```

Just wanted a pop up box showing the name you have entered in the field, not sure why it's not working. Am I way off?

Thanks.

答:
Here you go with the solution https://jsfiddle.net/aw27toyv/4/</p>

```<code>**HTML**
<form onsubmit="return false;" method="post" name="myForm">
    <label>Name</label>
    <input type="text" name="name" id="name" />
    <input type="submit" name="submit" onclick="validate()" />
</form>

**JS**
validate = function() {
    var name = document.getElementById("name").value;
    alert("Your name is " +name);
}
</code>```

Title: Run JavaScript function on form submit

Body:
Trying to get back into Javascript, having a little trouble with this very basic thing.

https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/

var name = document.getElementById("name");
function validate() {
  alert("Your name is " +name);
}

<form action="" method="post" name="myForm">
  Name
  <input type="text" name="name" id="name" />
  <input type="submit" name="submit" onclick="validate()" />
</form>

Just wanted a pop up box showing the name you have entered in the field, not sure why it's not working. Am I way off?

Thanks.

Body:
Here you go with the solution https://jsfiddle.net/aw27toyv/4/

**HTML**
<form onsubmit="return false;" method="post" name="myForm">
    <label>Name</label>
    <input type="text" name="name" id="name" />
    <input type="submit" name="submit" onclick="validate()" />
</form>

**JS**
validate = function() {
    var name = document.getElementById("name").value;
    alert("Your name is " +name);
}


问:
Print and sum each element in a array in Python
Let's say I have the array list=[1, 2, 3, 4]

How do I get the following output?

```<code>1+2+3+4 = 10
</code>```

I know I could use sum(list), but I need each item on the array printed with "+"

答:
```<code>print('+'.join(mylist) + ' = ' + str(sum(mylist)))
</code>```

This should work for you

Body:
Let's say I have the array list=[1, 2, 3, 4]

How do I get the following output?

1+2+3+4 = 10

I know I could use sum(list), but I need each item on the array printed with "+"

Body:
print('+'.join(mylist) + ' = ' + str(sum(mylist)))

This should work for you


问:
How to autofill values in excel based on the cells above and below
good people, I have a table full of unique id's (as mentioned below) but there are missing values for few id's.

I want a formula/code to fill in the blanks based on the values above and below of any cell.

For example: here there are two empty rows between two unique id~(620006845180).

can anyone help me with filling up these spaces with the same value as above and below. :( I am stuck.

```<code>    620006845180
    xxxxxxxxxxxx
    xxxxxxxxxxxx
    620006845180
    620006845180
</code>```

答:
You cannot do this in a same column because of circular reference. But you can use another column to do it.

I assume that you have these numbers in column A and from row 2 and you insert an empty column in B and you enter the following formula in B2. Then copy the rest of the rows of the column B from the cell B2. Then Hide your column A, you will get what you wanted in column B.

```<code>=IF(A2<>"",A2,IFERROR(IF(MATCH(B1,A3:A100,0)>0,B1,""),""))
</code>```

If you feel there could more than 100 empty rows. Then you may need to replace the 100 found in the formula to what is the maximum number of rows that you expect to be empty.

Body:
good people, I have a table full of unique id's (as mentioned below) but there are missing values for few id's.

I want a formula/code to fill in the blanks based on the values above and below of any cell.

For example: here there are two empty rows between two unique id~(620006845180).

can anyone help me with filling up these spaces with the same value as above and below. :( I am stuck.

    620006845180
    xxxxxxxxxxxx
    xxxxxxxxxxxx
    620006845180
    620006845180

Body:
You cannot do this in a same column because of circular reference. But you can use another column to do it.

I assume that you have these numbers in column A and from row 2 and you insert an empty column in B and you enter the following formula in B2. Then copy the rest of the rows of the column B from the cell B2. Then Hide your column A, you will get what you wanted in column B.

=IF(A2<>"",A2,IFERROR(IF(MATCH(B1,A3:A100,0)>0,B1,""),""))

If you feel there could more than 100 empty rows. Then you may need to replace the 100 found in the formula to what is the maximum number of rows that you expect to be empty.


问:
Array property in Javascript object is undefined
I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

```<code>User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})
</code>```

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

```<code>{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO',
        ...
    ]
}
</code>```

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

```<code>for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}
</code>```

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

```<code>for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}
</code>```

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

```<code>console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)
</code>```

And here's what is printed on my console:

---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...
```

<p>Here is my entire code base:</p>

```setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);
```

答:
Try this:</p>

```<code>User.find({UserType: "Artist"}, '_id Firstname BIOlist_artworks').then((artists) =>{
             var index = i.toString();
            console.log(artists[index][‘list_artworks’]);
        }
   }
</code>```

Body:
I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO',
        ...
    ]
}

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)

And here's what is printed on my console:

---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...

Here is my entire code base:

setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);

Body:
Try this:

User.find({UserType: "Artist"}, '_id Firstname BIOlist_artworks').then((artists) =>{
             var index = i.toString();
            console.log(artists[index][‘list_artworks’]);
        }
   }


问:
printing variable in class in javascript
guys i have that simple code ... but it print undeifned but i dont know why

function myMove() {
  this.pos = 0;
  this.right = function() {
  fun();
  }
  function fun(){
   this.pos++;
  }

}

var move = new myMove();
alert(move.right());```

any help ???

答:
function myMove() {
  pos = 0;
  this.right = function() {
  return fun();
  }
  function fun(){
     return ++this.pos;
  }

}

var move = new myMove();
alert(move.right());```

In javascript use need to user return keyword to return a value from a function
Also
Instead of postfix pos++ operator you will have to use a prefix operator ++pos

Difference is that postfix operator will first return a value and the increment it whereas
Prefix operator will first increment the value and then it will process it

Body:
guys i have that simple code ... but it print undeifned but i dont know why

function myMove() {
  this.pos = 0;
  this.right = function() {
  fun();
  }
  function fun(){
   this.pos++;
  }

}

var move = new myMove();
alert(move.right());

any help ???

Body:
function myMove() {
  pos = 0;
  this.right = function() {
  return fun();
  }
  function fun(){
     return ++this.pos;
  }

}

var move = new myMove();
alert(move.right());

In javascript use need to user return keyword to return a value from a function
Also
Instead of postfix pos++ operator you will have to use a prefix operator ++pos

Difference is that postfix operator will first return a value and the increment it whereas
Prefix operator will first increment the value and then it will process it


问:
Hibernate ManyToMany save
I have two classes with relation ManyToMany, I want create Audiences and later add them to events, but it throwing "detached" exception.</p>

```<code>class Event {
    @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "UC_EVENT_AUDIENCE",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"))
    private List<Audience> targetAudiences = new ArrayList<>();
}

clsas Audience {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
    private List<Event> events = new ArrayList<>();
}

public void run(ApplicationArguments args) throws Exception {
    //Generate audience data
    List<Audience> audiences = dataGenerator.createAudiences();
    //Save to db
    audienceRepository.save(audiences);

    Event event = new Event();
    event.setTargetAudiences(audiences);
    eventRepository.save(events);
}
</code>```

答:
I done this and it's work for me:

```<code>public class Event {

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "event_audience",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"),
            uniqueConstraints = @UniqueConstraint(columnNames = {"event_id", "audience_id"}))
    private List<Audience> audiences = new ArrayList<>();
}

public class Audience {

    @Column(name = "audience_name", nullable = false, unique = true)
    private String name;
}
</code>```

Also i have two repositories for save Audience and Events extending spring's JpaRepository.

Now i can create Audience like this:

```<code>audienceRepository.save(new Audience("Name"));
</code>```

And add them to my Events like this:

```<code>Event eventFirst = new Event();
eventFirst.getAudiences().add(audiences.get(0));
eventRepository.save(eventFirst);
</code>```

Title: Hibernate ManyToMany save

Body:
I have two classes with relation ManyToMany, I want create Audiences and later add them to events, but it throwing "detached" exception.

class Event {
    @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "UC_EVENT_AUDIENCE",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"))
    private List<Audience> targetAudiences = new ArrayList<>();
}

clsas Audience {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
    private List<Event> events = new ArrayList<>();
}

public void run(ApplicationArguments args) throws Exception {
    //Generate audience data
    List<Audience> audiences = dataGenerator.createAudiences();
    //Save to db
    audienceRepository.save(audiences);

    Event event = new Event();
    event.setTargetAudiences(audiences);
    eventRepository.save(events);
}

Body:
I done this and it's work for me:

public class Event {

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "event_audience",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"),
            uniqueConstraints = @UniqueConstraint(columnNames = {"event_id", "audience_id"}))
    private List<Audience> audiences = new ArrayList<>();
}

public class Audience {

    @Column(name = "audience_name", nullable = false, unique = true)
    private String name;
}

Also i have two repositories for save Audience and Events extending spring's JpaRepository.

Now i can create Audience like this:

audienceRepository.save(new Audience("Name"));

And add them to my Events like this:

Event eventFirst = new Event();
eventFirst.getAudiences().add(audiences.get(0));
eventRepository.save(eventFirst);


问:
PHP Object Can't Call Function Inside If Statements
please point out the obvious as I just started learning about OOP in PHP. My class books contains two public functions: one to display a request books form, and the other to submit the book details to my database. I use two if statements to call these functions when the user clicks the request book or submit form buttons.

Here is my class:

```<code>class Book
{
    public $title;
    public $author;
    public $id;

    public function SendToDatabase()
    {
        echo "inside SendToDatabase";
    }

    public function Display()
    {
        echo "<form action='' method='post'>
    Title: <input type='text' name='title'><br>
    Author: <input type='text' name='author'><br>
    <input type='submit' name='submitBook' value='submit'>
    </form>";
    }

}
</code>```

And here is my code to call the functions using buttons (in the same file). As is, the SendToDatabase() function is never called. I am able to get it working when I combine the if statements, but then the buttons would not work properly. I am a little confused because I thought the scope of the object is the same across if statements. I would really appreciate anyone pointing out my mistake. Cheers.

```<code>echo "<form action='' method='post'><input type='submit' name='submit' value='Request Book'></form>";
$request = $_POST['submit'];
$submit  = $_POST['submitBook'];
if ($request) {
    $book = new Book();
    $book->Display();
}

if ($submit) {
    $book->SendToDatabase();
}
</code>```

答:
You need to define what $book is in both cases, so get the assignment out of the first if block:

```<code>$book = new Book();
if ($request) $book->Display();
if ($submit) $book->SendToDatabase();
</code>```

Body:
please point out the obvious as I just started learning about OOP in PHP. My class books contains two public functions: one to display a request books form, and the other to submit the book details to my database. I use two if statements to call these functions when the user clicks the request book or submit form buttons.

Here is my class:

class Book
{
    public $title;
    public $author;
    public $id;

    public function SendToDatabase()
    {
        echo "inside SendToDatabase";
    }

    public function Display()
    {
        echo "<form action='' method='post'>
    Title: <input type='text' name='title'>

    Author: <input type='text' name='author'>

    <input type='submit' name='submitBook' value='submit'>
    </form>";
    }

}

And here is my code to call the functions using buttons (in the same file). As is, the SendToDatabase() function is never called. I am able to get it working when I combine the if statements, but then the buttons would not work properly. I am a little confused because I thought the scope of the object is the same across if statements. I would really appreciate anyone pointing out my mistake. Cheers.

echo "<form action='' method='post'><input type='submit' name='submit' value='Request Book'></form>";
$request = $_POST['submit'];
$submit  = $_POST['submitBook'];
if ($request) {
    $book = new Book();
    $book->Display();
}

if ($submit) {
    $book->SendToDatabase();
}

Body:
You need to define what $book is in both cases, so get the assignment out of the first if block:

$book = new Book();
if ($request) $book->Display();
if ($submit) $book->SendToDatabase();


问:
How to delay changing background color of a square in a grid if that square's color has just been changed?
I'm doing an exercise with vanilla javascript that changes a random square in a grid to a random color every 400ms, but the square cannot change color for at least another 3s once once it has changed color. This delay logic is what I'm hung up on.

What's the best way to check to see if the current square has just changed color, and to prevent that square from changing colors for 3 seconds?

As you can see, I've experimented with adding a new class once a square's color has been changed. I've also tried placing the set timeout within the colorChange function.

codepen

HTML:

```<code><div id="content">
  <div class = "box" id="square1"></div>
  <div class = "box" id="square2"></div>
  <div class = "box" id="square3"></div>
  <div class = "box" id="square4"></div> <br>
  <div class = "box" id="square5"></div>
  <div class = "box" id="square6"></div>
  <div class = "box" id="square7"></div>
  <div class = "box" id="square8"></div> <br>
  <div class = "box" id="square9"></div>
  <div class = "box" id="square10"></div>
  <div class = "box" id="square11"></div>
  <div class = "box" id="square12"></div> <br>
  <div class = "box" id="square13"></div>
  <div class = "box" id="square14"></div>
  <div class = "box" id="square15"></div>
  <div class = "box" id="square16"></div>
</div>
</code>```

Javascript:

```<code>setInterval(colorChange, 400);

if (square.className = "colored") {
    square.setTimeout(setColor(), 3000);
}

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 17);
    var square = document.getElementById("square"+randomId);
    square.style.backgroundColor = specificColor;
    square.addClass = "colored";
}
</code>```

Thanks for any help.

答:
Why not create a Square object that will retain a reference to the dom node, and a flag to see if it was changed in the past 3 seconds?

You can create an array of Squares, choose a Square and check if it is flagged ; if it isn't, change its color, otherwise, call the Square choosing function again.

See this codepen

Oh, and use Math.floor otherwise you won't change the first square.

JS

```<code>const COLOR_CHANGE_INTERVAL = 400;
const DRYING_INTERVAL = 3000;

let Square = function(tag){
  this.dom = tag;
  this.flagged = false;
}

// Create an array and populate it
let squares = [];

// convert from html collection into array
const _squares = Array.prototype.slice.call(document.getElementsByClassName("box"));
_squares.forEach(function(square,idx){
  squares.push(new Square(square));
});

setInterval(chooseSquare, COLOR_CHANGE_INTERVAL, squares);

function chooseSquare(arr){
  var randomId = Math.floor(Math.random() * arr.length);
  const currentSquare = arr[randomId];
  if(!currentSquare.flagged){
    colorChange(currentSquare);
  } else {
    chooseSquare(currentSquare);
  }
}

function colorChange(square) {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    square.dom.style.backgroundColor = specificColor;
    square.flagged = true;
    setTimeout(function(){
      square.flagged = false;
    }, DRYING_INTERVAL);
}
</code>```

Body:
I'm doing an exercise with vanilla javascript that changes a random square in a grid to a random color every 400ms, but the square cannot change color for at least another 3s once once it has changed color. This delay logic is what I'm hung up on.

What's the best way to check to see if the current square has just changed color, and to prevent that square from changing colors for 3 seconds?

As you can see, I've experimented with adding a new class once a square's color has been changed. I've also tried placing the set timeout within the colorChange function.

codepen

HTML:

Javascript:

setInterval(colorChange, 400);

if (square.className = "colored") {
    square.setTimeout(setColor(), 3000);
}

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 17);
    var square = document.getElementById("square"+randomId);
    square.style.backgroundColor = specificColor;
    square.addClass = "colored";
}

Thanks for any help.

Body:
Why not create a Square object that will retain a reference to the dom node, and a flag to see if it was changed in the past 3 seconds?

You can create an array of Squares, choose a Square and check if it is flagged ; if it isn't, change its color, otherwise, call the Square choosing function again.

See this codepen

Oh, and use Math.floor otherwise you won't change the first square.

JS

const COLOR_CHANGE_INTERVAL = 400;
const DRYING_INTERVAL = 3000;

let Square = function(tag){
  this.dom = tag;
  this.flagged = false;
}

// Create an array and populate it
let squares = [];

// convert from html collection into array
const _squares = Array.prototype.slice.call(document.getElementsByClassName("box"));
_squares.forEach(function(square,idx){
  squares.push(new Square(square));
});

setInterval(chooseSquare, COLOR_CHANGE_INTERVAL, squares);

function chooseSquare(arr){
  var randomId = Math.floor(Math.random() * arr.length);
  const currentSquare = arr[randomId];
  if(!currentSquare.flagged){
    colorChange(currentSquare);
  } else {
    chooseSquare(currentSquare);
  }
}

function colorChange(square) {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    square.dom.style.backgroundColor = specificColor;
    square.flagged = true;
    setTimeout(function(){
      square.flagged = false;
    }, DRYING_INTERVAL);
}


问:
Error in render function: “TypeError: Cannot read property of undefined”, using Vuex and Vue Router
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

```<code>export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}
</code>```

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

```<code>getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}
</code>```

Here is Card.vue:

```<code><template>
  <div>
    <br>
    <div v-if="flipped" class="container">
      <div class="box">
        <pre v-if="card.code"><code class="preserve-ws">{{card.back}}</code>```

{{card.back}}

{{card.front}}

</template>

```

<p>I am getting the TypeError referenced in the title. My understanding is that the <code>created()</code> hook happens after <code>data()</code> has been set up, so then I can assign <code>{card}</code> using the getter. Unfortunately this displays nothing...</p>

<p>If I assign <code>card()</code> as a computed property:</p>

```computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}
```

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

答:
I tried everyone else's solutions and they did not work. But I got it to work finally. Here is what worked for me:

I ended up including a top-level:

```<code><div v-if="!card"> Loading card... </div>
<div v-else> Rest of card template </div>
</code>```

That seems to have silenced the error. Also, the card lives as a computed property:

```<code>card() {
  return this.$store.getters.cardById(this.$route.params.id);
}
</code>```

Body:
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}

Here is Card.vue:

<template>

{{card.back}}

{{card.back}}

{{card.front}}

</template>

I am getting the TypeError referenced in the title. My understanding is that the created() hook happens after data() has been set up, so then I can assign {card} using the getter. Unfortunately this displays nothing...

If I assign card() as a computed property:

computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

Body:
I tried everyone else's solutions and they did not work. But I got it to work finally. Here is what worked for me:

I ended up including a top-level:

<div v-if="!card"> Loading card... </div>
<div v-else> Rest of card template </div>

That seems to have silenced the error. Also, the card lives as a computed property:

card() {
  return this.$store.getters.cardById(this.$route.params.id);
}


问:
How do I use valgrind to find memory leaks?
How do I use valgrind to find the memory leaks in a program?

I am using Ubuntu 10.04 and I have a program a.c.

答:
How to Run Valgrind

Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.

```<code>sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.
sudo pacman -Syu valgrind  # Arch, Manjaro, Garuda, etc
</code>```

Valgrind is readily usable for C/C++ code, but can even be used for other
languages when configured properly (see this for Python).

To run Valgrind, pass the executable as an argument (along with any
parameters to the program).

```<code>valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1
</code>```

The flags are, in short:

--leak-check=full: "each individual leak will be shown in detail"

--show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.

--track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.

--verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.

--log-file: Write to a file. Useful when output exceeds terminal space.

Finally, you would like to see a Valgrind report that looks like this:

```<code>HEAP SUMMARY:
    in use at exit: 0 bytes in 0 blocks
  total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated

All heap blocks were freed -- no leaks are possible

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

I have a leak, but WHERE?

So, you have a memory leak, and Valgrind isn't saying anything meaningful.
Perhaps, something like this:

```<code>5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (in /home/Peri461/Documents/executable)
</code>```

Let's take a look at the C code I wrote too:

```<code>#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}
</code>```

Well, there were 5 bytes lost. How did it happen? The error report just says
main and malloc. In a larger program, that would be seriously troublesome to
hunt down. This is because of how the executable was compiled. We can
actually get line-by-line details on what went wrong. Recompile your program
with a debug flag (I'm using gcc here):

```<code>gcc -o executable -std=c11 -Wall main.c         # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c  # add -ggdb3 to it
</code>```

Now with this debug build, Valgrind points to the exact line of code
allocating the memory that got leaked! (The wording is important: it might not
be exactly where your leak is, but what got leaked. The trace helps you find
where.)

```<code>5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (main.c:4)
</code>```

Techniques for Debugging Memory Leaks & Errors

Make use of www.cplusplus.com! It has great documentation on C/C++ functions.

General advice for memory leaks:

Make sure your dynamically allocated memory does in fact get freed.

Don't allocate memory and forget to assign the pointer.

Don't overwrite a pointer with a new one unless the old memory is freed.

General advice for memory errors:

Access and write to addresses and indices you're sure belong to you. Memory
errors are different from leaks; they're often just IndexOutOfBoundsException
type problems.

Don't access or write to memory after freeing it.

Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:

List out the functions in your code that depend on/are dependent on the
"offending" code that has the memory error. Follow the program's execution
(maybe even in gdb perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.

Try commenting out the "offending" block of code (within reason, so your code
still compiles). If the Valgrind error goes away, you've found where it is.

If all else fails, try looking it up. Valgrind has documentation too!

A Look at Common Leaks and Errors

Watch your pointers

```<code>60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)
</code>```

And the code:

```<code>#include <stdlib.h>
#include <stdint.h>

struct _List {
    int32_t* data;
    int32_t length;
};
typedef struct _List List;

List* resizeArray(List* array) {
    int32_t* dPtr = array->data;
    dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
    return array;
}

int main() {
    List* array = calloc(1, sizeof(List));
    array->data = calloc(10, sizeof(int32_t));
    array = resizeArray(array);

    free(array->data);
    free(array);
    return 0;
}
</code>```

As a teaching assistant, I've seen this mistake often. The student makes use of
a local variable and forgets to update the original pointer. The error here is
noticing that realloc can actually move the allocated memory somewhere else
and change the pointer's location. We then leave resizeArray without telling
array->data where the array was moved to.

Invalid write

```<code>1 errors in context 1 of 1:
Invalid write of size 1
   at 0x4005CA: main (main.c:10)
 Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
   at 0x4C2B975: calloc (vg_replace_malloc.c:711)
   by 0x400593: main (main.c:5)
</code>```

And the code:

```<code>valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1
</code>```0

Notice that Valgrind points us to the commented line of code above. The array
of size 26 is indexed [0,25] which is why *(alphabet + 26) is an invalid
write—it's out of bounds. An invalid write is a common result of
off-by-one errors. Look at the left side of your assignment operation.

Invalid read

```<code>valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1
</code>```1

And the code:

```<code>valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1
</code>```2

Valgrind points us to the commented line above. Look at the last iteration here,
which is
 *(destination + 26) = *(source + 26);. However, *(source + 26) is
out of bounds again, similarly to the invalid write. Invalid reads are also a
common result of off-by-one errors. Look at the right side of your assignment
operation.

The Open Source (U/Dys)topia

How do I know when the leak is mine? How do I find my leak when I'm using
someone else's code? I found a leak that isn't mine; should I do something? All
are legitimate questions. First, 2 real-world examples that show 2 classes of
common encounters.

Jansson: a JSON library

```<code>#include <jansson.h>
#include <stdio.h>

int main() {
    char* string = "{ \"key\": \"value\" }";

    json_error_t error;
    json_t* root = json_loads(string, 0, &error); //obtaining a pointer
    json_t* value = json_object_get(root, "key"); //obtaining a pointer
    printf("\"%s\" is the value field.\n", json_string_value(value)); //use value

    json_decref(value); //Do I free this pointer?
    json_decref(root);  //What about this one? Does the order matter?
    return 0;
}
</code>```

This is a simple program: it reads a JSON string and parses it. In the making,
we use library calls to do the parsing for us. Jansson makes the necessary
allocations dynamically since JSON can contain nested structures of itself.
However, this doesn't mean we decref or "free" the memory given to us from
every function. In fact, this code I wrote above throws both an "Invalid read"
and an "Invalid write". Those errors go away when you take out the decref line
for value.

Why? The variable value is considered a "borrowed reference" in the Jansson
API. Jansson keeps track of its memory for you, and you simply have to decref
JSON structures independent of each other. The lesson here:
read the documentation. Really. It's sometimes hard to understand, but
they're telling you why these things happen. Instead, we have
existing questions about this memory error.

SDL: a graphics and gaming library

```<code>#include "SDL2/SDL.h"

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Quit();
    return 0;
}
</code>```

What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.

That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)

Answers unto the void

How do I know when the leak is mine?

It is. (99% sure, anyway)

How do I find my leak when I'm using someone else's code?

Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.

I found a leak that isn't mine; should I do something?

Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!

Further Reading

Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:

More about malloc, C's memory allocator

Definition of a segmentation fault

Definition of a memory leak

Definition of a memory access error

How does Valgrind work?

ContentLicense: CC BY-SA 4.0

Body:
How to Run Valgrind

Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.
sudo pacman -Syu valgrind  # Arch, Manjaro, Garuda, etc

Valgrind is readily usable for C/C++ code, but can even be used for other
languages when configured properly (see this for Python).

To run Valgrind, pass the executable as an argument (along with any
parameters to the program).

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

The flags are, in short:

--leak-check=full: "each individual leak will be shown in detail"

--show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.

--track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.

--verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.

--log-file: Write to a file. Useful when output exceeds terminal space.

Finally, you would like to see a Valgrind report that looks like this:

HEAP SUMMARY:
    in use at exit: 0 bytes in 0 blocks
  total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated

All heap blocks were freed -- no leaks are possible

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I have a leak, but WHERE?

So, you have a memory leak, and Valgrind isn't saying anything meaningful.
Perhaps, something like this:

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (in /home/Peri461/Documents/executable)

Let's take a look at the C code I wrote too:

#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}

Well, there were 5 bytes lost. How did it happen? The error report just says
main and malloc. In a larger program, that would be seriously troublesome to
hunt down. This is because of how the executable was compiled. We can
actually get line-by-line details on what went wrong. Recompile your program
with a debug flag (I'm using gcc here):

gcc -o executable -std=c11 -Wall main.c         # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c  # add -ggdb3 to it

Now with this debug build, Valgrind points to the exact line of code
allocating the memory that got leaked! (The wording is important: it might not
be exactly where your leak is, but what got leaked. The trace helps you find
where.)

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (main.c:4)

Techniques for Debugging Memory Leaks & Errors

Make use of www.cplusplus.com! It has great documentation on C/C++ functions.

General advice for memory leaks:

Make sure your dynamically allocated memory does in fact get freed.

Don't allocate memory and forget to assign the pointer.

Don't overwrite a pointer with a new one unless the old memory is freed.

General advice for memory errors:

Access and write to addresses and indices you're sure belong to you. Memory
errors are different from leaks; they're often just IndexOutOfBoundsException
type problems.

Don't access or write to memory after freeing it.

Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:

List out the functions in your code that depend on/are dependent on the
"offending" code that has the memory error. Follow the program's execution
(maybe even in gdb perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.

Try commenting out the "offending" block of code (within reason, so your code
still compiles). If the Valgrind error goes away, you've found where it is.

If all else fails, try looking it up. Valgrind has documentation too!

A Look at Common Leaks and Errors

Watch your pointers

60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)

And the code:

#include <stdlib.h>
#include <stdint.h>

struct _List {
    int32_t* data;
    int32_t length;
};
typedef struct _List List;

List* resizeArray(List* array) {
    int32_t* dPtr = array->data;
    dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
    return array;
}

int main() {
    List* array = calloc(1, sizeof(List));
    array->data = calloc(10, sizeof(int32_t));
    array = resizeArray(array);

    free(array->data);
    free(array);
    return 0;
}

As a teaching assistant, I've seen this mistake often. The student makes use of
a local variable and forgets to update the original pointer. The error here is
noticing that realloc can actually move the allocated memory somewhere else
and change the pointer's location. We then leave resizeArray without telling
array->data where the array was moved to.

Invalid write

1 errors in context 1 of 1:
Invalid write of size 1
   at 0x4005CA: main (main.c:10)
 Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
   at 0x4C2B975: calloc (vg_replace_malloc.c:711)
   by 0x400593: main (main.c:5)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* alphabet = calloc(26, sizeof(char));

    for(uint8_t i = 0; i < 26; i++) {
        *(alphabet + i) = 'A' + i;
    }
    *(alphabet + 26) = '\0'; //null-terminate the string?

    free(alphabet);
    return 0;
}

Notice that Valgrind points us to the commented line of code above. The array
of size 26 is indexed [0,25] which is why *(alphabet + 26) is an invalid
write—it's out of bounds. An invalid write is a common result of
off-by-one errors. Look at the left side of your assignment operation.

Invalid read

1 errors in context 1 of 1:
Invalid read of size 1
   at 0x400602: main (main.c:9)
 Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x4005E1: main (main.c:6)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* destination = calloc(27, sizeof(char));
    char* source = malloc(26 * sizeof(char));

    for(uint8_t i = 0; i < 27; i++) {
        *(destination + i) = *(source + i); //Look at the last iteration.
    }

    free(destination);
    free(source);
    return 0;
}

Valgrind points us to the commented line above. Look at the last iteration here,
which is
 *(destination + 26) = *(source + 26);. However, *(source + 26) is
out of bounds again, similarly to the invalid write. Invalid reads are also a
common result of off-by-one errors. Look at the right side of your assignment
operation.

The Open Source (U/Dys)topia

How do I know when the leak is mine? How do I find my leak when I'm using
someone else's code? I found a leak that isn't mine; should I do something? All
are legitimate questions. First, 2 real-world examples that show 2 classes of
common encounters.

Jansson: a JSON library

#include <jansson.h>
#include <stdio.h>

int main() {
    char* string = "{ \"key\": \"value\" }";

    json_error_t error;
    json_t* root = json_loads(string, 0, &error); //obtaining a pointer
    json_t* value = json_object_get(root, "key"); //obtaining a pointer
    printf("\"%s\" is the value field.\n", json_string_value(value)); //use value

    json_decref(value); //Do I free this pointer?
    json_decref(root);  //What about this one? Does the order matter?
    return 0;
}

This is a simple program: it reads a JSON string and parses it. In the making,
we use library calls to do the parsing for us. Jansson makes the necessary
allocations dynamically since JSON can contain nested structures of itself.
However, this doesn't mean we decref or "free" the memory given to us from
every function. In fact, this code I wrote above throws both an "Invalid read"
and an "Invalid write". Those errors go away when you take out the decref line
for value.

Why? The variable value is considered a "borrowed reference" in the Jansson
API. Jansson keeps track of its memory for you, and you simply have to decref
JSON structures independent of each other. The lesson here:
read the documentation. Really. It's sometimes hard to understand, but
they're telling you why these things happen. Instead, we have
existing questions about this memory error.

SDL: a graphics and gaming library

#include "SDL2/SDL.h"

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Quit();
    return 0;
}

What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.

That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)

Answers unto the void

How do I know when the leak is mine?

It is. (99% sure, anyway)

How do I find my leak when I'm using someone else's code?

Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.

I found a leak that isn't mine; should I do something?

Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!

Further Reading

Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:

More about malloc, C's memory allocator

Definition of a segmentation fault

Definition of a memory leak

Definition of a memory access error

How does Valgrind work?


问:
making a .exe from python including .txt files?
I have a python script that relies on over 400 .txt files (with HUGE dictionaries, so much so it needs to choose each one by itself and only load one at a time). How could I make an exe file from the python script that will come with the .txt files? I've looked at both pyInstaller and py2exe but nothing I see I understand/works for me?
Thank you in advance

EDIT: The text files have sensitive data in them, would it be possible for them to be only accessible by the python script itself?

答:
You could also use the cx_freeze module to accomplish this. Similar to Moe's suggestion it also takes a --onefile flag I believe.

Here is a link to another stack question that is similar. The answer in there not only shows how to construct the setup.py file for cx but also error handling when it inevitably misses some dependencies.

EDIT**

Here is a link to an article about securing your data. I don't think that you can do it in any straight forward way so here are some suggestions.

first you could store your data in a non usual format. Such as bytes.

second there are programs to obfuscate the data. The link provided above discusses some.

Third you could host the data online and use some sort of encrypted key pair connection to securely acquire necessary data.


问:
Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED?
I am developing a small application that lists all the applications present/ installed on the android device.  But I'm getting the below error while i'm trying to run the code.

Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED

Please can any one help me to sort out this error.

答: activity created name folder must be small letters, Dont use capital letters for activity folder name....  its always better to use small letters.</p>


问:
Swift 3 - Detail Disclosure Button Size
In storyboards, I currently have a custom tableview cell with a detail disclosure button in it. I increased the size of the cell and the font of the text label inside the cell, but now the detail disclosure button seems too small. I thought that the detail disclosure button would automatically increase in size as I made the cell bigger but it didn't. Is there a way to increase the size of the detail disclosure button? </p>

答:
The default rule for almost anything in iOS: if something standard doesn't work then you have to implement custom one. So the easiest way to use custom accessory view:</p>

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = // get cell
    let button = UIButton(type: .system)
    button.setImage(<your big image here>, for: .normal)
    button.sizeToFit()
    cell.accessoryView = button
    // configure rest of the cell
    return cell
}
</code>```

Title: Swift 3 - Detail Disclosure Button Size

Body:
The default rule for almost anything in iOS: if something standard doesn't work then you have to implement custom one. So the easiest way to use custom accessory view:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = // get cell
    let button = UIButton(type: .system)
    button.setImage(<your big image here>, for: .normal)
    button.sizeToFit()
    cell.accessoryView = button
    // configure rest of the cell
    return cell
}


问:
java.lang.IllegalArgumentException: JSON object doesn't have the primary key field 'id'
I use realm to parse this JSON, but I get this error:
java.lang.IllegalArgumentException: JSON object doesn't have the primary key field 'id'.

LINK of Json

this is my method :

```<code>    Realm r = Realm.getDefaultInstance();
        r.beginTransaction();
        r.createOrUpdateObjectFromJson(Application.class,result);
        r.commitTransaction();
</code>```

my Application class is :

```<code>public class Application extends RealmObject {

    @PrimaryKey
    private int id;
    private RealmList<girl> girls;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public RealmList<girl> getGirls() {
        return girls;
    }

    public void setGirls(RealmList<girl> girls) {
        this.girls = girls;
    }

    public Application() {
    }

    public Application(int id, RealmList<girl> girls) {
        this.id = id;
        this.girls = girls;
    }
}
</code>```

my class girl is

```<code>public class girl extends RealmObject {

    @PrimaryKey
    private int id;
    private String name;
    private String ville;
    private String tel;
    private String photo;
         //getters and setters and constructors with and without params
}
</code>```

答:
try to use realm.copyFromRealm(); and for more refer bellow link

https://github.com/realm/realm-java/issues/1973

Body:
I use realm to parse this JSON, but I get this error:
java.lang.IllegalArgumentException: JSON object doesn't have the primary key field 'id'.

LINK of Json

this is my method :

    Realm r = Realm.getDefaultInstance();
        r.beginTransaction();
        r.createOrUpdateObjectFromJson(Application.class,result);
        r.commitTransaction();

my Application class is :

public class Application extends RealmObject {

    @PrimaryKey
    private int id;
    private RealmList<girl> girls;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public RealmList<girl> getGirls() {
        return girls;
    }

    public void setGirls(RealmList<girl> girls) {
        this.girls = girls;
    }

    public Application() {
    }

    public Application(int id, RealmList<girl> girls) {
        this.id = id;
        this.girls = girls;
    }
}

my class girl is

public class girl extends RealmObject {

    @PrimaryKey
    private int id;
    private String name;
    private String ville;
    private String tel;
    private String photo;
         //getters and setters and constructors with and without params
}


问:
Conflicting Constraints Error Message in Debugger
I'm working through an online tutorial. I have followed everything step by step and am getting a message in the debugger when running the simulator saying I have conflicting constraints. I don't believe there is conflicting constraints, so I figured I would reach out for an informed second opinion.

Here is a screenshot of the view controller with the conflicting constraints.

View Controller from Xcode Project

Here are the screenshots of the error message in the debugger: It looks like it has an issue with the width constraint on the stop button, but I can't tell from the error message how to fix it.

Part of Error Message

Any help is greatly appreciated!

答:
I was able to find the answer. I had to change the priority to 999 on the width constraint of the stop button. The debug message was saying the below constraints were in conflict.

```<code>(
"<NSLayoutConstraint:0x600000096080 UIButton:0x7fb874e157d0.width == 64   (active)>",
"<NSLayoutConstraint:0x610000097ac0 'fittingSizeHTarget' UIStackView:0x7fb874e155d0.width == 0   (active)>",
"<NSLayoutConstraint:0x600000096210 'UISV-canvas-connection' UIStackView:0x7fb874e155d0.leading <= UIButton:0x7fb874e157d0.leading   (active)>",
"<NSLayoutConstraint:0x600000097ca0 'UISV-canvas-connection' UIStackView:0x7fb874e155d0.centerX == UIButton:0x7fb874e157d0.centerX   (active)>"
)
</code>```

Then it said it needed to break the width constraint of the stop button in order to fix the conflicting constraints issue.

```<code>Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000096080 UIButton:0x7fb874e157d0.width == 64
(active)>
</code>```

Dropping the priority to 999 prevented the debug message from appearing, and kept the buttons were I wanted them.

I found the solution information here:

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/DebuggingTricksandTips.html

[From the link]
Of these constraints, the last one was created by the system. You cannot change it. Furthermore, it creates an obvious conflict with the first constraint. If you superview is only 320 points wide, you can never have a 400-point-wide label. Fortunately, you don’t have to get rid of the first constraint. If you drop its priority to 999, the system still tries to provide the selected width—coming as close as it can while still satisfying the other constraints.

Body:
I was able to find the answer. I had to change the priority to 999 on the width constraint of the stop button. The debug message was saying the below constraints were in conflict.

(
"<NSLayoutConstraint:0x600000096080 UIButton:0x7fb874e157d0.width == 64   (active)>",
"<NSLayoutConstraint:0x610000097ac0 'fittingSizeHTarget' UIStackView:0x7fb874e155d0.width == 0   (active)>",
"<NSLayoutConstraint:0x600000096210 'UISV-canvas-connection' UIStackView:0x7fb874e155d0.leading <= UIButton:0x7fb874e157d0.leading   (active)>",
"<NSLayoutConstraint:0x600000097ca0 'UISV-canvas-connection' UIStackView:0x7fb874e155d0.centerX == UIButton:0x7fb874e157d0.centerX   (active)>"
)

Then it said it needed to break the width constraint of the stop button in order to fix the conflicting constraints issue.

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000096080 UIButton:0x7fb874e157d0.width == 64
(active)>

Dropping the priority to 999 prevented the debug message from appearing, and kept the buttons were I wanted them.

I found the solution information here:

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/DebuggingTricksandTips.html

[From the link]
Of these constraints, the last one was created by the system. You cannot change it. Furthermore, it creates an obvious conflict with the first constraint. If you superview is only 320 points wide, you can never have a 400-point-wide label. Fortunately, you don’t have to get rid of the first constraint. If you drop its priority to 999, the system still tries to provide the selected width—coming as close as it can while still satisfying the other constraints.


问:
Are Tries appropriate for languages which have no alphabet?
I am trying to work out the most efficient way for achieving similar efficiency as if using a Trie to store english words, but instead I want to store words in languages that have no alphabet such as Chinese. For example I want to be able to load a word list and have an application which as the user is typing gives suggestions in real time based on the characters typed already. Any suggestions how this could be achieved as if I use Tries I will have enormous number of parent nodes as there are thousands unique characters. Is there any established way for achieving what I have described above ? </p>

答:
A terminological detour: the word "alphabet" is commonly used to refer to the symbols in writing systems (like those of the various European languages) where each symbol roughly corresponds to a single phoneme (sound). There are also writing systems in which symbols correspond to syllables, morphemes or whole words; the symbols of such languages, which are much more numerous than alphabets, have different technical names: syllabaries, abugida, logographs, and so on, but the discrimination is not precise.

In computational theory, however, it is usual to use the word "alphabet" to describe any finite collection of symbols, regardless of how small or large the set is. Any alphabet -- or finite set of symbols -- can be transcoded into fixed-length sequences from a smaller alphabet of size at least two, with a change in length which is logarithmic in the size of the alphabet. Consequently, it is often convenient to assume that only binary representations are used: that is, representations from the alphabet {0, 1}.

A trie will work with any alphabet size; there is no requirement that the trie's alphabet be an "alphabet" from a human writing system, nor is there a prohibition against it being a larger collection of symbols, although naïve implementations with large alphabets can be very wasteful of space. In particular, nothing stops you from using a recoding of the original written characters into a smaller alphabet, using several trie levels for each character. For example, if the original string is represented in UTF-8, then you could use individual bytes (and you might want to distinguish between leading nodes, where the alphabet size is 178 although only 99 correspond to "letters", and interior nodes, where the alphabet size is 64). Alternatively, you could just split the Unicode code-point into three or four bit-sequences, each of a manageable size.

You can optimize tries by compressing successive nodes which have only a single child; that may be effective with the above schemes. A compact trie over the binary alphabet is called a Patricia trie, and it might be worth looking at as well.

Another common solution for dealing with sparse trie nodes is to use some kind of associative structure for children, rather than an array. In ternary search trees, the children are simply kept in a sorted list so that the correct child can be found with a binary search in time logarithmic in the alphabet size, which is constant for a given alphabet. (The time is actually logarithmic in the number of children, which could be much smaller than the alphabet size.)

Another solution, practical for medium-sized alphabets, is to keep a bit vector of present children as well as a sorted vector of children; modern CPUs have instructions which can rapidly sum the number of set bits in a word, making it efficient to use the bit vector to find the index of the child in the vector.

Yet another possible solution is to use a hash table whose entries are keyed by a 2-tuple consisting of the parent node's id and the child's leading character. This data structure is easy to maintain and space-efficient, but has very poor locality of reference. (One disadvantage is that additional work needs to be done to construct the list of children of a parent node: for example, by explicitly linking the children.)


问:
Optimal way to store follower and following MySQL
I have 2 tables one is user and another is company. Both have the following columns common while other columns are different.

```<code>id   email                name
1    first@email.com      First user
2    second@email.com     Second User
3    third@email.com      Third User
</code>```

Now a user can follow many companies but a company does not follow back user. Company should have data with users who follow them and a user should also store the companies they are following.

What is the simplest and optimal to make this happen on MySQL? Either should I create separate table for it or just add a column on existing tables with array of followers. Please answer assuming I have working level of knowledge on PHP and MySQL.

答:
You have the tables User and Company. Let's suppose they contain these values:

User

UserId
UserName
UserMail

1
Alice
alice@mail.com

2
Bob
bob@mail.com

Company

CompanyId
CompanyName
CompanyAddress

1
Microsoft
Redmond

2
Apple
Cupertino

3
Google
Mountain View

Then you should create a many-to-many table - e.g. let's call it UserCompany - which contains at least the columns UserId and CompanyId (coming from the first two tables).

Let's suppose that Alice follows Microsoft and Apple, and Bob follows Google. Your new UserCompany table will contain the following data:

UserId
CompanyId

1
1

1
2

2
3

Company should have data of users who follow them

Here you are the query to get the data of the users that follow Microsoft:

```<code>SELECT u.UserName, u.UserMail
FROM User AS u
JOIN UserCompany AS uc ON u.UserId = uc.UserId
WHERE uc.CompanyId = 1
</code>```

User should also have data of companies they are following.

And here you are the query to get the data of the companies followed by Alice:

```<code>SELECT c.CompanyName, c.CompanyCity
FROM UserCompany AS uc
JOIN Company AS c ON c.CompanyId = uc.CompanyId
WHERE uc.UserId = 1
</code>```

Body:
I have 2 tables one is user and another is company. Both have the following columns common while other columns are different.

id   email                name
1    first@email.com      First user
2    second@email.com     Second User
3    third@email.com      Third User

Now a user can follow many companies but a company does not follow back user. Company should have data with users who follow them and a user should also store the companies they are following.

What is the simplest and optimal to make this happen on MySQL? Either should I create separate table for it or just add a column on existing tables with array of followers. Please answer assuming I have working level of knowledge on PHP and MySQL.

Body:
You have the tables User and Company. Let's suppose they contain these values:

User

UserId
UserName
UserMail

1
Alice
alice@mail.com

2
Bob
bob@mail.com

Company

CompanyId
CompanyName
CompanyAddress

1
Microsoft
Redmond

2
Apple
Cupertino

3
Google
Mountain View

Then you should create a many-to-many table - e.g. let's call it UserCompany - which contains at least the columns UserId and CompanyId (coming from the first two tables).

Let's suppose that Alice follows Microsoft and Apple, and Bob follows Google. Your new UserCompany table will contain the following data:

UserId
CompanyId

1
1

1
2

2
3

Company should have data of users who follow them

Here you are the query to get the data of the users that follow Microsoft:

SELECT u.UserName, u.UserMail
FROM User AS u
JOIN UserCompany AS uc ON u.UserId = uc.UserId
WHERE uc.CompanyId = 1

User should also have data of companies they are following.

And here you are the query to get the data of the companies followed by Alice:

SELECT c.CompanyName, c.CompanyCity
FROM UserCompany AS uc
JOIN Company AS c ON c.CompanyId = uc.CompanyId
WHERE uc.UserId = 1


答:
```<code>select  1152  as clientid,        68 as releaseid , 'Yes' as status    ,  '' as ParentSignature    into #input
union select   1152 ,        70 , 'Yes'    , ''
union select   5059 ,        68 , 'Yes'    , 'ad '
union select   5410 ,        68 , 'Yes'    , '111 '
union select   5410 ,        70 , 'Yes'    , '111 '
union select   5410 ,        71 , 'Yes'    , ''

WITH Clients
AS (
    SELECT DISTINCT ClientId
    FROM #Input
    )
    ,Releases
AS (
    SELECT DISTINCT releaseid
    FROM #input
    )
    ,ClientReleases
AS (
    SELECT ClientId
        ,ReleaseId
    FROM Clients
    CROSS JOIN Releases
    )
SELECT *
FROM #input

UNION

SELECT ClientId
    ,ReleaseId
    ,''
    ,''
FROM ClientReleases cr
WHERE NOT EXISTS (
        SELECT 1
        FROM #input i
        WHERE i.clientid = cr.clientid
            AND i.releaseid = cr.releaseid
        )
</code>```

Title: How to insert dummy rows for distinct ids in a result set

Body:
I have a result set as follows:

+---------+-----------+--------+-----------------+
| ChildID | ReleaseID | Status | ParentSignature |
+---------+-----------+--------+-----------------+
|    1152 |        68 | Yes    |                 |
|    1152 |        70 | Yes    |                 |
|    5059 |        68 | Yes    | ad              |
|    5410 |        68 | Yes    | 111             |
|    5410 |        70 | Yes    | 111             |
|    5410 |        71 | Yes    |                 |
+---------+-----------+--------+-----------------+

In the above result set, there are 3 distinct values in ReleaseID column such as 68, 70 and 71.
Only one child id  (5410) has records corresponding to all the releaseids.

My requirement is to get an output result set in which there are records for each child for each release id with blank values for remaining columns.
The number of maximum distinct releaseids can vary. In this example, there are 3 releaseids.

Expected output:-

+---------+-----------+--------+-----------------+
| ChildID | ReleaseID | Status | ParentSignature |
+---------+-----------+--------+-----------------+
|    1152 |        68 | Yes    |                 |
|    1152 |        70 | Yes    |                 |
|    1152 |        71 |        |                 |
|    5059 |        68 | Yes    | ad              |
|    5059 |        70 |        |                 |
|    5059 |        71 |        |                 |
|    5410 |        68 | Yes    | 111             |
|    5410 |        70 | Yes    | 111             |
|    5410 |        71 | Yes    |                 |
+---------+-----------+--------+-----------------+