问:
Extending Func to accept array parameter in C#
I have been using Func to create

```<code>Expression.Lambda<Func<object, object>>(block, paramValues).Compile();
</code>```

Where block is Expression.Block that creates the required execution plan. paramValues is an array of Expression.Parameter values:

```<code> var paramValues = epDef.Value.Parameters.Select(p => Expression.Parameter(typeof(object), p.Name))
            .ToArray();
</code>```

I am trying to modify this to accept an array, so that I can use Func when I have more than 16 input parameters:

```<code>Expression.Lambda<Func<object[], object>>(block, paramValues).Compile();
</code>```

However this gives me the following error:

```<code>Incorrect number of parameters supplied for lambda declaration
</code>```

Can anyone help me with using Func to accept more than 16 parameters in this case? either using an array as input or by creating a custom delegate

@MethodMan:

I tried to implement the solution in that question, but I am getting the same error. From what I understood, changing the Expression.Parameter from typeof(object) to typeof(object[]) should have worked in my case, but I get the same error

EDIT:

Here's the modified version of what I tried from the linked version:

```<code>class Program
    {
        static void Main(string[] argas)
        {
            Type[] types = new Type[] { typeof(object[]) };

            var constructorInfo = typeof(Program).GetConstructor(types);
            var parameters = types.Select((t, i) => Expression.Parameter(t, "p" + i)).ToArray();
            var someType1Exp = Expression.New(constructorInfo, parameters);
            var inner = Expression.Lambda(someType1Exp, parameters);

            var args = Expression.Parameter(typeof(object[]), "args");
            var body = Expression.Invoke(inner,
                parameters.Select((p, i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), p.Type)).ToArray());
            var outer = Expression.Lambda<Func<object[], object>>(body, args);
            var func = outer.Compile();

            object[] values = { 1, 123.45F, "abc" };
            object obj = func(values);
            Console.WriteLine(obj);
            Console.WriteLine("test");
            Console.ReadLine();
        }
        //public Program() { }
        public Program(object[] values) { Console.WriteLine(values.ToString()); }

    }
</code>```

I get the following error:

```<code>System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Object[]'.'
</code>```

答:
You're problem is you changed your lambda to take a single array argument, object[] but you are still passing in multiple arguments (paramValues). You need to pass in a single value, the Array. You will also need to modify your expression body to expect an array.

Consider before you had the equivalent of

```<code>(a,b,c,d) => new Program(a, b, c, d)
</code>```

Now you want

```<code>(object[] a) => new Program((type0)a[0], (type1)a[1], (type2)a[2], (type3)a[3])
</code>```

So you need to modify your code to reference the elements of the parameter array instead of the parameters directly:

```<code>class Program
    {
        static void Main(string[] argas)
        {
            var constructorInfo = typeof(Program).GetConstructors()[0];
            var types = constructorInfo.GetParameters().Select(p => p.ParameterType);
            var parm = Expression.Parameter(typeof(object[]), "args");
            var parameters = types.Select((t, i) => Expression.Convert(Expression.ArrayIndex(parm, Expression.Constant(i)), t)).ToArray();
            var someType1Exp = Expression.New(constructorInfo, parameters);
            var outer = Expression.Lambda<Func<object[], object>>(someType1Exp, parm);
            var func = outer.Compile();

            object[] values = { 1, 123.45F, "abc" };
            object obj = func(values);
            Console.WriteLine(obj);
            Console.WriteLine("test");
            Console.ReadLine();
        }

        //public Program() { }
        public Program(int val1, float val2, string val3) {
            Console.WriteLine(val1);
            Console.WriteLine(val2);
            Console.WriteLine(val3);
        }
    }
</code>```

If you want to pass the object[] to the constructor, as in

```<code>(object[] args) => new Program(args)
</code>```

you can just do that directly (sorry for formatting, copied from my LINQPad):

```<code>public class Program  {
void Main() {
    var constructorInfo = typeof(Program).GetConstructors()[0];
    var parm = Expression.Parameter(typeof(object[]), "args");
    var someType1Exp = Expression.New(constructorInfo, parm);
    var outer = Expression.Lambda<Func<object[], object>>(someType1Exp, parm);
    var func = outer.Compile();

    object[] values = { 1, 123.45F, "abc" };
    object obj = func(values);
    Console.WriteLine(obj);
    Console.WriteLine("test");
}

// Define other methods and classes here
    public Program(object[] parms) {
        Console.WriteLine(parms.ToString());
    }
}
</code>```

Body:
I have been using Func to create

Expression.Lambda<Func<object, object>>(block, paramValues).Compile();

Where block is Expression.Block that creates the required execution plan. paramValues is an array of Expression.Parameter values:

 var paramValues = epDef.Value.Parameters.Select(p => Expression.Parameter(typeof(object), p.Name))
            .ToArray();

I am trying to modify this to accept an array, so that I can use Func when I have more than 16 input parameters:

Expression.Lambda<Func<object[], object>>(block, paramValues).Compile();

However this gives me the following error:

Incorrect number of parameters supplied for lambda declaration

Can anyone help me with using Func to accept more than 16 parameters in this case? either using an array as input or by creating a custom delegate

@MethodMan:

I tried to implement the solution in that question, but I am getting the same error. From what I understood, changing the Expression.Parameter from typeof(object) to typeof(object[]) should have worked in my case, but I get the same error

EDIT:

Here's the modified version of what I tried from the linked version:

class Program
    {
        static void Main(string[] argas)
        {
            Type[] types = new Type[] { typeof(object[]) };

            var constructorInfo = typeof(Program).GetConstructor(types);
            var parameters = types.Select((t, i) => Expression.Parameter(t, "p" + i)).ToArray();
            var someType1Exp = Expression.New(constructorInfo, parameters);
            var inner = Expression.Lambda(someType1Exp, parameters);

            var args = Expression.Parameter(typeof(object[]), "args");
            var body = Expression.Invoke(inner,
                parameters.Select((p, i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), p.Type)).ToArray());
            var outer = Expression.Lambda<Func<object[], object>>(body, args);
            var func = outer.Compile();

            object[] values = { 1, 123.45F, "abc" };
            object obj = func(values);
            Console.WriteLine(obj);
            Console.WriteLine("test");
            Console.ReadLine();
        }
        //public Program() { }
        public Program(object[] values) { Console.WriteLine(values.ToString()); }

    }

I get the following error:

System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Object[]'.'

Body:
You're problem is you changed your lambda to take a single array argument, object[] but you are still passing in multiple arguments (paramValues). You need to pass in a single value, the Array. You will also need to modify your expression body to expect an array.

Consider before you had the equivalent of

(a,b,c,d) => new Program(a, b, c, d)

Now you want

(object[] a) => new Program((type0)a[0], (type1)a[1], (type2)a[2], (type3)a[3])

So you need to modify your code to reference the elements of the parameter array instead of the parameters directly:

class Program
    {
        static void Main(string[] argas)
        {
            var constructorInfo = typeof(Program).GetConstructors()[0];
            var types = constructorInfo.GetParameters().Select(p => p.ParameterType);
            var parm = Expression.Parameter(typeof(object[]), "args");
            var parameters = types.Select((t, i) => Expression.Convert(Expression.ArrayIndex(parm, Expression.Constant(i)), t)).ToArray();
            var someType1Exp = Expression.New(constructorInfo, parameters);
            var outer = Expression.Lambda<Func<object[], object>>(someType1Exp, parm);
            var func = outer.Compile();

            object[] values = { 1, 123.45F, "abc" };
            object obj = func(values);
            Console.WriteLine(obj);
            Console.WriteLine("test");
            Console.ReadLine();
        }

        //public Program() { }
        public Program(int val1, float val2, string val3) {
            Console.WriteLine(val1);
            Console.WriteLine(val2);
            Console.WriteLine(val3);
        }
    }

If you want to pass the object[] to the constructor, as in

(object[] args) => new Program(args)

you can just do that directly (sorry for formatting, copied from my LINQPad):

public class Program  {
void Main() {
    var constructorInfo = typeof(Program).GetConstructors()[0];
    var parm = Expression.Parameter(typeof(object[]), "args");
    var someType1Exp = Expression.New(constructorInfo, parm);
    var outer = Expression.Lambda<Func<object[], object>>(someType1Exp, parm);
    var func = outer.Compile();

    object[] values = { 1, 123.45F, "abc" };
    object obj = func(values);
    Console.WriteLine(obj);
    Console.WriteLine("test");
}

// Define other methods and classes here
    public Program(object[] parms) {
        Console.WriteLine(parms.ToString());
    }
}


来源: stackexchange

问:
C# new in method declaration
```<code>public new int AdjustedBaseValue
</code>```

<p>What does the new here mean or do? </p>

答:
It means you are shadowing the int value. It is declared in a base class and you are re-declaring it in a derived class, effectively hiding the base class version.

See documentation here for more information.

Refer example here

ContentLicense: CC BY-SA 2.5

Title: C# new in method declaration

Body:
public new int AdjustedBaseValue

