问:
Library's style attributes have no values even though they are explicitly set
I made a library with a custom view that inflates a layout when created. Views in the layout are styled with style="?attr/labelStyle" or any other attribute.

The attribute is declared the library's attrs.xml:

```<code><attr name="myViewStyle" format="reference"/>

<declare-styleable name="MyView">
    <attr name="labelStyle" format="reference|color"/>
</declare-styleable>
</code>```

I have set a default value to this attribute in the library's styles.xml:

```<code><style name="MyViewStyle">
    <item name="labelStyle">@style/LabelStyle</item>
</style>

<style name="LabelStyle">
    <item name="android:textColor">?android:attr/textColorPrimary</item>
    <item name="...">...</item>
</style>
</code>```

And finally in the library's themes.xml:

```<code><style name="MyViewStyleLight" parent="Theme.AppCompat.Light">
    <item name="myViewStyle">@style/MyViewStyle</item>
</style>
</code>```

Now this was the library's default styles, but it is overridden in the main project styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="myViewStyle">@style/MyViewStyleCustom</item>
</style>

<style name="MyViewStyleCustom" parent="MyViewStyleLight">
    <item name="android:textColor">@color/gray</item>
    <item name="...">...</item>
</style>
</code>```

The custom view code:

```<code>public MyView(Context context) {
    this(context, null, R.attr.myViewStyle, 0);
}

public MyView(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, R.attr.myViewStyle, 0);
}

public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    this(context, attrs, defStyleAttr, 0);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(createThemeWrapper(context, R.attr.myViewStyle, R.style.MyViewStyleLight),
            attrs, defStyleAttr, defStyleRes);
    initLayout();
}

private static Context createThemeWrapper(Context context, int styleAttr, int defaultStyle) {
    final TypedArray ta = context.obtainStyledAttributes(new int[]{styleAttr});
    int style = ta.getResourceId(0, defaultStyle);
    ta.recycle();
    return new ContextThemeWrapper(context, style);
}

private void initLayout() {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    inflater.inflate(R.layout.my_view, this);
    ...
}
</code>```

I explain about the ContextThemeWrapper below. Now the app crashes on the line where the layout gets inflated. Here's the important part of the crash log:

```<code>android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.MyView
      at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
      [...]
    Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f030057 a=-1}
      at android.content.res.TypedArray.getDrawable(TypedArray.java:867)
      [...]
</code>```

The layout inflater can't find the attribute's value. When I tried to get the attribute by code, it returns nothing. The attribute actually exists, only it has no value set to it even though I have clearly set one.

How exactly I am supposed to style my library? I am almost certain that I did every thing the same as the SublimePicker library but it just won't work. There's a little difference in the part with the ContextThemeWrapper, but it probably isn't the problem. I feel like I forgot a tiny thing somewhere that makes the attribute have no value, something is not connected, I don't know.

I know this is a very long question, but it cannot be more concise, I simplified everything as much as I could. I changed most of the information that was in the previous version of my question, making it completely different. The two answers are not relevant at all now, not that they ever were. The bounty was automatically rewarded.

If that could help someone I can add a download to my actual project, but as I said this simplified example has the exact same form as my project.

Body:
I made a library with a custom view that inflates a layout when created. Views in the layout are styled with style="?attr/labelStyle" or any other attribute.

The attribute is declared the library's attrs.xml:

<attr name="myViewStyle" format="reference"/>

<declare-styleable name="MyView">
    <attr name="labelStyle" format="reference|color"/>
</declare-styleable>

I have set a default value to this attribute in the library's styles.xml:

And finally in the library's themes.xml:

Now this was the library's default styles, but it is overridden in the main project styles.xml

The custom view code:

public MyView(Context context) {
    this(context, null, R.attr.myViewStyle, 0);
}

public MyView(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, R.attr.myViewStyle, 0);
}

public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    this(context, attrs, defStyleAttr, 0);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(createThemeWrapper(context, R.attr.myViewStyle, R.style.MyViewStyleLight),
            attrs, defStyleAttr, defStyleRes);
    initLayout();
}

private static Context createThemeWrapper(Context context, int styleAttr, int defaultStyle) {
    final TypedArray ta = context.obtainStyledAttributes(new int[]{styleAttr});
    int style = ta.getResourceId(0, defaultStyle);
    ta.recycle();
    return new ContextThemeWrapper(context, style);
}

private void initLayout() {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    inflater.inflate(R.layout.my_view, this);
    ...
}

I explain about the ContextThemeWrapper below. Now the app crashes on the line where the layout gets inflated. Here's the important part of the crash log:

android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.MyView
      at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
      [...]
    Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f030057 a=-1}
      at android.content.res.TypedArray.getDrawable(TypedArray.java:867)
      [...]

The layout inflater can't find the attribute's value. When I tried to get the attribute by code, it returns nothing. The attribute actually exists, only it has no value set to it even though I have clearly set one.

How exactly I am supposed to style my library? I am almost certain that I did every thing the same as the SublimePicker library but it just won't work. There's a little difference in the part with the ContextThemeWrapper, but it probably isn't the problem. I feel like I forgot a tiny thing somewhere that makes the attribute have no value, something is not connected, I don't know.

I know this is a very long question, but it cannot be more concise, I simplified everything as much as I could. I changed most of the information that was in the previous version of my question, making it completely different. The two answers are not relevant at all now, not that they ever were. The bounty was automatically rewarded.

If that could help someone I can add a download to my actual project, but as I said this simplified example has the exact same form as my project.

Body:
Here's my guess: I suspect that, despite <style> tag you posted above, the attribute is actually not defined when inflating from your library, probably because your library project is using a Context with a "bad" theme when inflating the dialog.

The ?attr syntax means that the value for the variable is read from the context's theme, not from a view's style or attributes. From a Google dev blog post:

This ?attr/ format allows you to pull any attribute out of your theme, making it easy to consolidate your theming into a single place and avoid finding/replacing across many files.

So you have to make sure that you either handle the case where the inflating context's theme does not define this attribute, or only ever inflate this dialog with a theme that defines the attribute.


来源: stackexchange

问:
Visual Studio 2017 .Net Core 2.0 Angular Publish Fails
I am running a Windows 7 Professional PC, using Visual Studio 2017 version 15.4.5. When I created a .Net Core 2.0 project and selected the type of Angular, it ran fine out of the box.

Then I added font awesome and primeng (https://www.primefaces.org/primeng/#/) in what I think is the standard way, i.e., adding references to the package.json file, then to the nonTreeShakableModules section of the webpack.config.vendor.js file, then adding modules to app.module.shared.ts. This was primeng version 5.0.2 and font-awesome version 4.7.0.

In development, all is good - everything is running fine. However, when I try to publish, I see the following lines in the Output window:

```<code>npm install
removed 3 packages in 3.389s
node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod
</code>```

What? Why would it remove 3 packages?

And then the publish attempt fails. After the failure, I see that 3 of my npm packages have been UNINSTALLED:
1) @types/jquery
2) font-awesome
3) primeng

And I see a bunch of "Module not found" errors - of course they are not found, because they were just removed!

I looked at the .csproj file, and I see the following:

```<code><Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec Command="npm install" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --env.prod" />
</code>```

So, as far as I can tell, the "npm install" command, or something triggered by that command, is removing these modules. I have to re-install them after every Publish attempt.

So, my question: Why are these packages being removed, and what can I do about it?

My package.json file:

```<code>{
    "name": "CaseManagementReporting",
    "private": true,
    "version": "0.0.0",
    "scripts": {
        "test": "karma start ClientApp/test/karma.conf.js"
    },
    "dependencies": {
        "@angular/animations": "4.2.5",
        "@angular/common": "4.2.5",
        "@angular/compiler": "4.2.5",
        "@angular/compiler-cli": "4.2.5",
        "@angular/core": "4.2.5",
        "@angular/forms": "4.2.5",
        "@angular/http": "4.2.5",
        "@angular/platform-browser": "4.2.5",
        "@angular/platform-browser-dynamic": "4.2.5",
        "@angular/platform-server": "4.2.5",
        "@angular/router": "4.2.5",
        "@ngtools/webpack": "1.5.0",
        "@types/webpack-env": "1.13.0",
        "angular2-template-loader": "0.6.2",
        "aspnet-prerendering": "^3.0.1",
        "aspnet-webpack": "^2.0.1",
        "awesome-typescript-loader": "3.2.1",
        "bootstrap": "3.3.7",
        "css": "2.2.1",
        "css-loader": "0.28.4",
        "es6-shim": "0.35.3",
        "event-source-polyfill": "0.0.9",
        "expose-loader": "0.7.3",
        "extract-text-webpack-plugin": "2.1.2",
        "file-loader": "0.11.2",
        "font-awesome": "4.7.0",
        "html-loader": "0.4.5",
        "isomorphic-fetch": "2.2.1",
        "jquery": "3.2.1",
        "json-loader": "0.5.4",
        "preboot": "4.5.2",
        "primeng": "5.0.2",
        "raw-loader": "0.5.1",
        "reflect-metadata": "0.1.10",
        "rxjs": "5.4.2",
        "style-loader": "0.18.2",
        "to-string-loader": "1.1.5",
        "typescript": "2.4.1",
        "url-loader": "0.5.9",
        "webpack": "2.5.1",
        "webpack-hot-middleware": "2.18.2",
        "webpack-merge": "4.1.0",
        "zone.js": "0.8.12"
    },
    "devDependencies": {
        "@types/chai": "4.0.1",
        "@types/jasmine": "2.5.53",
        "@types/jquery": "3.2.1",
        "chai": "4.0.2",
        "jasmine-core": "2.6.4",
        "karma": "1.7.0",
        "karma-chai": "0.1.0",
        "karma-chrome-launcher": "2.2.0",
        "karma-cli": "1.0.1",
        "karma-jasmine": "1.1.0",
        "karma-webpack": "2.0.3"
    }
}
</code>```

My tsconfig.json file:

```<code>{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "skipLibCheck": true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
    "strict": true,
    "lib": [ "es6", "dom" ],
    "types": [ "webpack-env", "jquery" ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}
</code>```

My webpack.config.vendor.js file:

```<code>const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
    '@angular/animations',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    'zone.js'
];

