问:
Why a lot of lapack functions are missing from scipy interface
In lapack there are much more functions than in "lapack interface" in scipy. Is there any reason behind this and is there OS-independentway to call lapack functions directly?

I realize that I may call dinamic library directly, but this means writing my own wrapper and this is not what I want.

To make a real usecase, I need to call dsbgv to solve generalized eigenproblem for banded matrix. It is orders of magnitude faster than using eig which is for general matrix.

答:
scipy.linalg.lapack is an organically grown (tm) set of wrappers, added by different people with different goals, needs, motivations and time budgets over quite a few years.

cython_lapack is a complete set of wrappers for a certain (old enough) version of LAPACK. It is lower level however: you need to supply all lapack arguments, ensure the correct array ordering, alignment etc.


来源: stackexchange

问:
Gulp sourcemaps + different CSS preprocessors?
Here's a simplified version of the task I'm using:

```<code>g = require 'gulp'
$ = require('gulp-load-plugins')()

g.task 'vendor:styles', ->
    sass_filter = $.filter('*.scss')
    less_filter = $.filter('*.less')

    g.src(['vendor/font-awesome-4.2.0/scss/font-awesome.scss', 'vendor/bootstrap-3.2.0/less/bootstrap.less'])
        .pipe $.sourcemaps.init()
        .pipe(sass_filter).pipe($.sass()).pipe(sass_filter.restore())
        .pipe(less_filter).pipe($.less(strictMath: true)).pipe(less_filter.restore())
        .pipe $.concat('vendor.css')
        .pipe $.sourcemaps.write('./maps')
        .pipe g.dest('.tmp/styles/vendor')
</code>```

(This is Coffeescript, but the Javascript is almost identical. I can provide the JS if the above is difficult to parse.)

When running the above, gulp-sourcemaps throws:

```<code>gulp-sourcemap-write: source file not found:/Users/pikeas/Documents/code/pypjs/crypto/front/merged/vendor/font-awesome-4.2.0/scss/normalize.less
...(repeated x20, for print.less, carousel.less, etc)
</code>```

In other words, it's looking for Bootstrap's files in the Font Awesome directory. I've tried using gulp-if instead of gulp-filter, but that also fails with the same error.

What's the right way to write this task?

答:
I managed to write a gulpfile.js that takes care of whatever styles my project contains (.scss, .less, .css). All neccessary files are compiled into css, then all is automatically prefixed, minimalized and concated into 1 file. All with their sourcemaps.

const sass = require('gulp-sass');
const less = require('gulp-less');
const gulpIf = require('gulp-if');
const browserSync = require('browser-sync').create();
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const autoprefixer = require('autoprefixer');
const concat = require('gulp-concat');

gulp.task('styles', function() {
  return gulp.src(['assets/libs/**/*.less', 'assets/libs/**/*.scss', 'assets/libs/**/*.css', '!assets/libs/all.css'])
    .pipe(sourcemaps.init())
    .pipe(gulpIf('**/*.less', less().on('error', onErrorLogContinue), gulpIf('**/*.scss', sass().on('error', onErrorLogContinue))))
    .pipe(postcss([
        autoprefixer({browsers: ['last 2 versions']}),
        cssnano(),
    ]))
    .pipe(concat('all.css',{newLine: ''}))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('assets/libs'))
    .pipe(browserSync.reload({
      stream: true
    }));
});```

ContentLicense: CC BY-SA 3.0

Body:
Here's a simplified version of the task I'm using:

g = require 'gulp'
$ = require('gulp-load-plugins')()

g.task 'vendor:styles', ->
    sass_filter = $.filter('*.scss')
    less_filter = $.filter('*.less')

    g.src(['vendor/font-awesome-4.2.0/scss/font-awesome.scss', 'vendor/bootstrap-3.2.0/less/bootstrap.less'])
        .pipe $.sourcemaps.init()
        .pipe(sass_filter).pipe($.sass()).pipe(sass_filter.restore())
        .pipe(less_filter).pipe($.less(strictMath: true)).pipe(less_filter.restore())
        .pipe $.concat('vendor.css')
        .pipe $.sourcemaps.write('./maps')
        .pipe g.dest('.tmp/styles/vendor')

(This is Coffeescript, but the Javascript is almost identical. I can provide the JS if the above is difficult to parse.)

When running the above, gulp-sourcemaps throws:

gulp-sourcemap-write: source file not found:/Users/pikeas/Documents/code/pypjs/crypto/front/merged/vendor/font-awesome-4.2.0/scss/normalize.less
...(repeated x20, for print.less, carousel.less, etc)

In other words, it's looking for Bootstrap's files in the Font Awesome directory. I've tried using gulp-if instead of gulp-filter, but that also fails with the same error.

What's the right way to write this task?


问:
Calling pkill to pause a process with subprocess inside a class in python suspends the python script
I have a class that contains a "blocking method". Inside that method, I am listening to keys to perform some actions. The action in question is pkill. Below I am pasting it:

```<code>def show_control(self, control):
    """docstring for control"""
    if control == True:
        from mkchromecast.getch import getch, pause

        self.controls_msg()
        try:
            while(True):
                key = getch()
                if(key == 'p'):
                    if self.videoarg == True:
                        print('Pausing Casting Process...')
                        subprocess.call(['pkill', '-STOP', '-f', 'ffmpeg'])
                    ...
</code>```

It turns out that the ffmpeg process is paused, but the python script gets suspended?. I don't understand why that is the case. If one creates the same function in a regular script (not inside a class to be clearer) this does not happen. I have tried using multithreading and multiprocessing modules without success. What am I doing wrong?. Thanks.

答:
I will answer myself. The problem was related to the subprocess being inside the try block. What I did to solve it was to create a new method that contained the subprocess launching the  pkill command:

```<code>def show_control(self, control):
"""docstring for control"""
if control == True:
    from mkchromecast.getch import getch, pause

    self.controls_msg()
    try:
        while(True):
            key = getch()
            if(key == 'p'):
                if self.videoarg == True:
                    print('Pausing Casting Process...')
                    action = 'pause'
                    self.ffmpeg_handler(action)
                ...

def ffmpeg_handler(self, action):
    if action ==  'pause':
        subprocess.call(['pkill', '-STOP', '-f', 'ffmpeg'])
</code>```

See here.

Body:
I have a class that contains a "blocking method". Inside that method, I am listening to keys to perform some actions. The action in question is pkill. Below I am pasting it:

def show_control(self, control):
    """docstring for control"""
    if control == True:
        from mkchromecast.getch import getch, pause

        self.controls_msg()
        try:
            while(True):
                key = getch()
                if(key == 'p'):
                    if self.videoarg == True:
                        print('Pausing Casting Process...')
                        subprocess.call(['pkill', '-STOP', '-f', 'ffmpeg'])
                    ...

It turns out that the ffmpeg process is paused, but the python script gets suspended?. I don't understand why that is the case. If one creates the same function in a regular script (not inside a class to be clearer) this does not happen. I have tried using multithreading and multiprocessing modules without success. What am I doing wrong?. Thanks.

Body:
I will answer myself. The problem was related to the subprocess being inside the try block. What I did to solve it was to create a new method that contained the subprocess launching the  pkill command:

def show_control(self, control):
"""docstring for control"""
if control == True:
    from mkchromecast.getch import getch, pause

    self.controls_msg()
    try:
        while(True):
            key = getch()
            if(key == 'p'):
                if self.videoarg == True:
                    print('Pausing Casting Process...')
                    action = 'pause'
                    self.ffmpeg_handler(action)
                ...

def ffmpeg_handler(self, action):
    if action ==  'pause':
        subprocess.call(['pkill', '-STOP', '-f', 'ffmpeg'])

See here.


问:
Random A everywhere in HTML page
I just started learning HTML and I'm getting all these capital As everywhere in my page when I load it in I.E. or Firefox

For example

```<code><p style="color:red; text-align:center; text-shadow: 2px 2px
yellow;">
Hello I'm new to HTML but -j won't help -A idk why! & bye.
</code>```

And it'll show up as

```<code> HelloÂ I'm new toÂÂ HTML butÂ -j wontÂ help -ÂÂ idk whyÂ! & byeÂ.
</code>```

答:
This is a problem with HTML encoding. Your file is probably encoded in UTF-8, and your browser is probably trying to read it as if it were encoded in ISO-8859-1. Adding a charset declaration inside you head tags like this should fix your problem: </p>

```<code><html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    // Your text here
  </body>
</html>
</code>```

Title: Random A everywhere in HTML page

Body:
I just started learning HTML and I'm getting all these capital As everywhere in my page when I load it in I.E. or Firefox

For example

Hello I'm new to HTML but -j won't help -A idk why! & bye.

And it'll show up as

 HelloÂ I'm new toÂÂ HTML butÂ -j wontÂ help -ÂÂ idk whyÂ! & byeÂ.

Body:
This is a problem with HTML encoding. Your file is probably encoded in UTF-8, and your browser is probably trying to read it as if it were encoded in ISO-8859-1. Adding a charset declaration inside you head tags like this should fix your problem:

<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    // Your text here
  </body>
</html>


问:
How to apply different policies to service and proxy service?
I have a mule service, named IS, deployed on mule runtime and proxied on API gateway. I'd like to set up different policies to the IS and its proxy service. How can I do it?

My environment:

Mule runtime: 3.7.4

Mule API gateway: 2.1.1

答:
If you're using Mule runtime v3.8.x, and if the service is an HTTP/S listener, you can actually make it auto-discovered in the API Manager and have policies applied directly on it, even if the mule config is not generated using APIkit.

https://docs.mulesoft.com/api-manager/api-auto-discovery

Choose the flow that you want the API Manager to manage and apply policies.

Do note that you will need to have to right entitlement (API Gateway) in the Mule Runtime license and that it has the right Anypoint Platform Client ID/Secret pairs configured in the wrapper.conf. The IDs should be automatically configured if you've added the Mule Runtime server in the Anypoint Runtime Manager.


问:
Installing an R package from local unzipped folder
I am having difficulty installing an unzipped package on a Windows 7 computer without administrative privileges and no internet access. I am using the RGui (not RStudio).

Right now I have an unzipped library sitting in a directory. Unfortunately, when I try:

```<code>install.packages("C://path//to//directory",
    repos = NULL,
    lib = "C://path//to//newDirectory")