What does the new here mean or do?

ContentLicense: CC BY-SA 4.0


问:
How to solve webpack build errors with Angular5 where I see ...node_modules/xxxx is not part of the compilation output
I have recently upgraded to the most current angular-stater which works fine by itself.  However in my project I am seeing a number of errors like:

```<code>Module build failed: Error: /home/joel/.../Tracker3/node_modules/angular2-color-picker/lib/index.ts is not part of the compilation output.
</code>```

I have tried directly including this source file in my tsconfig.json or tsconfig.webpack.json but these changes have had no effect.  Clearly I don't yet understand how to properly handle the changes due to addition of ngc-webpack withe angular5.

The 'npm run build' gives:  (which shows the host of build errors)

```<code>...
7377ms building modules
37ms sealing
4ms optimizing
0ms basic module optimization
41ms module optimization
0ms advanced module optimization
12ms basic chunk optimization
0ms chunk optimization
0ms advanced chunk optimization
4ms module and chunk tree optimization
0ms chunk modules optimization
0ms advanced chunk modules optimization
15ms module reviving
8ms module order optimization
18ms module id optimization
6ms chunk reviving
0ms chunk order optimization
28ms chunk id optimization
61ms hashing
0ms module assets processing
5122ms chunk assets processing
6ms additional chunk assets processing
0ms recording
0ms additional asset processing
0ms chunk asset optimization
235ms asset optimization
133ms emitting
Hash: a180140e440f968bc44e
Version: webpack 3.9.1
Time: 16820ms
                                          Asset       Size  Chunks                    Chunk Names
        assets/icon/tracker/ms-icon-150x150.png    22.5 kB          [emitted]
           d34bc3300c4ca1084d6416f466e1b7df.gif   75 bytes          [emitted]
                                 main.bundle.js    34.2 MB       0  [emitted]  [big]  main
                            polyfills.bundle.js     595 kB       1  [emitted]  [big]  polyfills
                               inline.bundle.js     5.8 kB       2  [emitted]         inline
                               assets/data.json   30 bytes          [emitted]
 .
 .
 .
         assets/skins/lightgray/content.min.css    3.33 kB          [emitted]
assets/skins/lightgray/fonts/tinymce-small.woff    9.38 kB          [emitted]
                                     humans.txt  251 bytes          [emitted]
                                     robots.txt   31 bytes          [emitted]
                                     index.html    3.03 kB          [emitted]
[./$$_lazy_route_resource lazy recursive] ./$$_lazy_route_resource lazy 160 bytes {0} [built]
       [] -> factory:62ms building:1ms = 63ms
[./credentials.ts] ./credentials.ts 1.52 kB {0} [built]
       [] -> factory:32ms building:1ms = 33ms
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {0} {1} [built]
       [] -> factory:0ms building:0ms = 0ms
[./src/app/app.component.ts] ./src/app/app.component.ts 1.72 kB {0} [built]
       [] -> factory:29ms building:1ms dependencies:767ms = 797ms
[./src/app/app.module.ts] ./src/app/app.module.ts 14.8 kB {0} [built]
       [] -> factory:230ms building:16ms dependencies:812ms = 1058ms
[./src/app/app.routes.ts] ./src/app/app.routes.ts 542 bytes {0} [built]
       [] -> factory:27ms building:1ms dependencies:172ms = 200ms
[./src/app/environment.ts] ./src/app/environment.ts 1.28 kB {0} [built]
       [] -> factory:23ms building:1ms dependencies:787ms = 811ms
[./src/app/index.ts] ./src/app/index.ts 37 bytes {0} [built]
       [] -> factory:205ms building:1ms = 206ms
[./src/app/tracker/index.ts] ./src/app/tracker/index.ts 234 bytes {0} [built]
       [] -> factory:200ms building:0ms = 200ms
[./src/app/tracker/shared/notification/notification.component.ts] ./src/app/tracker/shared/notification/notification.component.ts 3.02 kB {0} [built]
       [] -> factory:38ms building:3ms dependencies:758ms = 799ms
[./src/app/tracker/shared/specialNotification/specialNotification.component.ts] ./src/app/tracker/shared/specialNotification/specialNotification.component.ts 3.45 kB {0} [built]
       [] -> factory:43ms building:5ms dependencies:751ms = 799ms
[./src/environments/environment.ts] ./src/environments/environment.ts 830 bytes {0} [built]
       [] -> factory:195ms building:2ms = 197ms
[./src/main.browser.ts] ./src/main.browser.ts 966 bytes {0} [built]
        factory:3701ms building:9ms = 3710ms
[./src/polyfills.browser.ts] ./src/polyfills.browser.ts 2.65 kB {1} [built]
        factory:3701ms building:6ms = 3707ms
[./src/service/index.ts] ./src/service/index.ts 323 bytes {0} [built]
       [] -> factory:198ms building:1ms dependencies:4781ms = 4980ms
    + 1709 hidden modules

WARNING in ./node_modules/app-root-path/browser-shim.js
10:8-46 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/app-root-path/browser-shim.js
 @ ./node_modules/codelyzer/angular/config.js
 @ ./node_modules/codelyzer/util/logger.js
 @ ./src/app/tracker/east/body/taskDetailsBody.component.ts
 @ ./src/app/tracker/east/index.ts
 @ ./src/app/tracker/index.ts
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-color-picker/lib/index.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-color-picker/lib/index.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:648:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/angular2-color-picker/index.js 5:9-31
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-logger/app/core/level.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-logger/app/core/level.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:643:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
 @ ./node_modules/angular2-logger/core.js 6:9-36
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-logger/app/core/logger.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-logger/app/core/logger.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:643:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
 @ ./node_modules/angular2-logger/core.js 7:9-37
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-logger/app/core/providers.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-logger/app/core/providers.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:643:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
 @ ./node_modules/angular2-logger/core.js 8:9-40
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/ng-socket-io/socket-io.module.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/ng-socket-io/socket-io.module.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:648:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/ng-socket-io/index.js 3:25-54
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/ng-socket-io/socket-io.service.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/ng-socket-io/socket-io.service.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:648:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/ng-socket-io/index.js 5:26-56
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/font-awesome-webpack/node_modules/css-loader!./node_modules/less-loader!./node_modules/font-awesome-webpack/font-awesome-styles.loader.js!./node_modules/font-awesome-webpack/font-awesome.config.js
Module build failed: Error: Cannot find module 'less'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/joel/workspace/Tracker3/node_modules/less-loader/index.js:8:12)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at loadLoader (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/loadLoader.js:13:17)
    at iteratePitchingLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at iteratePitchingLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:165:10)
    at /home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:173:18
    at loadLoader (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/loadLoader.js:36:3)
    at iteratePitchingLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at runLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:362:2)
    at NormalModule.doBuild (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModule.js:182:3)
    at NormalModule.build (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModule.js:275:15)
    at Compilation.buildModule (/home/joel/workspace/Tracker3/node_modules/webpack/lib/Compilation.js:151:10)
    at factoryCallback (/home/joel/workspace/Tracker3/node_modules/webpack/lib/Compilation.js:344:12)
    at factory (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:241:5)
    at applyPluginsAsyncWaterfall (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:94:13)
    at /home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:268:11
    at NormalModuleFactory.params.normalModuleFactory.plugin (/home/joel/workspace/Tracker3/node_modules/webpack/lib/CompatibilityPlugin.js:52:5)
    at NormalModuleFactory.applyPluginsAsyncWaterfall (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:272:13)
    at resolver (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:69:10)
    at process.nextTick (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:194:7)
 @ ./node_modules/font-awesome-webpack/node_modules/style-loader!./node_modules/font-awesome-webpack/node_modules/css-loader!./node_modules/less-loader!./node_modules/font-awesome-webpack/font-awesome-styles.loader.js!./node_modules/font-awesome-webpack/font-awesome.config.js 4:14-142
 @ ./node_modules/font-awesome-webpack/index.js
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/app/tracker/west/listHeader/listHeader.component.scss
Module not found: Error: Can't resolve '../../../../../node_modules/ng2-dnd/style.css' in '/home/joel/workspace/Tracker3/src/app/tracker/west/listHeader'
 @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/app/tracker/west/listHeader/listHeader.component.scss 3:10-116
 @ ./src/app/tracker/west/listHeader/listHeader.component.scss
 @ ./src/app/tracker/west/listHeader/listHeader.component.ts
 @ ./src/app/tracker/west/listHeader/index.ts
 @ ./src/app/tracker/west/index.ts
 @ ./src/app/tracker/index.ts
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts
Child html-webpack-plugin for "index.html":
     1 asset
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 2.29 kB {0} [built]
            factory:3684ms building:17ms = 3701ms
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {0} [built]
           [] -> factory:10ms building:6ms = 16ms
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 517 bytes {0} [built]
           [] -> factory:11ms building:5ms = 16ms
        + 1 hidden module
</code>```

It seems that these errors are coming from:

