问:
Naming: Why should named constants be all uppercase in C++/Java?
I know, that for C++ and Java it is a well established naming convention, that constants should be written all uppercase, with underscores to separate words. Like this (Java-example):

```<code>public final static Color BACKGROUND_COLOR = Color.WHITE;
public final static Color TEXT_COLOR = Color.BLACK;
</code>```

This naming convention is easy to understand and to follow, but I ask myself, why choose this naming convention over the normal naming-convention for variables:

```<code>public final static Color backgroundColor = COLOR.WHITE;
public final static Color textColor = COLOR.BLACK;
</code>```

Theres seems to be no need to change the look of constants. If we want to assign a value to them, the compiler will prevent this anyways. Actually it makes problems, if later the constant will be changed into a proper variable (because the colors get configurable for instance).

So what's the ultimate reason to write named constants all uppercase? Historical reasons?

答:
In C (and then C++), symbols that were defined with the preprocessor #define directive were written all in caps as a loud signal to developers that the code was not as it seemed and to not treat as a normal symbol.  Constants did not initially exist in K&R C (although const was brought back from C++ later) so developers used #define instead, hence the caps.

For some reason, this got twisted into Java as "constants are caps", hence the current misguided (IMO) convention.

Body:
I know, that for C++ and Java it is a well established naming convention, that constants should be written all uppercase, with underscores to separate words. Like this (Java-example):

public final static Color BACKGROUND_COLOR = Color.WHITE;
public final static Color TEXT_COLOR = Color.BLACK;

This naming convention is easy to understand and to follow, but I ask myself, why choose this naming convention over the normal naming-convention for variables:

public final static Color backgroundColor = COLOR.WHITE;
public final static Color textColor = COLOR.BLACK;

Theres seems to be no need to change the look of constants. If we want to assign a value to them, the compiler will prevent this anyways. Actually it makes problems, if later the constant will be changed into a proper variable (because the colors get configurable for instance).

So what's the ultimate reason to write named constants all uppercase? Historical reasons?


来源: stackexchange

问:
I receive 404 node_modules not found
I'm using gulp and angular to create a simple web application.

When I make gulp serve the application cannot find whatever I have in node_modules folder.

Here is my gulp file:

```<code>// generated on 2017-10-12 using generator-webapp 3.0.1
const gulp = require('gulp');
const gulpLoadPlugins = require('gulp-load-plugins');
const browserSync = require('browser-sync').create();
const del = require('del');
const runSequence = require('run-sequence');

const $ = gulpLoadPlugins();
const reload = browserSync.reload;

let dev = true;

gulp.task('styles', () => {
  return gulp.src('app/styles/*.css')
    .pipe($.if(dev, $.sourcemaps.init()))
    .pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']}))
    .pipe($.if(dev, $.sourcemaps.write()))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(reload({stream: true}));
});

gulp.task('html', ['styles'], () => {
  return gulp.src('app/*.html')
    .pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
    .pipe($.if(/\.js$/, $.uglify({compress: {drop_console: true}})))
    .pipe($.if(/\.css$/, $.cssnano({safe: true, autoprefixer: false})))
    .pipe($.if(/\.html$/, $.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: {compress: {drop_console: true}},
      processConditionalComments: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true
    })))
    .pipe(gulp.dest('dist'));
});

gulp.task('images', () => {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', () => {
  return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {})
    .concat('app/fonts/**/*'))
    .pipe($.if(dev, gulp.dest('.tmp/fonts'), gulp.dest('dist/fonts')));
});

gulp.task('extras', () => {
  return gulp.src([
    'app/*',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

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

gulp.task('serve', () => {
  runSequence(['clean'], ['styles', 'fonts'], () => {
    browserSync.init({
      notify: false,
      port: 9000,
      server: {
        baseDir: ['.tmp', 'app']
      }
    });

    gulp.watch([
      'app/*.html',
      'app/images/**/*',
      '.tmp/fonts/**/*'
    ]).on('change', reload);

    gulp.watch('app/styles/**/*.css', ['styles']);
    gulp.watch('app/fonts/**/*', ['fonts']);
  });
});

gulp.task('serve:dist', ['default'], () => {
  browserSync.init({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['dist']
    }
  });
});

gulp.task('build', ['html', 'images', 'fonts', 'extras'], () => {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', () => {
  return new Promise(resolve => {
    dev = false;
    runSequence(['clean'], 'build', resolve);
  });
});
</code>```

And my index.html inside app is something like:

```<code><!doctype html>
<html class="no-js" lang="">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>paykey</title>
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <link rel="stylesheet" href="styles/main.css">
    <script src="node_modules/angular/angular.js"></script>
  </head>
  <body ng-app="myApp" >
</code>```

So for everything I point to node_modules is not found, and for example "styles" folder is at the same level and is found. Any idea why this is happening?

package.json:

```<code>{
  "private": true,
  "engines": {
    "node": ">=4"
  },
  "devDependencies": {
    "babel-core": "^6.4.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-register": "^6.5.2",
    "browser-sync": "^2.2.1",
    "del": "^2.2.0",
    "gulp": "^3.9.0",
    "gulp-autoprefixer": "^3.0.1",
    "gulp-babel": "^6.1.1",
    "gulp-cache": "^0.4.2",
    "gulp-cssnano": "^2.0.0",
    "gulp-eslint": "^3.0.0",
    "gulp-htmlmin": "^3.0.0",
    "gulp-if": "^2.0.2",
    "gulp-imagemin": "^3.0.1",
    "gulp-load-plugins": "^1.2.4",
    "gulp-plumber": "^1.0.1",
    "gulp-size": "^2.1.0",
    "gulp-sourcemaps": "^2.2.0",
    "gulp-uglify": "^2.0.0",
    "gulp-useref": "^3.0.0",
    "main-bower-files": "^2.5.0",
    "run-sequence": "^1.2.2",
    "wiredep": "^4.0.0"
  },
  "eslintConfig": {
    "env": {
      "es6": true,
      "node": true,
      "browser": true
    },
    "rules": {
      "quotes": [
        2,
        "single"
      ]
    }
  },
  "dependencies": {
    "angular": "^1.6.6",
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1",
    "modernizr": "^3.5.0",
    "popper": "^1.0.0"
  }
}
</code>```

答: Your serve:dist gulp task is serving the content from the dist directory. You need to create a new gulp task to copy over your scripts found in node_modules. Or better yet, just use Webpack.

ContentLicense: CC BY-SA 3.0

Title: I receive 404 node_modules not found

Body:
I'm using gulp and angular to create a simple web application.

When I make gulp serve the application cannot find whatever I have in node_modules folder.

Here is my gulp file:

// generated on 2017-10-12 using generator-webapp 3.0.1
const gulp = require('gulp');
const gulpLoadPlugins = require('gulp-load-plugins');
const browserSync = require('browser-sync').create();
const del = require('del');
const runSequence = require('run-sequence');

const $ = gulpLoadPlugins();
const reload = browserSync.reload;

let dev = true;

gulp.task('styles', () => {
  return gulp.src('app/styles/*.css')
    .pipe($.if(dev, $.sourcemaps.init()))
    .pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']}))
    .pipe($.if(dev, $.sourcemaps.write()))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(reload({stream: true}));
});

gulp.task('html', ['styles'], () => {
  return gulp.src('app/*.html')
    .pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
    .pipe($.if(/\.js$/, $.uglify({compress: {drop_console: true}})))
    .pipe($.if(/\.css$/, $.cssnano({safe: true, autoprefixer: false})))
    .pipe($.if(/\.html$/, $.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: {compress: {drop_console: true}},
      processConditionalComments: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true
    })))
    .pipe(gulp.dest('dist'));
});

gulp.task('images', () => {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', () => {
  return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {})
    .concat('app/fonts/**/*'))
    .pipe($.if(dev, gulp.dest('.tmp/fonts'), gulp.dest('dist/fonts')));
});