const nonTreeShakableModules = [
    'bootstrap',
    'bootstrap/dist/css/bootstrap.css',
    'es6-promise',
    'es6-shim',
    'event-source-polyfill',
    'jquery',
    'font-awesome/css/font-awesome.css',
    'primeng/resources/themes/bootstrap/theme.css',
    'primeng/resources/primeng.min.css',
    'primeng/primeng'
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        resolve: { extensions: [ '.js' ] },
        module: {
            rules: [
                { test: /\.(png|woff|woff2|eot|ttf|svg|jpg|jpeg|gif)(\?|$)/, use: 'url-loader?limit=100000' }
            ]
        },
        output: {
            publicPath: 'dist/',
            filename: '[name].js',
            library: '[name]_[hash]'
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
            new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
            new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
            new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        entry: {
            // To keep development builds fast, include all vendor dependencies in the vendor bundle.
            // But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
            vendor: isDevBuild ? allModules : nonTreeShakableModules
        },
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
            ]
        },
        plugins: [
            extractCSS,
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    const serverBundleConfig = merge(sharedConfig, {
        target: 'node',
        resolve: { mainFields: ['main'] },
        entry: { vendor: allModules.concat(['aspnet-prerendering']) },
        output: {
            path: path.join(__dirname, 'ClientApp', 'dist'),
            libraryTarget: 'commonjs2',
        },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] }
            ]
        },
        plugins: [
            new webpack.DllPlugin({
                path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ]
    });

    return [clientBundleConfig, serverBundleConfig];
}
</code>```

My webpack.config.js file:

```<code>const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};
</code>```

答:
I found a solution for this problem (which sadly just led to another, but...).

I believe that this was/is a bug in the version of NPM which I was using. I had npm version 5.0.3 installed. After hours of searching, I came across this GitHub discussion: here in which many people complained about the npm install command actually removing modules. I downgraded my npm instance from 5.0.3 to 3.10.3 (which is what my home environment was using), and I found that the packages were no longer removed. (Why anybody would write something that would remove packages with a command like "npm install" is utterly beyond me, but read the linked article and you will see the frustration this has caused!)

As a .Net developer, of course, I did not even know how to downgrade my npm instance, so I had to look that up. For those who might be helped, the command is: npm install -g npm@3.10.3. I found that here

So, now my publish process runs without deleting packages, which is what I asked about in my question. That issue is resolved, so I am treating this as an answer.

But this is not to say that the downgrade solved all of my problems. When I attempted to publish, I got new errors, which I think are unrelated to the npm version:

Can't resolve './../$$_gendir/ClientApp/app/app.module.browser.ngfactory' in 'C:\Projects\ForthrightProjects\CaseManagementReporting\CaseManagementReporting\ClientApp' CaseManagementReporting Module not found    0

Can't resolve './../$$_gendir/ClientApp/app/app.module.server.ngfactory' in 'C:\Projects\ForthrightProjects\CaseManagementReporting\CaseManagementReporting\ClientApp'  CaseManagementReporting Module not found    0

Yet more Googling found this article: here
which suggests commenting out this line in the webpack.config.js file:

// { test: /.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },

Or, alternatively, changing it to this:
{ test: /.ts$/, include: /ClientApp/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] },

I tried both options, and both of them worked to get past the errors above. HOWEVER, I now am faced with yet another error in attempting to publish:
ERROR in Metadata version mismatch for module: C:/Projects/ForthrightProjects/CaseManagementReporting/CaseManagementReporting/node_modules/primeng/components/dom/domhandler.d.ts, found version 4, expected 3

So, after some additional searching and trials and errors, I came across this link: here
One of the suggestions there was to change the primeng entry in the project.json file to this: "primeng": "^4.2.4"

Amazingly enough, this actually worked. I am now able to publish. Hopefully successful deployment of the published files will not be so terribly painful.

To .Net developers: Remember back when you just added a package with NuGet, and everything just worked? Sigh...

ContentLicense: CC BY-SA 3.0

Body:
I am running a Windows 7 Professional PC, using Visual Studio 2017 version 15.4.5. When I created a .Net Core 2.0 project and selected the type of Angular, it ran fine out of the box.

Then I added font awesome and primeng (https://www.primefaces.org/primeng/#/) in what I think is the standard way, i.e., adding references to the package.json file, then to the nonTreeShakableModules section of the webpack.config.vendor.js file, then adding modules to app.module.shared.ts. This was primeng version 5.0.2 and font-awesome version 4.7.0.

In development, all is good - everything is running fine. However, when I try to publish, I see the following lines in the Output window:

npm install
removed 3 packages in 3.389s
node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod

What? Why would it remove 3 packages?

And then the publish attempt fails. After the failure, I see that 3 of my npm packages have been UNINSTALLED:
1) @types/jquery
2) font-awesome
3) primeng

And I see a bunch of "Module not found" errors - of course they are not found, because they were just removed!

I looked at the .csproj file, and I see the following:

<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">

    <Exec Command="npm install" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod" />
    <Exec Command="node node_modules/webpack/bin/webpack.js --env.prod" />

So, as far as I can tell, the "npm install" command, or something triggered by that command, is removing these modules. I have to re-install them after every Publish attempt.

So, my question: Why are these packages being removed, and what can I do about it?

My package.json file:

{
    "name": "CaseManagementReporting",
    "private": true,
    "version": "0.0.0",
    "scripts": {
        "test": "karma start ClientApp/test/karma.conf.js"
    },
    "dependencies": {
        "@angular/animations": "4.2.5",
        "@angular/common": "4.2.5",
        "@angular/compiler": "4.2.5",
        "@angular/compiler-cli": "4.2.5",
        "@angular/core": "4.2.5",
        "@angular/forms": "4.2.5",
        "@angular/http": "4.2.5",
        "@angular/platform-browser": "4.2.5",
        "@angular/platform-browser-dynamic": "4.2.5",
        "@angular/platform-server": "4.2.5",
        "@angular/router": "4.2.5",
        "@ngtools/webpack": "1.5.0",
        "@types/webpack-env": "1.13.0",
        "angular2-template-loader": "0.6.2",
        "aspnet-prerendering": "^3.0.1",
        "aspnet-webpack": "^2.0.1",
        "awesome-typescript-loader": "3.2.1",
        "bootstrap": "3.3.7",
        "css": "2.2.1",
        "css-loader": "0.28.4",
        "es6-shim": "0.35.3",
        "event-source-polyfill": "0.0.9",
        "expose-loader": "0.7.3",
        "extract-text-webpack-plugin": "2.1.2",
        "file-loader": "0.11.2",
        "font-awesome": "4.7.0",
        "html-loader": "0.4.5",
        "isomorphic-fetch": "2.2.1",
        "jquery": "3.2.1",
        "json-loader": "0.5.4",
        "preboot": "4.5.2",
        "primeng": "5.0.2",
        "raw-loader": "0.5.1",
        "reflect-metadata": "0.1.10",
        "rxjs": "5.4.2",
        "style-loader": "0.18.2",
        "to-string-loader": "1.1.5",
        "typescript": "2.4.1",
        "url-loader": "0.5.9",
        "webpack": "2.5.1",
        "webpack-hot-middleware": "2.18.2",
        "webpack-merge": "4.1.0",
        "zone.js": "0.8.12"
    },
    "devDependencies": {
        "@types/chai": "4.0.1",
        "@types/jasmine": "2.5.53",
        "@types/jquery": "3.2.1",
        "chai": "4.0.2",
        "jasmine-core": "2.6.4",
        "karma": "1.7.0",
        "karma-chai": "0.1.0",
        "karma-chrome-launcher": "2.2.0",
        "karma-cli": "1.0.1",
        "karma-jasmine": "1.1.0",
        "karma-webpack": "2.0.3"
    }
}

My tsconfig.json file:

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "skipLibCheck": true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
    "strict": true,
    "lib": [ "es6", "dom" ],
    "types": [ "webpack-env", "jquery" ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}

My webpack.config.vendor.js file:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
    '@angular/animations',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    'zone.js'
];

const nonTreeShakableModules = [
    'bootstrap',
    'bootstrap/dist/css/bootstrap.css',
    'es6-promise',
    'es6-shim',
    'event-source-polyfill',
    'jquery',
    'font-awesome/css/font-awesome.css',
    'primeng/resources/themes/bootstrap/theme.css',
    'primeng/resources/primeng.min.css',
    'primeng/primeng'
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        resolve: { extensions: [ '.js' ] },
        module: {
            rules: [
                { test: /\.(png|woff|woff2|eot|ttf|svg|jpg|jpeg|gif)(\?|$)/, use: 'url-loader?limit=100000' }
            ]
        },
        output: {
            publicPath: 'dist/',
            filename: '[name].js',
            library: '[name]_[hash]'
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
            new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
            new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
            new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        entry: {
            // To keep development builds fast, include all vendor dependencies in the vendor bundle.
            // But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
            vendor: isDevBuild ? allModules : nonTreeShakableModules
        },
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
            ]
        },
        plugins: [
            extractCSS,
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    const serverBundleConfig = merge(sharedConfig, {
        target: 'node',
        resolve: { mainFields: ['main'] },
        entry: { vendor: allModules.concat(['aspnet-prerendering']) },
        output: {
            path: path.join(__dirname, 'ClientApp', 'dist'),
            libraryTarget: 'commonjs2',
        },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] }
            ]
        },
        plugins: [
            new webpack.DllPlugin({
                path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ]
    });

    return [clientBundleConfig, serverBundleConfig];
}

My webpack.config.js file:

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

ContentLicense: CC BY-SA 4.0


问:
Is there a more optimal way to concatenate this string
I was wondering if there's a more simple way to concatenate this string instead of declaring a temporary variable

```<code>string tempValue = "000000000000000" + moneyValue;
 moneyValue= tempValue.Substring((tempValue).Length - 15, 15);