```<code>node_modules/angular2-color-picker/lib/index.ts
node_modules/angular2-logger/app/core/level.ts
node_modules/angular2-logger/app/core/logger.ts
node_modules/angular2-logger/app/core/providers.ts
node_modules/ng-socket-io/socket-io.module.ts
node_modules/ng-socket-io/socket-io.service.ts
</code>```

somehow not being included, but this cannot be correct, since when I include them directly -- there is no improvement.  So what am I doing wrong?  How to properly setup the build for these few node packages???  And why do all the other packages work fine??  Or how can I learn how to fix this?

I have included what I believe are the relevant config files here:
First: webpack.dev.ts:

```<code>  /**
   * @author: @AngularClass
   */

  const helpers = require('./helpers');
  const buildUtils = require('./build-utils');
  const webpackMerge = require('webpack-merge'); // used to merge webpack configs
  const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
  const fs = require('fs');

  /**
   * Webpack Plugins
   */
  const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
  const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
  const EvalSourceMapDevToolPlugin = require('webpack/lib/EvalSourceMapDevToolPlugin');

  /**
   * Webpack configuration
   *
   * See: http://webpack.github.io/docs/configuration.html#cli
   */
  module.exports = function (options) {
    const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
    const HOST = process.env.HOST || 'localhost';
    const PORT = process.env.PORT || 3000;

    const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, {
      host: HOST,
      port: PORT,
      ENV: ENV,
      HMR: helpers.hasProcessFlag('hot'),
      PUBLIC: process.env.PUBLIC_DEV || HOST + ':' + PORT
    });

    return webpackMerge(commonConfig({ env: ENV, metadata: METADATA  }), {
      /**
       * Options affecting the output of the compilation.
       *
       * See: http://webpack.github.io/docs/configuration.html#output
       */
      output: {

        /**
         * The output directory as absolute path (required).
         *
         * See: http://webpack.github.io/docs/configuration.html#output-path
         */
        path: helpers.root('dist'),

        /**
         * Specifies the name of each output file on disk.
         * IMPORTANT: You must not specify an absolute path here!
         *
         * See: http://webpack.github.io/docs/configuration.html#output-filename
         */
        filename: '[name].bundle.js',

        /**
         * The filename of the SourceMaps for the JavaScript files.
         * They are inside the output.path directory.
         *
         * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
         */
        sourceMapFilename: '[file].map',

        /** The filename of non-entry chunks as relative path
         * inside the output.path directory.
         *
         * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
         */
        chunkFilename: '[id].chunk.js',

        library: 'ac_[name]',
        libraryTarget: 'var',
      },

      module: {

        rules: [

          /**
           * Css loader support for *.css files (styles directory only)
           * Loads external css styles into the DOM, supports HMR
           *
           */
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
            include: [helpers.root('src', 'styles')]
          },

          /**
           * Sass loader support for *.scss files (styles directory only)
           * Loads external sass styles into the DOM, supports HMR
           *
           */
          {
            test: /\.scss$/,
            use: ['style-loader', 'css-loader', 'sass-loader'],
            include: [helpers.root('src', 'styles')]
          },

        ]

      },

      plugins: [
        new EvalSourceMapDevToolPlugin({
          moduleFilenameTemplate: '[resource-path]',
          sourceRoot: 'webpack:///'
        }),

        /**
         * Plugin: NamedModulesPlugin (experimental)
         * Description: Uses file names as module name.
         *
         * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
         */
        new NamedModulesPlugin(),

        /**
         * Plugin LoaderOptionsPlugin (experimental)
         *
         * See: https://gist.github.com/sokra/27b24881210b56bbaff7
         */
        new LoaderOptionsPlugin({
          debug: true,
          options: { }
        }),

        // TODO: HMR
      ],

      /**
       * Webpack Development Server configuration
       * Description: The webpack-dev-server is a little node.js Express server.
       * The server emits information about the compilation state to the client,
       * which reacts to those events.
       *
       * See: https://webpack.github.io/docs/webpack-dev-server.html
       */
      devServer: {
        port: METADATA.port,
        host: METADATA.host,
        hot: METADATA.HMR,
        public: METADATA.PUBLIC,
        historyApiFallback: true,
        https: {
          key: fs.readFileSync('/etc/apache2/certwork/newDragon.key'),
          cert: fs.readFileSync('/etc/apache2/certwork/STAR_dynazu_com.crt'),
          ca: fs.readFileSync('/etc/apache2/certwork/ssl-bundle.crt')
        },
        watchOptions: {
          // if you're using Docker you may need this
          // aggregateTimeout: 300,
          // poll: 1000,
          ignored: /node_modules/
        },
        /**
        * Here you can access the Express app object and add your own custom middleware to it.
        *
        * See: https://webpack.github.io/docs/webpack-dev-server.html
        */
        setup: function(app) {
          // For example, to define custom handlers for some paths:
          // app.get('/some/path', function(req, res) {
          //   res.json({ custom: 'response' });
          // });
        }
      },

      /**
       * Include polyfills or mocks for various node stuff
       * Description: Node configuration
       *
       * See: https://webpack.github.io/docs/configuration.html#node
       */
      node: {
        global: true,
        crypto: 'empty',
        process: true,
        module: false,
        clearImmediate: false,
        setImmediate: false
      }

    });
  }
</code>```

The plot thickens: In an attempt to dig further, I did a 'npm run build:prod' which fails differently:

```<code>         57% building modules 396/442 modules 46 active ...odules/rxjs/operators/windowToggle.jsModuleNotFoundError: Module not found: Error: Can't resolve '../../../../../node_modules/ng2-dnd/style.css' in '/home/joel/workspace/Tracker3/src/app/tracker/west/listHeader'
        at factoryCallback (/home/joel/workspace/Tracker3/node_modules/webpack/lib/Compilation.js:276:40)
        at factory (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:235:20)
        at resolver (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:60:20)
        at asyncLib.parallel (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:127:20)
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:3874:9
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:473:16
        at iteratorCallback (/home/joel/workspace/Tracker3/node_modules/async/dist/async.js:1048:13)
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:958:16
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:3871:13
        at resolvers.normal.resolve (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:119:22)
        at onError (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:65:10)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at runAfter (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
        at innerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:252:11)
        at /home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:40:4
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at runAfter (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
        at innerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:252:11)
        at innerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:144:11)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:249:35)
        at resolver.doResolve.createInnerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:44:6)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at afterInnerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:168:10)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:252:11)
    resolve '../../../../../node_modules/ng2-dnd/style.css' in '/home/joel/workspace/Tracker3/src/app/tracker/west/listHeader'
      using description file: /home/joel/workspace/Tracker3/package.json (relative path: ./src/app/tracker/west/listHeader)
        Field 'browser' doesn't contain a valid alias configuration
      after using description file: /home/joel/workspace/Tracker3/package.json (relative path: ./src/app/tracker/west/listHeader)
        using description file: /home/joel/workspace/Tracker3/node_modules/ng2-dnd/package.json (relative path: ./style.css)
          no extension
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css doesn't exist
          .ts
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css.ts doesn't exist
          .js
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css.js doesn't exist
          .json
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css.json doesn't exist
          as directory
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css doesn't exist
</code>```

So perhaps these two issues are related? If you have any insight, thanks!

答:
It turns out that the issues were connected to packages that need to be updated for the changes for webpack builds for angular 5.

Also, I had one @include in a scss file where the path needed to be changed due to a change in the ng2-dnd package.

For ng-socket-io, I stopped using this package and grabbed some of the code and inserted it directly into one of my classes.

At this point, I was down to a single error from the angular2-color-picker package that has not been maintained in over a year.  So I switched to the ngx-color-picker package and all now builds!

Thanks to all who looked at this issue and hopefully this answer will help someone else.

ContentLicense: CC BY-SA 3.0

Body:
I have recently upgraded to the most current angular-stater which works fine by itself.  However in my project I am seeing a number of errors like:

Module build failed: Error: /home/joel/.../Tracker3/node_modules/angular2-color-picker/lib/index.ts is not part of the compilation output.

I have tried directly including this source file in my tsconfig.json or tsconfig.webpack.json but these changes have had no effect.  Clearly I don't yet understand how to properly handle the changes due to addition of ngc-webpack withe angular5.

The 'npm run build' gives:  (which shows the host of build errors)

...
7377ms building modules
37ms sealing
4ms optimizing
0ms basic module optimization
41ms module optimization
0ms advanced module optimization
12ms basic chunk optimization
0ms chunk optimization
0ms advanced chunk optimization
4ms module and chunk tree optimization
0ms chunk modules optimization
0ms advanced chunk modules optimization
15ms module reviving
8ms module order optimization
18ms module id optimization
6ms chunk reviving
0ms chunk order optimization
28ms chunk id optimization
61ms hashing
0ms module assets processing
5122ms chunk assets processing
6ms additional chunk assets processing
0ms recording
0ms additional asset processing
0ms chunk asset optimization
235ms asset optimization
133ms emitting
Hash: a180140e440f968bc44e
Version: webpack 3.9.1
Time: 16820ms
                                          Asset       Size  Chunks                    Chunk Names
        assets/icon/tracker/ms-icon-150x150.png    22.5 kB          [emitted]
           d34bc3300c4ca1084d6416f466e1b7df.gif   75 bytes          [emitted]
                                 main.bundle.js    34.2 MB       0  [emitted]  [big]  main
                            polyfills.bundle.js     595 kB       1  [emitted]  [big]  polyfills
                               inline.bundle.js     5.8 kB       2  [emitted]         inline
                               assets/data.json   30 bytes          [emitted]
 .
 .
 .
         assets/skins/lightgray/content.min.css    3.33 kB          [emitted]
