问:
Password validation fails in two opposed scenarios
I am working through the Ruby on Rails Tutorial by Michael Hartl and have generated an interesting dilemma. I will have done something wrong, so I need your help finding the issue.

The issue surrounds the validation of a password property within a User model. The initial validation of this property was:

```<code>validates :password,  presence: true,
                        confirmation: true,
                        length: { minimum: 6 }
</code>```

This requires a minimum length of the password and is designed to satisfy the situation where a new user creates their instance.

I have created the following tests (and I wish I had used Rspec!) guided by the book. These tests check that the validations work:

```<code>test "password must not be blank or made up of spaces" do
  @user.password = @user.password_confirmation = " "
  assert_not @user.valid?
end

test "password must not be empty/nil" do
  @user.password = @user.password_confirmation = ""
  assert_not @user.valid?
end
</code>```

So, we’re checking that the password field cannot contain either a space, or a nil entry. With the current validations, these tests pass. All is well.

I have progressed to allowing a user to edit their profile. This enables the user to change their name, email address and password/confirmation if they choose. In order to allow a user not to change their password if they don’t want to, additional validation is added to the password property of the model, adding allow_blank: true such as:

```<code>validates :password,  presence: true,
                      confirmation: true,
                      length: { minimum: 6 },
                      allow_blank: true # added this!
</code>```

So, the user can now leave the two password fields blank when they edit their profile if they don’t want to change their profile. This satisfies the test:

```<code>test "successful edit" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  name = "Foo Bar"
  email = "foo@valid.co.uk"
  patch user_path(@user), params: { user: { name: name,
                                            email: email,
                                            password: "",
                                            password_confirmation: "" } }
  assert_not flash.empty?
  assert_redirected_to @user
  @user.reload
  assert_equal @user.name, name
  assert_equal @user.email, email
end
</code>```

This enables a user to edit just their name & email and, by leaving their two password fields blank, there’s no need to change, or re-enter, their password. This throws a FAIL on a long passing test, as above, such as:

```<code>test "password must not be blank or made up of spaces" do
  @user.password = @user.password_confirmation = " "
  assert_not @user.valid?
end
</code>```

The test fails because the user is validated. The slightly different test, which tests for nil, not blank, passes:

```<code>test "password must not be empty/nil" do
  @user.password = @user.password_confirmation = ""
  assert_not @user.valid?
end
</code>```

So a password of “” is caught but a password of “ “ works fine for creating a new user or editing an existing user.

Adding allow_blank: true to the user model validation of password seems to have caused this. So, I am stuck between two tests failing. If I omit allow_blank: true, this test fails (full test pasted above):

```<code>test "successful edit" do
.
.
  patch user_path(@user), params: { user:
                                    { name: name,
                                      email: email,
                                      password: "",
                                      password_confirmation: "" } }
.
  assert_equal @user.name, name
  assert_equal @user.email, email
end
</code>```

Sending the blank password and password_confirmation fails the test as it isn’t allowed to be blank.

Adding allow_blank: true within the validation fails this test:

```<code>test "password must not be blank or made up of spaces" do
  @user.password = @user.password_confirmation = " "
  assert_not @user.valid?
end
</code>```

This fail allows a user to be created with a password consisting of spaces. A nil password, i.e. no characters at all, is not allowed. That test works.

This leaves me in the position where I must decide between a user having to change/repeat their two password fields if they edit their profile, OR, allowing a scenario where a user can sign up with a password consisting of one space, or many spaces, as this test doesn’t throw the expected failure message:

```<code>test "password must not be blank or made up of spaces" do
   @user.password = @user.password_confirmation = " "
   assert_not @user.valid?
end
</code>```

The addition of allow_blank: true bypasses this test or the validation generally. A password of any number of spaces is accepted which is against the validation in the model. How is that possible?

Any thoughts how to test better (apart from using Rspec!). I bow to your greater knowledge.

TIA.

[EDIT]

The suggested changes in the comments below made my test suite green. This was due to the suite being inadequate. To test the unsuccessful integration, the suggested code tested multiple scenarios in one go, such as:

```<code>test "unsuccessful edit with multiple errors" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  patch user_path(@user), params: { user:
                                    { name: "",
                                      email: "foo@invalid",
                                      password: "foo",
                                      password_confirmation: "bar" } }
  assert_template 'users/edit'
  assert_select 'div.alert', "The form contains 3 errors."
end
</code>```

The key part here is getting the number of expected errors correct so that assert_select gives the right result. I didn't. The errors should be blank name, invalid email format, password too short, pwd & confirmation don't match. The error for short password isn't showing.

I decided to pull out two more tests to demonstrate the failure of the validations of password length and presence. The point of allow_blank is to allow the password & confirmation fields to have nothing in them when editing the user profile so it isn't compulsory to enter the password every time the user profile is edited. These tests are:

```<code>test "unsuccessful edit with short password" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  patch user_path(@user), params: { user:
                                    { name: @user.name,
                                      email: "foo@valid.com",
                                      password: "foo",
                                      password_confirmation: "foo" } }
  assert_select 'div.alert', "The form contains 1 error."
end

test "unsuccessful edit with blank (spaces) password" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  patch user_path(@user), params: { user:
                                    { name: @user.name,
                                      email: "foo@valid.com",
                                      password: " ",
                                      password_confirmation: " " } }
  assert_select 'div.alert', "The form contains 1 error."
end
</code>```

If the password is changed, then the validation rules should apply, i.e. the password should not be blank and must have a minimum length. That's not what's happening here either in the code the Tutorial book suggests or the amended code using on: :create and on: :edit.

答:
I figured this out so am posting here in case others come across a similar problem.

I amended the validations to include the :update action on the User, rather than just :edit. This covered the action of saving to the database and caught the short password update validations but still allowed passwords made of spaces.

A bit of checking the documentation showed me that using allow_blank: true allows nil and strings made up of spaces. The scenario here wants a nil password to be acceptable, but not a blank one. The alternative validation of allow_nil: true is more appropriate to the scenario here.

The updated code from above looks like, in User.rb:

```<code>validates :password,  presence: true,
                      length: { minimum: 6 },
                      allow_nil: true,
                      on: [:edit, :update]

validates :password,  presence: true,
                      confirmation: true,
                      length: { minimum: 6 },
                      on: :create
</code>```

The extended test suite is now all green.

Body:
I am working through the Ruby on Rails Tutorial by Michael Hartl and have generated an interesting dilemma. I will have done something wrong, so I need your help finding the issue.

The issue surrounds the validation of a password property within a User model. The initial validation of this property was:

validates :password,  presence: true,
                        confirmation: true,
                        length: { minimum: 6 }

This requires a minimum length of the password and is designed to satisfy the situation where a new user creates their instance.

I have created the following tests (and I wish I had used Rspec!) guided by the book. These tests check that the validations work:

test "password must not be blank or made up of spaces" do
  @user.password = @user.password_confirmation = " "
  assert_not @user.valid?
end

test "password must not be empty/nil" do
  @user.password = @user.password_confirmation = ""
  assert_not @user.valid?
end

So, we’re checking that the password field cannot contain either a space, or a nil entry. With the current validations, these tests pass. All is well.

I have progressed to allowing a user to edit their profile. This enables the user to change their name, email address and password/confirmation if they choose. In order to allow a user not to change their password if they don’t want to, additional validation is added to the password property of the model, adding allow_blank: true such as:

validates :password,  presence: true,
                      confirmation: true,
                      length: { minimum: 6 },
                      allow_blank: true # added this!

So, the user can now leave the two password fields blank when they edit their profile if they don’t want to change their profile. This satisfies the test:

test "successful edit" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  name = "Foo Bar"
  email = "foo@valid.co.uk"
  patch user_path(@user), params: { user: { name: name,
                                            email: email,
                                            password: "",
                                            password_confirmation: "" } }
  assert_not flash.empty?
  assert_redirected_to @user
  @user.reload
  assert_equal @user.name, name
  assert_equal @user.email, email
end

This enables a user to edit just their name & email and, by leaving their two password fields blank, there’s no need to change, or re-enter, their password. This throws a FAIL on a long passing test, as above, such as:

test "password must not be blank or made up of spaces" do
  @user.password = @user.password_confirmation = " "
  assert_not @user.valid?
end

The test fails because the user is validated. The slightly different test, which tests for nil, not blank, passes:

test "password must not be empty/nil" do
  @user.password = @user.password_confirmation = ""
  assert_not @user.valid?
end

So a password of “” is caught but a password of “ “ works fine for creating a new user or editing an existing user.

Adding allow_blank: true to the user model validation of password seems to have caused this. So, I am stuck between two tests failing. If I omit allow_blank: true, this test fails (full test pasted above):

test "successful edit" do
.
.
  patch user_path(@user), params: { user:
                                    { name: name,
                                      email: email,
                                      password: "",
                                      password_confirmation: "" } }
.
  assert_equal @user.name, name
  assert_equal @user.email, email
end

Sending the blank password and password_confirmation fails the test as it isn’t allowed to be blank.

Adding allow_blank: true within the validation fails this test:

test "password must not be blank or made up of spaces" do
  @user.password = @user.password_confirmation = " "
  assert_not @user.valid?
end

This fail allows a user to be created with a password consisting of spaces. A nil password, i.e. no characters at all, is not allowed. That test works.