</code>```

I'm looking to a shorter way of achieving same result , is there any?

答:
It looks like you are looking for a more succinct way to left-pad a string with zeroes.

.NET has a built-in method for that:

```<code>moneyValue = moneyValue.PadLeft(15, '0');
</code>```

Body:
I was wondering if there's a more simple way to concatenate this string instead of declaring a temporary variable

string tempValue = "000000000000000" + moneyValue;
 moneyValue= tempValue.Substring((tempValue).Length - 15, 15);

I'm looking to a shorter way of achieving same result , is there any?

Body:
It looks like you are looking for a more succinct way to left-pad a string with zeroes.

.NET has a built-in method for that:

moneyValue = moneyValue.PadLeft(15, '0');


问:
Why torrent can't download some files via HTTP?
There is a torrent file in which the web seed is configured. Most files are loaded normally, but when downloading some files (text\american.ini) the connection to the server suddenly terminates and the download stops. This can be checked if, when adding a torrent, select only this file to download. At the same time, this file is loaded normally from the browser. Because of what it can be? Tested on uTorrent and libtorrent.

Here you can download the torrent file and check it personally.

Download

答: The problem was that FileZilla, when downloading some files to FTP, changed them and the torrent considered these files different. Solution: change the transfer mode from ASCII to binary.</p>


问:
Dapper reporting invalid syntax near parameter name when attempting to pass null in a DynamicParameter
I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL and COALESCE are not options here. Changing the schema of the database is not an option either.

This is the code I'm running to try to retrieve the records.

```<code>using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperMCVE
{
    internal class UserFinder
    {
        public static void Main(string[] args)
        {
            using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
            {
                connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
                                        CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
                connection.Execute(@"DELETE Users");
                connection.Execute(@"INSERT INTO Users(NullableUserId)
                                     VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
                var parameters = new DynamicParameters();
                parameters.Add("UserIdNull", (string)null);
                parameters.Add("UserIdBlank", "");
                try
                {
                    var users = connection.Query(@"SELECT *
                                                   FROM Users
                                                   WHERE NullableUserId IS NOT @UserIdNull
                                                     AND NullableUserId != @UserIdBlank", parameters);
                    Console.WriteLine(users.ToList());
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                }
                Console.ReadKey();
            }
        }
    }
}
</code>```

The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.

My assumption is that the above code should replicate this query:

```<code>SELECT *
  FROM Users
  WHERE NullableUserId IS NOT NULL
    AND NullableUserId != ''
</code>```

but it seems to be doing something closer to

```<code>SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
  AND NullableUserId != ''
</code>```

If I change the query to

```<code>SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')
</code>```

it works fine. Unfortunately, I cannot use ISNULL in this case.

I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.

The profiler reports that the following command is being run:

```<code>exec sp_executesql N'SELECT *
                     FROM Users
                     WHERE NullableUserId IS NOT @UserIdNull
                       AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''
</code>```

Which makes me suspect this may be an issue with SQL Server itself?

Things I've tried (to no avail):

Casting the parameter to various nullable types

Using DBNull.Value

答:
You can not use IS NOT and variable. You can hardcode NullableUserId IS NOT NULL if you always expect null.
Or create query text using some string concatenation</p>

Body:
I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL and COALESCE are not options here. Changing the schema of the database is not an option either.

This is the code I'm running to try to retrieve the records.

using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperMCVE
{
    internal class UserFinder
    {
        public static void Main(string[] args)
        {
            using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
            {
                connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
                                        CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
                connection.Execute(@"DELETE Users");
                connection.Execute(@"INSERT INTO Users(NullableUserId)
                                     VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
                var parameters = new DynamicParameters();
                parameters.Add("UserIdNull", (string)null);
                parameters.Add("UserIdBlank", "");
                try
                {
                    var users = connection.Query(@"SELECT *
                                                   FROM Users
                                                   WHERE NullableUserId IS NOT @UserIdNull
                                                     AND NullableUserId != @UserIdBlank", parameters);
                    Console.WriteLine(users.ToList());
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                }
                Console.ReadKey();
            }
        }
    }
}

The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.

My assumption is that the above code should replicate this query:

SELECT *
  FROM Users
  WHERE NullableUserId IS NOT NULL
    AND NullableUserId != ''

but it seems to be doing something closer to

SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
  AND NullableUserId != ''

If I change the query to

SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')

it works fine. Unfortunately, I cannot use ISNULL in this case.

I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.

The profiler reports that the following command is being run:

exec sp_executesql N'SELECT *
                     FROM Users
                     WHERE NullableUserId IS NOT @UserIdNull
                       AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''

Which makes me suspect this may be an issue with SQL Server itself?

Things I've tried (to no avail):

Casting the parameter to various nullable types

Using DBNull.Value


问:
What is the VBA formula to copy and paste the Output from a User Form into multiple rows
I have created a User Form in Excel that follows the following VBA code:

```<code>Private Sub CommandButton1_Click()

If TextBox1.Value = "" Then
    If MsgBox("Form is not complete. Continue?", vbQuestion + vbYesNo) <> vbYes Then
    Exit Sub
    End If
End If

ActiveCell = TextBox1.Value

ActiveCell.Offset(20, 0).Select

Call resetForm

End Sub

Sub resetForm()

TextBox1.Value = ""
UserForm1.TextBox1.SetFocus

End Sub
</code>```

This VBA code provides me the result generated in the User Form in the active cell of the WorkSheet.

I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.

The idea being if a User generates another result through the User Form (command button) will copy and paste this result 18 rows below and then the active cell should be offset to the row below this cell.

答:
Try</p>

```<code>Const NumberOfRows = 18
' ...
Range(ActiveCell, ActiveCell.Offset(NumberOfRows - 1, 0)) = TextBox1.Value
ActiveCell.Offset(NumberOfRows, 0).Activate
</code>```

Body:
I have created a User Form in Excel that follows the following VBA code:

Private Sub CommandButton1_Click()

If TextBox1.Value = "" Then
    If MsgBox("Form is not complete. Continue?", vbQuestion + vbYesNo) <> vbYes Then
    Exit Sub
    End If
End If

ActiveCell = TextBox1.Value

ActiveCell.Offset(20, 0).Select

Call resetForm

End Sub

Sub resetForm()

TextBox1.Value = ""
UserForm1.TextBox1.SetFocus

End Sub

This VBA code provides me the result generated in the User Form in the active cell of the WorkSheet.

I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.

The idea being if a User generates another result through the User Form (command button) will copy and paste this result 18 rows below and then the active cell should be offset to the row below this cell.

Body:
Try

Const NumberOfRows = 18
' ...
Range(ActiveCell, ActiveCell.Offset(NumberOfRows - 1, 0)) = TextBox1.Value
ActiveCell.Offset(NumberOfRows, 0).Activate


问:
Creating text box programmatically and accessing it in another function
```<code>private void AddModuleButton_Click(object sender, EventArgs e)
{
    TextBox[] ModuleNameTF = new TextBox[NoOfModules];
}

private void SummaryViewButton_Click(object sender, EventArgs e)
{

}
</code>```

<p>I have 2 click events. How would I access the textbox that I created from AddModule to the Summaryview? </p>

答:
How would I access the textbox that I created from AddModule to the Summaryview?

Up to now you have not created a single TextBox. You created only a local array that can hold objects of type TextBox. To answer the first part of your question: you need to move the declaration of the array outside of the scope of the AddModuleButton_Click method. The initialization can stay inside:

```<code>TextBox[] ModuleNameTF;

private void AddModuleButton_Click(object sender, EventArgs e)
{
    ModuleNameTF = new TextBox[NoOfModules];
}
</code>```

Now ModuleNameTF becomes accessible throughout the entire class. You just need to use the [ ] operator to index the array:

```<code>private void SummaryViewButton_Click(object sender, EventArgs e)
{
    ModuleNameTF[0].Text = "From SummaryView method";
}
</code>```

Don't forget to fill your array with actual TextBoxes. Otherwise the access in SummaryViewButton_Click will fail.

Body:
private void AddModuleButton_Click(object sender, EventArgs e)
{
    TextBox[] ModuleNameTF = new TextBox[NoOfModules];
}

private void SummaryViewButton_Click(object sender, EventArgs e)
{

}

I have 2 click events. How would I access the textbox that I created from AddModule to the Summaryview?

Body:
How would I access the textbox that I created from AddModule to the Summaryview?

Up to now you have not created a single TextBox. You created only a local array that can hold objects of type TextBox. To answer the first part of your question: you need to move the declaration of the array outside of the scope of the AddModuleButton_Click method. The initialization can stay inside:

TextBox[] ModuleNameTF;

private void AddModuleButton_Click(object sender, EventArgs e)
{
    ModuleNameTF = new TextBox[NoOfModules];
}

Now ModuleNameTF becomes accessible throughout the entire class. You just need to use the [ ] operator to index the array:

private void SummaryViewButton_Click(object sender, EventArgs e)
{
    ModuleNameTF[0].Text = "From SummaryView method";
}

Don't forget to fill your array with actual TextBoxes. Otherwise the access in SummaryViewButton_Click will fail.


问:
Creating a lock on List<String> or Hastable<String,String>
A List of String or Hastable of (String,String) type that contains certain values.
I have situation where multiple threads are running and I want each thread to use only one of the values from the above mentioned lists.

Example:
List - Set1,Set2,Set3

If Thread1 is using Set1 and thread2 tries to use one of the values in the list, It should get only Set2 and Set3 as available. Set1 should be available when Thread1 is done.

答:
you could implement it by locking on the List and removing/adding the appropriate Set before starting/after finishing the work:

```<code>public class ListLock {
    private List<Set<String>> list = new ArrayList<>();

    //initialize with some values
    public ListLock(List<Set<String>> availableValues) {
        this.list = availableValues;
    }

    //this will allow your Thread to get an available value. Your Thread needs to keep the selected value until the job is done and put it back
    public void synchronized aquireValue(Selector selector) {
        //this one is little bit tricky, you provide some interface, that has 1 method, that will call a "select" function on your Thread.
        Set<String> selected = selector.select(list);
        this.list.remove(selected);
    }

    //after job is done, put the value back in the list, so it's available for another Thread
    public void synchronized releaseValue(Set<String> value) {
        this.list.add(value);
    }
}
</code>```

of course you could use generics to make this class more general

Body:
you could implement it by locking on the List and removing/adding the appropriate Set before starting/after finishing the work:

public class ListLock {
    private List<Set<String>> list = new ArrayList<>();

    //initialize with some values
    public ListLock(List<Set<String>> availableValues) {
        this.list = availableValues;
    }

    //this will allow your Thread to get an available value. Your Thread needs to keep the selected value until the job is done and put it back
    public void synchronized aquireValue(Selector selector) {
        //this one is little bit tricky, you provide some interface, that has 1 method, that will call a "select" function on your Thread.
        Set<String> selected = selector.select(list);
        this.list.remove(selected);
    }

    //after job is done, put the value back in the list, so it's available for another Thread
    public void synchronized releaseValue(Set<String> value) {
        this.list.add(value);
    }
}

of course you could use generics to make this class more general


问:
Angular 2 How to Apply Multiple Guards with Or-Relationship on the Same Path
My application allows access to contents based on user roles. I wrote a Router Guard for each role. Some contents allow access for role1 or role2 or role3. How should I write that canActivate declaration in the feature-routing.module.ts file? As I understand, if I write

```<code>canActivate:[Role1Guard, Role2Guard, Role3Guard]
</code>```

The access will be denied if any of the guards returns false. But in my case, I should allow access if any of the guards returns true. How to do it? Many thanks in advance!

答:
What we can do in this case is create a Master Guard which will trigger the application guards as per our requirement.

Checkout this answer to understand the approach.

Assuming you have gone through it above link, the approach in this case could be as simple as modifying the data property in Route class.

Something like this -

```<code>{
    path: "view2",
    component: View2Component,
    //attach master guard here
    canActivate: [MasterGuard],
    //this is the data object which will be used by
    //masteer guard to execute guard1, guard 2, guard 3 & guard 4
    data: {
        trigger: {
            operator: "OR",
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2,
                GUARDS.GUARD3,
                GUARDS.GUARD4
            ]
        }
    }
}
</code>```

And then use operator flag to fire all guards accordingly.

I hope this helps :)

Body:
My application allows access to contents based on user roles. I wrote a Router Guard for each role. Some contents allow access for role1 or role2 or role3. How should I write that canActivate declaration in the feature-routing.module.ts file? As I understand, if I write

canActivate:[Role1Guard, Role2Guard, Role3Guard]

The access will be denied if any of the guards returns false. But in my case, I should allow access if any of the guards returns true. How to do it? Many thanks in advance!

Body:
What we can do in this case is create a Master Guard which will trigger the application guards as per our requirement.

Checkout this answer to understand the approach.

Assuming you have gone through it above link, the approach in this case could be as simple as modifying the data property in Route class.

Something like this -

{
    path: "view2",
    component: View2Component,
    //attach master guard here
    canActivate: [MasterGuard],
    //this is the data object which will be used by
    //masteer guard to execute guard1, guard 2, guard 3 & guard 4
    data: {
        trigger: {
            operator: "OR",
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2,
                GUARDS.GUARD3,
                GUARDS.GUARD4
            ]
        }
    }
}

And then use operator flag to fire all guards accordingly.

I hope this helps :)


问:
customized Doughnut char using charjs
I am using yii2 charjs but not able to customize the Doughnut chart.

Moreover i have tried options from the given document.

```<code><?php echo ChartJs::widget([
        'type' => 'pie',
        'data' => [
            'labels' => ["test","test1","test2","Test4"],

            'datasets' => [
                [
                    'label' => 'level',
                    'data' => [10,20,30,40],
                    'backgroundColor' => "blue",

                ],

            ],
        ],
        'options' => [
            'height' => 200,
            'width' => 500,
        ],
]);?>
</code>```

something like this

Here how can i set separate color for every parts test, test1, test2, test3 respectively green,yellow,blue and red ??

答:
you should add  the cooresponding color</p>

```<code>  'datasets' => [
            [
                'label' => 'level',
                'data' => [10,20,30,40],
                'backgroundColor' => ["green", "yellow","blue" ,"red"],

            ],
</code>```

Title: customized Doughnut char using charjs

Body:
I am using yii2 charjs but not able to customize the Doughnut chart.

Moreover i have tried options from the given document.

<?php echo ChartJs::widget([
        'type' => 'pie',
        'data' => [
            'labels' => ["test","test1","test2","Test4"],

            'datasets' => [
                [
                    'label' => 'level',
                    'data' => [10,20,30,40],
                    'backgroundColor' => "blue",

                ],

            ],
        ],
        'options' => [
            'height' => 200,
            'width' => 500,
        ],
]);?>

something like this

Here how can i set separate color for every parts test, test1, test2, test3 respectively green,yellow,blue and red ??

Body:
you should add  the cooresponding color

  'datasets' => [
            [
                'label' => 'level',
                'data' => [10,20,30,40],
                'backgroundColor' => ["green", "yellow","blue" ,"red"],

            ],


问:
Compilation fails in VS2010 for C++ programs building fine in Linux
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one.

```<code>Error   1   error C2061: syntax error : identifier 'acosf'  c:\program files\microsoft visual studio 10.0\vc\include\cmath  19  1   MyPROJ
</code>```

Also I get many file operations related compilation errors like:

```<code>Error   1   error C3861: 'lseek': identifier not found  g:\project\file.cc  274 1   MyPROJ

Error   2   error C3861: 'write': identifier not found  g:\project\file.cc  275 1   MyPROJ
</code>```

How to eliminate these errors.

答:
You will get better results easier ifyou use some port of gcc compiler for Windows. Try mingw32 or cygwin. Visual Studio is good compiler, but it is not the same as gcc and doesn't have identical libraries, so you will need to rewrite some parts of your source code.

The errors you get are about missing functions.

ContentLicense: CC BY-SA 2.5

Body:
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one.

Error   1   error C2061: syntax error : identifier 'acosf'  c:\program files\microsoft visual studio 10.0\vc\include\cmath  19  1   MyPROJ

Also I get many file operations related compilation errors like:

Error   1   error C3861: 'lseek': identifier not found  g:\project\file.cc  274 1   MyPROJ

Error   2   error C3861: 'write': identifier not found  g:\project\file.cc  275 1   MyPROJ

How to eliminate these errors.


答:
You need to add colors for each label in datasets

```<code>'datasets'=> [{
             'label' => 'level',
             'data' => [10,20,30,40],
            backgroundColor: [
                'rgba(75, 192, 192, 0.2)', // green
                'rgba(255, 206, 86, 0.2)', // yellow
                'rgba(54, 162, 235, 0.2)', // blue
                'rgba(255, 99, 132, 0.2)', // red

            ],
        }]
</code>```

Check this link for more options http://www.chartjs.org/docs/latest/

Title: customized Doughnut char using charjs

Body:
You need to add colors for each label in datasets

'datasets'=> [{
             'label' => 'level',
             'data' => [10,20,30,40],
            backgroundColor: [
                'rgba(75, 192, 192, 0.2)', // green
                'rgba(255, 206, 86, 0.2)', // yellow
                'rgba(54, 162, 235, 0.2)', // blue
                'rgba(255, 99, 132, 0.2)', // red

            ],
        }]

Check this link for more options http://www.chartjs.org/docs/latest/


问:
Woocommerce: Set checkout field values
For a special group of customers that aren't yet WP user in my system, I am directing them to a special page, where they'll choose from a limited set of products. I already have all of their information and I it's going to pre-populate on this landing page. When they've verified their information, it will add their product to the cart and skip straight to the checkout. I've got all that down so far.

What I want to do is pre-populate the checkout data with the customer name and billing information that I have and I'm not entirely certain how to do that. But here's what I've got so far:

```<code>    function onboarding_update_fields( $fields = array() ) {

      $token = ( ! empty( $_GET['token'] ) ) ? $_GET['token'] : '';
      if( 'testtoken' == $token ) {
        $fields['billing']['billing_first_name']['value'] = 'Joe';
        var_dump( $fields );
      }
      return $fields;
     }

    add_filter( 'woocommerce_checkout_fields', 'onboarding_update_fields' );
</code>```

How do I change the value of the checkout fields? The code above doesn't do it. Point me in the right direction on one, and I can do the rest.

I looked here but didn't quite find what I was looking for either.

Thanks!

答:
Please use 'default', like:

```<code>$fields['billing']['billing_first_name']['default'] = "Thomas";
</code>```

Refer to WooCommerce | Set billing field value

Title: Woocommerce: Set checkout field values

Body:
For a special group of customers that aren't yet WP user in my system, I am directing them to a special page, where they'll choose from a limited set of products. I already have all of their information and I it's going to pre-populate on this landing page. When they've verified their information, it will add their product to the cart and skip straight to the checkout. I've got all that down so far.

What I want to do is pre-populate the checkout data with the customer name and billing information that I have and I'm not entirely certain how to do that. But here's what I've got so far:

    function onboarding_update_fields( $fields = array() ) {

      $token = ( ! empty( $_GET['token'] ) ) ? $_GET['token'] : '';
      if( 'testtoken' == $token ) {
        $fields['billing']['billing_first_name']['value'] = 'Joe';
        var_dump( $fields );
      }
      return $fields;
     }

    add_filter( 'woocommerce_checkout_fields', 'onboarding_update_fields' );

How do I change the value of the checkout fields? The code above doesn't do it. Point me in the right direction on one, and I can do the rest.

I looked here but didn't quite find what I was looking for either.

Thanks!

Body:
Please use 'default', like:

$fields['billing']['billing_first_name']['default'] = "Thomas";

Refer to WooCommerce | Set billing field value


问:
Getting the date goes back one day
I have an entity with the field

```<code>public class MovieReleaseDateEntity {
     @Basic
     @Column(name = "release_date")
     @Temporal(TemporalType.DATE)
     private Date date;
}
</code>```

I save the date in the database

```<code>https://zapodaj.net/14dfcfb70926a.png.html
</code>```

I get it after downloading it from the database

```<code>"date": "2017-12-06T23:00:00.000+0000"
</code>```

The date is withdrawn by one day. Why?

答:
It does not revert the day back, it retrieves the date in a different timezone, one hour less and it shows as a day before (so 2017-12-07 00:00:00 becomes 2017-12-06 23:00:00). java.date and java.sql packages that you are probably using are just wrappers around milliseconds represented as Longs so timezone is also needed.

Check your time zone and check the timezone of your server and make sure they match. If you cannot change it for any reason, you can use date formatters to parse the time in a specific timezone when retrieving from the database

Title: Getting the date goes back one day

Body:
I have an entity with the field

public class MovieReleaseDateEntity {
     @Basic
     @Column(name = "release_date")
     @Temporal(TemporalType.DATE)
     private Date date;
}

I save the date in the database

https://zapodaj.net/14dfcfb70926a.png.html

I get it after downloading it from the database

"date": "2017-12-06T23:00:00.000+0000"

The date is withdrawn by one day. Why?


问:
hg Mercurial repo size / file size / file size in commits
1) How to get the list of files with their sizes of some commit through command line like this:

```<code>hg files --template "{name} {length}\n"
</code>```

2) How to get the size of Mercurial through command line like this:

```<code>hg size my_directory
</code>```

答:
To my knowledge there's no straight forward way without any external utilities.

Make use of the appropriate OS utilities, answering both of your question at once (should work on *nix and OSX):

```<code>hg files -rXXX | xargs du -h
</code>```

Body:
1) How to get the list of files with their sizes of some commit through command line like this:

hg files --template "{name} {length}\n"

2) How to get the size of Mercurial through command line like this:

hg size my_directory

Body:
To my knowledge there's no straight forward way without any external utilities.

Make use of the appropriate OS utilities, answering both of your question at once (should work on *nix and OSX):

hg files -rXXX | xargs du -h


问:
When will Spark clean the cached RDDs automatically?
The RDD, which have been cached used the rdd.cache() method from the scala terminal, are being stored in the memory.

That means it will consume some part of the ram being available for the Spark process itself.

Having said that if the ram is being limited, and more and more RDDs have been cached, when will spark clean the memory automatically which has been occupied by the rdd cache?

答:
Spark will clean cached RDDs and Datasets / DataFrames:

When it is explicitly asked to by calling RDD.unpersist (How to uncache RDD?) / Dataset.unpersist methods or Catalog.clearCache.

In regular intervals, by the cache cleaner:

Spark automatically monitors cache usage on each node and drops out old data partitions in a least-recently-used (LRU) fashion. If you would like to manually remove an RDD instead of waiting for it to fall out of the cache, use the RDD.unpersist() method.

When corresponding distributed data structure is garbage collected.


问:
How to import experiment data to an Excel file?
I'm writing my first experiment on Python. I have created my experiment using Psychopy and everything is working but I'm having problems to import the data from my experiment in Python to an Excel file.

My Excel file is blank once I'm done running my experiment. I will share the lines of code in which I try to import the data to Excel.

Thank you for your help!

```<code>df = pandas.DataFrame(columns=['answer', 'correctness', 'RT'])
df.loc[csvcounter] = [user_response[0][0], correctness, user_response[0][1]] #[0],[0] ... [0][1]
df = pandas.DataFrame(columns=['answer', 'correctness', 'RT'])
df.to_csv(FILE_DIR + r"/Experiment.csv")
</code>```

答:
Your third line creates a new empty DataFrame and overwrites the variable with the filled DataFrame. Next, you write the empty DataFrame to a csv file.

Answer to question in the comments:

Depends how your experiment's data is structured. But here's an example for numpy.ndarray: Assume we got data with 1) the participants number, 2) their gender and 3) their age:

```<code>import numpy as np
import pandas as pd

data = np.array([[1,2,3,4], ['M', 'F', 'F', 'M'], [18, 21, 35, 27]]).T
</code>```

so data now looks like this:

```<code>array([['1', 'M', '18'],
       ['2', 'F', '21'],
       ['3', 'F', '35'],
       ['4', 'M', '27']], ='<U11')
</code>```

now we create an empty DataFrame similar to what  you did:

```<code>df = pd.DataFrame({'number':[], 'gender':[], 'age':[]})
</code>```

and write the ndarray to it:

```<code>df[['number', 'gender', 'age']] = data
</code>```

And if you write this DataFrame to a file it should contain the 4 people:

```<code>df.to_csv(FILE_DIR + r"/Experiment.csv")
</code>```

Body:
I'm writing my first experiment on Python. I have created my experiment using Psychopy and everything is working but I'm having problems to import the data from my experiment in Python to an Excel file.

My Excel file is blank once I'm done running my experiment. I will share the lines of code in which I try to import the data to Excel.

Thank you for your help!

df = pandas.DataFrame(columns=['answer', 'correctness', 'RT'])
df.loc[csvcounter] = [user_response[0][0], correctness, user_response[0][1]] #[0],[0] ... [0][1]
df = pandas.DataFrame(columns=['answer', 'correctness', 'RT'])
df.to_csv(FILE_DIR + r"/Experiment.csv")

Body:
Your third line creates a new empty DataFrame and overwrites the variable with the filled DataFrame. Next, you write the empty DataFrame to a csv file.

Answer to question in the comments:

Depends how your experiment's data is structured. But here's an example for numpy.ndarray: Assume we got data with 1) the participants number, 2) their gender and 3) their age:

import numpy as np
import pandas as pd

data = np.array([[1,2,3,4], ['M', 'F', 'F', 'M'], [18, 21, 35, 27]]).T

so data now looks like this:

array([['1', 'M', '18'],
       ['2', 'F', '21'],
       ['3', 'F', '35'],
       ['4', 'M', '27']], ='<U11')

now we create an empty DataFrame similar to what  you did:

df = pd.DataFrame({'number':[], 'gender':[], 'age':[]})

and write the ndarray to it:

df[['number', 'gender', 'age']] = data

And if you write this DataFrame to a file it should contain the 4 people:

df.to_csv(FILE_DIR + r"/Experiment.csv")


问:
Socket read and unknown length data
I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

```<code>static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}
</code>```

fd in this case is FILENO_STDIN

答: Just read by some blocks (buffers) until it returns 0 or you'll see that there is an end of the data according to the protocol.</p>

Title: Socket read and unknown length data

Body:
I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}

fd in this case is FILENO_STDIN


问:
Python: how to increment number and store in variable every time function runs
(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

```<code>    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)
</code>```

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

答:
What do you think about this solution?

If you put here while loop you will forced on user to put correct answer.

Also i placed between if/elif/else statements input function.

count - That variable is counting wrong options

```<code>choice = int(input("> "))
count =0
while choice !=3:
    if choice == 1:
        print("This is the wrong hall.")
        count += 1
        choice = int(input("> ")) # Also i place in the if/elif/else statements input function
    elif choice == 2:
        print("This is the wrong hall.")
        count +=1
        choice = int(input("> "))
    elif choice == 3:
        hall_passage()
    else:
        end("You failed")
        count += 1
        choice = int(input("> "))