assets/skins/lightgray/fonts/tinymce-small.woff    9.38 kB          [emitted]
                                     humans.txt  251 bytes          [emitted]
                                     robots.txt   31 bytes          [emitted]
                                     index.html    3.03 kB          [emitted]
[./$$_lazy_route_resource lazy recursive] ./$$_lazy_route_resource lazy 160 bytes {0} [built]
       [] -> factory:62ms building:1ms = 63ms
[./credentials.ts] ./credentials.ts 1.52 kB {0} [built]
       [] -> factory:32ms building:1ms = 33ms
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {0} {1} [built]
       [] -> factory:0ms building:0ms = 0ms
[./src/app/app.component.ts] ./src/app/app.component.ts 1.72 kB {0} [built]
       [] -> factory:29ms building:1ms dependencies:767ms = 797ms
[./src/app/app.module.ts] ./src/app/app.module.ts 14.8 kB {0} [built]
       [] -> factory:230ms building:16ms dependencies:812ms = 1058ms
[./src/app/app.routes.ts] ./src/app/app.routes.ts 542 bytes {0} [built]
       [] -> factory:27ms building:1ms dependencies:172ms = 200ms
[./src/app/environment.ts] ./src/app/environment.ts 1.28 kB {0} [built]
       [] -> factory:23ms building:1ms dependencies:787ms = 811ms
[./src/app/index.ts] ./src/app/index.ts 37 bytes {0} [built]
       [] -> factory:205ms building:1ms = 206ms
[./src/app/tracker/index.ts] ./src/app/tracker/index.ts 234 bytes {0} [built]
       [] -> factory:200ms building:0ms = 200ms
[./src/app/tracker/shared/notification/notification.component.ts] ./src/app/tracker/shared/notification/notification.component.ts 3.02 kB {0} [built]
       [] -> factory:38ms building:3ms dependencies:758ms = 799ms
[./src/app/tracker/shared/specialNotification/specialNotification.component.ts] ./src/app/tracker/shared/specialNotification/specialNotification.component.ts 3.45 kB {0} [built]
       [] -> factory:43ms building:5ms dependencies:751ms = 799ms
[./src/environments/environment.ts] ./src/environments/environment.ts 830 bytes {0} [built]
       [] -> factory:195ms building:2ms = 197ms
[./src/main.browser.ts] ./src/main.browser.ts 966 bytes {0} [built]
        factory:3701ms building:9ms = 3710ms
[./src/polyfills.browser.ts] ./src/polyfills.browser.ts 2.65 kB {1} [built]
        factory:3701ms building:6ms = 3707ms
[./src/service/index.ts] ./src/service/index.ts 323 bytes {0} [built]
       [] -> factory:198ms building:1ms dependencies:4781ms = 4980ms
    + 1709 hidden modules

WARNING in ./node_modules/app-root-path/browser-shim.js
10:8-46 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/app-root-path/browser-shim.js
 @ ./node_modules/codelyzer/angular/config.js
 @ ./node_modules/codelyzer/util/logger.js
 @ ./src/app/tracker/east/body/taskDetailsBody.component.ts
 @ ./src/app/tracker/east/index.ts
 @ ./src/app/tracker/index.ts
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-color-picker/lib/index.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-color-picker/lib/index.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:648:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/angular2-color-picker/index.js 5:9-31
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-logger/app/core/level.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-logger/app/core/level.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:643:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
 @ ./node_modules/angular2-logger/core.js 6:9-36
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-logger/app/core/logger.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-logger/app/core/logger.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:643:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
 @ ./node_modules/angular2-logger/core.js 7:9-37
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/angular2-logger/app/core/providers.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/angular2-logger/app/core/providers.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:643:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
 @ ./node_modules/angular2-logger/core.js 8:9-40
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/ng-socket-io/socket-io.module.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/ng-socket-io/socket-io.module.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:648:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/ng-socket-io/index.js 3:25-54
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/ng-socket-io/socket-io.service.ts
Module build failed: Error: /home/joel/workspace/Tracker3/node_modules/ng-socket-io/socket-io.service.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:648:23)
    at plugin.done.then (/home/joel/workspace/Tracker3/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/ng-socket-io/index.js 5:26-56
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/font-awesome-webpack/node_modules/css-loader!./node_modules/less-loader!./node_modules/font-awesome-webpack/font-awesome-styles.loader.js!./node_modules/font-awesome-webpack/font-awesome.config.js
Module build failed: Error: Cannot find module 'less'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/joel/workspace/Tracker3/node_modules/less-loader/index.js:8:12)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at loadLoader (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/loadLoader.js:13:17)
    at iteratePitchingLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at iteratePitchingLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:165:10)
    at /home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:173:18
    at loadLoader (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/loadLoader.js:36:3)
    at iteratePitchingLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at runLoaders (/home/joel/workspace/Tracker3/node_modules/loader-runner/lib/LoaderRunner.js:362:2)
    at NormalModule.doBuild (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModule.js:182:3)
    at NormalModule.build (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModule.js:275:15)
    at Compilation.buildModule (/home/joel/workspace/Tracker3/node_modules/webpack/lib/Compilation.js:151:10)
    at factoryCallback (/home/joel/workspace/Tracker3/node_modules/webpack/lib/Compilation.js:344:12)
    at factory (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:241:5)
    at applyPluginsAsyncWaterfall (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:94:13)
    at /home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:268:11
    at NormalModuleFactory.params.normalModuleFactory.plugin (/home/joel/workspace/Tracker3/node_modules/webpack/lib/CompatibilityPlugin.js:52:5)
    at NormalModuleFactory.applyPluginsAsyncWaterfall (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:272:13)
    at resolver (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:69:10)
    at process.nextTick (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:194:7)
 @ ./node_modules/font-awesome-webpack/node_modules/style-loader!./node_modules/font-awesome-webpack/node_modules/css-loader!./node_modules/less-loader!./node_modules/font-awesome-webpack/font-awesome-styles.loader.js!./node_modules/font-awesome-webpack/font-awesome.config.js 4:14-142
 @ ./node_modules/font-awesome-webpack/index.js
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts

ERROR in ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/app/tracker/west/listHeader/listHeader.component.scss
Module not found: Error: Can't resolve '../../../../../node_modules/ng2-dnd/style.css' in '/home/joel/workspace/Tracker3/src/app/tracker/west/listHeader'
 @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/app/tracker/west/listHeader/listHeader.component.scss 3:10-116
 @ ./src/app/tracker/west/listHeader/listHeader.component.scss
 @ ./src/app/tracker/west/listHeader/listHeader.component.ts
 @ ./src/app/tracker/west/listHeader/index.ts
 @ ./src/app/tracker/west/index.ts
 @ ./src/app/tracker/index.ts
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.browser.ts
Child html-webpack-plugin for "index.html":
     1 asset
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 2.29 kB {0} [built]
            factory:3684ms building:17ms = 3701ms
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {0} [built]
           [] -> factory:10ms building:6ms = 16ms
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 517 bytes {0} [built]
           [] -> factory:11ms building:5ms = 16ms
        + 1 hidden module

It seems that these errors are coming from:

node_modules/angular2-color-picker/lib/index.ts
node_modules/angular2-logger/app/core/level.ts
node_modules/angular2-logger/app/core/logger.ts
node_modules/angular2-logger/app/core/providers.ts
node_modules/ng-socket-io/socket-io.module.ts
node_modules/ng-socket-io/socket-io.service.ts

somehow not being included, but this cannot be correct, since when I include them directly -- there is no improvement.  So what am I doing wrong?  How to properly setup the build for these few node packages???  And why do all the other packages work fine??  Or how can I learn how to fix this?