This leaves me in the position where I must decide between a user having to change/repeat their two password fields if they edit their profile, OR, allowing a scenario where a user can sign up with a password consisting of one space, or many spaces, as this test doesn’t throw the expected failure message:

test "password must not be blank or made up of spaces" do
   @user.password = @user.password_confirmation = " "
   assert_not @user.valid?
end

The addition of allow_blank: true bypasses this test or the validation generally. A password of any number of spaces is accepted which is against the validation in the model. How is that possible?

Any thoughts how to test better (apart from using Rspec!). I bow to your greater knowledge.

TIA.

[EDIT]

The suggested changes in the comments below made my test suite green. This was due to the suite being inadequate. To test the unsuccessful integration, the suggested code tested multiple scenarios in one go, such as:

test "unsuccessful edit with multiple errors" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  patch user_path(@user), params: { user:
                                    { name: "",
                                      email: "foo@invalid",
                                      password: "foo",
                                      password_confirmation: "bar" } }
  assert_template 'users/edit'
  assert_select 'div.alert', "The form contains 3 errors."
end

The key part here is getting the number of expected errors correct so that assert_select gives the right result. I didn't. The errors should be blank name, invalid email format, password too short, pwd & confirmation don't match. The error for short password isn't showing.

I decided to pull out two more tests to demonstrate the failure of the validations of password length and presence. The point of allow_blank is to allow the password & confirmation fields to have nothing in them when editing the user profile so it isn't compulsory to enter the password every time the user profile is edited. These tests are:

test "unsuccessful edit with short password" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  patch user_path(@user), params: { user:
                                    { name: @user.name,
                                      email: "foo@valid.com",
                                      password: "foo",
                                      password_confirmation: "foo" } }
  assert_select 'div.alert', "The form contains 1 error."
end

test "unsuccessful edit with blank (spaces) password" do
  log_in_as @user
  get edit_user_path(@user)
  assert_template 'users/edit'
  patch user_path(@user), params: { user:
                                    { name: @user.name,
                                      email: "foo@valid.com",
                                      password: " ",
                                      password_confirmation: " " } }
  assert_select 'div.alert', "The form contains 1 error."
end

If the password is changed, then the validation rules should apply, i.e. the password should not be blank and must have a minimum length. That's not what's happening here either in the code the Tutorial book suggests or the amended code using on: :create and on: :edit.

Body:
I figured this out so am posting here in case others come across a similar problem.

I amended the validations to include the :update action on the User, rather than just :edit. This covered the action of saving to the database and caught the short password update validations but still allowed passwords made of spaces.

A bit of checking the documentation showed me that using allow_blank: true allows nil and strings made up of spaces. The scenario here wants a nil password to be acceptable, but not a blank one. The alternative validation of allow_nil: true is more appropriate to the scenario here.

The updated code from above looks like, in User.rb:

validates :password,  presence: true,
                      length: { minimum: 6 },
                      allow_nil: true,
                      on: [:edit, :update]

validates :password,  presence: true,
                      confirmation: true,
                      length: { minimum: 6 },
                      on: :create

The extended test suite is now all green.


来源: stackexchange

问:
Angular 5 - How to generate definition files
I have been trying several ways but I am not able to understand how to generate definition files for my project. I have two angular-cli generated applications A and B, I want A to consume B as a package (with npm link). As far as I understand I need to create an index.ts file in project B with all the modules I want to export and run 'ng build' command. I have seen that only creates the bundles but not the definition files, how can I generate definition files? Is this the correct approach?.

I have tried some other options like 'rollup' and 'ngmakelib' but it seems to be pretty hard to do that simple task. Do we have an easy way to generate Angular 5 projects as libraries and consume that libraries from another projects?

答:
At a high level, here are the steps you would need to do to create a reusable Angular module (all done without webpack):

Create a public_api.ts file within your src folder. This should contain all your exported symbols, so that users of your library can do: import { symbol } from 'your-library'

Copy your src folder to a build/dist folder making sure to inline your templates. I use gulp and gulp-inline-ng2-template for this.

gulpfile.js

```<code>    const gulp = require('gulp');
    const replace = require('gulp-replace');
    const inlineNg2Template = require('gulp-inline-ng2-template');
    const del = require('del');

    gulp.task('clean', function () {
        return del([
           "dist/**"
        ], { force: true });
    });

    gulp.task('copy-public-api', ['clean'], function () {
        return gulp.src([
            '../src/public_api.ts'
        ])
        .pipe(replace('./app', './src'))
        .pipe(gulp.dest('dist'))

    });
    gulp.task('copy-src', ['copy-public-api'], function () {
        return gulp.src([
           '../src/app/**/*.ts',
           '!../src/app/**/*.spec.ts'
        ])
        .pipe(inlineNg2Template({ base: '../src', useRelativePaths: true }))
        .pipe(gulp.dest('dist/src'))
    });
</code>```

public_api.ts

```<code>    export * from './app/app.module';
    // ... other exports ...
</code>```

Create a tsconfig file for ngc.  You'll be using ngc to generate the necessary metadata files. Here are the settings that I use. The file is placed in a "build" folder (notice the relative paths for typeRoots and paths).

build/tsconfig.json

```<code>    {
        "compilerOptions": {
            "baseUrl": ".",
            "rootDir": ".",
            "outDir": "",
            "paths": {
                "*": [
                    "../node_modules/*"
                ]
            },
            "declaration": true,
            "stripInternal": true,
            "noImplicitAny": true,
            "strictNullChecks": true,
            "noFallthroughCasesInSwitch": true,
            "moduleResolution": "node",
            "module": "es2015",
            "target": "es5",
            "lib": [
                "es2015",
                "dom"
            ],
            "skipLibCheck": true,
            "typeRoots": [
                "../node_modules/@types/"
            ],
            "experimentalDecorators": true,
            "emitDecoratorMetadata": true,
            "sourceMap": true,
            "inlineSources": true
        },
        "files": [
            "dist/public_api.ts"
        ],
        "angularCompilerOptions": {
            "annotateForClosureCompiler": true,
            "strictMetadataEmit": false,
            "skipTemplateCodegen": true,
            "flatModuleOutFile": "index.js",
            "flatModuleId": "ng-module-template"
        }

    }
</code>```

The angularCompilerOptions ensure that one metadata file is created (index.js).

Use ngc to compile the module from the build folder. Make sure to install @angular/compiler and @angular/compiler-cli:

```<code>../node_modules/.bin/ngc -p tsconfig.json
</code>```

Deploy only the files that are needed.  I deploy from build\dist to dist:

```<code>gulp.task('build', [], function (done) {
    gulp.src([
        'dist/index.js',
        'dist/public_api.js',
        'dist/index.metadata.json',
        'dist/**/*.d.ts',
        '!../src/app/**/*.spec.ts'
    ], { base: 'dist' })
        .pipe(gulp.dest('../dist'))
        .on('end', function () {
            del('dist/**', { force: true }).then(function () {
                done();
            });
        });
});
</code>```

Make sure you modify your package.json to point to index.js:

```<code>{
  "name": "ng-module-template",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
}
</code>```

Optional: Creating Bundles

Here is a gulp build target for compiling and creating bundles using rollup with treeshaking:

```<code>gulp.task('compile', ['copy-src'], function (done) {
    gulp.src('tsconfig.json')
        .pipe(shell(['"../node_modules/.bin/ngc" -p <%= file.path %>']))
        .on('end', function () {
            del('node_modules/**', { force: true }).then(function () {
                done();
            });
        });
});

gulp.task('bundle', ['compile'], function (done) {
    var external = [
        '@angular/core',
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        '@angular/router-deprecated'
    ];

    var globals = {
        '@angular/core': 'vendor._angular_core',
        '@angular/http': 'vendor._angular_http',
        '@angular/platform-browser': 'vendor._angular_platformBrowser',
        '@angular/platform-browser-dynamic': 'vendor._angular_platformBrowserDynamic',
        '@angular/router-deprecated': 'vendor._angular_routerDeprecated'
    };

    rollup.rollup({
        input: 'dist/index.js',
        onwarn: function (warning) {
            if (warning.message.indexOf("treating it as an external dependency") > -1)
                return;

            console.warn(warning.message);
        }

    }).then(function (bundle) {
        var umd = bundle.write({
            file: `dist/bundles/${pkg.name}.umd.js`,
            format: 'umd',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals
        });
        var cjs = bundle.write({
            file: `dist/bundles/${pkg.name}.cjs.js`,
            format: 'cjs',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals
        });
        var amd = bundle.write({
            file: `dist/bundles/${pkg.name}.amd.js`,
            format: 'amd',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals
        });

        var es = bundle.write({
            file: `dist/index.es5.js`,
            format: 'es',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals

        });

        return Promise.all([umd, cjs, amd, es]).then(function () {
            done();
        });

    });
});
</code>```

Source Code Demo

Pre-requisites

Angular5+

  Git (installed locally if you are publishing to a local folder)

https://github.com/angular-patterns/ng-module-template

Build Targets

npm run dev

For development

npm run build

For production app build (outputs to dist folder)

npm run build-module

For a module build (outputs to dist folder)

npm run publish

For publishing to c:\packages using git. Alternatively, run npm publish to publish to npm.

npm run name-module -- --(module-name)

For naming the module. This modifies the source.