</code>```

I am getting the error:

```<code>Warning in `install.packages("C://path//to//directory",`   :
   'lib = "C://path//to//newDirectory"' is not writable
</code>```

Which is strange because I do have write privileges to where I am attempting to store the package.

When I get this error, I also get a popup from RGui:

```<code>Would you like to use a personal library instead?
</code>```

If I click Yes, it throws the error:

```<code>Error in `install.packages("C://path//to//directory",`   :
    type == "both" cannot be used with 'repos = NULL'
</code>```

I also cannot install devtools. Any ideas?

答:
I think the error message is actually just wrong.  You need to give the file name of the package, not just the directory.  </p>

```<code>install.packages("C://path//to//directory//MY_PACKAGE.tar.gz",
    repos = NULL,
    lib = "C://path//to//newDirectory")
</code>```

Body:
I am having difficulty installing an unzipped package on a Windows 7 computer without administrative privileges and no internet access. I am using the RGui (not RStudio).

Right now I have an unzipped library sitting in a directory. Unfortunately, when I try:

install.packages("C://path//to//directory",
    repos = NULL,
    lib = "C://path//to//newDirectory")

I am getting the error:

Warning in `install.packages("C://path//to//directory",`   :
   'lib = "C://path//to//newDirectory"' is not writable

Which is strange because I do have write privileges to where I am attempting to store the package.

When I get this error, I also get a popup from RGui:

Would you like to use a personal library instead?

If I click Yes, it throws the error:

Error in `install.packages("C://path//to//directory",`   :
    type == "both" cannot be used with 'repos = NULL'

I also cannot install devtools. Any ideas?

Body:
I think the error message is actually just wrong.  You need to give the file name of the package, not just the directory.

install.packages("C://path//to//directory//MY_PACKAGE.tar.gz",
    repos = NULL,
    lib = "C://path//to//newDirectory")


问:
How to use quotes in bash scrips when a command in the script needs quotes too?
I am attempting to make a script that will make a backup file of a video file in the same directory with the time stamp at the end of the tar file. The script is for demonstration purposes only, that is why I do not intend on sending the file to a different directory. Below is how far I have come with it.

```<code>#!/bin/bash
cd Compression_Play/
echo Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz
tar -I "pixz -9t" -cvf Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz 2017-03-23_01-13-02.avi
</code>```

My problem is whenever I try to execute the script it gives me this:

```<code>Me.29_Mar_2017-22:03:49.tar.xz
tar: -9: (PROGRAM ERROR) Option should have been recognized!?
Try 'tar --help' or 'tar --usage' for more information.
</code>```

As best as I can tell the problem is with the quotes in my tar command. Is there a way to make the script so I can keep the quotes or substitute them?

答:
Greg gave a good answer and it works very well. I also figured out another way after nocking my head on it for several hours and taking the things from the help I got.

#!/bin/bash
cd /home/apowell/Compression_Play/Test_Backup
tar -I 'pixz -9t' -cvf Me.$(date +%d_%b_%Y-%H_%M_%S).tar.xz /home/apowell/Compression_Play/Linux_Programs

and this one compresses a little more by replacing pixz with just plain xz.

#!/bin/bash
cd /home/apowell/Compression_Play/Test_Backup
tar -I 'xz -9ve -T8 -k' -cvf Me.$(date +%d_%b_%Y-%H_%M_%S).tar.xz /home/apowell/Compression_Play/Linux_Programs

Body:
I am attempting to make a script that will make a backup file of a video file in the same directory with the time stamp at the end of the tar file. The script is for demonstration purposes only, that is why I do not intend on sending the file to a different directory. Below is how far I have come with it.

#!/bin/bash
cd Compression_Play/
echo Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz
tar -I "pixz -9t" -cvf Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz 2017-03-23_01-13-02.avi

My problem is whenever I try to execute the script it gives me this:

Me.29_Mar_2017-22:03:49.tar.xz
tar: -9: (PROGRAM ERROR) Option should have been recognized!?
Try 'tar --help' or 'tar --usage' for more information.

As best as I can tell the problem is with the quotes in my tar command. Is there a way to make the script so I can keep the quotes or substitute them?


问:
How to detect UserAgent within an NPAPI plug-in before it is registered by the browser?
I need to figure out a way to install plug-ins specifically for Safari on Mac. If I copy the .plugin files into the Internet Plug-ins folder, it will be detected by Firefox and Google Chrome as well when they are run.

To prevent this I was using the NP_UserAgent API call to determine the user agent, and exit if it wasn't Safari. However the plug-ins are still registered by Google Chrome and Firefox. Is there anyway to do the same thing without having either browser register the plug-in?

答:
If you are writing an NPAPI plugin it should work in any browser. Can you explain why you are trying to prevent users running other browsers from using the plugin? Depending on the underlying need there may be a better approach. (For instance, if this is to work in conjunction with a Safari extension, all you need to do is have your extension use a MIME type that only your plugin handles, and then it doesn't matter if other browsers detect the plugin because it will never actually be instantiated).

Do you want to target only Safari, or any browser using Apple's WebKit framework? If the latter, you could write a WebKit plugin instead of an NPAPI plugin.

ContentLicense: CC BY-SA 2.5


问:
c# dot operator overhead: What is more efficient
So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

```<code>public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}
</code>```

And the following two examples of usage is where I want the insight.

Example 1:

```<code>public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}
</code>```

Example 2:

```<code>public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}
</code>```

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC.
Does this matter? Is the difference in performance significant?

答:
While the initial thought would be that the compiler would optimize to the same IL, that apparently isn't true

While I haven't checked the IL, a quick and dirty stopwatch test shows that the grandchild route is much faster

Using the view models from the question, this would be the results:

```<code>var parent = new ParentViewModel();
var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;
var watch = new Stopwatch();

var a = parent.Child.GrandChild.GreatGrandChild.intA;
var b = parent.Child.GrandChild.GreatGrandChild.intB;
var c = parent.Child.GrandChild.GreatGrandChild.intC;

var bothTotal = 0L;
var longTotal = 0L;
var shortTotal = 0L;

watch.Start();
a = parent.Child.GrandChild.GreatGrandChild.intA;
b = parent.Child.GrandChild.GreatGrandChild.intB;
c = parent.Child.GrandChild.GreatGrandChild.intC;
a = greatGrandChild.intA;
b = greatGrandChild.intB;
c = greatGrandChild.intC;
watch.Stop();
bothTotal += watch.ElapsedTicks;
watch.Reset();
Console.WriteLine("Longhand and Shorthand: " + bothTotal);

watch.Start();
a = parent.Child.GrandChild.GreatGrandChild.intA;
b = parent.Child.GrandChild.GreatGrandChild.intB;
c = parent.Child.GrandChild.GreatGrandChild.intC;
a = parent.Child.GrandChild.GreatGrandChild.intA;
b = parent.Child.GrandChild.GreatGrandChild.intB;
c = parent.Child.GrandChild.GreatGrandChild.intC;
watch.Stop();
longTotal += watch.ElapsedTicks;
watch.Reset();
Console.WriteLine("Longhand Only: " + longTotal);

watch.Start();
a = greatGrandChild.intA;
b = greatGrandChild.intB;
c = greatGrandChild.intC;
a = greatGrandChild.intA;
b = greatGrandChild.intB;
c = greatGrandChild.intC;
watch.Stop();
shortTotal += watch.ElapsedTicks;
watch.Reset();
Console.WriteLine("Shorthand Only: " + shortTotal);
</code>```

These were my typical results:

```<code>Longhand and Shorthand: 22
Longhand Only: 3
Shorthand Only: 2
</code>```

This is obviously not the most granular test and there are definitely things about it that could be argued lean this towards confirmation bias - but on the surface it does appear that the 'shorthand' route is more optimal and that further testing is merited

UPDATE

I went through and checked out the IL that is generated and, well, the results are pretty clear:

Longhand:

```<code>// Setup the object:
newobj     instance void ParentViewModel::.ctor()

// Actually call the members:
callvirt   instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel
GrandChildViewModel::get_GreatGrandChild()
callvirt   instance int32 GreatGrandChildViewModel::get_intA()
callvirt   instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel
GrandChildViewModel::get_GreatGrandChild()
callvirt   instance int32 GreatGrandChildViewModel::get_intB()
callvirt   instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel
GrandChildViewModel::get_GreatGrandChild()
callvirt   instance int32 GreatGrandChildViewModel::get_intC()
</code>```

Shorthand:

```<code>// Setup the object
newobj     instance void ParentViewModel::.ctor()
call       instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel GrandChildViewModel::get_GreatGrandChild()