I have included what I believe are the relevant config files here:
First: webpack.dev.ts:

  /**
   * @author: @AngularClass
   */

  const helpers = require('./helpers');
  const buildUtils = require('./build-utils');
  const webpackMerge = require('webpack-merge'); // used to merge webpack configs
  const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
  const fs = require('fs');

  /**
   * Webpack Plugins
   */
  const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
  const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
  const EvalSourceMapDevToolPlugin = require('webpack/lib/EvalSourceMapDevToolPlugin');

  /**
   * Webpack configuration
   *
   * See: http://webpack.github.io/docs/configuration.html#cli
   */
  module.exports = function (options) {
    const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
    const HOST = process.env.HOST || 'localhost';
    const PORT = process.env.PORT || 3000;

    const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, {
      host: HOST,
      port: PORT,
      ENV: ENV,
      HMR: helpers.hasProcessFlag('hot'),
      PUBLIC: process.env.PUBLIC_DEV || HOST + ':' + PORT
    });

    return webpackMerge(commonConfig({ env: ENV, metadata: METADATA  }), {
      /**
       * Options affecting the output of the compilation.
       *
       * See: http://webpack.github.io/docs/configuration.html#output
       */
      output: {

        /**
         * The output directory as absolute path (required).
         *
         * See: http://webpack.github.io/docs/configuration.html#output-path
         */
        path: helpers.root('dist'),

        /**
         * Specifies the name of each output file on disk.
         * IMPORTANT: You must not specify an absolute path here!
         *
         * See: http://webpack.github.io/docs/configuration.html#output-filename
         */
        filename: '[name].bundle.js',

        /**
         * The filename of the SourceMaps for the JavaScript files.
         * They are inside the output.path directory.
         *
         * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
         */
        sourceMapFilename: '[file].map',

        /** The filename of non-entry chunks as relative path
         * inside the output.path directory.
         *
         * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
         */
        chunkFilename: '[id].chunk.js',

        library: 'ac_[name]',
        libraryTarget: 'var',
      },

      module: {

        rules: [

          /**
           * Css loader support for *.css files (styles directory only)
           * Loads external css styles into the DOM, supports HMR
           *
           */
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
            include: [helpers.root('src', 'styles')]
          },

          /**
           * Sass loader support for *.scss files (styles directory only)
           * Loads external sass styles into the DOM, supports HMR
           *
           */
          {
            test: /\.scss$/,
            use: ['style-loader', 'css-loader', 'sass-loader'],
            include: [helpers.root('src', 'styles')]
          },

        ]

      },

      plugins: [
        new EvalSourceMapDevToolPlugin({
          moduleFilenameTemplate: '[resource-path]',
          sourceRoot: 'webpack:///'
        }),

        /**
         * Plugin: NamedModulesPlugin (experimental)
         * Description: Uses file names as module name.
         *
         * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
         */
        new NamedModulesPlugin(),

        /**
         * Plugin LoaderOptionsPlugin (experimental)
         *
         * See: https://gist.github.com/sokra/27b24881210b56bbaff7
         */
        new LoaderOptionsPlugin({
          debug: true,
          options: { }
        }),

        // TODO: HMR
      ],

      /**
       * Webpack Development Server configuration
       * Description: The webpack-dev-server is a little node.js Express server.
       * The server emits information about the compilation state to the client,
       * which reacts to those events.
       *
       * See: https://webpack.github.io/docs/webpack-dev-server.html
       */
      devServer: {
        port: METADATA.port,
        host: METADATA.host,
        hot: METADATA.HMR,
        public: METADATA.PUBLIC,
        historyApiFallback: true,
        https: {
          key: fs.readFileSync('/etc/apache2/certwork/newDragon.key'),
          cert: fs.readFileSync('/etc/apache2/certwork/STAR_dynazu_com.crt'),
          ca: fs.readFileSync('/etc/apache2/certwork/ssl-bundle.crt')
        },
        watchOptions: {
          // if you're using Docker you may need this
          // aggregateTimeout: 300,
          // poll: 1000,
          ignored: /node_modules/
        },
        /**
        * Here you can access the Express app object and add your own custom middleware to it.
        *
        * See: https://webpack.github.io/docs/webpack-dev-server.html
        */
        setup: function(app) {
          // For example, to define custom handlers for some paths:
          // app.get('/some/path', function(req, res) {
          //   res.json({ custom: 'response' });
          // });
        }
      },

      /**
       * Include polyfills or mocks for various node stuff
       * Description: Node configuration
       *
       * See: https://webpack.github.io/docs/configuration.html#node
       */
      node: {
        global: true,
        crypto: 'empty',
        process: true,
        module: false,
        clearImmediate: false,
        setImmediate: false
      }

    });
  }