print(count)
</code>```

Body:
(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

Body:
What do you think about this solution?

If you put here while loop you will forced on user to put correct answer.

Also i placed between if/elif/else statements input function.

count - That variable is counting wrong options

choice = int(input("> "))
count =0
while choice !=3:
    if choice == 1:
        print("This is the wrong hall.")
        count += 1
        choice = int(input("> ")) # Also i place in the if/elif/else statements input function
    elif choice == 2:
        print("This is the wrong hall.")
        count +=1
        choice = int(input("> "))
    elif choice == 3:
        hall_passage()
    else:
        end("You failed")
        count += 1
        choice = int(input("> "))

print(count)


问:
Debugging Internet Explorer in windbg
I was doing some crash analysis using windbg. Suppose the stack trace indicates the crash is at mshtml!CBase::put_String ,is there a way to figure out what javascript or DOM manipulation leads to the function?</p>

答:
Based on the stack you can sometimes make a pretty good guess.  Since you only get public symbols you don't have the ability to easily get detailed information about the internal state of the objects.  If you post your whole stack I may be able to help you figure it out.

If there is some identifying characteristic, you may be able to call the getter.  You can use .call to do that.  See Raymonds post describing .call.

If you think you've found a real bug in IE, you can always post it to http://connect.microsoft.com/ie for the IE team to have a look at.  Be sure to include a link to the site or minimal HTML repro...

Title: Debugging Internet Explorer in windbg


问:
android cordova-media-plugin don't demand audio focus
I am making a dirt simple app for myself because I would like to play the sound of rain at the same time as listening to an audiobook in another app.

As I understand it, there's something in java land that does a requestAudioFocus. Snippet from cordova-plugin-media:

```<code>AudioManager am = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
        int result = am.requestAudioFocus(focusChangeListener,
                                          AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
</code>```

Years ago, I could make most apps play audio at the same time. I thought maybe this has just become 'best practice' to not play audio at the same time (battery life reasons, or something like that), but if it's just an app for me, that's not a concern.

I thought I could solve this just by taking this plugin and not demanding audio focus, but it looks like that's implicit. Is there a way to say not to? So if I start playing an audio book in another app, my app won't pause it when it starts playing rain sounds?

Can it be done from Javascript, can I edit the java plugin? (Not a java programmer). Or is this perhaps just imposed by the current android OS?

Here is my code, though it does nothing interesting:

```<code>var path = '/android_asset/www/rain.mp3';

var media = new Media( path,
                       ()  => alert('success'),
                       err => document.body.innerHTML = JSON.stringify(err) );
media.play({ numberOfLoops: 10, playAudioWhenScreenIsLocked : true });
</code>```

Thanks in advance,

答:
The Cordova plugin you mention indeed requests audio focus when it starts playing the stream: see startPlayingAudio() [Github link] and Android AudioFocusRequest documentation

This means that when you start your app, it will automatically ask the audiobook app to pause.

It would be helpful if it would be possible to also request for instance AUDIOFOCUS_GAIN_TRANSIENT if you want your app to only provide small sound effects or spoken hints, and have that not stop an app as Spotify playing in the background; this plugin does not provide such functionality.

You could modify this plugin so you can make getting audio focus optional, or TRANSIENT; or you could decide to write your 'dirt simple' app in native Android so you have more direct control over the APIs.

Body:
I am making a dirt simple app for myself because I would like to play the sound of rain at the same time as listening to an audiobook in another app.

As I understand it, there's something in java land that does a requestAudioFocus. Snippet from cordova-plugin-media:

AudioManager am = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
        int result = am.requestAudioFocus(focusChangeListener,
                                          AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);

Years ago, I could make most apps play audio at the same time. I thought maybe this has just become 'best practice' to not play audio at the same time (battery life reasons, or something like that), but if it's just an app for me, that's not a concern.

I thought I could solve this just by taking this plugin and not demanding audio focus, but it looks like that's implicit. Is there a way to say not to? So if I start playing an audio book in another app, my app won't pause it when it starts playing rain sounds?

Can it be done from Javascript, can I edit the java plugin? (Not a java programmer). Or is this perhaps just imposed by the current android OS?

Here is my code, though it does nothing interesting:

var path = '/android_asset/www/rain.mp3';

var media = new Media( path,
                       ()  => alert('success'),
                       err => document.body.innerHTML = JSON.stringify(err) );
media.play({ numberOfLoops: 10, playAudioWhenScreenIsLocked : true });

Thanks in advance,


问:
Shuffling the items in a ListBox
I have a system that contains integers in a ListBox. I have included a 'Shuffle' Button, which should shuffle the stored items in the ListBox into a random order, when clicked by the user.

However, the code I am using is not working for this. Has anyone got any suggestions on how to generate a shuffle button to randomize the data within a ListBox?

答:
Make your life a bit easier, use a DataTable to hold your list items, give it another column that you can sort:

```<code>//this is a class wide variable
DataTable _d = new DataTable();

//in your constructor
_d.Columns.Add("DisplayThis");
_d.Columns.Add("SortThis", typeof(int));

_d.DefaultView.Sort = "[SortThis] ASC";

yourListBox.DataSource = _d.DefaultView;
yourListBox.DisplayMember = "DisplayThis";

//in your method that formerly loaded the listbox items
Random r = new Random();
foreach(string s in yourListItemsToDisplayArray)
  d.Rows.Add(new object[] { s, (int)r.Next(1000) });

//or if the listbox is to show numbers
Random r = new Random();
foreach(int i in yourListItemsToDisplayArray)
  d.Rows.Add(new object[] { i.ToString(), (int)r.Next(1000) });
</code>```

And every time you want to shuffle them, just pass over the datatable, changing the numbers:

```<code>//your shuffle button click handler
shuffleButton_Click(object sender, ClickEventArgs e){
  Random r = new Random();
  foreach(var ro in _d.Rows)
    ro["SortThis"] = r.Next(1000);
}
</code>```

Title: Shuffling the items in a ListBox

Body:
Make your life a bit easier, use a DataTable to hold your list items, give it another column that you can sort:

//this is a class wide variable
DataTable _d = new DataTable();

//in your constructor
_d.Columns.Add("DisplayThis");
_d.Columns.Add("SortThis", typeof(int));

_d.DefaultView.Sort = "[SortThis] ASC";

yourListBox.DataSource = _d.DefaultView;
yourListBox.DisplayMember = "DisplayThis";

//in your method that formerly loaded the listbox items
Random r = new Random();
foreach(string s in yourListItemsToDisplayArray)
  d.Rows.Add(new object[] { s, (int)r.Next(1000) });

//or if the listbox is to show numbers
Random r = new Random();
foreach(int i in yourListItemsToDisplayArray)
  d.Rows.Add(new object[] { i.ToString(), (int)r.Next(1000) });

And every time you want to shuffle them, just pass over the datatable, changing the numbers:

//your shuffle button click handler
shuffleButton_Click(object sender, ClickEventArgs e){
  Random r = new Random();
  foreach(var ro in _d.Rows)
    ro["SortThis"] = r.Next(1000);
}


问:
Pen tool Scaling (Silverlight, Expression Blend)
I have a custom shape which is drawn out by the pen tool.  For example, lets pretend I drew a trapezoid.  When you scale the object, the whole thing gets resized appropriately.

My question is: When I scale it width-wise, I only want the top and the bottom edges to expand.  I do not want the 'diagonal' edges to be changed.  What is the easiest way to go about doing this?

答: Right-click the Path in Objects and Timeline and select Group Into -> Grid.  Then pick the Path again and change its HorizontalAlignment to Center.  Now resizing the width of the Grid will not distort the Path.


问:
Recursion Limit Exceeded in javascriptSerializer.serialize
I'm using JavascriptSerializer to convert the list into string, but its not working and its throwing an error as Recursion Limit Exceeded. I have searched a lot but i didn't found any solutions to overcome this issue.

My conversion is like below

```<code>List<CustomType> _customValues= serializer.ConvertToType<List<CustomType>>(dictionary["CustomValues"]);
string CustomString = new JavaScriptSerializer().Serialize(_customValues);
</code>```

EDIT

My custom type is below

```<code> public class CustomType
    {
        private string _name;
        public string Name
        {
            get
            { return _name; }
            set
            {
                if (this._name != value)
                {
                    this._name= value;
                }
            }
        }

        private double _mark;
        public double Mark
        {
            get
            { return _mark; }
            set
            {
                if (this._mark!= value)
                {
                    this._mark= value;
                }
            }
        }

        private int _id;
        public int Id
        {
            get
            { return _id; }
            set
            {
                if (this._id!= value)
                {
                    this._id= value;
                }
            }
        }

    }
</code>```

How can i convert that list into string?.
How can i overcome this issue?.

Thanks,

Karthik

答: Use a JSON Serializer that ignores circular references. System.Web.Script.Serialization.JavaScriptSerializer can't ignore circular references and will easily get stuck in recursion and reach recursion limit.

Body:
I'm using JavascriptSerializer to convert the list into string, but its not working and its throwing an error as Recursion Limit Exceeded. I have searched a lot but i didn't found any solutions to overcome this issue.

My conversion is like below

List<CustomType> _customValues= serializer.ConvertToType<List<CustomType>>(dictionary["CustomValues"]);
string CustomString = new JavaScriptSerializer().Serialize(_customValues);

EDIT

My custom type is below

 public class CustomType
    {
        private string _name;
        public string Name
        {
            get
            { return _name; }
            set
            {
                if (this._name != value)
                {
                    this._name= value;
                }
            }
        }

        private double _mark;
        public double Mark
        {
            get
            { return _mark; }
            set
            {
                if (this._mark!= value)
                {
                    this._mark= value;
                }
            }
        }

        private int _id;
        public int Id
        {
            get
            { return _id; }
            set
            {
                if (this._id!= value)
                {
                    this._id= value;
                }
            }
        }

    }

How can i convert that list into string?.
How can i overcome this issue?.

Thanks,

Karthik


问:
Is `-1` correct for using as maximum value of an unsigned integer?
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

```<code>unsigned short i = -1; // unsigned short max
</code>```

can easily be changed to any other type, like

```<code>unsigned long i = -1; // unsigned long max
</code>```

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

答:
Regarding conversions of integers, C 2011 [draft N1570] 6.3.1.3 2 says

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Thus, converting -1 to an unsigned integer type necessarily produces the maximum value of that type.

There may be issues with using -1 in various contexts where it is not immediately converted to the desired type. If it is immediately converted to the desired unsigned integer type, as by assignment or explicit conversion, then the result is clear. However, if it is a part of an expression, its type is int, and it behaves like an int until converted. In contrast, UINT_MAX has the type unsigned int, so it behaves like an unsigned int.

As chux points out in a comment, USHRT_MAX effectively has a type of int, so even the named limits are not fully safe from type issues.

Body:
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

unsigned short i = -1; // unsigned short max

can easily be changed to any other type, like

unsigned long i = -1; // unsigned long max

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.


问:
Dapper reporting invalid syntax near parameter name when attempting to pass null in a DynamicParameter
I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL and COALESCE are not options here. Changing the schema of the database is not an option either.

This is the code I'm running to try to retrieve the records.

```<code>using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperMCVE
{
    internal class UserFinder
    {
        public static void Main(string[] args)
        {
            using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
            {
                connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
                                        CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
                connection.Execute(@"DELETE Users");
                connection.Execute(@"INSERT INTO Users(NullableUserId)
                                     VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
                var parameters = new DynamicParameters();
                parameters.Add("UserIdNull", (string)null);
                parameters.Add("UserIdBlank", "");
                try
                {
                    var users = connection.Query(@"SELECT *
                                                   FROM Users
                                                   WHERE NullableUserId IS NOT @UserIdNull
                                                     AND NullableUserId != @UserIdBlank", parameters);
                    Console.WriteLine(users.ToList());
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                }
                Console.ReadKey();
            }
        }
    }
}
</code>```

The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.

My assumption is that the above code should replicate this query:

```<code>SELECT *
  FROM Users
  WHERE NullableUserId IS NOT NULL
    AND NullableUserId != ''
</code>```

but it seems to be doing something closer to

```<code>SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
  AND NullableUserId != ''
</code>```

If I change the query to

```<code>SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')
</code>```

it works fine. Unfortunately, I cannot use ISNULL in this case.

I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.

The profiler reports that the following command is being run:

```<code>exec sp_executesql N'SELECT *
                     FROM Users
                     WHERE NullableUserId IS NOT @UserIdNull
                       AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''
</code>```

Which makes me suspect this may be an issue with SQL Server itself?

Things I've tried (to no avail):

Casting the parameter to various nullable types

Using DBNull.Value

答:
You cannot use IS NOT and parameter in sp_executesql or anywhere else.

Look at this example.

This query returns 4 records from my table :

```<code>exec sp_executesql
N'SELECT * FROM tblUser WHERE gsm IS NOT null AND gsm != '''''
</code>```

So now I try it with parameters for both values, and now I get an error

```<code>exec sp_executesql
N'SELECT * FROM tblUser WHERE gsm IS NOT @UserIdNull AND gsm <> @UserIdBlank',
N'@UserIdNull nvarchar(100),@UserIdBlank nvarchar(100)',
@UserIdNull=NULL,@UserIdBlank=N''
</code>```

but now I get the error

Incorrect syntax near '@UserIdNull'

It will give the same error when you do it without sp_executesql

```<code>declare @UserIdNull nvarchar(100) = null
declare @UserIdBlank nvarchar(100) = ''
SELECT * FROM tblUser WHERE gsm IS NOT @UserIdNull AND gsm <> @UserIdBlank
</code>```

This produces the same error

So the only option you have is to build your query without a parameter for the IS NOT value or use ISNULL()

In the query you build in your question, you known when to write IS NOT and then followed by a parameter.

I suggest to simply write IS NOT NULL in stead of using a parameter there

Body:
I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL and COALESCE are not options here. Changing the schema of the database is not an option either.

This is the code I'm running to try to retrieve the records.

using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperMCVE
{
    internal class UserFinder
    {
        public static void Main(string[] args)
        {
            using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
            {
                connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
                                        CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
                connection.Execute(@"DELETE Users");
                connection.Execute(@"INSERT INTO Users(NullableUserId)
                                     VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
                var parameters = new DynamicParameters();
                parameters.Add("UserIdNull", (string)null);
                parameters.Add("UserIdBlank", "");
                try
                {
                    var users = connection.Query(@"SELECT *
                                                   FROM Users
                                                   WHERE NullableUserId IS NOT @UserIdNull
                                                     AND NullableUserId != @UserIdBlank", parameters);
                    Console.WriteLine(users.ToList());
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                }
                Console.ReadKey();
            }
        }
    }
}

The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.

My assumption is that the above code should replicate this query:

SELECT *
  FROM Users
  WHERE NullableUserId IS NOT NULL
    AND NullableUserId != ''

but it seems to be doing something closer to

SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
  AND NullableUserId != ''

If I change the query to

SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')

it works fine. Unfortunately, I cannot use ISNULL in this case.

I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.

The profiler reports that the following command is being run:

exec sp_executesql N'SELECT *
                     FROM Users
                     WHERE NullableUserId IS NOT @UserIdNull
                       AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''

Which makes me suspect this may be an issue with SQL Server itself?

Things I've tried (to no avail):

Casting the parameter to various nullable types

Using DBNull.Value

Body:
You cannot use IS NOT and parameter in sp_executesql or anywhere else.

Look at this example.

This query returns 4 records from my table :

exec sp_executesql
N'SELECT * FROM tblUser WHERE gsm IS NOT null AND gsm != '''''

So now I try it with parameters for both values, and now I get an error

exec sp_executesql
N'SELECT * FROM tblUser WHERE gsm IS NOT @UserIdNull AND gsm <> @UserIdBlank',
N'@UserIdNull nvarchar(100),@UserIdBlank nvarchar(100)',
@UserIdNull=NULL,@UserIdBlank=N''

but now I get the error

Incorrect syntax near '@UserIdNull'

It will give the same error when you do it without sp_executesql

declare @UserIdNull nvarchar(100) = null
declare @UserIdBlank nvarchar(100) = ''
SELECT * FROM tblUser WHERE gsm IS NOT @UserIdNull AND gsm <> @UserIdBlank

This produces the same error

So the only option you have is to build your query without a parameter for the IS NOT value or use ISNULL()

In the query you build in your question, you known when to write IS NOT and then followed by a parameter.

I suggest to simply write IS NOT NULL in stead of using a parameter there