// Actually call the members:
callvirt   instance int32 GreatGrandChildViewModel::get_intA()
callvirt   instance int32 GreatGrandChildViewModel::get_intB()
callvirt   instance int32 GreatGrandChildViewModel::get_intC()
</code>```

Body:
So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}

And the following two examples of usage is where I want the insight.

Example 1:

public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}

Example 2:

public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC.
Does this matter? Is the difference in performance significant?

Body:
While the initial thought would be that the compiler would optimize to the same IL, that apparently isn't true

While I haven't checked the IL, a quick and dirty stopwatch test shows that the grandchild route is much faster

Using the view models from the question, this would be the results:

var parent = new ParentViewModel();
var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;
var watch = new Stopwatch();

var a = parent.Child.GrandChild.GreatGrandChild.intA;
var b = parent.Child.GrandChild.GreatGrandChild.intB;
var c = parent.Child.GrandChild.GreatGrandChild.intC;

var bothTotal = 0L;
var longTotal = 0L;
var shortTotal = 0L;

watch.Start();
a = parent.Child.GrandChild.GreatGrandChild.intA;
b = parent.Child.GrandChild.GreatGrandChild.intB;
c = parent.Child.GrandChild.GreatGrandChild.intC;
a = greatGrandChild.intA;
b = greatGrandChild.intB;
c = greatGrandChild.intC;
watch.Stop();
bothTotal += watch.ElapsedTicks;
watch.Reset();
Console.WriteLine("Longhand and Shorthand: " + bothTotal);

watch.Start();
a = parent.Child.GrandChild.GreatGrandChild.intA;
b = parent.Child.GrandChild.GreatGrandChild.intB;
c = parent.Child.GrandChild.GreatGrandChild.intC;
a = parent.Child.GrandChild.GreatGrandChild.intA;
b = parent.Child.GrandChild.GreatGrandChild.intB;
c = parent.Child.GrandChild.GreatGrandChild.intC;
watch.Stop();
longTotal += watch.ElapsedTicks;
watch.Reset();
Console.WriteLine("Longhand Only: " + longTotal);

watch.Start();
a = greatGrandChild.intA;
b = greatGrandChild.intB;
c = greatGrandChild.intC;
a = greatGrandChild.intA;
b = greatGrandChild.intB;
c = greatGrandChild.intC;
watch.Stop();
shortTotal += watch.ElapsedTicks;
watch.Reset();
Console.WriteLine("Shorthand Only: " + shortTotal);

These were my typical results:

Longhand and Shorthand: 22
Longhand Only: 3
Shorthand Only: 2

This is obviously not the most granular test and there are definitely things about it that could be argued lean this towards confirmation bias - but on the surface it does appear that the 'shorthand' route is more optimal and that further testing is merited

UPDATE

I went through and checked out the IL that is generated and, well, the results are pretty clear:

Longhand:

// Setup the object:
newobj     instance void ParentViewModel::.ctor()

// Actually call the members:
callvirt   instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel
GrandChildViewModel::get_GreatGrandChild()
callvirt   instance int32 GreatGrandChildViewModel::get_intA()
callvirt   instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel
GrandChildViewModel::get_GreatGrandChild()
callvirt   instance int32 GreatGrandChildViewModel::get_intB()
callvirt   instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel
GrandChildViewModel::get_GreatGrandChild()
callvirt   instance int32 GreatGrandChildViewModel::get_intC()

Shorthand:

// Setup the object
newobj     instance void ParentViewModel::.ctor()
call       instance class ChildViewModel ParentViewModel::get_Child()
callvirt   instance class GrandChildViewModel ChildViewModel::get_GrandChild()
callvirt   instance class GreatGrandChildViewModel GrandChildViewModel::get_GreatGrandChild()

// Actually call the members:
callvirt   instance int32 GreatGrandChildViewModel::get_intA()
callvirt   instance int32 GreatGrandChildViewModel::get_intB()
callvirt   instance int32 GreatGrandChildViewModel::get_intC()


问:
Declaring Height of an Article
 I am working on creating my Portfolio Website gw.mvctc.com/Class2018/smcintosh I recently converted it partly to bootstrap, and it looks ok, but as you can see, on the home page, there is a horizontal scroll to nothing, and the boxes are not the same height. I have figured out that the horiz. scroll is the same width as the vertical scroll bar, so I'm not sure if that is part of the issue, or not.

How can I fix the horizontal scroll issue and how do I make the boxes  the same height?

At the moment i have this style code on my article, the object that has the box:

```<code>article {
    padding: 10px;
    border: #ff4100 solid 7.5px;
    border-radius: 15px;
}
</code>```

and this is the HTML for the article itself:

```<code><div class="fluid-container">
    <div class="row">
        <section class="col-lg-4 col-md-6 col-sm-6">
            <article>
                <h2>Education Goals</h2>
                <ul>
                    <li>At the moment my largest education goal is to graduate
                        from high school</li>
                    <li>I hope to have enough scholarships to be able to go to a
                        good college to further my education and gain more knowledge</li>
                    <li>I hope to graduate from a good college with a bachelor's
                        degree in some form of computer science</li>
                </ul>
            </article>
        </section>
        //More sections follow, hence the 2 other boxes
        //...
    </div>
</div>
</code>```

答:
The issue with the horizontal scrollbar is that you are applying a fluid-container class, when it should be container-fluid.

For the height you could use a plugin like matchHeight or override the bootstrap CSS and make it use flexbox (see How can I make Bootstrap columns all the same height?).

(btw, bootstrap 4 uses flexbox)

Title: Declaring Height of an Article

Body:
 I am working on creating my Portfolio Website gw.mvctc.com/Class2018/smcintosh I recently converted it partly to bootstrap, and it looks ok, but as you can see, on the home page, there is a horizontal scroll to nothing, and the boxes are not the same height. I have figured out that the horiz. scroll is the same width as the vertical scroll bar, so I'm not sure if that is part of the issue, or not.

How can I fix the horizontal scroll issue and how do I make the boxes  the same height?

At the moment i have this style code on my article, the object that has the box:

article {
    padding: 10px;
    border: #ff4100 solid 7.5px;
    border-radius: 15px;
}

and this is the HTML for the article itself:

Education Goals

At the moment my largest education goal is to graduate
                        from high school

I hope to have enough scholarships to be able to go to a
                        good college to further my education and gain more knowledge

I hope to graduate from a good college with a bachelor's
                        degree in some form of computer science

        //More sections follow, hence the 2 other boxes
        //...


问:
How to make a jQuery autocomplete's results go away immediately
I have a jQuery autocomplete field on one of my pages. When I'm focused on the autocomplete field and I hit tab, it takes a little bit for the list of results to go away. Also, if I hit enter in the autocomplete field, the results stick around forever.

Is there an easy, preferably built-in way to make the result list go away immediately when the field loses focus or when I press enter? I could write my own solution by observing the blur and keypress events but it seems like something that would probably already be out there.

Body: $(".ac_results").css("display", "none");


问:
What is the date format for this string?
I've got the following date as a string

```<code>2017-03-01T10:15:41-0800
</code>```

that I'm trying to use with

```<code>new Date().parse('dd/mm/yyyy', dateString)
</code>```

However, I can't figure out the format.

答:
Consider using SimpleDateFormat:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class Main {
  public static void main(String[] args) {
    try {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
      Date parsed = format.parse("2017-03-01T10:15:41-0800");
    } catch (ParseException e){
      e.printStackTrace();
    }
  }
}
</code>```

Try it here!

Body:
I've got the following date as a string

2017-03-01T10:15:41-0800

that I'm trying to use with

new Date().parse('dd/mm/yyyy', dateString)

However, I can't figure out the format.

Body:
Consider using SimpleDateFormat:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class Main {
  public static void main(String[] args) {
    try {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
      Date parsed = format.parse("2017-03-01T10:15:41-0800");
    } catch (ParseException e){
      e.printStackTrace();
    }
  }
}

Try it here!


问:
C: how to structure if-else statements
I'm trying to build a weather calculator for a class.

The problem seems to be with my if-else statements. The if's are supposed to print out separate statements about weather conditions based on average temperatures. For some reason, the program always outputs the second statement: "\nThese two weeks were quite hot".

How can I structure my if-else statements correctly?

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