gulp.task('extras', () => {
  return gulp.src([
    'app/*',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

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

gulp.task('serve', () => {
  runSequence(['clean'], ['styles', 'fonts'], () => {
    browserSync.init({
      notify: false,
      port: 9000,
      server: {
        baseDir: ['.tmp', 'app']
      }
    });

    gulp.watch([
      'app/*.html',
      'app/images/**/*',
      '.tmp/fonts/**/*'
    ]).on('change', reload);

    gulp.watch('app/styles/**/*.css', ['styles']);
    gulp.watch('app/fonts/**/*', ['fonts']);
  });
});

gulp.task('serve:dist', ['default'], () => {
  browserSync.init({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['dist']
    }
  });
});

gulp.task('build', ['html', 'images', 'fonts', 'extras'], () => {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', () => {
  return new Promise(resolve => {
    dev = false;
    runSequence(['clean'], 'build', resolve);
  });
});

And my index.html inside app is something like:

<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>paykey</title>
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <link rel="stylesheet" href="styles/main.css">

So for everything I point to node_modules is not found, and for example "styles" folder is at the same level and is found. Any idea why this is happening?

package.json:

{
  "private": true,
  "engines": {
    "node": ">=4"
  },
  "devDependencies": {
    "babel-core": "^6.4.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-register": "^6.5.2",
    "browser-sync": "^2.2.1",
    "del": "^2.2.0",
    "gulp": "^3.9.0",
    "gulp-autoprefixer": "^3.0.1",
    "gulp-babel": "^6.1.1",
    "gulp-cache": "^0.4.2",
    "gulp-cssnano": "^2.0.0",
    "gulp-eslint": "^3.0.0",
    "gulp-htmlmin": "^3.0.0",
    "gulp-if": "^2.0.2",
    "gulp-imagemin": "^3.0.1",
    "gulp-load-plugins": "^1.2.4",
    "gulp-plumber": "^1.0.1",
    "gulp-size": "^2.1.0",
    "gulp-sourcemaps": "^2.2.0",
    "gulp-uglify": "^2.0.0",
    "gulp-useref": "^3.0.0",
    "main-bower-files": "^2.5.0",
    "run-sequence": "^1.2.2",
    "wiredep": "^4.0.0"
  },
  "eslintConfig": {
    "env": {
      "es6": true,
      "node": true,
      "browser": true
    },
    "rules": {
      "quotes": [
        2,
        "single"
      ]
    }
  },
  "dependencies": {
    "angular": "^1.6.6",
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1",
    "modernizr": "^3.5.0",
    "popper": "^1.0.0"
  }
}


问:
How to combine multiple SQL SELECT results into one array in PHP?
Hello this code works but currently it is very repetitive.

I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.

I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(

I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..

```<code>                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                // Select data from table from a random row
                $grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
                $grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
                $grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
                $grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
                $grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
                $grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";

                $result1 = $mysqli->query($grab1);
                $result2 = $mysqli->query($grab2);
                $result3 = $mysqli->query($grab3);
                $result4 = $mysqli->query($grab4);
                $result5 = $mysqli->query($grab5);
                $result6 = $mysqli->query($grab6);

                // Convert result into an array called items
                $item1 = mysqli_fetch_row($result1);
                $item2 = mysqli_fetch_row($result2);
                $item3 = mysqli_fetch_row($result3);
                $item4 = mysqli_fetch_row($result4);
                $item5 = mysqli_fetch_row($result5);
                $item6 = mysqli_fetch_row($result6);
</code>```

I managed to solve this with help on this thread..
I replaced all this code with:

```<code>                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                foreach ($ran_num as $key => $value) {
                  $grab[$key] = "select * from stock_tbl where stock_id='$value'";
                  $result = $mysqli->query($grab[$key]);
                  $item[$key] = mysqli_fetch_row($result);
                }
</code>```

Thank you very much :)

答:
You can concatenate strings in PHP with the '.' operator. Also, setting the grab variables as an array will make this easier as well, if that is possible in your implementation. You're probably looking for code such as:</p>

```<code>for (int i=0; i < 20; i++)
    $grab[i] = "select * from stock_tbl where stock_id='$ran_num[".i."]'";
</code>```

Body:
Hello this code works but currently it is very repetitive.

I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.

I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(

I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..

                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                // Select data from table from a random row
                $grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
                $grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
                $grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
                $grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
                $grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
                $grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";

                $result1 = $mysqli->query($grab1);
                $result2 = $mysqli->query($grab2);
                $result3 = $mysqli->query($grab3);
                $result4 = $mysqli->query($grab4);
                $result5 = $mysqli->query($grab5);
                $result6 = $mysqli->query($grab6);

                // Convert result into an array called items
                $item1 = mysqli_fetch_row($result1);
                $item2 = mysqli_fetch_row($result2);
                $item3 = mysqli_fetch_row($result3);
                $item4 = mysqli_fetch_row($result4);
                $item5 = mysqli_fetch_row($result5);
                $item6 = mysqli_fetch_row($result6);

I managed to solve this with help on this thread..
I replaced all this code with:

                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                foreach ($ran_num as $key => $value) {
                  $grab[$key] = "select * from stock_tbl where stock_id='$value'";
                  $result = $mysqli->query($grab[$key]);
                  $item[$key] = mysqli_fetch_row($result);
                }

Thank you very much :)

Body:
You can concatenate strings in PHP with the '.' operator. Also, setting the grab variables as an array will make this easier as well, if that is possible in your implementation. You're probably looking for code such as:

for (int i=0; i < 20; i++)
    $grab[i] = "select * from stock_tbl where stock_id='$ran_num[".i."]'";


问:
TYPO3 Constant Editor is not working with Internet Explorer or Microsoft Edge
In TYPO3 8.7.8 and 7.6.23 (I tested this two versions) you cannot enable or disable boolean fields in Internet Explorer (tested with Version 11) or Microsoft Edge: the click is not "recognized" on the checkbox. It is no problem with Chrome or Firefox.</p>

答:
I confirm this. TYPO3 8.7.8.
Looks like a bug</p>


问:
Whats the difference between these two classes
Hi I have a question about these two class's , •    The bus (i.e., what values does it need to store and what actions can it take)
•   The command (i.e., what type of command has been issued to what bus and what values) I'm confused as to what the difference would be, the bus class will have the function where it moves it self. But then what is the command class for? I need to use to different classes for this one has been called bus and other command.

Guidlines---
You are running a bus company with four buses.  These buses will move around based on commands provided from keyboard input.  To move a bus, you will issue a command from the keyboard with the bus identification, direction, and number of spaces to move.  For example:
B W 3
Would move Bus “B” three spaces to the West.  All buses will start at the bus station at coordinates (0,0).  A “N”orth command would increment the y-coordinate; “S”outh decrement the y-coordinate.  A “E”ast command increments the x-coordinate and a “W”est command decrements the x-coordinate.
You will also accept commands to pick up and drop off people:
D P 5
A D 2

答:
Still confusing, but I'll give it a shot. If these are the only two classes in your program I think the division is pretty clear.

The Bus will be a class that holds information about the bus. It will have member variables that represent its position on the "map" (x,y) with a move function that will update these member variables. So when you call busname.move(variables) it will move like you want it to and update its position. Additionally it seems like it would have a variable representing how many people are on board.

The command class is something else entirely, it would be the main control for your program. It would have instances of the bus class as its members (A,B,C,D) and it would interpret commands from the keyboard to determine what command to issue to what bus. For example, if you type A W 3 on the keyboard how is bus A ever supposed to know to move to the west three spaces? Because the command class will take the keyboard input and call A.move(-3, 0) or something like that to update its position.

Hope this helps.


答:
First of all, do you really need *?

What's wrong with using a single query with the IN() function? For example:

```<code>// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));

// Select(grab) data from table from a random row
$grab = 'SELECT * FROM stock_tbl WHERE stock_id IN ('.implode(',', $ran_num).')';
</code>```

Title: How to combine multiple SQL SELECT results into one array in PHP?

Body:
First of all, do you really need *?

What's wrong with using a single query with the IN() function? For example:

// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));

// Select(grab) data from table from a random row
$grab = 'SELECT * FROM stock_tbl WHERE stock_id IN ('.implode(',', $ran_num).')';


问:
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
C# Which Event should I use to display data in a textbox when I select an item in a listbox?

I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text update with each click.

Thanks

答:
You will want to handle either SelectedIndexChanged or SelectedValueChanged.

(Note that the SelectedValueChanged MSDN article has an example that sounds like exactly what you are doing.)

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Andrew Hare


问:
Best source control development tool for Windows / .NET
What are your recommendations to use as a source control, project repository for a Windows - .NET development environment (two coders, possible one using the system)?

Addition: also the team includes three developers. One Visual Basic 6.0 moving to .NET, myself in .NET, and one web developer (PHP, JavaScript, etc.)

The system I am looking for would be something that easily integrates into the IDE of Visual Studio.

答:
Give a try to Plastic SCM Community Edition. It is a free version control system for up to 15 users, commercially supported, distributed (if you want to, it can be centralized) and with integrated diff and merge tools.

The entire GUI is totally integrated with Visual Studio.

Branching and merging can be tracked visually with the branch explorer.

XDiff and XMerge for diffing and merging code supporting refactors.

Cool features like the "method history" support. (Note: also available for SVN).

Hope it helps.

ContentLicense: CC BY-SA 4.0


问:
How handle watchify errors in gulp. Watchify prevent error from being reported
When I include watchify plugin in a browserify bundler and there is an compile time error, the error is not logged. </p>

```<code>const gulp        = require('gulp');
const browserify  = require('browserify');            //js bundler
const watchify    = require('watchify');              //allows incremental bundling
const hbsfy       = require('hbsfy');                 //precompiles hbs files
const babelify    = require('babelify');              //ES2015 to ES5
const source      = require('vinyl-source-stream');   //Gulp and NodeJS stream interop. Use conventional text streams at the start of your gulp or vinyl pipelines, making for nicer interoperability with the existing npm stream ecosystem.
const buffer      = require('vinyl-buffer');          //Convert streaming vinyl files to use buffers. Usually used with vinyl-source-stream and gulp-sourcemaps
const uglify      = require('gulp-uglify');           //uglifyjs (js minimalizer) plugin for gulp (would be nice to use uglyfyjs directly)
const sourcemaps  = require('gulp-sourcemaps');       //generate source maps when tranforming js or css
const gutil       = require('gulp-util');             //utlis for gulp, e.g. console logging

gulp.task("watch-js", function(done){
    var b = browserify({
        entries: 'main.js',
        debug: true,
        cache: {},
        packageCache: {},
      });
    b.external(config.vendorJsLibs);
    b.transform(hbsfy);
    b.transform(babelify, { presets: ['es2015'] });

    b.plugin(watchify); //when I comment this, errors are reported
    b.on('error', function(err){
       gutil.log(err.toString());
       this.emit('end');
       done();
    });
    compileJs(b, 'app.js');
    b.on('update', function(evt){
        gutil.log('watchify update '+ evt);
        compileJs(b, 'app.js');
    });
});

function compileJs(bundler, bundleFileName){
    return bundler.bundle()
        .pipe(source(bundleFileName))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
            // Add transformation tasks to the pipeline here.
            .pipe(uglify())
            .on('error', function(error){
                gutil.log(error);
                this.emit('end');
            })
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(dest + '/scripts'));
}
</code>```

答:
You don't have any error handlers on your bundle, that's why node crashes and prints a stack trace. This is a safety mechanism that ensures error events are either handled or execution is aborted.

Watchify listens to error events on bundler for internal logic. This satisfies nodes error handling requirement.

In your code you should listen for error events on the stream returned by b.bundle(). The following code should do the trick:

```<code>function compileJs(bundler, bundleFileName){
    return bundler.bundle()
        .on('error', gutil.log)
        ...
}
</code>```

Body:
When I include watchify plugin in a browserify bundler and there is an compile time error, the error is not logged.

const gulp        = require('gulp');
const browserify  = require('browserify');            //js bundler
const watchify    = require('watchify');              //allows incremental bundling
const hbsfy       = require('hbsfy');                 //precompiles hbs files
const babelify    = require('babelify');              //ES2015 to ES5
const source      = require('vinyl-source-stream');   //Gulp and NodeJS stream interop. Use conventional text streams at the start of your gulp or vinyl pipelines, making for nicer interoperability with the existing npm stream ecosystem.
const buffer      = require('vinyl-buffer');          //Convert streaming vinyl files to use buffers. Usually used with vinyl-source-stream and gulp-sourcemaps
const uglify      = require('gulp-uglify');           //uglifyjs (js minimalizer) plugin for gulp (would be nice to use uglyfyjs directly)
const sourcemaps  = require('gulp-sourcemaps');       //generate source maps when tranforming js or css
const gutil       = require('gulp-util');             //utlis for gulp, e.g. console logging

gulp.task("watch-js", function(done){
    var b = browserify({
        entries: 'main.js',
        debug: true,
        cache: {},
        packageCache: {},
      });
    b.external(config.vendorJsLibs);
    b.transform(hbsfy);
    b.transform(babelify, { presets: ['es2015'] });

    b.plugin(watchify); //when I comment this, errors are reported
    b.on('error', function(err){
       gutil.log(err.toString());
       this.emit('end');
       done();
    });
    compileJs(b, 'app.js');
    b.on('update', function(evt){
        gutil.log('watchify update '+ evt);
        compileJs(b, 'app.js');
    });
});

function compileJs(bundler, bundleFileName){
    return bundler.bundle()
        .pipe(source(bundleFileName))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
            // Add transformation tasks to the pipeline here.
            .pipe(uglify())
            .on('error', function(error){
                gutil.log(error);
                this.emit('end');
            })
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(dest + '/scripts'));
}

Body:
You don't have any error handlers on your bundle, that's why node crashes and prints a stack trace. This is a safety mechanism that ensures error events are either handled or execution is aborted.

Watchify listens to error events on bundler for internal logic. This satisfies nodes error handling requirement.

In your code you should listen for error events on the stream returned by b.bundle(). The following code should do the trick:

function compileJs(bundler, bundleFileName){
    return bundler.bundle()
        .on('error', gutil.log)
        ...
}


问:
How to display number sequences in rows and columns in Python 3?
I have a coding assignment to input row and column length, and create a power table.  THe example below is for 5 rows, 5 columns.

The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work.  It just shows a table of 1's, five by five.

```<code>rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1
</code>```

答:
Here is a way to do it that preserves padding no matter what:</p>

```<code>def grid(rows, cols, padding):
  max_num_len = len(str(rows**cols))
  return '\n'.join([
    ''.join(['{{:>{}}}'.format(max_num_len+padding).format((row+1)**(col+1))
             for col in range(cols)])
    for row in range(rows)
  ])

print(grid(5, 5, 3))
</code>```

Body:
I have a coding assignment to input row and column length, and create a power table.  THe example below is for 5 rows, 5 columns.

The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work.  It just shows a table of 1's, five by five.

rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1

Body:
Here is a way to do it that preserves padding no matter what:

def grid(rows, cols, padding):
  max_num_len = len(str(rows**cols))
  return '\n'.join([
    ''.join(['{{:>{}}}'.format(max_num_len+padding).format((row+1)**(col+1))
             for col in range(cols)])
    for row in range(rows)
  ])

print(grid(5, 5, 3))


问:
How can I use case_when inside dplyr mutate() function?
As far as I understand, case_when() is a generalised version of ifelse().

However, I don't understand how to use this function inside dplyr::mutate() function. It used to work using github's last version of dplyr but since I'm back to the CRAN version (0.5), it doesn't work anymore. Does anyone has a clue ?

Here is my reproducible example :

library(devtools)
library(tibble)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

tibble(
  group = c("A", "A", "A", "B", "B", "B"),
  x = 1:6
  ) %>%
  mutate(
    y = ifelse(group == "A", -x, x)
    )
#> # A tibble: 6 × 3
#>   group     x     y
#>   <chr> <int> <int>
#> 1     A     1    -1
#> 2     A     2    -2
#> 3     A     3    -3
#> 4     B     4     4
#> 5     B     5     5
#> 6     B     6     6

tibble(
  group = c("A", "A", "A", "B", "B", "B"),
  x = 1:6
  ) %>%
  mutate(
    y = case_when(
      group == "A" ~ -x,
      TRUE ~ x
      )
  )
#> Error in mutate_impl(.data, dots): object 'group' not found

tibble(
  group = c("A", "A", "A", "B", "B", "B"),
  x = 1:6
  ) %>%
  mutate_(
    .dots = list(
      "y" = lazyeval::interp(
        ~ case_when(var1 == "A" ~ -var2, TRUE, var2),
        var1 = as.name(group),
        var2 = as.name(x)
        )
    )
  )
#> Error in as.name(group): object 'group' not found

devtools::session_info()
#> Session info -------------------------------------------------------------
#>  setting  value
#>  version  R version 3.3.2 (2016-10-31)
#>  system   x86_64, linux-gnu
#>  ui       X11
#>  language (EN)
#>  collate  C
#>  tz       <NA>
#>  date     2017-03-10
#> Packages -----------------------------------------------------------------
#>  package    * version     date       source
#>  assertthat   0.1         2013-12-06 CRAN (R 3.2.2)
#>  backports    1.0.5       2017-01-18 cran (@1.0.5)
#>  DBI          0.6         2017-03-09 cran (@0.6)
#>  devtools   * 1.12.0.9000 2017-03-07 Github (hadley/devtools@d8ab190)
#>  digest       0.6.12      2017-01-27 cran (@0.6.12)
#>  dplyr      * 0.5.0       2016-06-24 CRAN (R 3.3.2)
#>  evaluate     0.10        2016-10-11 cran (@0.10)
#>  htmltools    0.3.5       2016-03-21 CRAN (R 3.2.3)
#>  knitr        1.15.1      2016-11-22 cran (@1.15.1)
#>  lazyeval     0.2.0.9000  2016-10-14 Github (hadley/lazyeval@c155c3d)
#>  magrittr     1.5         2014-11-22 CRAN (R 3.2.3)
#>  memoise      1.0.0.9001  2017-02-13 Github (hadley/memoise@884d565)
#>  pkgbuild     0.0.0.9000  2017-03-07 Github (r-pkgs/pkgbuild@65eace0)
#>  pkgload      0.0.0.9000  2017-03-07 Github (r-pkgs/pkgload@fc907a1)
#>  R6           2.2.0       2016-10-05 cran (@2.2.0)
#>  Rcpp         0.12.9      2017-01-14 cran (@0.12.9)
#>  rmarkdown    1.3.9004    2017-03-09 Github (rstudio/rmarkdown@01dc037)
#>  rprojroot    1.2         2017-01-16 cran (@1.2)
#>  stringi      1.1.2       2016-10-01 CRAN (R 3.3.1)
#>  stringr      1.2.0       2017-02-18 cran (@1.2.0)
#>  tibble     * 1.2         2016-08-26 CRAN (R 3.2.3)
#>  withr        1.0.2       2016-06-20 CRAN (R 3.2.3)
#>  yaml         2.1.14      2016-11-12 cran (@2.1.14)
```

答:
I found a peculiar work around - It seems that piping the dataframe to mutate rather than including it as the 1st argument allows you to use case_when and it works as expected.

For example, this works:

```<code>df %>% mutate(new_var = case_when(old_var == 1 ~ TRUE,
                                  TRUE ~ FALSE)
</code>```

This doesn't work:

```<code>mutate(df, new_var = case_when(old_var == 1 ~ TRUE,
                               TRUE ~ FALSE)
</code>```

(using R 3.3.1, dplyr 0.5.0)

Body:
I found a peculiar work around - It seems that piping the dataframe to mutate rather than including it as the 1st argument allows you to use case_when and it works as expected.

For example, this works:

df %>% mutate(new_var = case_when(old_var == 1 ~ TRUE,
                                  TRUE ~ FALSE)

This doesn't work:

mutate(df, new_var = case_when(old_var == 1 ~ TRUE,
                               TRUE ~ FALSE)

(using R 3.3.1, dplyr 0.5.0)


问:
Require a form to be filled out to download a .pdf?
Can I dynamically make a page with download links for PDF files and require user fill out HTML form before able to download the .PDF files?</p>

答:
This could be accomplished all in html or with PHP and HTML.  But, I like the PHP implementation better because it allows for more secure input verification and it allows for more backward and browser compatibility.  The JavaScript method would require data urls, which aren't supported in certain web browsers.</p>

```<code><?php

  function startDownload($filePath) {
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=" . basename(urlencode($filePath)));
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    $fp = fopen($filePath, "r");
    while (!feof($fp)) {
      echo fread($fp, 65536);
      flush();
    }
    fclose($fp);
    die();
  }

  //Note that I decided to check specifically for the strings and didn't just take the hidden field here
  //  If we just assume the user isn't a liar,

  if (isset($_POST['name']) && isset($_POST['file'])) {
    if ($_POST['file'] == "pdfurl-guide.pdf") {
      startDownload("pdfurl-guide.pdf");
    } else if ($_POST['file'] == "someOther.pdf") {
      startDownload("someOther.pdf");
    } else {
      echo "error";
    }
  }

?>

Please fill out the following form to download:
<form method="post" action="">
  <input type="hidden" name="file" value="pdfurl-guide.pdf" />
  Name: <input type="text" name="name" /><br />
  <input type="submit" />
</form>
<br />
What if you want this file?
<form method="post" action="">
  <input type="hidden" name="file" value="someOther.pdf" />
  Name: <input type="text" name="name" /><br />
  <input type="submit" />
</form>
</code>```

Body:
This could be accomplished all in html or with PHP and HTML.  But, I like the PHP implementation better because it allows for more secure input verification and it allows for more backward and browser compatibility.  The JavaScript method would require data urls, which aren't supported in certain web browsers.

<?php

  function startDownload($filePath) {
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=" . basename(urlencode($filePath)));
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    $fp = fopen($filePath, "r");
    while (!feof($fp)) {
      echo fread($fp, 65536);
      flush();
    }
    fclose($fp);
    die();
  }

  //Note that I decided to check specifically for the strings and didn't just take the hidden field here
  //  If we just assume the user isn't a liar,

  if (isset($_POST['name']) && isset($_POST['file'])) {
    if ($_POST['file'] == "pdfurl-guide.pdf") {
      startDownload("pdfurl-guide.pdf");
    } else if ($_POST['file'] == "someOther.pdf") {
      startDownload("someOther.pdf");
    } else {
      echo "error";
    }
  }

?>

Please fill out the following form to download:
<form method="post" action="">
  <input type="hidden" name="file" value="pdfurl-guide.pdf" />
  Name: <input type="text" name="name" /><br />
  <input type="submit" />
</form>
<br />
What if you want this file?
<form method="post" action="">
  <input type="hidden" name="file" value="someOther.pdf" />
  Name: <input type="text" name="name" /><br />
  <input type="submit" />
</form>


问:
Game Center Multiplayer using GKMatch but seems can't be connected
Hi I'm a new bie in Game Center for iOS.  I'm trying to add the multiplayer feature using matches to my game and following the documentation.

So far I reached a point where 2 of my clients can successfully get a match, i.e. the matchmakerViewController:didFindMatch callback is called and a GKMatch object is delivered.

However after that I seems to be stuck there forever, because according to the documentation,  I'll have to wait until all the players (2 in my case) are actually connected before starting my game.   But it seems the match:player:didChangeState callback is never called to indicate a successful connection.   Well, I'm sure my clients are all in the same wifi network ( or is it a must?)  Could any one enlighten me on this case?  Do I have to do any extra things to make the clients to connect?    Thanks a lot for the help!

答:
So I was running into this and the solution (for me) was somewhat embarrasing.  I had copied and pasted a bunch of the code from the Apple docs..and they left out an obvious step.  They never actually set the match's delegate!

My code now is:

```<code>- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match {
[self dismissModalViewControllerAnimated:YES];
self.myMatch = match; // Use a retaining property to retain the match.
self.myMatch.delegate = self;  // THIS LINE WAS MISSING IN THE APPLE DOCS.  DOH.
// Start the game using the match.
NSLog(@"Match started! Expected Player Count:%d  %@",match.expectedPlayerCount, match.playerIDs);}
</code>```

Once I actually set the match delegate, the functions get called.  Doh.

Body:
So I was running into this and the solution (for me) was somewhat embarrasing.  I had copied and pasted a bunch of the code from the Apple docs..and they left out an obvious step.  They never actually set the match's delegate!

My code now is:

- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match {
[self dismissModalViewControllerAnimated:YES];
self.myMatch = match; // Use a retaining property to retain the match.
self.myMatch.delegate = self;  // THIS LINE WAS MISSING IN THE APPLE DOCS.  DOH.
// Start the game using the match.
NSLog(@"Match started! Expected Player Count:%d  %@",match.expectedPlayerCount, match.playerIDs);}

Once I actually set the match delegate, the functions get called.  Doh.


问:
TextEncoder and TextDecoder not perfect inverses of each other
I received this answer to my previous question about encoding strings. My hope in asking that question was to get some reversible way of shifting between a string and its representation as an array of bytes like in Python 3.

I ran into a problem with one particular Uint8Array though:

```<code>var encoder = new TextEncoder();
var decoder = new TextDecoder(encoder.encoding);
var s = [248, 35, 45, 41, 178, 175, 190, 62, 134, 39];
var t = Array.from(decoder.decode(encoder.encode(Uint8Array(s)));
</code>```

I expected the value of t to be [248, 35, 45, 41, 178, 175, 190, 62, 134, 39]. Instead, it is [239, 191, 189, 35, 45, 41, 239, 191, 189, 239, 191, 189, 239, 191, 189, 62, 239, 191, 189, 39]. The person who posted the answer was temporarily suspended from the site, so I cannot resolve this through commenting on his answer.

答:
change var t = Array.from(decoder.decode(encoder.encode(Uint8Array(s))); to

 var t = JSON.parse('['+decoder.decode(encoder.encode(new Uint8Array(s)))+']');.

var encoder = new TextEncoder();
var decoder = new TextDecoder(encoder.encoding);
var s = [248, 35, 45, 41, 178, 175, 190, 62, 134, 39];
var t = JSON.parse('['+decoder.decode(encoder.encode(new Uint8Array(s)))+']');
console.log(t);```

Body:
I received this answer to my previous question about encoding strings. My hope in asking that question was to get some reversible way of shifting between a string and its representation as an array of bytes like in Python 3.

I ran into a problem with one particular Uint8Array though:

var encoder = new TextEncoder();
var decoder = new TextDecoder(encoder.encoding);
var s = [248, 35, 45, 41, 178, 175, 190, 62, 134, 39];
var t = Array.from(decoder.decode(encoder.encode(Uint8Array(s)));

I expected the value of t to be [248, 35, 45, 41, 178, 175, 190, 62, 134, 39]. Instead, it is [239, 191, 189, 35, 45, 41, 239, 191, 189, 239, 191, 189, 239, 191, 189, 62, 239, 191, 189, 39]. The person who posted the answer was temporarily suspended from the site, so I cannot resolve this through commenting on his answer.


问:
How to stop safari (on ipad) from firing hover event?
I have a button that is fixed on my page and when you start to scroll it appears. I noticed on ipad safari I have to click this button twice to fire the click event once.

After searching around I found this sure enough when I commented out my "display:none" on the button it works.

How can I achieve having it hidden and then changing it to "display:block" without getting this double click issue?

答:
You can use css position instead to place it off screen:

```<code>.hide {
   position: absolute;
   left: -999em;
}
</code>```

You could also try the visibility property

```<code>.hide {
   visibility: hidden;
 }
</code>```

w3c example

Body:
You can use css position instead to place it off screen:

.hide {
   position: absolute;
   left: -999em;
}

You could also try the visibility property

.hide {
   visibility: hidden;
 }

w3c example


问:
How to show MediaElementJS audio playlist to be shown on top of the controls?
I have a mediaelementjs audio player in the footer as shown in this image below.

My questions are posted in the image above.

I want my audio player to look like this joomla audio player below (I am doing my project in Asp.Net MVC c#). Joomla player is in php,I could not use it my project.The playlist is shown to top of control bar when toggled. Mine toggles down below the control bar.

Joomla Sticky Full Width Audio

I used MediaElementJS audio, I want playlist toggle up above the control bar, not down.

答:
I was able to change the scrollbar design colors and color by using changing css of -webkit-scrollbar.

-webkit-scrollbar css

Then,for making the playlist appear on top of control bar rather than bottom of it,all I had to change is playlistposition property of the mediaelementJS to 'top'.

```<code>              $(function () {
                $('#mejsAudio').mediaelementplayer({
                    loop: true,
                    shuffle: true,
                    playlist: true,
                    audioHeight: 30,
                    audioWidth:  "100%",
                    playlistposition: 'top',
                    audioVolume: 'vertical',
                    features: ['playlistfeature', 'prevtrack', 'playpause', 'nexttrack', 'loop', 'shuffle', 'playlist', 'current', 'progress', 'duration', 'volume']
                      });

            });
</code>```

Body:
I was able to change the scrollbar design colors and color by using changing css of -webkit-scrollbar.

-webkit-scrollbar css

Then,for making the playlist appear on top of control bar rather than bottom of it,all I had to change is playlistposition property of the mediaelementJS to 'top'.

              $(function () {
                $('#mejsAudio').mediaelementplayer({
                    loop: true,
                    shuffle: true,
                    playlist: true,
                    audioHeight: 30,
                    audioWidth:  "100%",
                    playlistposition: 'top',
                    audioVolume: 'vertical',
                    features: ['playlistfeature', 'prevtrack', 'playpause', 'nexttrack', 'loop', 'shuffle', 'playlist', 'current', 'progress', 'duration', 'volume']
                      });

            });


问:
Extracting from a file and pasting details to another file
The problem is regarding extracting the details of the Oracle Virtual box(2nd paragraph) from the "nmap non-gui version". I understand the usage of "grep" and "loops" and have already tried everything but what if there are other systems connected on the same network. I just want the program to find the word "(Oracle VirtualBox virtual NIC)" and extract everything above it until it finds a blank-line.

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

root@PopeyeTheSailorMan:~# nmap 192.168.43.0/24 > Log.txt

**

```<code>Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-15 04:08 UTC
Nmap scan report for 192.168.43.1
Host is up (0.0025s latency).
Not shown: 999 closed ports
PORT   STATE SERVICE
53/tcp open  domain
MAC Address: 9A:10:94:51:42:ED (Unknown)

***Nmap scan report for 192.168.43.136
Host is up (0.00071s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
111/tcp  open  rpcbind
139/tcp  open  netbios-ssn
443/tcp  open  https
1024/tcp open  kdm
MAC Address: 08:00:27:D3:73:2E (Oracle VirtualBox virtual NIC)***

Nmap scan report for kali (192.168.43.79)
Host is up (0.0000070s latency).
All 1000 scanned ports on kali (192.168.43.79) are closed

Nmap done: 256 IP addresses (3 hosts up) scanned in 16.00 seconds
</code>```

答:
If I understand your question, this does what you want:

```<code>awk '/Oracle VirtualBox virtual NIC/' RS= Log.txt
</code>```

With your sample input:

```<code>$ awk '/Oracle VirtualBox virtual NIC/' RS= Log.txt
***Nmap scan report for 192.168.43.136
Host is up (0.00071s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
111/tcp  open  rpcbind
139/tcp  open  netbios-ssn
443/tcp  open  https
1024/tcp open  kdm
MAC Address: 08:00:27:D3:73:2E (Oracle VirtualBox virtual NIC)***
</code>```

How it works

RS=

This tells awk to read input a paragraph at a time.

/Oracle VirtualBox virtual NIC/

This tells awk to print any paragraph that contains the string Oracle VirtualBox virtual NIC.

Body:
The problem is regarding extracting the details of the Oracle Virtual box(2nd paragraph) from the "nmap non-gui version". I understand the usage of "grep" and "loops" and have already tried everything but what if there are other systems connected on the same network. I just want the program to find the word "(Oracle VirtualBox virtual NIC)" and extract everything above it until it finds a blank-line.

**

root@PopeyeTheSailorMan:~# nmap 192.168.43.0/24 > Log.txt

**

Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-15 04:08 UTC
Nmap scan report for 192.168.43.1
Host is up (0.0025s latency).
Not shown: 999 closed ports
PORT   STATE SERVICE
53/tcp open  domain
MAC Address: 9A:10:94:51:42:ED (Unknown)

***Nmap scan report for 192.168.43.136
Host is up (0.00071s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
111/tcp  open  rpcbind
139/tcp  open  netbios-ssn
443/tcp  open  https
1024/tcp open  kdm
MAC Address: 08:00:27:D3:73:2E (Oracle VirtualBox virtual NIC)***

Nmap scan report for kali (192.168.43.79)
Host is up (0.0000070s latency).
All 1000 scanned ports on kali (192.168.43.79) are closed

Nmap done: 256 IP addresses (3 hosts up) scanned in 16.00 seconds

Body:
If I understand your question, this does what you want:

awk '/Oracle VirtualBox virtual NIC/' RS= Log.txt

With your sample input:

$ awk '/Oracle VirtualBox virtual NIC/' RS= Log.txt
***Nmap scan report for 192.168.43.136
Host is up (0.00071s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
111/tcp  open  rpcbind
139/tcp  open  netbios-ssn
443/tcp  open  https
1024/tcp open  kdm
MAC Address: 08:00:27:D3:73:2E (Oracle VirtualBox virtual NIC)***

How it works

RS=

This tells awk to read input a paragraph at a time.

/Oracle VirtualBox virtual NIC/

This tells awk to print any paragraph that contains the string Oracle VirtualBox virtual NIC.


问:
Reading from URL, store data as double?
```<code>public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}
</code>```

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?

答: Double.parseDouble(string) is what you're after.</p>

Title: Reading from URL, store data as double?

Body:
public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?


问:
Gnuplot epslatex : whitespace optimization with reduced fontsize
I am plotting graphs in gnuplot with epslatex terminal.
Here is my .plt script :

```<code>set terminal epslatex size 2.5,2.5 color blacktext
set output 'xxx.tex'
set format x '$10^{%T}$'
set format y '${%1.1t}^{*}10^{%T}$'
set ytics add ('0' 0)
set xlabel "xxx"
set ylabel "xxx"
set logscale x
set key below
plot    "xxx.dat" using 1:2 title 'xxx' pt 4 ps 2 lc 1
set output
</code>```

And here is my .tex file where it is embedded :

```<code>\documentclass[10pt]{article}
\usepackage[pdftex]{graphicx}
\usepackage{epstopdf}
\usepackage[cp1252]{inputenc}
\usepackage{color}
\begin{document}

\begin{figure}[h!]
\fontsize{6}{2}\selectfont
\input{xxx.tex}
\end{figure}
</code>```

The resulting graph is fine, but with additional white space due to the reduced font size : plot

I tried the command "ylabel offset", but it just moves the white space to the left and does not resize the actual plot.

I also tried lmargin, but then the ylabel exits the figure space.

Putting \footnotesize in ylabel gave a worst result (ytics were poorly placed above y axis).

Would anyone have any tips on how to set the white space to a minimal value and optimize the plot? Ideally, it would be a command to set the spacing between ytics and ylabel to a fixed value...

Thank you

答:
The epslatex terminal will create enough whitespace around (offset) the axes or wherever there is text to make sure there is sufficient room to typeset the text when you include the output .tex document in your master document. It bases the amount of white space off the font size you specify in the epslatex terminal command:

```<code>set terminal epslatex size 2.5,2.5 color blacktext
</code>```

If you set the font size to what you're planning on using in your document it should calculate the appropriate amount of white space. You just need to include a font ",6pt" argument to your set terminal line:

```<code>set terminal epslatex font ",6pt" size 2.5,2.5 color blacktext
</code>```

That should work.

As an aside you can include extra latex commands in your output .tex with the header argument. That was you don'e need to include them when you \input your gnuplot output:

```<code>set terminal epslatex font ",6pt" size 2.5,2.5 color blacktext header "\\fontsize{6}{2}\\selectfont"
</code>```

Note that back slashes need to be escaped with a backslash. You can chuck all sorts of stuff in there. I often make my figure and graph text sans-serif so I use something like:

```<code>set terminal epslatex font ",9pt" round\
    size 10.5cm,9cm \
    header "\\sffamily"
</code>```

Body:
I am plotting graphs in gnuplot with epslatex terminal.
Here is my .plt script :

set terminal epslatex size 2.5,2.5 color blacktext
set output 'xxx.tex'
set format x '$10^{%T}$'
set format y '${%1.1t}^{*}10^{%T}$'
set ytics add ('0' 0)
set xlabel "xxx"
set ylabel "xxx"
set logscale x
set key below
plot    "xxx.dat" using 1:2 title 'xxx' pt 4 ps 2 lc 1
set output

And here is my .tex file where it is embedded :

\documentclass[10pt]{article}
\usepackage[pdftex]{graphicx}
\usepackage{epstopdf}
\usepackage[cp1252]{inputenc}
\usepackage{color}
\begin{document}

\begin{figure}[h!]
\fontsize{6}{2}\selectfont
\input{xxx.tex}
\end{figure}

The resulting graph is fine, but with additional white space due to the reduced font size : plot

I tried the command "ylabel offset", but it just moves the white space to the left and does not resize the actual plot.

I also tried lmargin, but then the ylabel exits the figure space.

Putting \footnotesize in ylabel gave a worst result (ytics were poorly placed above y axis).

Would anyone have any tips on how to set the white space to a minimal value and optimize the plot? Ideally, it would be a command to set the spacing between ytics and ylabel to a fixed value...

Thank you

Body:
The epslatex terminal will create enough whitespace around (offset) the axes or wherever there is text to make sure there is sufficient room to typeset the text when you include the output .tex document in your master document. It bases the amount of white space off the font size you specify in the epslatex terminal command:

set terminal epslatex size 2.5,2.5 color blacktext

If you set the font size to what you're planning on using in your document it should calculate the appropriate amount of white space. You just need to include a font ",6pt" argument to your set terminal line:

set terminal epslatex font ",6pt" size 2.5,2.5 color blacktext

That should work.

As an aside you can include extra latex commands in your output .tex with the header argument. That was you don'e need to include them when you \input your gnuplot output:

set terminal epslatex font ",6pt" size 2.5,2.5 color blacktext header "\\fontsize{6}{2}\\selectfont"

Note that back slashes need to be escaped with a backslash. You can chuck all sorts of stuff in there. I often make my figure and graph text sans-serif so I use something like:

set terminal epslatex font ",9pt" round\
    size 10.5cm,9cm \
    header "\\sffamily"


问:
link_to_add_association creating extra forms in a multi-level nested environment
My issue is best described with a picture:
extra forms added issue

Here is the top model:

```<code>class Profession < ApplicationRecord
  has_many :procedure_categories, dependent: :destroy
  accepts_nested_attributes_for :procedure_categories, allow_destroy: true
end
</code>```

And second:

```<code>class ProcedureCategory < ApplicationRecord
  belongs_to :profession
  has_many :procedures

  accepts_nested_attributes_for :procedures, allow_destroy: true
end
</code>```

And third:

```<code>class Procedure < ApplicationRecord
  belongs_to :procedure_category
end
</code>```

Here is where the code is that is causing the issue including the link_to_add_association method.

```<code><div class="nested-fields">
  <%= f.label :category %>
  <%= f.text_field :category, class: 'form-control' %>

  <%= f.label :description %>
  <%= f.text_field :description, class: 'form-control' %>

  <%= f.label :display_order %>
  <%= f.text_field :display_order, class: 'form-control' %>
    <% cs = options_for_select(controls, f.object.selection_type) %>

  <%= f.label :selection_type %>
  <%= f.select :selection_type, cs, class: 'form-control' %>

  <table class='table'>
    <thead>
      <tr>
        <th>Category</th>
        <th>Description</th>
        <th>Display Order</th>
        <th>Selection Type</th>
      </tr>
    </thead>
    <tbody class="procedures">
      <%= f.fields_for :procedures do |procedure| %>
        <%= render 'procedure_fields', f: procedure %>
      <% end %>
    </tbody>
  </table>

  <%= link_to_add_association 'Add Skill', f, :procedures,
    data: { association_insertion_node: '.procedures', association_insertion_method: :append } %>
  <br><br>

  <%= link_to_remove_association "Remove Category", f %>
</div>
</code>```

Finally, here is my partial for rendering Procedures:

```<code><tr class="nested-fields">

  <td><%= f.text_field :skill, class: 'form-control' %></td>
  <td><%= f.text_field :description, class: 'form-control' %></td>
  <td><%= f.text_field :display_order, class: 'form-control' %></td>

  <td><%= link_to_remove_association "Remove Skill", f %></td>
</tr>
</code>```

Thank you for having a look.

答:
I'm guessing you have .procedures under each of your Category sections. In which case, you're appending to both instances of the .procedures class.

You need to create a unique identifier for each Category section (e.g., #procedure-category-6 where 6 is assigned dynamically) and then use #procedure-category-6 .procedures for targeting your insertion.

Body:
My issue is best described with a picture:
extra forms added issue

Here is the top model:

class Profession < ApplicationRecord
  has_many :procedure_categories, dependent: :destroy
  accepts_nested_attributes_for :procedure_categories, allow_destroy: true
end

And second:

class ProcedureCategory < ApplicationRecord
  belongs_to :profession
  has_many :procedures

  accepts_nested_attributes_for :procedures, allow_destroy: true
end

And third:

class Procedure < ApplicationRecord
  belongs_to :procedure_category
end

Here is where the code is that is causing the issue including the link_to_add_association method.

  <%= f.label :category %>
  <%= f.text_field :category, class: 'form-control' %>

  <%= f.label :description %>
  <%= f.text_field :description, class: 'form-control' %>

  <%= f.label :display_order %>
  <%= f.text_field :display_order, class: 'form-control' %>
    <% cs = options_for_select(controls, f.object.selection_type) %>

  <%= f.label :selection_type %>
  <%= f.select :selection_type, cs, class: 'form-control' %>

        Category
        Description
        Display Order
        Selection Type

      <%= f.fields_for :procedures do |procedure| %>
        <%= render 'procedure_fields', f: procedure %>
      <% end %>

  <%= link_to_add_association 'Add Skill', f, :procedures,
    data: { association_insertion_node: '.procedures', association_insertion_method: :append } %>

  <%= link_to_remove_association "Remove Category", f %>

Finally, here is my partial for rendering Procedures:

  <%= f.text_field :skill, class: 'form-control' %>
  <%= f.text_field :description, class: 'form-control' %>
  <%= f.text_field :display_order, class: 'form-control' %>

  <%= link_to_remove_association "Remove Skill", f %>

Thank you for having a look.


问:
Sublime 3 - Modify Matching Tags
What changes are needed to modify tag matching in Sublime 3, Build 3143, from an underline to background color.  Much of the documentation I have been able to find online seems either out of date or incomplete.  Below is an example of the desired effect.

答:
Core Sublime only matches brackets and tags with a dotted underline, and as far as I'm aware it's not possible to visually modify the style in the general case.

To get around that, you can use the BracketHighlighter package to do what you want. Once you've installed it, you will need to configure it to your liking, for which you should check out the documentation.

Briefly, in order to get it to do something like what you've outlined above, you want to select Preferences > Package Settings > BracketHighlighter > Bracket Settings from the menu (Preferences is under Sublime Text if you're on MacOS) and then add the following to the default settings:

"user_bracket_styles": {
    "tag": {
        "icon": "tag",
        "color": "region.purplish",
        "style": "solid"
    },
}
```

Note that region.purplish as a potential scope name was added in Sublime build 3148, so for build 3143 you will need to select a scope name that is colored the way that you want in whatever color scheme you're using. For example, if you're using the Monokai color scheme, the scope constant.language looks purple.

Title: Sublime 3 - Modify Matching Tags

Body:
Core Sublime only matches brackets and tags with a dotted underline, and as far as I'm aware it's not possible to visually modify the style in the general case.

To get around that, you can use the BracketHighlighter package to do what you want. Once you've installed it, you will need to configure it to your liking, for which you should check out the documentation.

Briefly, in order to get it to do something like what you've outlined above, you want to select Preferences > Package Settings > BracketHighlighter > Bracket Settings from the menu (Preferences is under Sublime Text if you're on MacOS) and then add the following to the default settings:

"user_bracket_styles": {
    "tag": {
        "icon": "tag",
        "color": "region.purplish",
        "style": "solid"
    },
}

Note that region.purplish as a potential scope name was added in Sublime build 3148, so for build 3143 you will need to select a scope name that is colored the way that you want in whatever color scheme you're using. For example, if you're using the Monokai color scheme, the scope constant.language looks purple.


问:
Play MMS stream with clear HTML5/JS
Is it possible to play MMS audio stream with HTML5 / JavaScript in Google Chrome without any Windows Media Player object ?
I want to write a Google Chrome plugin that will allow playing that streams.

答: No. MMS is a proprietary Microsoft protocol.</p>

Title: Play MMS stream with clear HTML5/JS


问:
Prune MySQL Table With Group By
I have a table like below and would like to delete all rows where the pid, code and type are duplicates, keeping the row with the latest updated date.

e.g.

```<code>pid     code            type    updated
267985  9414202017604   R       2017-11-13 04:52:23 -- keep
267985  19414202017601  D       2017-11-13 04:52:23 -- keep
267985  19414202017601  D       2017-11-13 04:42:26 -- delete
267985  9414202017604   R       2017-11-13 04:42:26 -- delete
267986  19414202017601  D       2017-11-13 04:32:33 -- keep
...
</code>```

I can use GROUP BY to get max(updated) but how can I then include it in a delete statement?

Note that updated is not granular enough to act as a unique row identifier.

Title: Prune MySQL Table With Group By

Body:
I have a table like below and would like to delete all rows where the pid, code and type are duplicates, keeping the row with the latest updated date.

e.g.

pid     code            type    updated
267985  9414202017604   R       2017-11-13 04:52:23 -- keep
267985  19414202017601  D       2017-11-13 04:52:23 -- keep
267985  19414202017601  D       2017-11-13 04:42:26 -- delete
267985  9414202017604   R       2017-11-13 04:42:26 -- delete
267986  19414202017601  D       2017-11-13 04:32:33 -- keep
...

I can use GROUP BY to get max(updated) but how can I then include it in a delete statement?

Note that updated is not granular enough to act as a unique row identifier.

Body:
SQL Fiddle

MySQL 5.6 Schema Setup:

CREATE TABLE Table1
    ( `id` mediumint(8) unsigned NOT NULL auto_increment
     ,  `pid` int
     , `code` varchar(40)
     , `type` varchar(1)
     , `updated` datetime
     , `note` varchar(9)
     , PRIMARY KEY (`id`)
)
;

INSERT INTO Table1
    (`pid`, `code`, `type`, `updated`, `note`)
VALUES
    (267985, '9414202017604', 'R', '2017-11-13 04:52:23', '-- keep'),
    (267985, '19414202017601', 'D', '2017-11-13 04:52:23', '-- keep'),
    (267985, '19414202017601', 'D', '2017-11-13 04:42:26', '-- delete'),
    (267985, '9414202017604', 'R', '2017-11-13 04:42:26', '-- delete'),
    (267986, '19414202017601', 'D', '2017-11-13 04:32:33', '-- keep')
;

delete d
from table1 d
inner join table1 k
on k.pid = d.pid and k.code = d.code and k.type = d.type
and k.updated > d.updated
;

Query 1:

select *
from table1 d

Results:

| id |    pid |           code | type |              updated |    note |
|----|--------|----------------|------|----------------------|---------|
|  1 | 267985 |  9414202017604 |    R | 2017-11-13T04:52:23Z | -- keep |
|  2 | 267985 | 19414202017601 |    D | 2017-11-13T04:52:23Z | -- keep |
|  5 | 267986 | 19414202017601 |    D | 2017-11-13T04:32:33Z | -- keep |


问:
How to Resize UITextField Placeholder Text to Fit UITextField width?
Can Change UITextField Placeholder Text Color as follows:

```<code>[txtField setValue:[UIColor colorWithRed:128.0/255.0 green:128.0/255.0 blue:128.0/255.0 alpha:1.0]
                    forKeyPath:@"_placeholderLabel.textColor"];
</code>```

Similarly is there any way to Resize UITextField Placeholder Text Font to Fit UITextField width?

Note: I have text fields in custom cell of table view and also using autolayout in custom cell.

答:
I met the same issue, here is the solution:</p>

```<code>UILabel *placeHolderLabel = [self.registrationCodeTextfield valueForKey:@"_placeholderLabel"];
placeHolderLabel.adjustsFontSizeToFitWidth = YES;
</code>```

Body:
Can Change UITextField Placeholder Text Color as follows:

[txtField setValue:[UIColor colorWithRed:128.0/255.0 green:128.0/255.0 blue:128.0/255.0 alpha:1.0]
                    forKeyPath:@"_placeholderLabel.textColor"];

Similarly is there any way to Resize UITextField Placeholder Text Font to Fit UITextField width?

Note: I have text fields in custom cell of table view and also using autolayout in custom cell.

Body:
I met the same issue, here is the solution:

UILabel *placeHolderLabel = [self.registrationCodeTextfield valueForKey:@"_placeholderLabel"];
placeHolderLabel.adjustsFontSizeToFitWidth = YES;


问:
python multiple stacked plots along y axis
I have a binned data of an x-axis n-length vector and 3 y-axis n-length vector for 3 different histograms on the same x-axis.

Now I want this kind of stacked bar plot or any thing similar as below.

The nearest I have found is Qtiplot (which is not python). It can generate exactly this kind of histogram plots. But it computes the histogram by itself and requires the actual data samples which are not present in my case (I only have the histogram itself).

Please note that I don't know python very well. So I don't have a clue from where I shall start, neither I am really in a mood to learn programming in python. I need this only to make a nice vector-graphics plot for my research thesis.

I have tagged python as I think python is the most obvious language. In case someone knows any better solution other than in python (but not Matlab, I cannot install that huge pile), I will thankfully add the proper tag.

Thanks in advance for any help.

答:
use matplotlib package in python</p>

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

apple_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]
banana_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]
mango_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]

fig=plt.figure()
ax1=fig.add_subplot(311)
ax2=fig.add_subplot(312)
ax3=fig.add_subplot(313)
ax1.hist(apple_weight)
ax2.hist(banana_weight)
ax3.hist(mango_weight)
plt.show()
</code>```

Body:
use matplotlib package in python

import matplotlib.pyplot as plt

apple_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]
banana_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]
mango_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]

fig=plt.figure()
ax1=fig.add_subplot(311)
ax2=fig.add_subplot(312)
ax3=fig.add_subplot(313)
ax1.hist(apple_weight)
ax2.hist(banana_weight)
ax3.hist(mango_weight)
plt.show()


问:
Get Country of IP Address with PHP
Ideally I'm trying to put together a PHP script that I can query from any web browser and it returns the country of the IP address that accessed the PHP script.

Is this possible or is there a better solution?

答:
I run the service at IPLocate.io, which you can hook into for free with one easy call:

```<code><?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);
</code>```

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.

Title: Get Country of IP Address with PHP

Body:
I run the service at IPLocate.io, which you can hook into for free with one easy call:

<?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.


问:
grpc timeout in a celery task
I am trying to connect to a GRPC server in a celery task. I have the following piece of code

```<code>    timeout = 1
    host = '0.tcp.ngrok.io'
    port = '7145'
    channel = grpc.insecure_channel('{0}:{1}'.format(host, port))
    try:
        grpc.channel_ready_future(channel).result(timeout=timeout)
    except grpc.FutureTimeoutError:
        sys.exit(1)
    stub = stub(channel)
</code>```

When I run this snippet through the Python shell, I am able to establish the connection, and execute the GRPC methods. However, when I run this through the Celery task, I get the grpc.FutureTimeoutError, and the connection does not get established.

The Celery worker lies on the same machine as the grpc server. I tried using the socket library to ping the GRPC server, and that worked (It returned some junk response).

I am using Python 2.7, with grpcio==1.6.0 installed. The Celery version is 4.1.0. Any pointers would be helpful.

答:
I believe Celery uses fork under the hood, and gRPC 1.6 did not support any forking behavior.

Try updating to gRPC 1.7.

Title: grpc timeout in a celery task

Body:
I am trying to connect to a GRPC server in a celery task. I have the following piece of code

    timeout = 1
    host = '0.tcp.ngrok.io'
    port = '7145'
    channel = grpc.insecure_channel('{0}:{1}'.format(host, port))
    try:
        grpc.channel_ready_future(channel).result(timeout=timeout)
    except grpc.FutureTimeoutError:
        sys.exit(1)
    stub = stub(channel)

When I run this snippet through the Python shell, I am able to establish the connection, and execute the GRPC methods. However, when I run this through the Celery task, I get the grpc.FutureTimeoutError, and the connection does not get established.

The Celery worker lies on the same machine as the grpc server. I tried using the socket library to ping the GRPC server, and that worked (It returned some junk response).

I am using Python 2.7, with grpcio==1.6.0 installed. The Celery version is 4.1.0. Any pointers would be helpful.


问:
N x N identity matrix in MATLAB
I am having difficulty creating a generic N x N identity matrix in Matlab.

I am given a system where

```<code>Ai,j =

{1, if i does not equal j

{n, if i = j}
</code>```

You are asked to compute this when the value of the identity matrix n = 10, n = 20.

What I don't see is how to apply matrix indexing here. That is easy enough to do, but how do I account for the given linear system?

答:
There is a builtin function for creating a unit matrix called eye.

have a look at the documentation http://au.mathworks.com/help/matlab/ref/eye.html?requestedDomain=au.mathworks.com

Also, ones(n,m) creates a matrix of ones.

For a square matrix use (n-1)*eye(n) + ones(n) and for non-square
(n-1)*eye(n, m) + ones(n, m)

Title: N x N identity matrix in MATLAB

Body:
I am having difficulty creating a generic N x N identity matrix in Matlab.

I am given a system where

Ai,j =

{1, if i does not equal j

{n, if i = j}

You are asked to compute this when the value of the identity matrix n = 10, n = 20.

What I don't see is how to apply matrix indexing here. That is easy enough to do, but how do I account for the given linear system?


问:
Pasted code over to another class and it doesnt work?
I have a piece of code

```<code>string phoneMobileW = null;
string phoneMobileP = null;
string phoneMain = null;
string phoneWork = null;
string phoneHome = null;

if (coreData.ListOfAddress_0006 != null && coreData.ListOfAddress_0006.Count() > 0)
{
    var phoneqry = from list in coreData.ListOfAddress_0006
        .Where(a => a.Subtype.ID == "1")
        .OrderByDescending(a => a.StartDate)
        .Take(1)
        .Where(p => p.ListOfPhoneNumber_0006 != null)
        .SelectMany(p => p.ListOfPhoneNumber_0006)
        select list;

    if (phoneqry != null)
    {
        var phoneList = phoneqry.ToList();
        phoneMobileW = phoneList
            .Where(q => q.NumberType.ID == "MOBW")
            .Select(q => q.Number)
            .LastOrDefault();
    }
}
</code>```

The phone numbers are contained inside the address. If the address is not empty get the last phone number. However I have coped and pasted this piece of code over to another class it and it longer works.

So where it works you can see the 'var' for phoneqry is interface System.Collections.Generic.Ienumerable

As I said I have copied it over to another class which is a unit testing class.
I am trying to populate the phone number.

When I hold the cursor over var, nothing appears to show me what object it is(is this because its in a unitTest class?)

anyway the error I get is for .Where in var phoneqry = from list in coreData.ListOfAddress_0006.Where

Error 4   'System.Array' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) D:\MartinsCode\New folder\Trunk\BusinessLogic\SapEai.UnitTest\AdUnitTest.cs 166 73  RFS.BusinessLogic.SapEai.UnitTest

答:
Where is a Linq extension method, you need to add this at the top of your file:

```<code>using System.Linq;
</code>```

Alternatively, you can click on Where and press Ctrl+. on your keyboard, and it will prompt you to include the using for the System.Linq namespace.

See here for more information on what extension methods are.

Body:
I have a piece of code

string phoneMobileW = null;
string phoneMobileP = null;
string phoneMain = null;
string phoneWork = null;
string phoneHome = null;

if (coreData.ListOfAddress_0006 != null && coreData.ListOfAddress_0006.Count() > 0)
{
    var phoneqry = from list in coreData.ListOfAddress_0006
        .Where(a => a.Subtype.ID == "1")
        .OrderByDescending(a => a.StartDate)
        .Take(1)
        .Where(p => p.ListOfPhoneNumber_0006 != null)
        .SelectMany(p => p.ListOfPhoneNumber_0006)
        select list;

    if (phoneqry != null)
    {
        var phoneList = phoneqry.ToList();
        phoneMobileW = phoneList
            .Where(q => q.NumberType.ID == "MOBW")
            .Select(q => q.Number)
            .LastOrDefault();
    }
}

The phone numbers are contained inside the address. If the address is not empty get the last phone number. However I have coped and pasted this piece of code over to another class it and it longer works.

So where it works you can see the 'var' for phoneqry is interface System.Collections.Generic.Ienumerable

As I said I have copied it over to another class which is a unit testing class.
I am trying to populate the phone number.

When I hold the cursor over var, nothing appears to show me what object it is(is this because its in a unitTest class?)

anyway the error I get is for .Where in var phoneqry = from list in coreData.ListOfAddress_0006.Where

Error 4   'System.Array' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) D:\MartinsCode\New folder\Trunk\BusinessLogic\SapEai.UnitTest\AdUnitTest.cs 166 73  RFS.BusinessLogic.SapEai.UnitTest

Body:
Where is a Linq extension method, you need to add this at the top of your file:

using System.Linq;

Alternatively, you can click on Where and press Ctrl+. on your keyboard, and it will prompt you to include the using for the System.Linq namespace.

See here for more information on what extension methods are.


问:
Delay the response by some seconds when scraping a website
I am working on a php scraping server , so i have website list to loop and then return the content of each page to get the data that i want.

The problem that some sites are not fully returned and as i see some data appear after the page is fully loaded

I tried with both these methods but i cant get the full page

First method :

```<code>$opts = array('http' =>
    array(
        'method'  => 'GET',
        'timeout' => 10
    ) );

$context  = stream_context_create($opts);
$html = file_get_contents('some url',false,$context);
echo $html;
</code>```

Second method

```<code>$html = implode('',file('some url'));
echo $html;
</code>```

I just want to return the content of the page after 1 or 2 seconds after the page is loaded.

For Exemple with this url i cant get the search results just this

: Résultats

   News Photos Vidéos Tags Filtre par date

   Précédente Suivante

答:
Things are not as they seem to be.
Actually the url that you want to hit is
https://api.swiftype.com/api/v1/public/engines/search.json because the webpage on load makes a json request that is on this url.
in that url you have to post the following json

```<code>$search = array("engine_key"=>"naxCjQ58frTkB_diETvu","page"=>1,"q"=>"kardas","per_page"=>12,"sort_direction"=>"","filters"=>array("page"=>array("category"=>"News")),"facets"=>array("page"=>array("0"=>"tag")));
</code>```

A quick guide:

On the "page" property type a value, that represents the page number you want to get,

on the "q" property type the term that you want to search,

"per_page" property is the entries that you will get, try some
values, 12 is the default,

the rest you have to find them out yourself.

a code example that works

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"https://api.swiftype.com/api/v1/public/engines/search.json");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($search));
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
curl_setopt($ch,CURLOPT_HEADER, 0);

$data = curl_exec($ch);
curl_close($ch);
</code>```

and to check the results

```<code>print_r(json_decode($data));
</code>```

this thing is beautiful is like them to give you an API on the plate...

Body:
I am working on a php scraping server , so i have website list to loop and then return the content of each page to get the data that i want.

The problem that some sites are not fully returned and as i see some data appear after the page is fully loaded

I tried with both these methods but i cant get the full page

First method :

$opts = array('http' =>
    array(
        'method'  => 'GET',
        'timeout' => 10
    ) );

$context  = stream_context_create($opts);
$html = file_get_contents('some url',false,$context);
echo $html;

Second method

$html = implode('',file('some url'));
echo $html;

I just want to return the content of the page after 1 or 2 seconds after the page is loaded.

For Exemple with this url i cant get the search results just this

: Résultats

   News Photos Vidéos Tags Filtre par date

   Précédente Suivante

Body:
Things are not as they seem to be.
Actually the url that you want to hit is
https://api.swiftype.com/api/v1/public/engines/search.json because the webpage on load makes a json request that is on this url.
in that url you have to post the following json

$search = array("engine_key"=>"naxCjQ58frTkB_diETvu","page"=>1,"q"=>"kardas","per_page"=>12,"sort_direction"=>"","filters"=>array("page"=>array("category"=>"News")),"facets"=>array("page"=>array("0"=>"tag")));

A quick guide:

On the "page" property type a value, that represents the page number you want to get,

on the "q" property type the term that you want to search,

"per_page" property is the entries that you will get, try some
values, 12 is the default,

the rest you have to find them out yourself.

a code example that works

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"https://api.swiftype.com/api/v1/public/engines/search.json");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($search));
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
curl_setopt($ch,CURLOPT_HEADER, 0);

$data = curl_exec($ch);
curl_close($ch);

and to check the results

print_r(json_decode($data));

this thing is beautiful is like them to give you an API on the plate...


答:
```<code>    grep -n ^$ Log.txt | sed s/://
</code>```

will give the blank line numbers (suitable for an array)

```<code>    grep -n 'Oracle VirtualBox virtual NIC' Log.txt | cut -f1 -d\:
</code>```

will give the line numbers of the target

Use arrays, loops and sed to grok the block you want

```<code>    sed -n '8,19p' Log.txt
</code>```

Title: Extracting from a file and pasting details to another file

Body:
The problem is regarding extracting the details of the Oracle Virtual box(2nd paragraph) from the "nmap non-gui version". I understand the usage of "grep" and "loops" and have already tried everything but what if there are other systems connected on the same network. I just want the program to find the word "(Oracle VirtualBox virtual NIC)" and extract everything above it until it finds a blank-line.

**

root@PopeyeTheSailorMan:~# nmap 192.168.43.0/24 > Log.txt

**

Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-15 04:08 UTC
Nmap scan report for 192.168.43.1
Host is up (0.0025s latency).
Not shown: 999 closed ports
PORT   STATE SERVICE
53/tcp open  domain
MAC Address: 9A:10:94:51:42:ED (Unknown)

***Nmap scan report for 192.168.43.136
Host is up (0.00071s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
111/tcp  open  rpcbind
139/tcp  open  netbios-ssn
443/tcp  open  https
1024/tcp open  kdm
MAC Address: 08:00:27:D3:73:2E (Oracle VirtualBox virtual NIC)***

Nmap scan report for kali (192.168.43.79)
Host is up (0.0000070s latency).
All 1000 scanned ports on kali (192.168.43.79) are closed

Nmap done: 256 IP addresses (3 hosts up) scanned in 16.00 seconds

Body:
    grep -n ^$ Log.txt | sed s/://

will give the blank line numbers (suitable for an array)

    grep -n 'Oracle VirtualBox virtual NIC' Log.txt | cut -f1 -d\:

will give the line numbers of the target

Use arrays, loops and sed to grok the block you want

    sed -n '8,19p' Log.txt


问:
I used the correct code but still this returning false
```<code>SIGNUP.PHP/HTML
<?php
    require_once("connections/db.php");

    $error = array();
    if($user->is_loggedin())
    {
        $user->redirect('index.php');
    }

    if(isset($_POST['signup-btn']))
    {
      $username = $_POST['signup-username'];
      $password = $_POST['signup-password'];
      $email = $_POST['signup-email'];

      if($user='')
      {
          $error[] = "Please enter a username";
      }
      else if($pass='')
      {
          $error[] = "Please enter a password";
      }
      else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
      {
          $error[] = "Please enter a valid email address";
      }
      else
   {
      try
      {
            if($user->register($username, $password, $email))
            {
                echo "registered";
            }
     }
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  }
    }
   ?>
</code>```

class.user.php

```<code><?php
class USER{

    private $db;

    function __construct($db_con)
    {
        $this->db = $db_con;
    }

    public function register($username,$password,$email)
    {
        try
        {
          $protected_password = password_hash($upass, PASSWORD_DEFAULT);
          $stmt = $this->db->prepare("INSERT INTO users(username,password,email)
          VALUES(:username, :password, :email)");

           $stmt->bindparam(":username", $username);
           $stmt->bindparam(":password", $protected_password);
           $stmt->bindparam(":email", $email);
           $stmt->execute();

           return $stmt;
        }

        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

    public function is_loggedin()
    {
        if (isset($_SESSION['user_session']))
        {
            return true;
        }
    }

    public function redirect($url)
    {
        header("Location: $url");
    }

    public function logout()
    {
        session_destroy();
        unset($_SESSION['user_session']);
        return true;
    }
}

?>
</code>```

db.php

```<code><?php
session_start();

$connection = parse_ini_file('config.ini');

try{
    $db_con = new PDO("mysql:host={$connection['host']}; dbname={$connection['dbname']}", $connection['username'], $connection['password']);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e){
    echo $e->getMessage();
}

include_once 'class.user.php';
$user = new USER($db_con);
?>
</code>```

I keep receiving the error Fatal error: Call to a member function register() on string in C:\xampp\we\signup.php on line 32

I'm completely new to PDO's.  and I can't see why this is not working.
I tried changing the code up as much as I could, but this error doesn't change.  I'm sure it's a simple stupid problem i'm overlooking as well.

答:
We start out setting $username from your form

```<code>$username = $_POST['signup-username'];
</code>```

Then I assume an equality check was meant to happen on this variable ($username == ''?) but instead $user is set to an empty string.

```<code>if($user='')
{
    $error[] = "Please enter a username";
}
</code>```

Afterwards, $user->register() is called, and $user is still a string instead of an instance of your class USER.

Be careful that you dont put in variable assignments where you meant to put in equality checks elsewhere! I do it all the time.

```<code>if($user='')
{
    $error[] = "Please enter a username";
}
else if($pass='') // should this be $password == ''?
{
    $error[] = "Please enter a password";
}
</code>```

Body:
SIGNUP.PHP/HTML
<?php
    require_once("connections/db.php");

    $error = array();
    if($user->is_loggedin())
    {
        $user->redirect('index.php');
    }

    if(isset($_POST['signup-btn']))
    {
      $username = $_POST['signup-username'];
      $password = $_POST['signup-password'];
      $email = $_POST['signup-email'];

      if($user='')
      {
          $error[] = "Please enter a username";
      }
      else if($pass='')
      {
          $error[] = "Please enter a password";
      }
      else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
      {
          $error[] = "Please enter a valid email address";
      }
      else
   {
      try
      {
            if($user->register($username, $password, $email))
            {
                echo "registered";
            }
     }
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  }
    }
   ?>

class.user.php

<?php
class USER{

    private $db;

    function __construct($db_con)
    {
        $this->db = $db_con;
    }

    public function register($username,$password,$email)
    {
        try
        {
          $protected_password = password_hash($upass, PASSWORD_DEFAULT);
          $stmt = $this->db->prepare("INSERT INTO users(username,password,email)
          VALUES(:username, :password, :email)");

           $stmt->bindparam(":username", $username);
           $stmt->bindparam(":password", $protected_password);
           $stmt->bindparam(":email", $email);
           $stmt->execute();

           return $stmt;
        }

        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

    public function is_loggedin()
    {
        if (isset($_SESSION['user_session']))
        {
            return true;
        }
    }

    public function redirect($url)
    {
        header("Location: $url");
    }

    public function logout()
    {
        session_destroy();
        unset($_SESSION['user_session']);
        return true;
    }
}

?>

db.php

<?php
session_start();

$connection = parse_ini_file('config.ini');

try{
    $db_con = new PDO("mysql:host={$connection['host']}; dbname={$connection['dbname']}", $connection['username'], $connection['password']);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e){
    echo $e->getMessage();
}

include_once 'class.user.php';
$user = new USER($db_con);
?>

I keep receiving the error Fatal error: Call to a member function register() on string in C:\xampp\we\signup.php on line 32

I'm completely new to PDO's.  and I can't see why this is not working.
I tried changing the code up as much as I could, but this error doesn't change.  I'm sure it's a simple stupid problem i'm overlooking as well.

Body:
We start out setting $username from your form

$username = $_POST['signup-username'];

Then I assume an equality check was meant to happen on this variable ($username == ''?) but instead $user is set to an empty string.

if($user='')
{
    $error[] = "Please enter a username";
}

Afterwards, $user->register() is called, and $user is still a string instead of an instance of your class USER.

Be careful that you dont put in variable assignments where you meant to put in equality checks elsewhere! I do it all the time.

if($user='')
{
    $error[] = "Please enter a username";
}
else if($pass='') // should this be $password == ''?
{
    $error[] = "Please enter a password";
}


问:
How to combine multiple SQL SELECT results into one array in PHP?
Hello this code works but currently it is very repetitive.

I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.

I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(

I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..

```<code>                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                // Select data from table from a random row
                $grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
                $grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
                $grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
                $grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
                $grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
                $grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";

                $result1 = $mysqli->query($grab1);
                $result2 = $mysqli->query($grab2);
                $result3 = $mysqli->query($grab3);
                $result4 = $mysqli->query($grab4);
                $result5 = $mysqli->query($grab5);
                $result6 = $mysqli->query($grab6);

                // Convert result into an array called items
                $item1 = mysqli_fetch_row($result1);
                $item2 = mysqli_fetch_row($result2);
                $item3 = mysqli_fetch_row($result3);
                $item4 = mysqli_fetch_row($result4);
                $item5 = mysqli_fetch_row($result5);
                $item6 = mysqli_fetch_row($result6);
</code>```

I managed to solve this with help on this thread..
I replaced all this code with:

```<code>                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                foreach ($ran_num as $key => $value) {
                  $grab[$key] = "select * from stock_tbl where stock_id='$value'";
                  $result = $mysqli->query($grab[$key]);
                  $item[$key] = mysqli_fetch_row($result);
                }
</code>```

Thank you very much :)

答:
```<code><?php
    $ran_num = (RandomInRange(1,$total,6));
    foreach ($ran_num as $key => $value)
        {
            $grab[$value] = "select * from stock_tbl where stock_id='$value'";
        }
?>
</code>```

If you don't need to access each statement individually, this is also possible:

```<code><?php
    $ran_num = (RandomInRange(1,$total,6));
    $grab = '';
    foreach ($ran_num as $key => $value)
        {
            $grab .= "select * from stock_tbl where stock_id='$value';";
        }
?>
</code>```

That's essentially creating one long string that SQL will parse as individual commands using the semi-colon as the delimiter for each one.

Body:
Hello this code works but currently it is very repetitive.

I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.

I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(

I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..

                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                // Select data from table from a random row
                $grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
                $grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
                $grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
                $grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
                $grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
                $grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";

                $result1 = $mysqli->query($grab1);
                $result2 = $mysqli->query($grab2);
                $result3 = $mysqli->query($grab3);
                $result4 = $mysqli->query($grab4);
                $result5 = $mysqli->query($grab5);
                $result6 = $mysqli->query($grab6);

                // Convert result into an array called items
                $item1 = mysqli_fetch_row($result1);
                $item2 = mysqli_fetch_row($result2);
                $item3 = mysqli_fetch_row($result3);
                $item4 = mysqli_fetch_row($result4);
                $item5 = mysqli_fetch_row($result5);
                $item6 = mysqli_fetch_row($result6);

I managed to solve this with help on this thread..
I replaced all this code with:

                // Create 6 random numbers from table
                $ran_num = (RandomInRange(1,$total,6));

                foreach ($ran_num as $key => $value) {
                  $grab[$key] = "select * from stock_tbl where stock_id='$value'";
                  $result = $mysqli->query($grab[$key]);
                  $item[$key] = mysqli_fetch_row($result);
                }

Thank you very much :)

Body:
<?php
    $ran_num = (RandomInRange(1,$total,6));
    foreach ($ran_num as $key => $value)
        {
            $grab[$value] = "select * from stock_tbl where stock_id='$value'";
        }
?>

If you don't need to access each statement individually, this is also possible:

<?php
    $ran_num = (RandomInRange(1,$total,6));
    $grab = '';
    foreach ($ran_num as $key => $value)
        {
            $grab .= "select * from stock_tbl where stock_id='$value';";
        }
?>

That's essentially creating one long string that SQL will parse as individual commands using the semi-colon as the delimiter for each one.