Installing from c:\packages

```<code>npm install c:\packages\<module-name>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
At a high level, here are the steps you would need to do to create a reusable Angular module (all done without webpack):

Create a public_api.ts file within your src folder. This should contain all your exported symbols, so that users of your library can do: import { symbol } from 'your-library'

Copy your src folder to a build/dist folder making sure to inline your templates. I use gulp and gulp-inline-ng2-template for this.

gulpfile.js

    const gulp = require('gulp');
    const replace = require('gulp-replace');
    const inlineNg2Template = require('gulp-inline-ng2-template');
    const del = require('del');

    gulp.task('clean', function () {
        return del([
           "dist/**"
        ], { force: true });
    });

    gulp.task('copy-public-api', ['clean'], function () {
        return gulp.src([
            '../src/public_api.ts'
        ])
        .pipe(replace('./app', './src'))
        .pipe(gulp.dest('dist'))

    });
    gulp.task('copy-src', ['copy-public-api'], function () {
        return gulp.src([
           '../src/app/**/*.ts',
           '!../src/app/**/*.spec.ts'
        ])
        .pipe(inlineNg2Template({ base: '../src', useRelativePaths: true }))
        .pipe(gulp.dest('dist/src'))
    });

public_api.ts

    export * from './app/app.module';
    // ... other exports ...

Create a tsconfig file for ngc.  You'll be using ngc to generate the necessary metadata files. Here are the settings that I use. The file is placed in a "build" folder (notice the relative paths for typeRoots and paths).

build/tsconfig.json

    {
        "compilerOptions": {
            "baseUrl": ".",
            "rootDir": ".",
            "outDir": "",
            "paths": {
                "*": [
                    "../node_modules/*"
                ]
            },
            "declaration": true,
            "stripInternal": true,
            "noImplicitAny": true,
            "strictNullChecks": true,
            "noFallthroughCasesInSwitch": true,
            "moduleResolution": "node",
            "module": "es2015",
            "target": "es5",
            "lib": [
                "es2015",
                "dom"
            ],
            "skipLibCheck": true,
            "typeRoots": [
                "../node_modules/@types/"
            ],
            "experimentalDecorators": true,
            "emitDecoratorMetadata": true,
            "sourceMap": true,
            "inlineSources": true
        },
        "files": [
            "dist/public_api.ts"
        ],
        "angularCompilerOptions": {
            "annotateForClosureCompiler": true,
            "strictMetadataEmit": false,
            "skipTemplateCodegen": true,
            "flatModuleOutFile": "index.js",
            "flatModuleId": "ng-module-template"
        }

    }

The angularCompilerOptions ensure that one metadata file is created (index.js).

Use ngc to compile the module from the build folder. Make sure to install @angular/compiler and @angular/compiler-cli:

../node_modules/.bin/ngc -p tsconfig.json

Deploy only the files that are needed.  I deploy from build\dist to dist:

gulp.task('build', [], function (done) {
    gulp.src([
        'dist/index.js',
        'dist/public_api.js',
        'dist/index.metadata.json',
        'dist/**/*.d.ts',
        '!../src/app/**/*.spec.ts'
    ], { base: 'dist' })
        .pipe(gulp.dest('../dist'))
        .on('end', function () {
            del('dist/**', { force: true }).then(function () {
                done();
            });
        });
});

Make sure you modify your package.json to point to index.js:

{
  "name": "ng-module-template",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
}

Optional: Creating Bundles

Here is a gulp build target for compiling and creating bundles using rollup with treeshaking:

gulp.task('compile', ['copy-src'], function (done) {
    gulp.src('tsconfig.json')
        .pipe(shell(['"../node_modules/.bin/ngc" -p <%= file.path %>']))
        .on('end', function () {
            del('node_modules/**', { force: true }).then(function () {
                done();
            });
        });
});

gulp.task('bundle', ['compile'], function (done) {
    var external = [
        '@angular/core',
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        '@angular/router-deprecated'
    ];

    var globals = {
        '@angular/core': 'vendor._angular_core',
        '@angular/http': 'vendor._angular_http',
        '@angular/platform-browser': 'vendor._angular_platformBrowser',
        '@angular/platform-browser-dynamic': 'vendor._angular_platformBrowserDynamic',
        '@angular/router-deprecated': 'vendor._angular_routerDeprecated'
    };

    rollup.rollup({
        input: 'dist/index.js',
        onwarn: function (warning) {
            if (warning.message.indexOf("treating it as an external dependency") > -1)
                return;

            console.warn(warning.message);
        }

    }).then(function (bundle) {
        var umd = bundle.write({
            file: `dist/bundles/${pkg.name}.umd.js`,
            format: 'umd',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals
        });
        var cjs = bundle.write({
            file: `dist/bundles/${pkg.name}.cjs.js`,
            format: 'cjs',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals
        });
        var amd = bundle.write({
            file: `dist/bundles/${pkg.name}.amd.js`,
            format: 'amd',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals
        });

        var es = bundle.write({
            file: `dist/index.es5.js`,
            format: 'es',
            exports: 'named',
            name: pkg.name,
            sourcemap: true,
            external: external,
            globals: globals

        });

        return Promise.all([umd, cjs, amd, es]).then(function () {
            done();
        });

    });
});

Source Code Demo

Pre-requisites

Angular5+

  Git (installed locally if you are publishing to a local folder)

https://github.com/angular-patterns/ng-module-template

Build Targets

npm run dev

For development

npm run build

For production app build (outputs to dist folder)

npm run build-module

For a module build (outputs to dist folder)

npm run publish

For publishing to c:\packages using git. Alternatively, run npm publish to publish to npm.

npm run name-module -- --(module-name)

For naming the module. This modifies the source.

Installing from c:\packages

npm install c:\packages\<module-name>


问:
Fine Tuning dimensionality error
I am trying to use Resnet50 for image classification problem. However it shows error and I could not fix it.

```<code>RuntimeError: inconsistent tensor size, expected tensor [120 x 2048] and src [1000 x 2048] to have the same number of elements, but got 245760 and 2048000 elements respectively at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorCopy.c:86
</code>```

and error happens below.

```<code>self.resnet = models.resnet50(num_classes=num_breeds, pretrained='imagenet')
</code>```

Model is below

```<code>class Resnet(nn.Module):
    def __init__(self):
        super(Resnet,self).__init__()
        self.resnet = models.resnet50(num_classes=num_breeds, pretrained='imagenet')
        #self.resnet = nn.Sequential(*list(resnet.children())[:-2])
        #self.fc = nn.Linear(2048,num_breeds)

    def forward(self,x):
        x = self.resnet(x)
        return x
</code>```

答:
When you create your models.resnet50 with num_classes=num_breeds, the last layer is a fully connected layer from 2048 to num_classes (which is 120 in your case).

Having pretrained='imagenet' asks pytorch to load all the corresponding weights into your network, but it has for its last layer 1000 classes, not 120. This is the source of the error since the 2048x120 tensor doesn't match the loaded weights 2048x1000.

You should either create your network with 1000 classes and load the weights, then "trim" to the classes you want to keep. Or you could create the network you wished for with 120 classes, but manually load the weights. In the last case, you only need to pay specific attention to the last layer.

Title: Fine Tuning dimensionality error

Body:
I am trying to use Resnet50 for image classification problem. However it shows error and I could not fix it.

RuntimeError: inconsistent tensor size, expected tensor [120 x 2048] and src [1000 x 2048] to have the same number of elements, but got 245760 and 2048000 elements respectively at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorCopy.c:86

and error happens below.

self.resnet = models.resnet50(num_classes=num_breeds, pretrained='imagenet')

Model is below

class Resnet(nn.Module):
    def __init__(self):
        super(Resnet,self).__init__()
        self.resnet = models.resnet50(num_classes=num_breeds, pretrained='imagenet')
        #self.resnet = nn.Sequential(*list(resnet.children())[:-2])
        #self.fc = nn.Linear(2048,num_breeds)

    def forward(self,x):
        x = self.resnet(x)
        return x


问:
Getting current directory in VBScript
I'm trying to get the current directory and use it to run an application no matter where the file is put and no matter how the path is changed

```<code>Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim CurrentDirectory
CurrentDirectory = fso.GetAbsolutePathName(".")
Dim Directory
Directory = CurrentDirectory\attribute.exe

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Directory" & Chr(34), 0
Set WinScriptHost = Nothing
</code>```

How do I actually set up this code so it does what I want it to do correctly?

答:
simple:</p>

```<code>scriptdir = replace(WScript.ScriptFullName,WScript.ScriptName,"")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Getting current directory in VBScript

Body:
I'm trying to get the current directory and use it to run an application no matter where the file is put and no matter how the path is changed

Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim CurrentDirectory
CurrentDirectory = fso.GetAbsolutePathName(".")
Dim Directory
Directory = CurrentDirectory\attribute.exe

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Directory" & Chr(34), 0
Set WinScriptHost = Nothing

How do I actually set up this code so it does what I want it to do correctly?

Body:
simple:

scriptdir = replace(WScript.ScriptFullName,WScript.ScriptName,"")


问:
Play services 11.6: OAuth consent screen not showing when published
Despite having copied the code from the official sample app, authentication consent screen is not showing when app is released through Play Store. I have properly generated two OAuth 2.0 credential on Google Api Developer Console, one for release (using my private keystore) and one for debug (using Android Studio debug keystore).