int main(void){
    int high_temp[14];
    int warmdays = 0, colddays = 0, i = 0;
    float average = 0.0f, sum = 0.0f;

    printf("\nWeather Analyzer Application by Joey Peters");
    for(i = 0; i < 14; i++) {
        printf("\n\nPlease enter the temperature for day #%d ", i+1);
        scanf("%d", &high_temp[i]);

        sum += high_temp[i];

        if(high_temp[i] > 60){
            warmdays++;
        }

        if(high_temp[i] < 60){
            colddays++;
        }

    }

        average = sum / 14;
        printf("\nThe number of warm days: %d", warmdays);
        printf("\nThe nuber of cold days: %d", colddays);
        printf("\nThe average high temperature: %.2f", average);

        if(average = 100 || average >= 90 ){
            printf("These two weeks were blazing hot");
        }
    else
        if(average >= 80 || average <= 89){
            printf("\nThese two weeks were quite hot");
        }
    else

        if(average >= 70 || average <= 79){
            printf("\nThese two weeks hot for Michigan");
        }
    else

        if(average >= 60 || average <= 69){
            printf("\nThese two weeks were decent for Michigan");
        }
    else
        if(average >= 50 || average <= 59){
            printf("\nThese two weeks were somewhat cold");
        }
    else
        if(average < 50){
            printf("\nThese two weeks were basically cold");
        }

    printf("\n\nThank you for using the weather analyzer!");
    return 0;

}
</code>```

答:
The line where you have

if(average = 100 || average >= 90 )

You are assigning 100 to x, instead of comparing it. Change it to this:

if(average == 100 || average >= 90 )

Or simplify it further by changing it to

if(average >= 90 )

Since there's no point in checking if average is 100 if you're already checking if it's greater than 90.

Also, if you're checking if average is in between 2 numbers, like 80 and 89 for example, use the && operator:

if(average >= 80 && average <= 89)

Title: C: how to structure if-else statements

Body:
I'm trying to build a weather calculator for a class.

The problem seems to be with my if-else statements. The if's are supposed to print out separate statements about weather conditions based on average temperatures. For some reason, the program always outputs the second statement: "\nThese two weeks were quite hot".

How can I structure my if-else statements correctly?

#include <stdio.h>

int main(void){
    int high_temp[14];
    int warmdays = 0, colddays = 0, i = 0;
    float average = 0.0f, sum = 0.0f;

    printf("\nWeather Analyzer Application by Joey Peters");
    for(i = 0; i < 14; i++) {
        printf("\n\nPlease enter the temperature for day #%d ", i+1);
        scanf("%d", &high_temp[i]);

        sum += high_temp[i];

        if(high_temp[i] > 60){
            warmdays++;
        }

        if(high_temp[i] < 60){
            colddays++;
        }

    }

        average = sum / 14;
        printf("\nThe number of warm days: %d", warmdays);
        printf("\nThe nuber of cold days: %d", colddays);
        printf("\nThe average high temperature: %.2f", average);

        if(average = 100 || average >= 90 ){
            printf("These two weeks were blazing hot");
        }
    else
        if(average >= 80 || average <= 89){
            printf("\nThese two weeks were quite hot");
        }
    else

        if(average >= 70 || average <= 79){
            printf("\nThese two weeks hot for Michigan");
        }
    else

        if(average >= 60 || average <= 69){
            printf("\nThese two weeks were decent for Michigan");
        }
    else
        if(average >= 50 || average <= 59){
            printf("\nThese two weeks were somewhat cold");
        }
    else
        if(average < 50){
            printf("\nThese two weeks were basically cold");
        }

    printf("\n\nThank you for using the weather analyzer!");
    return 0;

}


问:
Is there some kind of open javascript library for BigQuery UDFs (for Google Analytics data)?
As in topic. Perphaps some of you have stumbled upon the javascript library available in public or list of examples that would be particulary useful while using BigQuery with Google Analytics data? Interesting blog articles count too :)</p>

答:
What you really need is BigQuery Analytics Cookbook

It has quite a wide range of useful use-cases / examples

```<code>Query optimization
Tips and best practices
    •   Query multiple tables
    •   3 Days using comma separated table names
    •   Last 7 Days using TABLE_DATE_RANGE
    •   Last 3 Months using TABLE_DATE_RANGE
    •   Last 1 Year using TABLE_DATE_RANGE
    •   Specific Date Range
    •   Last 6 Days plus Today’s data (intraday) using multiple TABLE_DATE_RANGE
Basic query examples
•   Total [metric] per [dimension]
•   Average bounce rate per [dimension]
•   Average number of product pageviews by purchaser type
•   Average number of transactions per purchaser
•   Average amount of money spent per session
•   Sequence of hits (pathing analysis)
•   Multiple custom dimensions at hit or session level
Advanced query examples
•   Products purchased by customers who purchased Product A (Classic Ecommerce)
•   Products purchased by customers who purchased product A (Enhanced Ecommerce)
•   Average number of user interactions before purchase
•   Percentage of stock sold per product
•   Profitability of each product
•   Real profitability of each product
</code>```

Note: Using JS UDF can be expensive and also have quite a limitations - so you should use them if you really need. In most (if not all ) reasonably practical cases - using pure BigQuery Standard SQL will be more than sufficient

Body:
What you really need is BigQuery Analytics Cookbook

It has quite a wide range of useful use-cases / examples

Query optimization
Tips and best practices
    •   Query multiple tables
    •   3 Days using comma separated table names
    •   Last 7 Days using TABLE_DATE_RANGE
    •   Last 3 Months using TABLE_DATE_RANGE
    •   Last 1 Year using TABLE_DATE_RANGE
    •   Specific Date Range
    •   Last 6 Days plus Today’s data (intraday) using multiple TABLE_DATE_RANGE
Basic query examples
•   Total [metric] per [dimension]
•   Average bounce rate per [dimension]
•   Average number of product pageviews by purchaser type
•   Average number of transactions per purchaser
•   Average amount of money spent per session
•   Sequence of hits (pathing analysis)
•   Multiple custom dimensions at hit or session level
Advanced query examples
•   Products purchased by customers who purchased Product A (Classic Ecommerce)
•   Products purchased by customers who purchased product A (Enhanced Ecommerce)
•   Average number of user interactions before purchase
•   Percentage of stock sold per product
•   Profitability of each product
•   Real profitability of each product

Note: Using JS UDF can be expensive and also have quite a limitations - so you should use them if you really need. In most (if not all ) reasonably practical cases - using pure BigQuery Standard SQL will be more than sufficient


问:
load html files with webpack into angular app using ngtemplate-loader
I'm trying to load html partials in to my angular app using ngtempalte-loader I can't figure out how to only include a certain folder.

Lets say my tree structure is as so:

```<code>-root/
     -webpack.config.js
     -app/
        -templates/
           -template1/
               -file.html
           -template2/
</code>```

And I'm using this in the config file for webpack:

```<code>{
   test: /\.html$/,
   loader: 'ngtemplate?prefix=app/templates/!html'
}
</code>```

I also tried with

relativeTo=

But i have no luck... It always goes through all my app and picks up all the html files. I would like to just have the partials in this folder being dealt with ngtemplate-loader.
You guys know how?

答:
Not sure if this is still relevant, but you can give this a try. You require Node's 'path' module for this.</p>

```<code>{
  test: /\.html$/,
  loader: 'ngtemplate?relativeTo=' + (path.resolve(__dirname, './app/templates')) + '/!html'
}
</code>```

Body:
I'm trying to load html partials in to my angular app using ngtempalte-loader I can't figure out how to only include a certain folder.

Lets say my tree structure is as so:

-root/
     -webpack.config.js
     -app/
        -templates/
           -template1/
               -file.html
           -template2/

And I'm using this in the config file for webpack:

{
   test: /\.html$/,
   loader: 'ngtemplate?prefix=app/templates/!html'
}

I also tried with

relativeTo=

But i have no luck... It always goes through all my app and picks up all the html files. I would like to just have the partials in this folder being dealt with ngtemplate-loader.
You guys know how?

Body:
Not sure if this is still relevant, but you can give this a try. You require Node's 'path' module for this.

{
  test: /\.html$/,
  loader: 'ngtemplate?relativeTo=' + (path.resolve(__dirname, './app/templates')) + '/!html'
}


问:
Finding the maximum depth of a binary tree
```<code>public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public int maxDepth(TreeNode root) {
        TreeNode focusNode = root;
        TreeNode focusNode2 = root;
        int count = 0;
        int count1 = 0;
        boolean a = true;
        while (a) {
           if (focusNode != null) {
               count++;
               focusNode = focusNode.left;
           }
           if (focusNode2 != null) {
               count++;
               focusNode2 = focusNode2.right;
           } else {
               a = false;
           }
        }
        return Math.max(count,count1);
    }
}
</code>```

<p>I am confused why this code I wrote cannot give expected output. And I am also confused with the definition of maximum depth. Is finding maximum depth just considering all the nodes that line up on the left or line up on the right? </p>

答:
I'm not sure are you talking about the height of tree or depth of a node.

Here is the definition of height and depth.

Height of node – The height of a node is the number of edges on the longest downward path between that node and a leaf.

Depth –The depth of a node is the number of edges from the node to the tree's root node.

```<code>                R
               / \
              A   B
             / \ / \
            C  D E  F
                \
                 G