The plot thickens: In an attempt to dig further, I did a 'npm run build:prod' which fails differently:

         57% building modules 396/442 modules 46 active ...odules/rxjs/operators/windowToggle.jsModuleNotFoundError: Module not found: Error: Can't resolve '../../../../../node_modules/ng2-dnd/style.css' in '/home/joel/workspace/Tracker3/src/app/tracker/west/listHeader'
        at factoryCallback (/home/joel/workspace/Tracker3/node_modules/webpack/lib/Compilation.js:276:40)
        at factory (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:235:20)
        at resolver (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:60:20)
        at asyncLib.parallel (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:127:20)
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:3874:9
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:473:16
        at iteratorCallback (/home/joel/workspace/Tracker3/node_modules/async/dist/async.js:1048:13)
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:958:16
        at /home/joel/workspace/Tracker3/node_modules/async/dist/async.js:3871:13
        at resolvers.normal.resolve (/home/joel/workspace/Tracker3/node_modules/webpack/lib/NormalModuleFactory.js:119:22)
        at onError (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:65:10)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at runAfter (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
        at innerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:252:11)
        at /home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:40:4
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at runAfter (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
        at innerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:252:11)
        at innerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:144:11)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:249:35)
        at resolver.doResolve.createInnerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:44:6)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at afterInnerCallback (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/Resolver.js:168:10)
        at loggingCallbackWrapper (/home/joel/workspace/Tracker3/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
        at next (/home/joel/workspace/Tracker3/node_modules/tapable/lib/Tapable.js:252:11)
    resolve '../../../../../node_modules/ng2-dnd/style.css' in '/home/joel/workspace/Tracker3/src/app/tracker/west/listHeader'
      using description file: /home/joel/workspace/Tracker3/package.json (relative path: ./src/app/tracker/west/listHeader)
        Field 'browser' doesn't contain a valid alias configuration
      after using description file: /home/joel/workspace/Tracker3/package.json (relative path: ./src/app/tracker/west/listHeader)
        using description file: /home/joel/workspace/Tracker3/node_modules/ng2-dnd/package.json (relative path: ./style.css)
          no extension
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css doesn't exist
          .ts
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css.ts doesn't exist
          .js
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css.js doesn't exist
          .json
            Field 'browser' doesn't contain a valid alias configuration
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css.json doesn't exist
          as directory
            /home/joel/workspace/Tracker3/node_modules/ng2-dnd/style.css doesn't exist

So perhaps these two issues are related? If you have any insight, thanks!


问:
how to load JPA jar with persistence.xml from outside of war file in jboss
I have JPA jar with persistence.xml and want to deploy in Jboss7.

Problem is that, i can't put inside WAR file(i know we can load from war file).

I have created module in jboss and placed jar file with including persistence.xml file inside META-INF\ of the jar
with ref:
http://javahowto.blogspot.sg/2007/06/where-to-put-persistencexml-in-web-app.html
Maven/Eclipse: Could not find any META-INF/persistence.xml file in the classpath

After that jar file loaded, but persistence.xml not loaded.

Is it possible to load persistence.xml from jar file ?

if possible, can someone please let me know, where to place inside jar

Thanks

答: If it is just about the persistence.xml, you could use a deployment-overlay. See e.g. https://docs.jboss.org/author/display/AS72/Deployment+Overlays </p>


问:
JavaScript callback to get selected glyph index in Bokeh
I've created a visual graph using Bokeh that shows a network I created using Networkx. I now want to use TapTool to show information pertinent to any node on the graph that I click on. The graph is just nodes and edges. I know I should be able to use var inds = cb_obj.selected['1d'].indices; in the JavaScript callback function to get the indices of the nodes (glyphs) that were clicked on, but that's not working somehow and I get the error message, Uncaught TypeError: Cannot read property '1d' of undefined. A nudge in the right direction would be greatly appreciated.

Below is my code. Please note that I've defined my plot as a Plot() and not as a figure(). I don't think that's the reason for the issue, but just wanted to mention it. Also, I'm using window.alert(inds); just to see what values I get. That's not my ultimate purpose, but I expect that bit to work anyway.

```<code>def draw_graph_____(self, my_network):
    self.graph_height, self.graph_width, self.graph_nodes, self.graph_edges, self.node_coords, self.node_levels = self.compute_graph_layout(my_network)

    graph = nx.DiGraph()
    graph.add_nodes_from(self.graph_nodes)
    graph.add_edges_from(self.graph_edges)

    plot            = Plot(plot_width = self.graph_width, plot_height = self.graph_height, x_range = Range1d(0.0, 1.0), y_range = Range1d(0.0, 1.0))
    plot.title.text = "Graph Demonstration"

    graph_renderer = from_networkx(graph, self.graph_layout, scale = 1, center = (-100, 100))
    graph_renderer.node_renderer.data_source.data["node_names"] = self.graph_nodes
    graph_renderer.node_renderer.data_source.data["index"]      = self.graph_nodes

    graph_renderer.node_renderer.glyph              = Circle(size = 40, fill_color = Spectral4[0])
    graph_renderer.node_renderer.selection_glyph    = Circle(size = 40, fill_color = Spectral4[2])
    graph_renderer.node_renderer.hover_glyph        = Circle(size = 40, fill_color = Spectral4[1])

    graph_renderer.edge_renderer.glyph              = MultiLine(line_color = "#CCCCCC", line_alpha = 0.8, line_width = 5)
    graph_renderer.edge_renderer.selection_glyph    = MultiLine(line_color = Spectral4[2], line_width = 5)
    graph_renderer.edge_renderer.hover_glyph        = MultiLine(line_color = Spectral4[1], line_width = 5)

    graph_renderer.selection_policy     = NodesAndLinkedEdges()
    graph_renderer.inspection_policy    = NodesAndLinkedEdges()

    x_coord = [coord[0] for coord in self.node_coords]
    y_coord = [coord[1] for coord in self.node_coords]
    y_offset = []

    for level in self.node_levels:
        for item in self.node_levels[level]:
            if self.node_levels[level].index(item) % 2 == 0:
                y_offset.append(20)
            else:
                y_offset.append(-40)

    graph_renderer.node_renderer.data_source.data["x_coord"]    = x_coord
    graph_renderer.node_renderer.data_source.data["y_coord"]    = y_coord
    graph_renderer.node_renderer.data_source.data["y_offset"]   = y_offset

    labels_source   = graph_renderer.node_renderer.data_source
    labels          = LabelSet(x = "x_coord", y = "y_coord", text = 'node_names', text_font_size = "12pt", level = 'glyph',
                               x_offset = -50, y_offset = "y_offset", source = labels_source, render_mode = 'canvas')
    plot.add_layout(labels)

    callback = CustomJS(args = dict(source = graph_renderer.node_renderer.data_source), code =
    """
    console.log(cb_obj)
    var inds = cb_obj.selected['1d'].indices;
    window.alert(inds);
    """)

    plot.add_tools(HoverTool(tooltips = [("Node", "@node_names"), ("Recomm", "Will put a sample recommendation message here later")]))
    plot.add_tools(TapTool(callback = callback))

    plot.renderers.append(graph_renderer)

    output_file("interactive_graphs.html")

    show(plot)
</code>```

My imports are as follows, by the way:

```<code>import collections
import networkx             as nx
import numpy                as np

from bokeh.io               import output_file, show
from bokeh.models           import Circle, ColumnDataSource, CustomJS, Div, HoverTool, LabelSet, MultiLine, OpenURL, Plot, Range1d, TapTool
from bokeh.models.graphs    import from_networkx, NodesAndLinkedEdges
from bokeh.palettes         import Spectral4
</code>```

I'm sorry for not posting entire code, but that would require quite a few changes to make dummy data and show other files and functions (which I should have), but I thought just this one function may suffice for the identification of the issue. If not, I'm happy to share more code. Thanks!

答:
The problem is that the callback is not attached to a data source. The value of cb_obj is whatever object triggers the callback. But only ColumnDataSource objects have a selected property, so only callbacks on data sources will have cb_obj.selected. If you are wanting to have a callback fire whenever a selection changes, i.e. whenever a node is clicked on, then you'd want to have the callback on the data source. [1]

However, if you want to have a callback when a node is merely hovered over (but not clicked on) that is an inspection, not a selection. You will want to follow this example:

https://docs.bokeh.org/en/latest/docs/user_guide/interaction/callbacks.html#customjs-for-hover

Although it is not often used (and thus not documented terribly well) the callback for hover tools gets passed additional information in a cb_data parameter. This cb_data parameter is used as a catch-all mechanism for tools to be able to pass extra things, specific to the tool, on to the callback. In the case of hover tools, cb_data is an object that has .index and .geometry attributes. So cb_data.index['1d'].indices has the indices of the points that are currently hovered over. The .geometry attribute as information about the kind of hit test that was performed (i.e. was a single point? or a vertical or horizontal span? And what was the location of the point or span?)

[1] Alternatively, tap tools also pass a specialized cb_data as described above. It is an object with a .source property that the the data source that made a selection. So cb_data.source.selected should work. In practice I never use this though, since a callback on the data source works equally well.

Body:
I've created a visual graph using Bokeh that shows a network I created using Networkx. I now want to use TapTool to show information pertinent to any node on the graph that I click on. The graph is just nodes and edges. I know I should be able to use var inds = cb_obj.selected['1d'].indices; in the JavaScript callback function to get the indices of the nodes (glyphs) that were clicked on, but that's not working somehow and I get the error message, Uncaught TypeError: Cannot read property '1d' of undefined. A nudge in the right direction would be greatly appreciated.

Below is my code. Please note that I've defined my plot as a Plot() and not as a figure(). I don't think that's the reason for the issue, but just wanted to mention it. Also, I'm using window.alert(inds); just to see what values I get. That's not my ultimate purpose, but I expect that bit to work anyway.

def draw_graph_____(self, my_network):
    self.graph_height, self.graph_width, self.graph_nodes, self.graph_edges, self.node_coords, self.node_levels = self.compute_graph_layout(my_network)

    graph = nx.DiGraph()
    graph.add_nodes_from(self.graph_nodes)
    graph.add_edges_from(self.graph_edges)

    plot            = Plot(plot_width = self.graph_width, plot_height = self.graph_height, x_range = Range1d(0.0, 1.0), y_range = Range1d(0.0, 1.0))
    plot.title.text = "Graph Demonstration"

    graph_renderer = from_networkx(graph, self.graph_layout, scale = 1, center = (-100, 100))
    graph_renderer.node_renderer.data_source.data["node_names"] = self.graph_nodes
    graph_renderer.node_renderer.data_source.data["index"]      = self.graph_nodes

    graph_renderer.node_renderer.glyph              = Circle(size = 40, fill_color = Spectral4[0])
    graph_renderer.node_renderer.selection_glyph    = Circle(size = 40, fill_color = Spectral4[2])
    graph_renderer.node_renderer.hover_glyph        = Circle(size = 40, fill_color = Spectral4[1])

    graph_renderer.edge_renderer.glyph              = MultiLine(line_color = "#CCCCCC", line_alpha = 0.8, line_width = 5)
    graph_renderer.edge_renderer.selection_glyph    = MultiLine(line_color = Spectral4[2], line_width = 5)
    graph_renderer.edge_renderer.hover_glyph        = MultiLine(line_color = Spectral4[1], line_width = 5)

    graph_renderer.selection_policy     = NodesAndLinkedEdges()
    graph_renderer.inspection_policy    = NodesAndLinkedEdges()

    x_coord = [coord[0] for coord in self.node_coords]
    y_coord = [coord[1] for coord in self.node_coords]
    y_offset = []

    for level in self.node_levels:
        for item in self.node_levels[level]:
            if self.node_levels[level].index(item) % 2 == 0:
                y_offset.append(20)
            else:
                y_offset.append(-40)

    graph_renderer.node_renderer.data_source.data["x_coord"]    = x_coord
    graph_renderer.node_renderer.data_source.data["y_coord"]    = y_coord
    graph_renderer.node_renderer.data_source.data["y_offset"]   = y_offset

    labels_source   = graph_renderer.node_renderer.data_source
    labels          = LabelSet(x = "x_coord", y = "y_coord", text = 'node_names', text_font_size = "12pt", level = 'glyph',
                               x_offset = -50, y_offset = "y_offset", source = labels_source, render_mode = 'canvas')
    plot.add_layout(labels)

    callback = CustomJS(args = dict(source = graph_renderer.node_renderer.data_source), code =
    """
    console.log(cb_obj)
    var inds = cb_obj.selected['1d'].indices;
    window.alert(inds);
    """)

    plot.add_tools(HoverTool(tooltips = [("Node", "@node_names"), ("Recomm", "Will put a sample recommendation message here later")]))
    plot.add_tools(TapTool(callback = callback))

    plot.renderers.append(graph_renderer)

    output_file("interactive_graphs.html")

    show(plot)

My imports are as follows, by the way:

import collections
import networkx             as nx
import numpy                as np

from bokeh.io               import output_file, show
from bokeh.models           import Circle, ColumnDataSource, CustomJS, Div, HoverTool, LabelSet, MultiLine, OpenURL, Plot, Range1d, TapTool
from bokeh.models.graphs    import from_networkx, NodesAndLinkedEdges
from bokeh.palettes         import Spectral4

I'm sorry for not posting entire code, but that would require quite a few changes to make dummy data and show other files and functions (which I should have), but I thought just this one function may suffice for the identification of the issue. If not, I'm happy to share more code. Thanks!


问:
Function from button change to press key. HTML5/JS
I have simple game script in JS but only way to accelerate object is pushbutton

```<code><button onmousedown="accelerate(-0.1)" onmouseup="accelerate(0.1)">speed ++</button>
</code>```

there is function:

```<code>function accelerate(n) {
    test.gravity = n;
}
</code>```

And question is How to change button click to key press for accelarate?
Basically I have no idea.

答:
You can add listener to window.document object for example</p>

```<code>const test = {
    gravity: 0.0
};

window.document.addEventListener('keyup', (e) => {
  // arrow up
  if (e.keyCode === 38) accelerate(0.1);
  // arrow down
  if (e.keyCode === 40) accelerate(-0.1);

  console.log(test.gravity);
})

function accelerate (n) {
    test.gravity = n;
}
</code>```

Body:
I have simple game script in JS but only way to accelerate object is pushbutton

<button onmousedown="accelerate(-0.1)" onmouseup="accelerate(0.1)">speed ++</button>

there is function:

function accelerate(n) {
    test.gravity = n;
}

And question is How to change button click to key press for accelarate?
Basically I have no idea.

Body:
You can add listener to window.document object for example

const test = {
    gravity: 0.0
};

window.document.addEventListener('keyup', (e) => {
  // arrow up
  if (e.keyCode === 38) accelerate(0.1);
  // arrow down
  if (e.keyCode === 40) accelerate(-0.1);

  console.log(test.gravity);
})

function accelerate (n) {
    test.gravity = n;
}


问:
How to mock functions in golang
I have written a simple package, which basically consists of a lot of getter functions. Each file in this package corresponds to a service, so for instance the product file, contains functions relating to the product service/db, order file to order service etc. Each function takes as parameters a db resource to the underlying db, and parameters for the sql, eg. productid, name, orderid. Each of the functions returns a struct (eg. Order, product) or an error:

```<code>// product.go

package lib

type Product struct {
   ID int
   Name string
   Price float
}

func GetProductById(DB *sql.DB, ID int) (p Product, err error) {
   q := "SELECT * FROM product WHERE id = " + ID
   ...
}

func GetProductByName(DB *sql.DB, name string) (p Product, err error) {
   ...
}

// order.go

package lib

type Order struct {
   ID int
   Date string
   Items []items
}

func GetOrderById(DB *sql.DB, ID int) (o Order, err error) {
   ...
}
</code>```

The problem is that I'm not able to mock these functions from my main package. What I really like to do, is to rewrite the package, so I somehow can pass to function to a type instead. But I'm not sure how to do this. Especially not when the functions take different input parameters and return different structs. Is there a way to do this?

答:
In Go you can NOT mock a function, or a method declared on a concrete type.

For example:

```<code>func F() { ... }

func (T) M() { ... }
</code>```

F and M are not mockable in Go.

However you can mock function values, whether they are variables, fields on a struct, or parameters passed to other functions.

For example:

```<code>var Fn = func() { ... }

type S struct {
    Fn func()
}

func F(Fn func())
</code>```

Fn in all three cases is mockable.

The other thing that you can mock in Go, and the prefered option most of the time, is an interface.

For example:

```<code>type ProductRepository interface {
    GetProductById(DB *sql.DB, ID int) (p Product, err error)
}

// the real implementater of the interface
type ProductStore struct{}

func (ProductStore) GetProductById(DB *sql.DB, ID int) (p Product, err error) {
    q := "SELECT * FROM product WHERE id = ?"
    // ...
}

// the mock implementer
type ProductRepositoryMock struct {}

func (ProductRepositoryMock) GetProductById(DB *sql.DB, ID int) (p Product, err error) {
    // ...
}
</code>```

Now any piece of code that depends on ProductRepository can be passed a value of type ProductStore when you're in "normal mode" and a value of type ProductRepositoryMock when you're testing.

Another option using interfaces, which allows you to keep your functions mostly unchaged is to define an interface that mimics the methods of *sql.DB then use that interface type as the type to be passed to your functions, implement a mock version of that interface and use that during testing.

For example:

```<code>type DBIface interface {
    Query(query string, args ...interface{}) (*sql.Rows, error)
    // ...
    // It's enough to implement only those methods that
    // the functions that depend on DBIface actually use.
    // If none of your functions ever calls SetConnMaxLifetime
    // you don't need to declare that method on the DBIface type.
}

type DBMock struct {}

func (DBMock) Query(query string, args ...interface{}) (*sql.Rows, error) {
    // ...
}

func GetProductByName(DB DBIface, name string) (p Product, err error) {
   ...
}
</code>```

DB parameter to GetProductByName is now mockable.

Title: How to mock functions in golang

Body:
I have written a simple package, which basically consists of a lot of getter functions. Each file in this package corresponds to a service, so for instance the product file, contains functions relating to the product service/db, order file to order service etc. Each function takes as parameters a db resource to the underlying db, and parameters for the sql, eg. productid, name, orderid. Each of the functions returns a struct (eg. Order, product) or an error:

// product.go

package lib

type Product struct {
   ID int
   Name string
   Price float
}

func GetProductById(DB *sql.DB, ID int) (p Product, err error) {
   q := "SELECT * FROM product WHERE id = " + ID
   ...
}

func GetProductByName(DB *sql.DB, name string) (p Product, err error) {
   ...
}

// order.go

package lib

type Order struct {
   ID int
   Date string
   Items []items
}

func GetOrderById(DB *sql.DB, ID int) (o Order, err error) {
   ...
}

The problem is that I'm not able to mock these functions from my main package. What I really like to do, is to rewrite the package, so I somehow can pass to function to a type instead. But I'm not sure how to do this. Especially not when the functions take different input parameters and return different structs. Is there a way to do this?

Body:
In Go you can NOT mock a function, or a method declared on a concrete type.

For example:

func F() { ... }

func (T) M() { ... }

F and M are not mockable in Go.

However you can mock function values, whether they are variables, fields on a struct, or parameters passed to other functions.

For example:

var Fn = func() { ... }

type S struct {
    Fn func()
}

func F(Fn func())

Fn in all three cases is mockable.

The other thing that you can mock in Go, and the prefered option most of the time, is an interface.

For example:

type ProductRepository interface {
    GetProductById(DB *sql.DB, ID int) (p Product, err error)
}

// the real implementater of the interface
type ProductStore struct{}

func (ProductStore) GetProductById(DB *sql.DB, ID int) (p Product, err error) {
    q := "SELECT * FROM product WHERE id = ?"
    // ...
}

// the mock implementer
type ProductRepositoryMock struct {}

func (ProductRepositoryMock) GetProductById(DB *sql.DB, ID int) (p Product, err error) {
    // ...
}

Now any piece of code that depends on ProductRepository can be passed a value of type ProductStore when you're in "normal mode" and a value of type ProductRepositoryMock when you're testing.

Another option using interfaces, which allows you to keep your functions mostly unchaged is to define an interface that mimics the methods of *sql.DB then use that interface type as the type to be passed to your functions, implement a mock version of that interface and use that during testing.

For example:

type DBIface interface {
    Query(query string, args ...interface{}) (*sql.Rows, error)
    // ...
    // It's enough to implement only those methods that
    // the functions that depend on DBIface actually use.
    // If none of your functions ever calls SetConnMaxLifetime
    // you don't need to declare that method on the DBIface type.
}

type DBMock struct {}

func (DBMock) Query(query string, args ...interface{}) (*sql.Rows, error) {
    // ...
}

func GetProductByName(DB DBIface, name string) (p Product, err error) {
   ...
}

DB parameter to GetProductByName is now mockable.


问:
Is there a SQL statement that will allow me to see results that match from 2 different tables?
I'm joining two tables (Employee and Matrix) and I'm wondering if there is a statement I can use to only show the names of employees that have a matrix attached to their names after joining the Employee and Matrix tables. I thought of possibly using 'Distinct', but I don't believe that would work as I'm trying to only see employees that have a matrix and this information would be coming from two different tables.
Any suggestion is appreciated. Thank you in advance.</p>

答:
It would definitely work:</p>

```<code>SELECT DISTINCT e.name
FROM employee e
INNER JOIN matrix m
ON e.id = m.employee_id
</code>```

Body:
It would definitely work:

SELECT DISTINCT e.name
FROM employee e
INNER JOIN matrix m
ON e.id = m.employee_id


问:
How to maintain action creator types in connected components with Redux, React and TypeScript?
I'm struggling to keep my actions in connected components type-safe.

Basically when I import a bunch of redux action creators, wrap them with the dispatcher using react-redux and pass them as props to a component, I'd like the resulting actions to maintain the original type information from the imported functions.

Actions have types and return type is inferred:

```<code>export const actionA = (p1: string, p2: number) =>
  ({ type: 'EXAMPLE_A', payload: { p1, p2 } })

export const actionB = (p1: number) =>
  ({ type: 'EXAMPLE_B', payload: p1 })
</code>```

But my component still has some any types to satisfy the compiler, losing type safety.

```<code>import * as React from 'react'
import { Dispatch, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as exampleActions from '../actions/example'

interface MyComponentProps {
  someStore: SomeStoreState,
  actions: any // <-- Just use whatever types exampleActions have?
}

class MyComponent extends React.Component<MyComponentProps, {}> {

  constructor(props: MyComponentProps) {
    super(props)
  }

  private foo() {
    const { actionA } = this.props.actions.exampleActions
    actionA('foo', 'bar') // <-- Compile time error pls
  }

  public render() {
    return null
  }

}

const mapStateToProps = (state: RootState) => ({
  someStore: state.someStore
})

const mapDispatchToProps = (dispatch: Dispatch<any>) => ({
  actions: {
    exampleActions: bindActionCreators<any>(exampleActions, dispatch)
  }
})

export default connect (mapStateToProps, mapDispatchToProps)(MyComponent)
</code>```

Declaring the function parameter types again in the props interface sorta helps, but I'd just like to maintain the original types so they are defined in one place.

I don't really care about the types within the dispatcher itself, so somehow casting the exampleTypes (and any other actions') type information to the props would be a good enough solution for me, as if the dispatch binding wasn't there at all and the creators themselves were passed as props.