UPDATE: installing my app on an older 4.4 emulator in debug mode I noticed the same behavior of the release app on newer devices. No consent screen appears, and Logcat shows this message:

W/GooglePlayServicesUtil: Google Play services out of date.  Requires
  11717000 but found 11509030

Could it be that newer GoogleApi interface fails to prompt the user to install/update PlayServices, even if the official documentation says that?

Here is my code:

build.gradle (app)

```<code>compile 'com.google.android.gms:play-services-auth:11.6.0'
compile 'com.google.android.gms:play-services-drive:11.6.0'
</code>```

AndroidManifest.xml

```<code><meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
</code>```

DriveActivity.java

```<code>private static final int REQUEST_CODE_SIGN_IN = 0;

protected GoogleSignInClient mGoogleSignInClient;
protected DriveClient mDriveClient;
protected DriveResourceClient mDriveResourceClient;

protected abstract void onDriveConnected();

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SIGN_IN:
                if (resultCode == RESULT_OK) {
                    Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
                    if (getAccountTask.isSuccessful()) {
                        initializeDriveClient(getAccountTask.getResult());
                    }
                    else {
                        Toast.makeText(this, "Sign-in failed.", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    protected void signIn() {
        GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
        if (signInAccount != null && signInAccount.getGrantedScopes().contains(Drive.SCOPE_FILE)) {
            initializeDriveClient(signInAccount);
        }
        else {
            GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .build();
            mGoogleSignInClient = GoogleSignIn.getClient(this, signInOptions);
            startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
        }
    }

    private void initializeDriveClient(GoogleSignInAccount signInAccount) {
        mDriveClient = Drive.getDriveClient(this, signInAccount);
        mDriveResourceClient = Drive.getDriveResourceClient(this, signInAccount);
        onDriveConnected();
    }
</code>```

答:
For other people, GoogleSignIn.getClient(this /* activity */, signInOptions) should usually auto-prompt for Play services update if needed.

But in newest 11.6 SDK, this feature is temporarily broken with targetSdkVersion 26. Consider using GoogleApiAvailability.showErrorDialogFragment() under these conditions for now until the fix it out in future releases.

Body:
Despite having copied the code from the official sample app, authentication consent screen is not showing when app is released through Play Store. I have properly generated two OAuth 2.0 credential on Google Api Developer Console, one for release (using my private keystore) and one for debug (using Android Studio debug keystore).

UPDATE: installing my app on an older 4.4 emulator in debug mode I noticed the same behavior of the release app on newer devices. No consent screen appears, and Logcat shows this message:

W/GooglePlayServicesUtil: Google Play services out of date.  Requires
  11717000 but found 11509030

Could it be that newer GoogleApi interface fails to prompt the user to install/update PlayServices, even if the official documentation says that?

Here is my code:

build.gradle (app)

compile 'com.google.android.gms:play-services-auth:11.6.0'
compile 'com.google.android.gms:play-services-drive:11.6.0'

AndroidManifest.xml

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

DriveActivity.java

private static final int REQUEST_CODE_SIGN_IN = 0;

protected GoogleSignInClient mGoogleSignInClient;
protected DriveClient mDriveClient;
protected DriveResourceClient mDriveResourceClient;

protected abstract void onDriveConnected();

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SIGN_IN:
                if (resultCode == RESULT_OK) {
                    Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
                    if (getAccountTask.isSuccessful()) {
                        initializeDriveClient(getAccountTask.getResult());
                    }
                    else {
                        Toast.makeText(this, "Sign-in failed.", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    protected void signIn() {
        GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
        if (signInAccount != null && signInAccount.getGrantedScopes().contains(Drive.SCOPE_FILE)) {
            initializeDriveClient(signInAccount);
        }
        else {
            GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .build();
            mGoogleSignInClient = GoogleSignIn.getClient(this, signInOptions);
            startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
        }
    }

    private void initializeDriveClient(GoogleSignInAccount signInAccount) {
        mDriveClient = Drive.getDriveClient(this, signInAccount);
        mDriveResourceClient = Drive.getDriveResourceClient(this, signInAccount);
        onDriveConnected();
    }


问:
Weighted avgerage of list columns in kdb
How can I calculate a column of weighted averages from 2 other columns that both have multiple entries per row in kdb?

For example, given the following table:

```<code>T:([]sym:`a`b`c;size:(2 8;5 2 10;3 7);price:(1 2;1 1 10;2 4))
</code>```

I would like to add the column (1.8 6.29 3.4) to the table.

答:
You can use the each-both adverb to apply the wavg function to each nested list in your table e.g.</p>

```<code>q)update x:wavg'[size;price] from T
sym size   price  x
--------------------------
a   2 8    1 2    1.8
b   5 2 10 1 1 10 6.294118
c   3 7    2 4    3.4
</code>```

Body:
How can I calculate a column of weighted averages from 2 other columns that both have multiple entries per row in kdb?

For example, given the following table:

T:([]sym:`a`b`c;size:(2 8;5 2 10;3 7);price:(1 2;1 1 10;2 4))

I would like to add the column (1.8 6.29 3.4) to the table.

Body:
You can use the each-both adverb to apply the wavg function to each nested list in your table e.g.

q)update x:wavg'[size;price] from T
sym size   price  x
--------------------------
a   2 8    1 2    1.8
b   5 2 10 1 1 10 6.294118
c   3 7    2 4    3.4


问:
Loop in Blogspot
I created a blog, used customize theme and I'm editing it, but I dont know much about it. Bros, please help me how I could show post title and image and loop three newest post in it.</p>

```<code><div class='carousel-inner' role='listbox'>
                      <div class='item active'>
                        <img alt='data:post.title' title='data:post.title' src='data:post.Image'/>
                        <div class='carousel-caption'>
                          <h2>
                            <data:post.title/>
                          </h2>
                          <p>data:post.content</p>
                        </div>
                      </div>
                    </div>
</code>```

答:
1) Go to your theme and find string .

2) After it find section ... - this is what you need.

3) Make your own loop section above this one with needed content.

More info on Blogger Help and OverAPI.

Title: Loop in Blogspot

Body:
I created a blog, used customize theme and I'm editing it, but I dont know much about it. Bros, please help me how I could show post title and image and loop three newest post in it.

                            <data:post.title/>

data:post.content

Body:
1) Go to your theme and find string <b:includable id='main' var='top'>.

2) After it find section <b:loop values='data:posts' var='post'>...</b:loop> - this is what you need.

3) Make your own loop section above this one with needed content.

More info on Blogger Help and OverAPI.


问:
Confusion Matrix - Not changing with predictive models (Sklearn)
I have 3 predictive models and I am evaluating there performance with a confusion matrix.
I am getting the same results for the confusion matrix for each of the 3 models.
I expect that the different models would perform differently and produce different confusion matrices. I am new to predictive modelling, so I suspect I am making a  "Rooky mistake" . The full script I am using  is sitting in a Jupyter notebook  on GiThub here

A screenshot of the code for the 3 models is below

Can some one point out what is going wrong?
Cheers
Mike

答:
As mentioned: make predictions on the test data. But keep in mind that your targets are skewed! So use StratifiedKFolds or something like this.

Also I guess that your data is a bit corrupted. While all models show the same result it may be a big mistake underneath.

Few questions/advises:
1. Did you scale your data?
2. Did you use one-hot-encoding?
2. Use don't Decision Trees but Forests/XGBoost. Easy to overfit with DT.
3. Don't use >2 hidden layers in NN because it's easy to overfit too. Use 2 firstly. And your architecture (30, 30, 30) with 2 target classes seems weird.
4. And if you wish to use >2 hidden layers - go to Keras or TF. You'll find there many features that can help you to not overfit.


问:
Passing an array to a function that's been scanned
I'm struggling with sending array data that's been previously scanned to a function.

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

int display(int a[21]);

int main(){
    int i;
    int a[21];
    FILE*fpointer;
    fpointer=fopen("data.txt","r");
    if (fpointer==NULL){
        printf("\nFile could not be found.");
        exit(1);
    }
    else{
        for (i=0;i<21;i++){
            fscanf(fpointer, "%d",&a[i]);
        }
        fclose(fpointer);
    }
    display(int a[21]);
    return 0;
}

int display(int a[21]){
    int i;
    for (i=0;i<21;i++){
        printf("%d\n",a[i]);
    }
    return 0;
}
</code>```

I want to use the display() function to display each value from data.txt. I am able to fscanf every into the array, I just can't seem the send the array to the function.

data.txt:

```<code>1
6
4
7
3
4
12
14
15
-17
-19
21
-23
0
37
0
-31
32
34
-37
-39
</code>```

Output values:

```<code>1065353216
1086324736
1082130432
1088421888
1077936128
1082130432
1094713344
1096810496
1097859072
-1048051712
-1047003136
1101529088
-1044905984
0
1108606976
0
-1040711680
1107296256
1107820544
-1038876672
-1038352384
</code>```

答:
```<code>#include <stdio.h>
#include <stdlib.h>

int display(int a[21]);