</code>```

For example:

the depth for node R is 0 and height is 3

the depth for node G is 3 and height is 0

Let assume you are finding the height of tree.

why your program can't get the outcome of what you desires?

It's because your code didn't traverse all nodes inside the tree

Let use the tree in diagram as example:

In your loop it will first let focusNode, focusNode2 = node R

focusNode R > A > C

focusNode2 R > B > F > Terminate

All sub nodes inside middle of tree didn't count, if your tree is not a perfect binary tree then you will get the wrong answer.

Suggest that you can read some algorithm on how to traverse a tree like Pre-order Travesal

https://en.wikipedia.org/wiki/Tree_traversal

Body:
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public int maxDepth(TreeNode root) {
        TreeNode focusNode = root;
        TreeNode focusNode2 = root;
        int count = 0;
        int count1 = 0;
        boolean a = true;
        while (a) {
           if (focusNode != null) {
               count++;
               focusNode = focusNode.left;
           }
           if (focusNode2 != null) {
               count++;
               focusNode2 = focusNode2.right;
           } else {
               a = false;
           }
        }
        return Math.max(count,count1);
    }
}

I am confused why this code I wrote cannot give expected output. And I am also confused with the definition of maximum depth. Is finding maximum depth just considering all the nodes that line up on the left or line up on the right?

Body:
I'm not sure are you talking about the height of tree or depth of a node.

Here is the definition of height and depth.

Height of node – The height of a node is the number of edges on the longest downward path between that node and a leaf.

Depth –The depth of a node is the number of edges from the node to the tree's root node.

                R
               / \
              A   B
             / \ / \
            C  D E  F
                \
                 G

For example:

the depth for node R is 0 and height is 3

the depth for node G is 3 and height is 0

Let assume you are finding the height of tree.

why your program can't get the outcome of what you desires?

It's because your code didn't traverse all nodes inside the tree

Let use the tree in diagram as example:

In your loop it will first let focusNode, focusNode2 = node R

focusNode R > A > C

focusNode2 R > B > F > Terminate

All sub nodes inside middle of tree didn't count, if your tree is not a perfect binary tree then you will get the wrong answer.

Suggest that you can read some algorithm on how to traverse a tree like Pre-order Travesal

https://en.wikipedia.org/wiki/Tree_traversal


问:
gh-pages failing while trying to deploy Reactjs app to GitHub in windows 10
I tried following the exact instructions listed in the react documentation on how to deploy a working app to github pages.  When I ran npm run deploy. It kept failing at the gh-pages -d build saying that the 'gh-pages' is not an internal or external command. I made sure I had the latest versions of node and npm installed

I had installed gh-pages using the -g tag to make it globally available.  Tried adding to the system path variable leading to the node modules folder where i knew gh-pages was loaded. Still nothing.

Finally i tried running it from the git bash window instead of the cmd terminal. This hadn't occurred to me at first as all of the other npm commands worked.  Don't know why this fixed things but it did. Just posting this so somebody else might be spared the pain

答:
If it says this, then node_modules/.bin/gh-pages doesn't exist (no, you don't need to install it globally). If it doesn't exist, then it means you either forgot to run npm install --save-dev gh-pages, or something went wrong during the installation.

I would not recommend installing it globally (although looks like it worked in your case).


问:
iPad video loading issue
I am developing a swipe based application. On each swipe a page will appear containing a video with some other asset. I am using the following code to do this for me on each swipe.

NSArray *file = [videoFile componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];

```<code>    NSString *moviePath = [[NSBundle mainBundle] pathForResource:[file objectAtIndex:0] ofType:[file objectAtIndex:1]];

    if (moviePath != nil)
    {
        //self.videoTimer = [NSTimer scheduledTimerWithTimeInterval:delayTime target:self selector:@selector(playVideo:) userInfo:nil repeats:NO];
        self.theMovie = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:moviePath]];
        self.theMovie.view.frame = self.bounds;
        self.theMovie.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
        self.theMovie.moviePlayer.controlStyle = MPMovieControlStyleNone;
        self.theMovie.moviePlayer.movieSourceType = MPMovieSourceTypeFile;

        [self addSubview:self.theMovie.view];
        [self.theMovie release];
    }
    else
    {
        [AssetValidator alertMissingFileInfo:videoFile];
    }
</code>```

This works fine.

My problem is that each time I swipe video starts with a delay and black screen.

Please guide how to solve this problem.

Regards.

答: How big are the movies? If their size is big then it's OK. There is a solution but it's quite irrational - load all the movies to memory during app startup and runtime. Otherwise (if the movies are quite big), the delay will happen anyway.</p>

Title: iPad video loading issue

Body:
I am developing a swipe based application. On each swipe a page will appear containing a video with some other asset. I am using the following code to do this for me on each swipe.

NSArray *file = [videoFile componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];

    NSString *moviePath = [[NSBundle mainBundle] pathForResource:[file objectAtIndex:0] ofType:[file objectAtIndex:1]];

    if (moviePath != nil)
    {
        //self.videoTimer = [NSTimer scheduledTimerWithTimeInterval:delayTime target:self selector:@selector(playVideo:) userInfo:nil repeats:NO];
        self.theMovie = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:moviePath]];
        self.theMovie.view.frame = self.bounds;
        self.theMovie.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
        self.theMovie.moviePlayer.controlStyle = MPMovieControlStyleNone;
        self.theMovie.moviePlayer.movieSourceType = MPMovieSourceTypeFile;

        [self addSubview:self.theMovie.view];
        [self.theMovie release];
    }
    else
    {
        [AssetValidator alertMissingFileInfo:videoFile];
    }

This works fine.

My problem is that each time I swipe video starts with a delay and black screen.

Please guide how to solve this problem.

Regards.


问:
Colorbar limits are not respecting set vmin/vmax in plt.contourf. How can I more explicitly set the colorbar limits?
Getting a strange result when trying to adjust the data range when plotting using contourf

```<code>import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

plt.figure()
CS = plt.contourf(X, Y, Z, vmin = 0, vmax = 3)
plt.title('Simplest default with labels')
plt.colorbar()

plt.show()
</code>```

Results in this for me:

It's like the colors match the vmin/vmax I set, but the number range displayed on the colorbar remains what it would be without setting vmin/vmax.

In this case, I would like the end result to have a colorbar that ranges from 0 to 3.

答:
We can explicitly set the colorbar limits by sending a scalar mappable to colorbar.

```<code>CS = plt.contourf(X, Y, Z, 5, vmin = 0., vmax = 2., cmap=cm.coolwarm)
plt.title('Simplest default with labels')
m = plt.cm.ScalarMappable(cmap=cm.coolwarm)
m.set_array(Z)
m.set_clim(0., 2.)
plt.colorbar(m, boundaries=np.linspace(0, 2, 6))
</code>```

Edit

See Bastian's answer for a complete solution. The problem with my approach is that the segments of the color bar don't correspond to the segments of the contour plot. They use the same coloring scale, but the contour plot and color bar have divided the color scale in different ways. Using the correct lower/upper bounds, this solution gives 6 levels of the contour plot and 6 levels of the colorbar. Since the contour plot and color bar have different bounds, the color segments are different.

ContentLicense: CC BY-SA 4.0

Body:
Getting a strange result when trying to adjust the data range when plotting using contourf

import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

plt.figure()
CS = plt.contourf(X, Y, Z, vmin = 0, vmax = 3)
plt.title('Simplest default with labels')
plt.colorbar()

plt.show()

Results in this for me:

It's like the colors match the vmin/vmax I set, but the number range displayed on the colorbar remains what it would be without setting vmin/vmax.

In this case, I would like the end result to have a colorbar that ranges from 0 to 3.

Body:
We can explicitly set the colorbar limits by sending a scalar mappable to colorbar.

CS = plt.contourf(X, Y, Z, 5, vmin = 0., vmax = 2., cmap=cm.coolwarm)
plt.title('Simplest default with labels')
m = plt.cm.ScalarMappable(cmap=cm.coolwarm)
m.set_array(Z)
m.set_clim(0., 2.)
plt.colorbar(m, boundaries=np.linspace(0, 2, 6))

Edit

See Bastian's answer for a complete solution. The problem with my approach is that the segments of the color bar don't correspond to the segments of the contour plot. They use the same coloring scale, but the contour plot and color bar have divided the color scale in different ways. Using the correct lower/upper bounds, this solution gives 6 levels of the contour plot and 6 levels of the colorbar. Since the contour plot and color bar have different bounds, the color segments are different.


问:
iOS ARC:What's the principle of xcode compiler to add retain and release to code under arc?
From iOS 5,Apple introduced ARC to replace MRC.When use MRC,the coder add retain and release for memory control.After use ARC the compiler will add retain and release for you.What's the principle of compiler to add retain and release for code?
You can paste some link or write someting you want.Thank you!!!</p>

答: Where retains and released are added are specified in the ARC specification, although it's kind of a technical read.</p>


问:
fast loading of large hash table in Perl
I have about 30 text files with the structure

```<code>wordleft1|wordright1
wordleft2|wordright2
wordleft3|wordright3
...
</code>```

The total size of the files is about 1 GB with about 32 million lines of word combinations.

I tried a few approaches to load them as fast as possible and store the combinations within a hash

```<code>$hash{$wordleft} = $wordright
</code>```

Opening file by file and reading line by line takes about 42 seconds. I then store the hash with the Storable module

```<code>store \%hash, $filename
</code>```

Loading the data again

```<code>$hashref = retrieve $filename
</code>```

reduces the time to about 28 seconds. I use a fast SSD drive and a fast CPU and have enough RAM to hold all the data (it takes about 7 GB).

I'm searching for a faster way to load this data into the RAM (I can't keep it there for a few reasons).

答:
It sounds like you do have a good use case for wanting an in-memory perl hash.

For faster storing/retrieving, I would recommend Sereal (Sereal::Encoder/Sereal::Decoder).  If your disk storage is slow, you may even want to enable Snappy compression.

Body:
I have about 30 text files with the structure

wordleft1|wordright1
wordleft2|wordright2
wordleft3|wordright3
...

The total size of the files is about 1 GB with about 32 million lines of word combinations.

I tried a few approaches to load them as fast as possible and store the combinations within a hash

$hash{$wordleft} = $wordright

Opening file by file and reading line by line takes about 42 seconds. I then store the hash with the Storable module

store \%hash, $filename

Loading the data again

$hashref = retrieve $filename

reduces the time to about 28 seconds. I use a fast SSD drive and a fast CPU and have enough RAM to hold all the data (it takes about 7 GB).

I'm searching for a faster way to load this data into the RAM (I can't keep it there for a few reasons).


问:
Service that uses libcurl not auto-starting on Debian?
I've written and compiled a daemon program in C which is meant to run in the background with root access. My program uses libcurl to make some occasional network calls. I've also written a simple init.d script to govern its startup and shutdown procedures. I would like this service to automatically start on boot, and based on what I've done I would expect it to already be doing this. However, I'm noticing an error in the logs relating to libcurl, and as a result the service is not being started automatically.

My program is located in /usr/bin/myprog and I have the following bash script located in /etc/init.d/myprog:

```<code>#!/bin/bash
### BEGIN INIT INFO
# Provides: myprog
# Required-Start: $remote_fs $network $syslog
# Required-Stop: $remote_fs $network $syslog
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: myprog
# Description: My Daemon Program
### END INIT INFO