Additionally, the application is using redux-promise-middleware, which means some actions may return promises. I'd also want that information to be preserved, so actions can be chained within the component. But I think with casting that shouldn't be an issue to begin with.

答:
You need to explicitly type your action creators, then import their types along with the functions themselves.  Creating some generic action interfaces can help with this, as typically I find the redux types themselves unhelpful.  It is a little verbose, but the type support is often worth it, especially as you can get excellent typings within your reducers as well.

I typically use something like this for the actions/creators:

```<code>export interface TypedAction<TAction, TPayload> {
     type: TAction;
     payload: TPayload;
}

export type TypeA = "EXAMPLE_A";
export type TypeB = "EXAMPLE_B";

export interface PayloadA {
    p1: string;
    p2: number;
}

export interface PayloadB {
    p1: number;
}

export type ActionA = TypedAction<TypeA, PayloadA>;
export type ActionB = TypedAction<TypeB, PayloadB>;

export type Actions = ActionA | ActionB;

export type ActionCreatorA = (p1: string, p2: number) => ActionA;

export type ActionCreatorB = (p1: number) => ActionB;

export const actionCreatorA: ActionCreatorA = (p1, p2) => ({
    type: "EXAMPLE_A",
    payload: {
        p1,
        p2
    }
});

export const actionCreatorB: ActionCreatorB = (p1) => ({
    type: "EXAMPLE_B",
    payload: {
        p1
    }
});
</code>```