int main(){
    int i;
    int a[21];
    FILE*fpointer;
    fpointer=fopen("data.txt","r");
    if (fpointer==NULL){
        printf("\nFile could not be found.");
        exit(1);}

    else{
        for (i=0;i<21;i++){
        fscanf(fpointer, "%d",&a[i]);}

        fclose(fpointer);}
        display(a);
return 0;
}
int display(int a[21]){
    int i;
    for (i=0;i<21;i++){
      printf("%d\n",a[i]);}
return 0;
}
</code>```

Results are now displayed. I was scanning a %f rather than a %d, also the display(a) in the main function rather than display(int a[])

Body:
I'm struggling with sending array data that's been previously scanned to a function.

#include <stdio.h>
#include <stdlib.h>

int display(int a[21]);

int main(){
    int i;
    int a[21];
    FILE*fpointer;
    fpointer=fopen("data.txt","r");
    if (fpointer==NULL){
        printf("\nFile could not be found.");
        exit(1);
    }
    else{
        for (i=0;i<21;i++){
            fscanf(fpointer, "%d",&a[i]);
        }
        fclose(fpointer);
    }
    display(int a[21]);
    return 0;
}

int display(int a[21]){
    int i;
    for (i=0;i<21;i++){
        printf("%d\n",a[i]);
    }
    return 0;
}

I want to use the display() function to display each value from data.txt. I am able to fscanf every into the array, I just can't seem the send the array to the function.

data.txt:

1
6
4
7
3
4
12
14
15
-17
-19
21
-23
0
37
0
-31
32
34
-37
-39

Output values:

1065353216
1086324736
1082130432
1088421888
1077936128
1082130432
1094713344
1096810496
1097859072
-1048051712
-1047003136
1101529088
-1044905984
0
1108606976
0
-1040711680
1107296256
1107820544
-1038876672
-1038352384

Body:
#include <stdio.h>
#include <stdlib.h>

int display(int a[21]);

int main(){
    int i;
    int a[21];
    FILE*fpointer;
    fpointer=fopen("data.txt","r");
    if (fpointer==NULL){
        printf("\nFile could not be found.");
        exit(1);}

    else{
        for (i=0;i<21;i++){
        fscanf(fpointer, "%d",&a[i]);}

        fclose(fpointer);}
        display(a);
return 0;
}
int display(int a[21]){
    int i;
    for (i=0;i<21;i++){
      printf("%d\n",a[i]);}
return 0;
}

Results are now displayed. I was scanning a %f rather than a %d, also the display(a) in the main function rather than display(int a[])


问:
Where or how I install directories with different file formats with setup.py?
I'm developing a module with python, now I understand how to install module with setup.py or setuptools and how to build a command line utility/tool for the user. I do not understand where & how I install some directories with different files, for example the module has a web interface, this interface of course have html, js, css, etc files.

How should I configure the setup.py to install this files in some path?

Cheers!

答: package_data is probably what you want. See https://docs.python.org/2/distutils/setupscript.html#installing-package-data


问:
Not sending userAgent in header, Node.js console application
I'm just beginning to learn javascript and https requests.  I'm working in Visual Studio 2017, I created a blank javascript console app from the template and added the following code.

```<code>const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();
</code>```

The response I get from the server is

```<code>{"message":"User-Agent header is required."}
</code>```

When I navigate to https://api.gdax.com/products/BTC-USD/stats in my browser I get the correct response.  How come I can't do the same in a javascript console?

答:
You need to explicitely set the User-Agent header in the headers property of your request options

```<code>const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false,
    headers: { 'User-Agent': 'Mosaic/1.0' }
};
</code>```

Body:
I'm just beginning to learn javascript and https requests.  I'm working in Visual Studio 2017, I created a blank javascript console app from the template and added the following code.

const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();

The response I get from the server is

{"message":"User-Agent header is required."}

When I navigate to https://api.gdax.com/products/BTC-USD/stats in my browser I get the correct response.  How come I can't do the same in a javascript console?

Body:
You need to explicitely set the User-Agent header in the headers property of your request options

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false,
    headers: { 'User-Agent': 'Mosaic/1.0' }
};


问:
Java Error: NullPointerException due to missing Constructor(s)
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

```<code>Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)
</code>```

This is where the error happens:

```<code>public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}
</code>```

The "Display" class I'm trying to access:

```<code>public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}
</code>```

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.

答:
If a java class is written without declaring any explicit constructors, it has a default, no-arguments constructor. However, if at least a constructor is declared explicitly, then the no-argument constructor is not present by default, and needs to be added if needed. In your case you have a Display(String title, int width, int height) constructor, hence the no-argument constructor has to be declared explicitly if needed.

This said, you have a constructor for Display calling arrayC.updatePosition(), which in turn creates another, distinct display object. That doesn't smell right. I suspect you want a single Display instance. I would create a separate method instantiating display, then instantiating all other objects that need to have a reference to it passing it as argument to their constructors.

Body:
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)

This is where the error happens:

public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}

The "Display" class I'm trying to access:

public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.


问:
Contact form - user's name and email coming through as 'unknown'
Apologies, I am aware this question has been asked quite afew times already on this site, however I have tried to implement what others have suggested but with no luck.

Same as everyone else I have a very simple contact form and for the sake of this example I have stripped the PHP coding to the bare minimum so it is simpler to look at.

It works fine in the sense I receive the email in GMail with the message, however the email and name the user filled-in never shows up.

I have tried taking '\r' out and just leaving '\n\

Other methods have either resulted in the email going to junk or the same (coming through as unknown).

```<code>  <form action="contact.php" method="post">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email">Email address</label>
                                    <input type="email" class="form-control" id="email" placeholder="Enter email">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name">Name</label>
                                    <input type="text" class="form-control" id="name" placeholder="Name">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="message">Message</label>
                            <textarea name="message" id="message" class="form-control" rows="3"></textarea>
                        </div>
                        <button type="submit" class="btn tf-btn btn-default">Submit</button>
                    </form>
</code>```

PHP Code

```<code><?php

$to = 'mymail@gmail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = 'RE: RMW interest';

$headers .= 'From:' .$name. " ".'<'.$email.'>'."\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";

mail($to, $subject, $message, $headers);

echo "Thank you for contacting us, we will respond shortly!";