. /lib/lsb/init-functions

SCRIPT=/usr/bin/myprog
PIDFILE=/var/run/myprog.pid

start() {
    if [ -f $PIDFILE ]; then
        echo "Service is already started"
        return 2
    else
        $SCRIPT
        $RETVAL="$?"
        return "${RETVAL}"
    fi
}

stop() {
    if [ -f $PIDFILE ]; then
        kill $(cat $PIDFILE)
        rm -f $PIDFILE
        return 0
    else
        echo "Service is not running"
        return 2
    fi
}

case "$1" in
    start)
        log_daemon_msg "Starting myprog" "myprog"
        start
        ;;
    stop)
        log_daemon_msg "Stopping myprog" "myprog"
        stop
        ;;
    status)
        status_of_proce "$SCRIPT" "myprog" && exit 0 || exit $?
        ;;
    restart)
        log_daemon_msg "Restarting myprog" "myprog"
        stop
        start
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart}" >&2
        exit 3
        ;;
esac
</code>```

I then ran sudo update-rc.d myprog defaults and this created the following files:

/etc/rc0.d/K01myprog

/etc/rc1.d/K01myprog

/etc/rc2.d/K01myprog

/etc/rc3.d/S02myprog

/etc/rc4.d/S02myprog

/etc/rc5.d/S02myprog

/etc/rc6.d/K01myprog

And as far as I can tell, each of those 7 files are identical copies of the one I posted above. Based on the various tutorials and forums I've been reading, I would think this would be sufficient. However, my service does not appear to be auto-starting on boot. If I call sudo /etc/init.d/myprog start directly, then it starts up fine. But otherwise it does not appear to be launched.

I then noticed an error message in the logs which said "curl error: could not resolve host," even though the particular host it was referencing was definitely valid. So I think perhaps it's trying to launch my application before something that libcurl needs is ready, and is therefore failing to launch. Again, if I launch it manually it works fine. How can I fix this?

答: If DNS resolution is the point of failure then use the IP address instead. If you are unwilling to use the IP address, add the hostname and IP address to /etc/hosts. </p>

Body:
I've written and compiled a daemon program in C which is meant to run in the background with root access. My program uses libcurl to make some occasional network calls. I've also written a simple init.d script to govern its startup and shutdown procedures. I would like this service to automatically start on boot, and based on what I've done I would expect it to already be doing this. However, I'm noticing an error in the logs relating to libcurl, and as a result the service is not being started automatically.

My program is located in /usr/bin/myprog and I have the following bash script located in /etc/init.d/myprog:

#!/bin/bash
### BEGIN INIT INFO
# Provides: myprog
# Required-Start: $remote_fs $network $syslog
# Required-Stop: $remote_fs $network $syslog
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: myprog
# Description: My Daemon Program
### END INIT INFO

. /lib/lsb/init-functions

SCRIPT=/usr/bin/myprog
PIDFILE=/var/run/myprog.pid

start() {
    if [ -f $PIDFILE ]; then
        echo "Service is already started"
        return 2
    else
        $SCRIPT
        $RETVAL="$?"
        return "${RETVAL}"
    fi
}

stop() {
    if [ -f $PIDFILE ]; then
        kill $(cat $PIDFILE)
        rm -f $PIDFILE
        return 0
    else
        echo "Service is not running"
        return 2
    fi
}

case "$1" in
    start)
        log_daemon_msg "Starting myprog" "myprog"
        start
        ;;
    stop)
        log_daemon_msg "Stopping myprog" "myprog"
        stop
        ;;
    status)
        status_of_proce "$SCRIPT" "myprog" && exit 0 || exit $?
        ;;
    restart)
        log_daemon_msg "Restarting myprog" "myprog"
        stop
        start
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart}" >&2
        exit 3
        ;;
esac

I then ran sudo update-rc.d myprog defaults and this created the following files:

/etc/rc0.d/K01myprog

/etc/rc1.d/K01myprog

/etc/rc2.d/K01myprog

/etc/rc3.d/S02myprog

/etc/rc4.d/S02myprog

/etc/rc5.d/S02myprog

/etc/rc6.d/K01myprog

And as far as I can tell, each of those 7 files are identical copies of the one I posted above. Based on the various tutorials and forums I've been reading, I would think this would be sufficient. However, my service does not appear to be auto-starting on boot. If I call sudo /etc/init.d/myprog start directly, then it starts up fine. But otherwise it does not appear to be launched.

I then noticed an error message in the logs which said "curl error: could not resolve host," even though the particular host it was referencing was definitely valid. So I think perhaps it's trying to launch my application before something that libcurl needs is ready, and is therefore failing to launch. Again, if I launch it manually it works fine. How can I fix this?


问:
How do I call a class from another class(not inheritance) in Java?
I can't remember what it's called when another class's method in java for example in a main class you call the scanner class to scan in user input?</p>

答:
If the scan method is an instance (object) method (not static), it would be something like this

```<code>Scanner s = new Scanner();
s.scan();
</code>```

If scan is static (a class method), then

```<code>Scanner.scan();
</code>```

Edit: The name of the relationship is Dependency in UML.  You say that Main depends on Scanner or Main uses-a Scanner.  I made this UML slideshow and cheatsheet:

http://www.loufranco.com/blog/files/UMLCheatsheet.html

If you have a Scanner member in the main class, then this is usually called has-a, composition, or an association.

Body:
If the scan method is an instance (object) method (not static), it would be something like this

Scanner s = new Scanner();
s.scan();

If scan is static (a class method), then

Scanner.scan();

Edit: The name of the relationship is Dependency in UML.  You say that Main depends on Scanner or Main uses-a Scanner.  I made this UML slideshow and cheatsheet:

http://www.loufranco.com/blog/files/UMLCheatsheet.html

If you have a Scanner member in the main class, then this is usually called has-a, composition, or an association.


问:
How to have multiple Qt buttons return each different values
I'm relatively new to Qt and I’m stuck with trying to figure out how to have different buttons each return a specific value when they're clicked.I've read through the Qt doc on signals and slots but I didn't find something useful.

I know that I can just have used the clicked function and return a value using the "goto slots" however, from the main, I would like to just call a getChoice function that would open a new window and based of what the user clicks I would return a corresponding int that I can use for later. Something like this is how it would look from the main.

```<code>OptionMenuWindow option;
int choice = option.checkChoice();
</code>```

So this is my code in the OptionMenuWindow class and I've tried passing an int as a reference through to the slot so that when choice0Clicked is activated I know which button was clicked.

```<code>int OptionMenuWindow::checkChoice(){

this->show();
QEventLoop waitForResponse;

//THIS IS WHERE I TRY AND DO THAT
connect(ui->manageEmployee, SIGNAL (clicked()), &waitForResponse, SLOT(choice0Clicked()));

connect(ui->view, SIGNAL (clicked()), &waitForResponse, SLOT(choice1Clicked()));

connect(ui->generatePayroll, SIGNAL (clicked()), &waitForResponse, SLOT(choice2Clicked()));

waitForResponse.exec();

cout << "here" << endl
cout << choice << endl;
return choice;

}
void OptionMenuWindow::choice0Clicked()
{
    choice = 0;

}

void OptionMenuWindow::choice1Clicked()
{
    choice = 1;
}

void OptionMenuWindow::choice2Clicked()
{
    choice = 2;
}
</code>```

choice is defined in the header file.

This is the error I'm getting:

QObject::connect: No such slot QEventLoop::choice0Clicked(&choice)

QObject::connect:  (sender name:   'manageEmployee')

QObject::connect: No such slot QEventLoop::choice1Clicked(&choice)

QObject::connect:  (sender name:   'view')

QObject::connect: No such slot QEventLoop::choice2Clicked(&choice)

QObject::connect:  (sender name:   'generatePayroll')

I really believe that there is a better of doing this so if there is, can someone please explain it?

And if there is anything you need me to elaborate on, please tell me it in the comments.

Thank you

答:
You can not overload a slot. It should match the signal signature.

It should be something like this only

```<code>QObject::connect(ui->manageEmployee, SIGNAL (clicked()), &waitForResponse, SLOT(choice0Clicked()));

QObject::connect(ui->view, SIGNAL (clicked()), &waitForResponse, SLOT(choice1Clicked()));

QObject::connect(ui->generatePayroll, SIGNAL (clicked()), &waitForResponse, SLOT(choice2Clicked()));
</code>```

Now coming to the button indexing

Let us assume you have push buttons -- "button1", "button2" and "button3".

Create "QButtonGroup" object.

```<code>QButtonGroup *bGroup = new  QButtonGroup ();
</code>```

Add all buttons with Ids.

```<code>bGroup->addButton(button1, 0);
bGroup->addButton(button2, 1);
bGroup->addButton(button3, 2);
</code>```

Now in the slots to get ID of button:

```<code>void OptionMenuWindow::choice0Clicked()
{
      QPushButton* button = qobject_cast<QPushButton*>(sender());
      int buttonID = bGroup->id(button);
}

void OptionMenuWindow::choice1Clicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    int buttonID = bGroup->id(button);
}