Which can be used in a component as:

```<code>import * as React from 'react'
import { Dispatch, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {
    actionCreatorA, ActionCreatorA,
    actionCreatorB, ActionCreatorB
} from '../actions/example'

interface MyComponentProps {
    someStore: SomeStoreState;
    actionCreatorA: ActionCreatorA;
    actionCreatorB: ActionCreatorB;
}

class MyComponent extends React.Component<MyComponentProps, {}> {

    constructor(props: MyComponentProps) {
        super(props)
    }

    private foo() {
        const { actionA } = this.props;
        actionA('foo', 'bar') // <-- Compiles
    }

    public render() {
        return null
    }

}

const mapStateToProps = (state: RootState) => ({
    someStore: state.someStore
})

const mapDispatchToProps = {
    actionCreatorA
};

export default connect (mapStateToProps, mapDispatchToProps)(MyComponent)
</code>```

Reducers can also benefit by using:

```<code>import ( Actions } from "./actions/example";

// Actions here is the union type of all actions this reducer will
// handle, as exported from the actions file
export const someReducer = (state = defaultState, action: Actions) => {
    switch (action.type) {
        case "EXAMPLE_A":
            // action is typed as ActionA
            return {
                p1: action.p1,
                p2: action.p2
            };
        case "EXAMPLE_B":
            // action is typed as ActionB
            return {
                p1: action.p1,
                p2: action.p2  // <-- Does not compile, p2 does not exist on ActionB
            };
        default:
            return state;
    }
}
</code>```

Body:
I'm struggling to keep my actions in connected components type-safe.

Basically when I import a bunch of redux action creators, wrap them with the dispatcher using react-redux and pass them as props to a component, I'd like the resulting actions to maintain the original type information from the imported functions.

Actions have types and return type is inferred:

export const actionA = (p1: string, p2: number) =>
  ({ type: 'EXAMPLE_A', payload: { p1, p2 } })

export const actionB = (p1: number) =>
  ({ type: 'EXAMPLE_B', payload: p1 })

But my component still has some any types to satisfy the compiler, losing type safety.

import * as React from 'react'
import { Dispatch, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as exampleActions from '../actions/example'

interface MyComponentProps {
  someStore: SomeStoreState,
  actions: any // <-- Just use whatever types exampleActions have?
}

class MyComponent extends React.Component<MyComponentProps, {}> {

  constructor(props: MyComponentProps) {
    super(props)
  }

  private foo() {
    const { actionA } = this.props.actions.exampleActions
    actionA('foo', 'bar') // <-- Compile time error pls
  }

  public render() {
    return null
  }

}

const mapStateToProps = (state: RootState) => ({
  someStore: state.someStore
})

const mapDispatchToProps = (dispatch: Dispatch<any>) => ({
  actions: {
    exampleActions: bindActionCreators<any>(exampleActions, dispatch)
  }
})

export default connect (mapStateToProps, mapDispatchToProps)(MyComponent)

Declaring the function parameter types again in the props interface sorta helps, but I'd just like to maintain the original types so they are defined in one place.

I don't really care about the types within the dispatcher itself, so somehow casting the exampleTypes (and any other actions') type information to the props would be a good enough solution for me, as if the dispatch binding wasn't there at all and the creators themselves were passed as props.

Additionally, the application is using redux-promise-middleware, which means some actions may return promises. I'd also want that information to be preserved, so actions can be chained within the component. But I think with casting that shouldn't be an issue to begin with.

Body:
You need to explicitly type your action creators, then import their types along with the functions themselves.  Creating some generic action interfaces can help with this, as typically I find the redux types themselves unhelpful.  It is a little verbose, but the type support is often worth it, especially as you can get excellent typings within your reducers as well.

I typically use something like this for the actions/creators:

export interface TypedAction<TAction, TPayload> {
     type: TAction;
     payload: TPayload;
}

export type TypeA = "EXAMPLE_A";
export type TypeB = "EXAMPLE_B";

export interface PayloadA {
    p1: string;
    p2: number;
}

export interface PayloadB {
    p1: number;
}

export type ActionA = TypedAction<TypeA, PayloadA>;
export type ActionB = TypedAction<TypeB, PayloadB>;

export type Actions = ActionA | ActionB;

export type ActionCreatorA = (p1: string, p2: number) => ActionA;

export type ActionCreatorB = (p1: number) => ActionB;

export const actionCreatorA: ActionCreatorA = (p1, p2) => ({
    type: "EXAMPLE_A",
    payload: {
        p1,
        p2
    }
});

export const actionCreatorB: ActionCreatorB = (p1) => ({
    type: "EXAMPLE_B",
    payload: {
        p1
    }
});

Which can be used in a component as:

import * as React from 'react'
import { Dispatch, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {
    actionCreatorA, ActionCreatorA,
    actionCreatorB, ActionCreatorB
} from '../actions/example'

interface MyComponentProps {
    someStore: SomeStoreState;
    actionCreatorA: ActionCreatorA;
    actionCreatorB: ActionCreatorB;
}

class MyComponent extends React.Component<MyComponentProps, {}> {

    constructor(props: MyComponentProps) {
        super(props)
    }

    private foo() {
        const { actionA } = this.props;
        actionA('foo', 'bar') // <-- Compiles
    }

    public render() {
        return null
    }

}

const mapStateToProps = (state: RootState) => ({
    someStore: state.someStore
})

const mapDispatchToProps = {
    actionCreatorA
};

export default connect (mapStateToProps, mapDispatchToProps)(MyComponent)

Reducers can also benefit by using:

import ( Actions } from "./actions/example";

// Actions here is the union type of all actions this reducer will
// handle, as exported from the actions file
export const someReducer = (state = defaultState, action: Actions) => {
    switch (action.type) {
        case "EXAMPLE_A":
            // action is typed as ActionA
            return {
                p1: action.p1,
                p2: action.p2
            };
        case "EXAMPLE_B":
            // action is typed as ActionB
            return {
                p1: action.p1,
                p2: action.p2  // <-- Does not compile, p2 does not exist on ActionB
            };
        default:
            return state;
    }
}


答:
I think exists does what you want:

```<code>select e.*
from employee e
where exists (select 1 from matrix m where m.employee_id = e.employee_id);
</code>```

Title: Is there a SQL statement that will allow me to see results that match from 2 different tables?

Body:
I'm joining two tables (Employee and Matrix) and I'm wondering if there is a statement I can use to only show the names of employees that have a matrix attached to their names after joining the Employee and Matrix tables. I thought of possibly using 'Distinct', but I don't believe that would work as I'm trying to only see employees that have a matrix and this information would be coming from two different tables.
Any suggestion is appreciated. Thank you in advance.

Body:
I think exists does what you want:

select e.*
from employee e
where exists (select 1 from matrix m where m.employee_id = e.employee_id);