?>
</code>```

I would be most grateful if someone could shed some light on this particular case please.

Many thanks

答:
The problem in HTML code not in PHP,

You forgot to name the inputs, so when you call print_r() in contact.php file you will found just the message.

in contact.php when you write print_r($_POST);
the output will be

```<code>Array ( [message] => message)
</code>```

Now you know the problem so you want to name all inputs.

```<code><input name="email" type="email" class="form-control" id="email" placeholder="Enter email">
...
<input name="name" type="text" class="form-control" id="name" placeholder="Name">
...
<button name="submit" type="submit" class="btn tf-btn btn-default">Submit</button>
</code>```

So the output now is

```<code>Array ( [email] => test@test.test [name] => test [message] => test message [submit] => )
</code>```

And here i named the button because you can check if the button clicked send the message.

```<code>if(isset($_POST['submit'])){
    //your code here
}
</code>```

hope this helps

Body:
Apologies, I am aware this question has been asked quite afew times already on this site, however I have tried to implement what others have suggested but with no luck.

Same as everyone else I have a very simple contact form and for the sake of this example I have stripped the PHP coding to the bare minimum so it is simpler to look at.

It works fine in the sense I receive the email in GMail with the message, however the email and name the user filled-in never shows up.

I have tried taking '\r' out and just leaving '\n\

Other methods have either resulted in the email going to junk or the same (coming through as unknown).

  <form action="contact.php" method="post">

                                    Email address
                                    <input type="email" class="form-control" id="email" placeholder="Enter email">

                                    Name
                                    <input type="text" class="form-control" id="name" placeholder="Name">

                            Message
                            <textarea name="message" id="message" class="form-control" rows="3"></textarea>

                        <button type="submit" class="btn tf-btn btn-default">Submit</button>
                    </form>

PHP Code

<?php

$to = 'mymail@gmail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = 'RE: RMW interest';

$headers .= 'From:' .$name. " ".'<'.$email.'>'."\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";

mail($to, $subject, $message, $headers);

echo "Thank you for contacting us, we will respond shortly!";

?>

I would be most grateful if someone could shed some light on this particular case please.

Many thanks

Body:
The problem in HTML code not in PHP,

You forgot to name the inputs, so when you call print_r() in contact.php file you will found just the message.

in contact.php when you write print_r($_POST);
the output will be

Array ( [message] => message)

Now you know the problem so you want to name all inputs.

<input name="email" type="email" class="form-control" id="email" placeholder="Enter email">
...
<input name="name" type="text" class="form-control" id="name" placeholder="Name">
...
<button name="submit" type="submit" class="btn tf-btn btn-default">Submit</button>

So the output now is

Array ( [email] => test@test.test [name] => test [message] => test message [submit] => )

And here i named the button because you can check if the button clicked send the message.

if(isset($_POST['submit'])){
    //your code here
}

hope this helps


问:
Code Igniter / Pyro CMS Call to a member function result_array() on boolean
I have just downloaded a git of a site running on Pyro CMS on the Code Igniter PHP framework and tried to run it locally however it is throwing this error:

```<code>[Mon Jul 24 10:05:39.868253 2017] [:error] [pid 5944:tid 1944] [client ::1:55468] PHP Fatal error:  Call to a member function result_array() on boolean in C:\\xampp\\htdocs\\system\\codeigniter\\database\\DB_driver.php on line 831
</code>```

I have tried using result() rather than result_array() however it throws the same error.

The site is running on PHP version 5.6.31 on an XAMPP local server.

Below is the file which is throwing the error:

https://pastebin.com/QXSUD5u6

答: Little late to the party here but usually that happens in codeigniter when there is no database connection. Check the database config file to make sure it is properly set up for your local host credentials; my guess is that it is still configured to access the 'online' database from which you downloaded the files. </p>

Body:
I have just downloaded a git of a site running on Pyro CMS on the Code Igniter PHP framework and tried to run it locally however it is throwing this error:

[Mon Jul 24 10:05:39.868253 2017] [:error] [pid 5944:tid 1944] [client ::1:55468] PHP Fatal error:  Call to a member function result_array() on boolean in C:\\xampp\\htdocs\\system\\codeigniter\\database\\DB_driver.php on line 831

I have tried using result() rather than result_array() however it throws the same error.

The site is running on PHP version 5.6.31 on an XAMPP local server.

Below is the file which is throwing the error:

https://pastebin.com/QXSUD5u6


问:
Autodesk Forge - Best training for transitioning from desktop .Net coding
I have background in Inventor/Revit API development only, and need to learn enough JS to be able to work comfortably with the Forge APIs. I'll be booking myself into a JS training course to learn general skills, but what topics/modules must I definitely cover to have a solid foundation for Forge API development. I'll be working with BOM data, viewers and possibly web configurators.

Many thanks for your help.

答:
You need the JavaScript, as you already know. Take some time to improve security and OAuth authentication workflow. This sample includes most of it.

In most cases, you'll need a hybrid desktop app that can connect to the cloud, the image below (from the blog post) shows a generic approach for the architecture using Autodesk Forge (or any other cloud APIs).


问:
How to loop over object with unknown keys and values
I get a JSON response of shoe sizes from an API endpoint that looks like this:

```<code>data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]
</code>```

The data shows e.g that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be A-Z or basically anything else.

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size.

What would be the best way to loop over an object like this to get the value of every shape? I would expect it to be an array of sizes.

ES6 or ES7 is fine but I would prefer to do it without jQuery.

EDIT:
Let me be more clear.
First of all I have considered improving data structure but unfortunately that's not an option.

I have tried Object.keys(sizes) which returns an array of the keys. Sure that's one step forward. But I would like to call a function that returns an object with the keys and its values. In my mind, that return value should be something like this:

```<code>sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]
</code>```

Does that makes sense? Of course, length is not absolutely necessary to include in the object.

答:
You can use array#map, Object.keys() and array#reduce.

const data = [{system:'US',sizes:{7:{B:3,C:6,D:1,E:1,}, 7.5: { A: 6, B: 7, C: 14, D: 11, E: 2, }, 8: { '2E': 1, A: 5, B: 32, C: 38, D: 23, }, 8.5: { '2E': 2, A: 9, B: 56, C: 79, D: 61, }, 9: { '2A': 5, '2E': 4, A: 17, B: 92, C: 143, }, 9.5: { '2A': 3, '2E': 3, A: 26, B: 132, C: 194, }, 10: { '2A': 5, '2E': 3, '3A': 1, A: 53, B: 159, }, }, }, ];

var result = data.map((obj) => {
  return Object.keys(obj.sizes).reduce((arr,k) => {
    let res = Object.keys(obj.sizes[k]).reduce((r, k1) => {
      r['size'] = k;
      r.shapes.push({name: k1, value: obj.sizes[k][k1]});
      r.total += obj.sizes[k][k1];
      return r;
    },{shapes:[],total:0});
    arr.push(res);
    return arr;
  },[]);
})

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I get a JSON response of shoe sizes from an API endpoint that looks like this:

data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]

The data shows e.g that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be A-Z or basically anything else.

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size.

What would be the best way to loop over an object like this to get the value of every shape? I would expect it to be an array of sizes.

ES6 or ES7 is fine but I would prefer to do it without jQuery.

EDIT:
Let me be more clear.
First of all I have considered improving data structure but unfortunately that's not an option.

I have tried Object.keys(sizes) which returns an array of the keys. Sure that's one step forward. But I would like to call a function that returns an object with the keys and its values. In my mind, that return value should be something like this:

sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]

Does that makes sense? Of course, length is not absolutely necessary to include in the object.

Body:
You can use array#map, Object.keys() and array#reduce.

const data = [{system:'US',sizes:{7:{B:3,C:6,D:1,E:1,}, 7.5: { A: 6, B: 7, C: 14, D: 11, E: 2, }, 8: { '2E': 1, A: 5, B: 32, C: 38, D: 23, }, 8.5: { '2E': 2, A: 9, B: 56, C: 79, D: 61, }, 9: { '2A': 5, '2E': 4, A: 17, B: 92, C: 143, }, 9.5: { '2A': 3, '2E': 3, A: 26, B: 132, C: 194, }, 10: { '2A': 5, '2E': 3, '3A': 1, A: 53, B: 159, }, }, }, ];

var result = data.map((obj) => {
  return Object.keys(obj.sizes).reduce((arr,k) => {
    let res = Object.keys(obj.sizes[k]).reduce((r, k1) => {
      r['size'] = k;
      r.shapes.push({name: k1, value: obj.sizes[k][k1]});
      r.total += obj.sizes[k][k1];
      return r;
    },{shapes:[],total:0});
    arr.push(res);
    return arr;
  },[]);
})

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答: If I'm not mistaken java also have this input and output buffering to read and write file.</p>

ContentLicense: CC BY-SA 2.5


问:
Get a List that is created reading an Excel File C#
In my Web API Project I have a method that reads an excel file, and set some values to a list, this part works, but when I want to get that list through a HTTP Get method only returns an empty list like this [{ },{ },{ }] and something I have to say is that those { } are exactly the number of users I have on my .xlsx file. I don't know if the problem is by returning that list or that I coded an incorrect Get Method.

HTTP get Method

```<code>[HttpGet]
    public List<User> GetUsersList()
    {
        List<User> userList = new List<User>();

        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\Username\UploadFile\Base.xlsx");
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;
        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;
        string code = "";
        string rolename = "";
        int count = 2;
        for (int i = 3; i <= rowCount; i++)
        {
            count += 1;
            for (int j = 1; j <= colCount; j++)
            {
                if (count == i & j == 1)
                {
                    code = xlRange.Cells[i, j].Value2.ToString();
                }
                else
                {
                    if (count == i & j == 2)
                    {
                        rolename = xlRange.Cells[i, j].Value2.ToString();
                        User user = new User(code, rolename);
                        userList.Add(user);
                    }
                }

            }
        }

        return userList;
    }
</code>```

Here I create the User Class

```<code>public class User
    {
        private string _code;
        private string _rolename;

        public User(string code, string rolename)
        {
            _code = code;
            _rolename = rolename;
        }
    }
</code>```

答:
As someone who also tried to use the Microsoft Excel Interoperability libraries on a server, I advise you not to use it.

One of the biggest problems when using it is the fact that it needs the right version of MS Excel to be installed on the server.

There are a lot of other libraries, free and paid, that you can use to read Excel files. If you want a suggestion, use ClosedXML

https://github.com/ClosedXML/ClosedXML.

It had enough documentation to get you started. And when you are posting a question please post the error you are getting too. Otherwise the community wouldn't be able to help you.

Body:
In my Web API Project I have a method that reads an excel file, and set some values to a list, this part works, but when I want to get that list through a HTTP Get method only returns an empty list like this [{ },{ },{ }] and something I have to say is that those { } are exactly the number of users I have on my .xlsx file. I don't know if the problem is by returning that list or that I coded an incorrect Get Method.

HTTP get Method

[HttpGet]
    public List<User> GetUsersList()
    {
        List<User> userList = new List<User>();

        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\Username\UploadFile\Base.xlsx");
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;
        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;
        string code = "";
        string rolename = "";
        int count = 2;
        for (int i = 3; i <= rowCount; i++)
        {
            count += 1;
            for (int j = 1; j <= colCount; j++)
            {
                if (count == i & j == 1)
                {
                    code = xlRange.Cells[i, j].Value2.ToString();
                }
                else
                {
                    if (count == i & j == 2)
                    {
                        rolename = xlRange.Cells[i, j].Value2.ToString();
                        User user = new User(code, rolename);
                        userList.Add(user);
                    }
                }

            }
        }

        return userList;
    }

Here I create the User Class

public class User
    {
        private string _code;
        private string _rolename;

        public User(string code, string rolename)
        {
            _code = code;
            _rolename = rolename;
        }
    }


问:
Ajax upload file not work
I dont know what wrong with this code but it show an error message "Uncaught TypeError: Illegal invocation"   </p>

```<code>     $('.upload-document').on("click", function() {
        $(this).parent().append("<input type='file' class='upload-btn' style='visibility:hidden' />");
        $('.upload-btn').click();
        $('.upload-btn').on("change", function(e){
            var file = $(this)[0].files[0];
            $.ajax({
                type: 'POST',
                url: "upload-file.php",
                data: {
                    file: file
                },
                success: function (data) {
                    console.log(data);
                }
            });
        })
    })