void OptionMenuWindow::choice2Clicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    int buttonID = bGroup->id(button);
}
</code>```

Body:
I'm relatively new to Qt and I’m stuck with trying to figure out how to have different buttons each return a specific value when they're clicked.I've read through the Qt doc on signals and slots but I didn't find something useful.

I know that I can just have used the clicked function and return a value using the "goto slots" however, from the main, I would like to just call a getChoice function that would open a new window and based of what the user clicks I would return a corresponding int that I can use for later. Something like this is how it would look from the main.

OptionMenuWindow option;
int choice = option.checkChoice();

So this is my code in the OptionMenuWindow class and I've tried passing an int as a reference through to the slot so that when choice0Clicked is activated I know which button was clicked.

int OptionMenuWindow::checkChoice(){

this->show();
QEventLoop waitForResponse;

//THIS IS WHERE I TRY AND DO THAT
connect(ui->manageEmployee, SIGNAL (clicked()), &waitForResponse, SLOT(choice0Clicked()));

connect(ui->view, SIGNAL (clicked()), &waitForResponse, SLOT(choice1Clicked()));

connect(ui->generatePayroll, SIGNAL (clicked()), &waitForResponse, SLOT(choice2Clicked()));

waitForResponse.exec();

cout << "here" << endl
cout << choice << endl;
return choice;

}
void OptionMenuWindow::choice0Clicked()
{
    choice = 0;

}

void OptionMenuWindow::choice1Clicked()
{
    choice = 1;
}

void OptionMenuWindow::choice2Clicked()
{
    choice = 2;
}

choice is defined in the header file.

This is the error I'm getting:

QObject::connect: No such slot QEventLoop::choice0Clicked(&choice)

QObject::connect:  (sender name:   'manageEmployee')

QObject::connect: No such slot QEventLoop::choice1Clicked(&choice)

QObject::connect:  (sender name:   'view')

QObject::connect: No such slot QEventLoop::choice2Clicked(&choice)

QObject::connect:  (sender name:   'generatePayroll')

I really believe that there is a better of doing this so if there is, can someone please explain it?

And if there is anything you need me to elaborate on, please tell me it in the comments.

Thank you

Body:
You can not overload a slot. It should match the signal signature.

It should be something like this only

QObject::connect(ui->manageEmployee, SIGNAL (clicked()), &waitForResponse, SLOT(choice0Clicked()));

QObject::connect(ui->view, SIGNAL (clicked()), &waitForResponse, SLOT(choice1Clicked()));

QObject::connect(ui->generatePayroll, SIGNAL (clicked()), &waitForResponse, SLOT(choice2Clicked()));

Now coming to the button indexing

Let us assume you have push buttons -- "button1", "button2" and "button3".

Create "QButtonGroup" object.

QButtonGroup *bGroup = new  QButtonGroup ();

Add all buttons with Ids.

bGroup->addButton(button1, 0);
bGroup->addButton(button2, 1);
bGroup->addButton(button3, 2);

Now in the slots to get ID of button:

void OptionMenuWindow::choice0Clicked()
{
      QPushButton* button = qobject_cast<QPushButton*>(sender());
      int buttonID = bGroup->id(button);
}

void OptionMenuWindow::choice1Clicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    int buttonID = bGroup->id(button);
}

void OptionMenuWindow::choice2Clicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    int buttonID = bGroup->id(button);
}


问:
Using CSS or JS to hide text inside the a href tag
I have a list in this format:

```<code><ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>
</code>```

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

答:
Usually done by negative indentation, which is SEO friendly; opposed to visibility: hidden; or display:none;

```<code>display: inline-block;
text-indent: -999px;
</code>```

But since you need the :before pseudo on the same element the above will not work well,

therefore font-size might be a better solution for your case:

li a{
  font-size: 0;            /* make really small */
}

li a:before{
  content: "CLICK";
  font-size: 1rem;         /* reset to 1 root-em for the pseudo */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>Part 1</li>
    <li>Part 2</li>
    <li>Part 3</li>
</ul></code>```

Beside font-size you could try opacity (0), color (transparent) etc...

Body:
I have a list in this format:

Part 1

Part 2

Part 3

I am using css :before to display something instead of the text inside the a href tag and I want to hide the text. I just want to hide Part 1, Part 2, Part 3 text and leave a href tag there.

If I use display:none; then everything is hidden, how can I just hide the text inside the href tag?

Body:
Usually done by negative indentation, which is SEO friendly; opposed to visibility: hidden; or display:none;

display: inline-block;
text-indent: -999px;

But since you need the :before pseudo on the same element the above will not work well,

therefore font-size might be a better solution for your case:

li a{
  font-size: 0;            /* make really small */
}

li a:before{
  content: "CLICK";
  font-size: 1rem;         /* reset to 1 root-em for the pseudo */
}

<ul>
    <li><a href="link">Part 1</a></li>
    <li><a href="link">Part 2</a></li>
    <li><a href="link">Part 3</a></li>
</ul>

Beside font-size you could try opacity (0), color (transparent) etc...


问:
How to make PrimeNG Menubar component work?
I'm trying to make a menubar using PrimeNG, based on example from http://www.primefaces.org/primeng/#/menubar

I create something like this:

app.component.ts

```<code>import {Component} from '@angular/core';
import {MenuBarComponent} from "./menubardemo.component";
@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1><demo></demo>`,
  directives:[MenuBarComponent] })
export class AppComponent { }
</code>```

menubardemo.components.ts

```<code>import {Component, OnInit} from "@angular/core";
import {Menubar, MenuItem} from "primeng/primeng";
@Component({
  selector: 'demo',
  template: `<p-menubar [model]="items"> </p-menubar>`,
  directives: [Menubar] })
export class MenuBarComponent implements OnInit {
  private items:MenuItem[];// you know how to fill this in the "OnInit" method

  ngOnInit() {
    this.items = [
      {
        label: 'File',
        icon: 'fa-file-o',
        items: [{
          label: 'New',
          icon: 'fa-plus',
          items: [
            {label: 'Project'},
            {label: 'Other'},
          ]
        },
          {label: 'Open'},
          {label: 'Quit'}
        ]
      },
      {
        label: 'Edit',
        icon: 'fa-edit',
        items: [
          {label: 'Undo', icon: 'fa-mail-forward'},
          {label: 'Redo', icon: 'fa-mail-reply'}
        ]
      },
      {
        label: 'Help',
        icon: 'fa-question',
        items: [
          {
            label: 'Contents'
          },
          {
            label: 'Search',
            icon: 'fa-search',
            items: [
              {
                label: 'Text',
                items: [
                  {
                    label: 'Workspace'
                  }
                ]
              },
              {
                label: 'File'
              }
            ]
          }
        ]
      },
      {
        label: 'Actions',
        icon: 'fa-gear',
        items: [
          {
            label: 'Edit',
            icon: 'fa-refresh',
            items: [
              {label: 'Save', icon: 'fa-save'},
              {label: 'Update', icon: 'fa-save'},
            ]
          },
          {
            label: 'Other',
            icon: 'fa-phone',
            items: [
              {label: 'Delete', icon: 'fa-minus'}
            ]
          }
        ]
      },
      {
        label: 'Quit', icon: 'fa-minus'
      }
    ];
  }
}
</code>```

after I checked out the data object is printed on the DOM, but the menubar is not showing.

UPDATE:

index.html

```<code><html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/themes/omega/theme.css" />
    <link rel="stylesheet" type="text/css" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/primeui-ng-all.min.css" />
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/primeui/primeui-ng-all.min.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
</code>```

package.json

```<code>{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "docker-build": "docker build -t ng2-quickstart .",
    "docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
    "pree2e": "npm run webdriver:update",
    "e2e": "tsc && concurrently \"http-server\" \"protractor protractor.config.js\"",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "postinstall": "typings install",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings",
    "webdriver:update": "webdriver-manager update"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
      "@angular/common":  "2.0.0-rc.1",
      "@angular/compiler":  "2.0.0-rc.1",
      "@angular/core":  "2.0.0-rc.1",
      "@angular/http":  "2.0.0-rc.1",
      "@angular/platform-browser":  "2.0.0-rc.1",
      "@angular/platform-browser-dynamic":  "2.0.0-rc.1",
      "@angular/router":  "2.0.0-rc.1",
      "@angular/router-deprecated":  "2.0.0-rc.1",
      "@angular/upgrade":  "2.0.0-rc.1",
      "systemjs": "0.19.27",
      "es6-shim": "^0.35.0",
      "reflect-metadata": "^0.1.3",
      "rxjs": "5.0.0-beta.6",
      "zone.js": "^0.6.12",
      "angular2-in-memory-web-api": "0.0.7",
      "primeng": "1.0.0-beta.7",
      "primeui": "4.1.12"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^1.0.4",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.7.4",
    "lodash": "^4.11.1",
    "jasmine-core": "~2.4.1",
    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.3",
    "karma-cli": "^0.1.2",
    "karma-htmlfile-reporter": "^0.2.2",
    "karma-jasmine": "^0.3.8",
    "protractor": "^3.3.0",
    "rimraf": "^2.5.2"
  },
  "repository": {}
}
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

systemjs.config.js

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {

  // map tells the System loader where to look for things
  var map = {
    'app': 'app', // 'dist',

    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'primeng': 'node_modules/primeng'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app': {main: 'main.js', defaultExtension: 'js'},
    'rxjs': {defaultExtension: 'js'},
    'angular2-in-memory-web-api': {main: 'index.js', defaultExtension: 'js'},
    'primeng': {defaultExtension: 'js'}
  };

  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];

  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/' + pkgName] = {main: 'index.js', defaultExtension: 'js'};
  }

  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/' + pkgName] = {main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js'};
  }

  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;

  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);

  // No umd for router yet
  packages['@angular/router'] = {main: 'index.js', defaultExtension: 'js'};

  var config = {
    map: map,
    packages: packages
  };

  System.config(config);

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