</code>```

答:
Change your code to this:</p>

```<code>$('.upload-document').on("click", function () {
    $(this).parent().append("<input type='file' class='upload-btn' style='visibility:hidden' />");
    $('.upload-btn').click();

})
$('body').on("change",'.upload-btn', function (e) {
    var file = $(this)[0].files[0];
    $.ajax({
        type: 'POST',
        url: "upload-file.php",
        data: {
            file: file
        },
        success: function (data) {
            console.log(data);
        }
    });
})
</code>```

Title: Ajax upload file not work

Body:
I dont know what wrong with this code but it show an error message "Uncaught TypeError: Illegal invocation"

     $('.upload-document').on("click", function() {
        $(this).parent().append("<input type='file' class='upload-btn' style='visibility:hidden' />");
        $('.upload-btn').click();
        $('.upload-btn').on("change", function(e){
            var file = $(this)[0].files[0];
            $.ajax({
                type: 'POST',
                url: "upload-file.php",
                data: {
                    file: file
                },
                success: function (data) {
                    console.log(data);
                }
            });
        })
    })

Body:
Change your code to this:

$('.upload-document').on("click", function () {
    $(this).parent().append("<input type='file' class='upload-btn' style='visibility:hidden' />");
    $('.upload-btn').click();

})
$('body').on("change",'.upload-btn', function (e) {
    var file = $(this)[0].files[0];
    $.ajax({
        type: 'POST',
        url: "upload-file.php",
        data: {
            file: file
        },
        success: function (data) {
            console.log(data);
        }
    });
})


问:
Typedef "AVMediaType cannot be referenced with enum spcecifier"
After updating to Mac High OS X Sierra in my Xcode9, my project has a lot of compile errors, as title describes. The AVMediaType are referenced nine times and I can't change it. These errors are in the built in avformat.h and avcodec.h files.

What should I do to change this?

答: Go to the library files such as ffmpeg and change the permissions in 'GetInfo' give yourself write and read access. Open the files in ffmpeg avutil.h in another program (I used Sublime) and edit your file as needed. Do this for all your ffmpeg files that use the AVMediaType that are giving you the name error.</p>


问:
Scala: Convert RDD[LabelledPoint] to RDD[(Long,Vector)]
I have data in an RDD[LabeledPoint] (denoted as sparse0.sparseData in the code below)

I want to convert to RDD[(Long,Vector)] so I can run the LDA analysis in mllib package.

The best I can manage is a map to RDD[(Long,Vector[Double])] which does not compile when entered into the LDA.run method

Trying to map to RDD[(Long,Vector)] does not compile in the .map method. (error Vector takes type parameters)

The fact that my map method seems tortuous suggests I am missing something obvious. Any hints would be greatly appreciated

```<code>val mappedData:Map[Long,Vector[Double]]=sparse0.sparseData().collect().map
{
      var count:Int=0
  row =>
    count=count+1
    new Tuple2[Long,Vector[Double]](count,row.features.toArray.toVector)

}.toMap

val mappedRDD=spark.sparkContext.parallelize(mappedData.toSeq)

// Cluster the documents into three topics using LDA
val ldaModel = new LDA().setK(3).run(mappedRDD)
</code>```

答:
Scala Vector is not the same as mllib.linalg.Vector. I'd zipWithIndex

```<code>val mappedRDD  = sparse0.sparseData().map(_.features).zipWithIndex.map(_.swap)
</code>```

Body:
I have data in an RDD[LabeledPoint] (denoted as sparse0.sparseData in the code below)

I want to convert to RDD[(Long,Vector)] so I can run the LDA analysis in mllib package.

The best I can manage is a map to RDD[(Long,Vector[Double])] which does not compile when entered into the LDA.run method

Trying to map to RDD[(Long,Vector)] does not compile in the .map method. (error Vector takes type parameters)

The fact that my map method seems tortuous suggests I am missing something obvious. Any hints would be greatly appreciated

val mappedData:Map[Long,Vector[Double]]=sparse0.sparseData().collect().map
{
      var count:Int=0
  row =>
    count=count+1
    new Tuple2[Long,Vector[Double]](count,row.features.toArray.toVector)

}.toMap

val mappedRDD=spark.sparkContext.parallelize(mappedData.toSeq)

// Cluster the documents into three topics using LDA
val ldaModel = new LDA().setK(3).run(mappedRDD)

Body:
Scala Vector is not the same as mllib.linalg.Vector. I'd zipWithIndex

val mappedRDD  = sparse0.sparseData().map(_.features).zipWithIndex.map(_.swap)


答:
Remove time from the group by.  I am guessing this FROM clause does what you want:

```<code>from TableB B left join
     (select max([time]) as maxtime, term_id, config1, config2
      from TableA
      group by term_id, config1, config2
     ) A
     on A.term_id = B.term_id
</code>```

Title: Insert Only One/the Very First Record Using an Left Join in T-Sql

Body:
I have two tables TableA and TableB. I am trying to join using a leftjoin and insert some records into TableA.

My TableA,

Time                             term_id   config1   config2    final
2017-04-19 23:59:00                 8        147       0        NULL
2017-04-19 23:59:00                 9        87        0        NULL
2017-04-19 23:59:00                10        284       0        NULL

My TableB

Time                             term_id   config1   config2       Claims     Rejects
2017-04-20 00:00:00                8         148       0            568.2        62
2017-04-20 01:00:00                8         148       0            569          62
2017-04-20 02:00:00                8         148       0            572          62
2017-04-20 00:00:00                9         88        0            458          12
2017-04-20 01:00:00                9         88        0            459          12
2017-04-20 02:00:00                9         88        0            462          12
2017-04-20 00:00:00               10         285       0            125          13
2017-04-20 01:00:00               10         285       0            123          13
2017-04-20 02:00:00               10         285       0            117          13
2017-04-20 03:00:00               10         286       1            119          13

My desired output is,

Time                           term_id         config1     config2     final
2017-04-19 23:59:00                 8            147           0        NULL
2017-04-19 23:59:00                 9            87            0        NULL
2017-04-19 23:59:00                 10           284           0        NULL
2017-04-20 00:00:00                 8            148           0         1
2017-04-20 00:00:00                 9            88            0         1
2017-04-20 00:00:00                 10           285           0         1
2017-04-20 03:00:00                 10           286           1         1

I want to insert only the changes in the config1, config2 from TableB into the TableA. So, I did a left join like this, (I don't need Claims and Rejects from TableB)

insert into TableA
select B.[time], B.term_id, B.Config1, B.config2,
        (CASE
        WHEN B.config1 <> A.config1 OR
             B.config2 <> A.config2
        THEN 1
        ELSE 0 END)
from
    TableB B
left join
    (select max([time]) as maxtime, term_id, config1, config2
     from TableA
     group by [time], term_id, config1, config2
    ) as A
on A.term_id = B.term_id

I do not get what I want. How can I change my code to get only the very first changing value inserted into TableA?

Body:
Remove time from the group by.  I am guessing this FROM clause does what you want:

from TableB B left join
     (select max([time]) as maxtime, term_id, config1, config2
      from TableA
      group by term_id, config1, config2
     ) A
     on A.term_id = B.term_id


问:
Adding clickable boxes inside picturebox c#
So I have a picture box that I need to draw rectangles or declare regions either or, so that the user can click on an area of the picture and it do something. I have searched and searched about this and have come to the conclusion that I do either need rectangles to target or a region. I really don't want a visible item over the map if that simplifies it, just a place for the user to click and it do an action.

On top of this the map will be changing and when it does I need to change the boxes to other locations.  Below is what I came up with and its not working. I am open to other ways as well.

```<code>    public Rectangle Location1;
    public Rectangle Location2;

    public String CharacterLocation == "WorldMap";

private void GenerateRegions ()
    {
        Pen blankPen = new Pen(Color.Transparent, 3);

        if (CharacterLocation == "WorldMap")
        {
            Rectangle[] rects =
        {
             Location1 = new Rectangle(100, 200, 250,  50),
             Location2 = new Rectangle(50, 100, 250,  50)

        };

            MapBox.CreateGraphics().DrawRectangles(blankPen, rects);
        }
    }
   private void MapBox_MouseDown(object sender, MouseEventArgs e)
    {
        if (Location1.Contains(e.Location))
       {

       }
   }