typings.json

```<code>{
  "globalDependencies": {
    "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320",
    "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
  }
}
</code>```

答:
I just figured this out I believe.

You need to import the MenuModule in the app.module.ts

```<code>//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {MenuModule} from 'primeng/primeng';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

This should fix your problem.

Body:
I'm trying to make a menubar using PrimeNG, based on example from http://www.primefaces.org/primeng/#/menubar

I create something like this:

app.component.ts

import {Component} from '@angular/core';
import {MenuBarComponent} from "./menubardemo.component";
@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1><demo></demo>`,
  directives:[MenuBarComponent] })
export class AppComponent { }

menubardemo.components.ts

import {Component, OnInit} from "@angular/core";
import {Menubar, MenuItem} from "primeng/primeng";
@Component({
  selector: 'demo',
  template: `<p-menubar [model]="items"> </p-menubar>`,
  directives: [Menubar] })
export class MenuBarComponent implements OnInit {
  private items:MenuItem[];// you know how to fill this in the "OnInit" method

  ngOnInit() {
    this.items = [
      {
        label: 'File',
        icon: 'fa-file-o',
        items: [{
          label: 'New',
          icon: 'fa-plus',
          items: [
            {label: 'Project'},
            {label: 'Other'},
          ]
        },
          {label: 'Open'},
          {label: 'Quit'}
        ]
      },
      {
        label: 'Edit',
        icon: 'fa-edit',
        items: [
          {label: 'Undo', icon: 'fa-mail-forward'},
          {label: 'Redo', icon: 'fa-mail-reply'}
        ]
      },
      {
        label: 'Help',
        icon: 'fa-question',
        items: [
          {
            label: 'Contents'
          },
          {
            label: 'Search',
            icon: 'fa-search',
            items: [
              {
                label: 'Text',
                items: [
                  {
                    label: 'Workspace'
                  }
                ]
              },
              {
                label: 'File'
              }
            ]
          }
        ]
      },
      {
        label: 'Actions',
        icon: 'fa-gear',
        items: [
          {
            label: 'Edit',
            icon: 'fa-refresh',
            items: [
              {label: 'Save', icon: 'fa-save'},
              {label: 'Update', icon: 'fa-save'},
            ]
          },
          {
            label: 'Other',
            icon: 'fa-phone',
            items: [
              {label: 'Delete', icon: 'fa-minus'}
            ]
          }
        ]
      },
      {
        label: 'Quit', icon: 'fa-minus'
      }
    ];
  }
}

after I checked out the data object is printed on the DOM, but the menubar is not showing.

UPDATE:

index.html

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/themes/omega/theme.css" />
    <link rel="stylesheet" type="text/css" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/primeui-ng-all.min.css" />
    <link rel="stylesheet" href="styles.css">

    <my-app>Loading...</my-app>

package.json

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "docker-build": "docker build -t ng2-quickstart .",
    "docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
    "pree2e": "npm run webdriver:update",
    "e2e": "tsc && concurrently \"http-server\" \"protractor protractor.config.js\"",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "postinstall": "typings install",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings",
    "webdriver:update": "webdriver-manager update"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
      "@angular/common":  "2.0.0-rc.1",
      "@angular/compiler":  "2.0.0-rc.1",
      "@angular/core":  "2.0.0-rc.1",
      "@angular/http":  "2.0.0-rc.1",
      "@angular/platform-browser":  "2.0.0-rc.1",
      "@angular/platform-browser-dynamic":  "2.0.0-rc.1",
      "@angular/router":  "2.0.0-rc.1",
      "@angular/router-deprecated":  "2.0.0-rc.1",
      "@angular/upgrade":  "2.0.0-rc.1",
      "systemjs": "0.19.27",
      "es6-shim": "^0.35.0",
      "reflect-metadata": "^0.1.3",
      "rxjs": "5.0.0-beta.6",
      "zone.js": "^0.6.12",
      "angular2-in-memory-web-api": "0.0.7",
      "primeng": "1.0.0-beta.7",
      "primeui": "4.1.12"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^1.0.4",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.7.4",
    "lodash": "^4.11.1",
    "jasmine-core": "~2.4.1",
    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.3",
    "karma-cli": "^0.1.2",
    "karma-htmlfile-reporter": "^0.2.2",
    "karma-jasmine": "^0.3.8",
    "protractor": "^3.3.0",
    "rimraf": "^2.5.2"
  },
  "repository": {}
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {

  // map tells the System loader where to look for things
  var map = {
    'app': 'app', // 'dist',

    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'primeng': 'node_modules/primeng'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app': {main: 'main.js', defaultExtension: 'js'},
    'rxjs': {defaultExtension: 'js'},
    'angular2-in-memory-web-api': {main: 'index.js', defaultExtension: 'js'},
    'primeng': {defaultExtension: 'js'}
  };

  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];

  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/' + pkgName] = {main: 'index.js', defaultExtension: 'js'};
  }

  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/' + pkgName] = {main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js'};
  }

  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;

  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);

  // No umd for router yet
  packages['@angular/router'] = {main: 'index.js', defaultExtension: 'js'};

  var config = {
    map: map,
    packages: packages
  };

  System.config(config);

})(this);

typings.json

{
  "globalDependencies": {
    "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320",
    "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
  }
}

Body:
I just figured this out I believe.

You need to import the MenuModule in the app.module.ts

//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {MenuModule} from 'primeng/primeng';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This should fix your problem.


问:
Can't parse GET request using express
I read a lot about node, express and many useful modules.
I'm trying to parse GET HTTP request but I'm doing something wrong.

Maybe this problem could be solved using express.Router() and views engine but I would like to know WHY this code doesn't work?

Server is up and running! Public files are very well served BUT I cannot parse GET request.

```<code>app.use(express.static(path.join(__dirname, 'public')));

/*I would like to get req.session here*/
app.get('/', function (req, res, next) {
    console.log('I'm trying to log this string');
})
</code>```

I'm also using morgan to log all HTTP request and this is the output:

```<code>Listening at: http://localhost:8080
GET / 200 14.288 ms - 9139
GET /css/materialize.css 304 16.311 ms - -
GET /css/style.css 304 24.775 ms - -
GET /js/materialize.js 304 21.287 ms - -
GET /js/init.js 304 20.238 ms - -
GET /js/index.js 200 51.159 ms - 2719
GET /fonts/roboto/Roboto-Regular.woff2 304 2.419 ms - -
GET /fonts/roboto/Roboto-Medium.woff2 304 3.663 ms - -
GET /fonts/roboto/Roboto-Light.woff2 304 7.958 ms - -
GET /fonts/roboto/Roboto-Bold.woff2 304 9.010 ms - -
</code>```

It works commenting :

```<code>//app.use(express.static(path.join(__dirname, 'public')));
</code>```

But, obviously, no file are served.

Thank you!

PS: I never seen tutorial or code snippet explaining the situation described above.

答:
Thanks to @robertklep, I solved doing this : </p>

```<code>app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  next();
});

app.use(express.static(path.join(__dirname, 'public')));
</code>```

Title: Can't parse GET request using express

Body:
I read a lot about node, express and many useful modules.
I'm trying to parse GET HTTP request but I'm doing something wrong.

Maybe this problem could be solved using express.Router() and views engine but I would like to know WHY this code doesn't work?

Server is up and running! Public files are very well served BUT I cannot parse GET request.

app.use(express.static(path.join(__dirname, 'public')));

/*I would like to get req.session here*/
app.get('/', function (req, res, next) {
    console.log('I'm trying to log this string');
})

I'm also using morgan to log all HTTP request and this is the output:

Listening at: http://localhost:8080
GET / 200 14.288 ms - 9139
GET /css/materialize.css 304 16.311 ms - -
GET /css/style.css 304 24.775 ms - -
GET /js/materialize.js 304 21.287 ms - -
GET /js/init.js 304 20.238 ms - -
GET /js/index.js 200 51.159 ms - 2719
GET /fonts/roboto/Roboto-Regular.woff2 304 2.419 ms - -
GET /fonts/roboto/Roboto-Medium.woff2 304 3.663 ms - -
GET /fonts/roboto/Roboto-Light.woff2 304 7.958 ms - -
GET /fonts/roboto/Roboto-Bold.woff2 304 9.010 ms - -

It works commenting :

//app.use(express.static(path.join(__dirname, 'public')));

But, obviously, no file are served.

Thank you!

PS: I never seen tutorial or code snippet explaining the situation described above.

Body:
Thanks to @robertklep, I solved doing this :

app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  next();
});

app.use(express.static(path.join(__dirname, 'public')));


问:
How to verify events fired when a button is clicked using selenium?
I have a selenium suite that runs on our user interactive website. Our company also tracks the event that are fired when a user interact with an input field (such a numeric input or slider) on third party such as google analytics. I am trying to verify the events fired when a user clicks on a button on a page. Is there a way, selenium can track that event in console and verify it? </p>

答:
There are 2 approaches that you could take in order to achieve what you're looking for:

Parse WebDriver's logs and get required info from there, here is an example on how to get them from chromedriver: https://sites.google.com/a/chromium.org/chromedriver/logging/performance-log - please note that for, for example, firefox - capabilities would be different, also you won't be able to get response codes and response time, only basic info.

Create proxy, configure wd to use it and capture traffic using proxy, one of the solutions is called BrowserMob proxy. Once traffic goes through you may get Har file from proxy and get all the data from there. Har captures all the data you may need: request, params, response code, response timings.