</code>```

答:
OK so here is what got it going for me. Its drawing the rectangles at the wrong spot, but I assume its cause the image is zoomed.

```<code>       private void GenerateRegions ()
    {

        MapBox.Invalidate();
        Pen blankPen = new Pen(Color.Transparent, 3);
        Console.WriteLine(CharacterLocation);

        if (CharacterLocation == "WorldMap")
        {
            Console.WriteLine(CharacterLocation);

            Rectangle[] rects =
        {
             Location1 = new Rectangle(64, 25, 20,  20),
             Location2 = new Rectangle(68, 70, 20,  20)

        };

            using (var g = Graphics.FromImage(MapBox.Image))
            {
                g.DrawRectangles(blankPen, rects);
                MapBox.Refresh();
            }
        }
   private void MapBox_MouseDown(object sender, MouseEventArgs e)
    {
        if (Location1.Contains(e.Location))
       {
            arealbl.Text = "You clicked it 1";
        }
        if (Location2.Contains(e.Location))
        {
            arealbl.Text = "You clicked it 2";
        }
</code>```

}

Body:
So I have a picture box that I need to draw rectangles or declare regions either or, so that the user can click on an area of the picture and it do something. I have searched and searched about this and have come to the conclusion that I do either need rectangles to target or a region. I really don't want a visible item over the map if that simplifies it, just a place for the user to click and it do an action.

On top of this the map will be changing and when it does I need to change the boxes to other locations.  Below is what I came up with and its not working. I am open to other ways as well.

    public Rectangle Location1;
    public Rectangle Location2;

    public String CharacterLocation == "WorldMap";

private void GenerateRegions ()
    {
        Pen blankPen = new Pen(Color.Transparent, 3);

        if (CharacterLocation == "WorldMap")
        {
            Rectangle[] rects =
        {
             Location1 = new Rectangle(100, 200, 250,  50),
             Location2 = new Rectangle(50, 100, 250,  50)

        };

            MapBox.CreateGraphics().DrawRectangles(blankPen, rects);
        }
    }
   private void MapBox_MouseDown(object sender, MouseEventArgs e)
    {
        if (Location1.Contains(e.Location))
       {

       }
   }

Body:
OK so here is what got it going for me. Its drawing the rectangles at the wrong spot, but I assume its cause the image is zoomed.

       private void GenerateRegions ()
    {

        MapBox.Invalidate();
        Pen blankPen = new Pen(Color.Transparent, 3);
        Console.WriteLine(CharacterLocation);

        if (CharacterLocation == "WorldMap")
        {
            Console.WriteLine(CharacterLocation);

            Rectangle[] rects =
        {
             Location1 = new Rectangle(64, 25, 20,  20),
             Location2 = new Rectangle(68, 70, 20,  20)

        };

            using (var g = Graphics.FromImage(MapBox.Image))
            {
                g.DrawRectangles(blankPen, rects);
                MapBox.Refresh();
            }
        }
   private void MapBox_MouseDown(object sender, MouseEventArgs e)
    {
        if (Location1.Contains(e.Location))
       {
            arealbl.Text = "You clicked it 1";
        }
        if (Location2.Contains(e.Location))
        {
            arealbl.Text = "You clicked it 2";
        }

}


问:
Error while saving a workflow via sharepoint designer: Server-side activities have been updated
While saving a workflow using SharePoint designer on a SharePoint site, I get the following error:

Server-side activities have been updated. You need to restart SharePoint Designer to use the updated version of activities.

Steps to recreate error:

Login to the WFE server hosting IIS and workflow manager, open SharePoint Designer 2013 and login to a SharePoint site.

Access the list using SharePoint Designer 2013, in the workflow section, click new workflow.

In the new workflow dialog, enter workflow details, click save

Error message is displayed as below:
Server-side activities have been updated. You need to restart SharePoint Designer to use the updated version of activities.

After restarting SharePoint Designer, the saved workflow is not seen in the site/workflows or list/workflow section.

Workaround

When the above steps are repeated while accessing the site via SPD from any other box besides the WFE/Workflow manager host server, the error is not encountered and its possible to save/publish workflows.

Notes

Workflow Manager 1.0 is installed.

The site has been registered with Workflow manager using Register-SPWorkflowService cmdlet.

Any clue on why is this happening?

答:
Update WorkflowManager and WorkflowManagerClient to CU4

Uninstall Visual Studio

Uninstall SPD

Deactivate Distributed Cache

Delete WebApplications (Except Central Admin)

Run CMD commands:

cd "%APPDATA%\Microsoft\Web Server Extensions\Cache"
del *.web /S /Q "%APPDATA%\Microsoft\Web Server Extensions\Cache"
cd "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache\"
rmdir /S /Q "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache."
mkdir "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache"
dir "%APPDATA%\Microsoft\Web Server Extensions\Cache"
dir "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache"

Run iisreset

Restart VM

Create Web Application

Install SPD

Execute iisreset

Restart VM

Open SPD

Go to "Options > Application Options > General Tab" and let -only
 the following- boxes checked: "Show status bar" and "Show catalog
 lists and system objects" > OK > OK

Open the site via SPD

Create new Workflow 2013 via SPD

Thats what I did. Hope it helps.


问:
How to avoid duplicate file upload but keep the uploader unaware of it?
First of all, I apologize if the question is not clear, I'm explaining it below.

For every file uploaded, I'm renaming the file and recording the hash values (using sha1_files function, please suggest if there are some better or faster hashing techniques for the file in php) in a separate DB table and checking the hash of every new file to avoid duplicate files.

In this manner, the one uploading a duplicate file will get an error msg and the file won't be uploaded.

My question is, is there any techniques or algorithm by which I can prevent duplicate file upload but the duplicate file uploader will be unaware of it and will find the file in his/her account with a different name than the one already present. However, users won't be able to upload banned files by any means.

答:
You could create an extra table which links files uploaded (so entries in your table with file hashes) with useraccounts. This table can contain an individual file name for every file belonging to a specific user (so the same file can have a different name per user). With current technologies you could also think about creating the file hash in the browser via javascript and then upload the file only if there isn't already a file with that hash in your database if it is you can instead just link this user to the file.

Addition because of comment:
If you want the same file to be accessible through multiple urls you can use something like apache's mod_ rewrite. I'm no expert with that but you can look here  for a first idea. You could update the .htaccess dynamically with your upload script.


问:
Core plot not sizing the plot area appropriately for bar graph
I've got a container view that holds 2 view controllers, each of which in turn hosts a CPGraphHostingView. The heirarchy is something like this

ContainerView
      - TopView
      - BottomView

I initialize topViewController(initWithNibName), resize the view to 70% of the height and add the topViewController.view to  containerView subviews

Similarly for BottomView, except that the height is 30%

These 2 views now span the height of the container view.

However, the bar plot drawn in the bottom view does not respect the super views height coordinates and draws the bars out of range resulting in the need for a vertical scroll. I've also tried adjusting the plotScale post addition of graph, but causes me to lose some alignment.

Strangely, the scatter chart view in the top view seems to behave better and scales when i flip  the top: bottom ratio to 3:7 from the original 7:3.

Are bar plots supposed to behave differently ? Or am i missing something here. Attached are the images for my issue. notice that in both cases , the top scatter chart seems to have scaled correctly.

Also, i tested by using the scatter chart code in the bottomViewController (to make sure that this wasn't some nib issue) and again with scatter chart the scaling seems to just work.

Thanks a lot.

PS: i didn't use google groups because i could not post images there.

答:
The fact that it works for the scatter plot makes me think there is an issue with the way your bar plot is set up.

Double-check your plot ranges in the plot space for the bar plot. The bars are being clipped because the yRange is too short and starts at a location above the minimum data value.


问:
Git ignore trailing whitespace in markdown files only
I have a markdown file with lines that have trailing whitespace (which is correct and should be commited). I'm unable to add these changes using git add -p to the index because git complains about trailing whitespace. They are added correctly if I use git add -A, but I want it to work with git add -p.

I have in my ~/.gitconfig:

```<code>[core]
  whitespace = trailing-space,space-before-tab
</code>```

This has been working fine since for the most part I DO want to warn on trailing whitespace (it is incorrect in HTML, JS and Ruby files).

How do I ignore the trailing whitespace in Markdown files only?

答:
Use this in .gitattributes:

```<code>**/*.md text whitespace=-cr-at-eol,-trailing-space
</code>```

**/*.md  whitespace=space-before-tab does not work. Try this in cmd.exe:

```<code>$ git config --show-origin --get core.whitespace
file:C:/Users/kevin/.gitconfig  trailing-space,space-before-tab,cr-at-eol

$ git init .
Initialized empty Git repository in trailing/.git/

$ cat > README.md
Trailing space here:
check it

$ git add README.md

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

$ echo **/*.md  -whitespace > .gitattributes

$ git check-attr --all -- README.md
README.md: whitespace: unset

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904

$ echo **/*.md  whitespace=space-before-tab > .gitattributes

$ git check-attr --all -- README.md
README.md: whitespace: space-before-tab

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

$ echo **/*.md text whitespace=-cr-at-eol,-trailing-space > .gitattributes

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
</code>```

Body:
I have a markdown file with lines that have trailing whitespace (which is correct and should be commited). I'm unable to add these changes using git add -p to the index because git complains about trailing whitespace. They are added correctly if I use git add -A, but I want it to work with git add -p.

I have in my ~/.gitconfig:

[core]
  whitespace = trailing-space,space-before-tab

This has been working fine since for the most part I DO want to warn on trailing whitespace (it is incorrect in HTML, JS and Ruby files).

How do I ignore the trailing whitespace in Markdown files only?

Body:
Use this in .gitattributes:

**/*.md text whitespace=-cr-at-eol,-trailing-space

**/*.md  whitespace=space-before-tab does not work. Try this in cmd.exe:

$ git config --show-origin --get core.whitespace
file:C:/Users/kevin/.gitconfig  trailing-space,space-before-tab,cr-at-eol

$ git init .
Initialized empty Git repository in trailing/.git/

$ cat > README.md
Trailing space here:
check it

$ git add README.md

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

$ echo **/*.md  -whitespace > .gitattributes

$ git check-attr --all -- README.md
README.md: whitespace: unset

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904

$ echo **/*.md  whitespace=space-before-tab > .gitattributes

$ git check-attr --all -- README.md
README.md: whitespace: space-before-tab

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

$ echo **/*.md text whitespace=-cr-at-eol,-trailing-space > .gitattributes

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904