问:
How to route to a Module as a child of a Module - Angular 2 RC 5
I am in the process upgrading an application I'm working on to the latest Angular 2 release candidate. As part of this work I am attempting to use the NgModule spec and migrating all of the parts of my application to modules. For the most part, this has gone very well with the exception of an issue with routing.

```<code>"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/forms": "0.3.0",
"@angular/http": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-rc.1",
</code>```

My app is built as a composition of modules, with several modules being glued together as children of a parent module. For example, I have an Admin Module that consists of a Notifications Module, a Users Module, and a Telphony Module (for example). The routes to these modules should look like...

```<code>/admin/notifications/my-notifications
/admin/users/new-user
/admin/telephony/whatever
</code>```

In the earlier release of the router, this was easy to accomplish using "children"

```<code>export const AdminRoutes: RouterConfig = [
   {
      path: "Admin",
      component: AdminComponent,
      Children: [
         ...UserRoutes,
         ...TelephonyRoutes,
         ...NotificationRoutes
      ]
   }
]
</code>```

In another file, as part of the sub-modules, I'd define the individual module routes as well i.e.

```<code>export const UserRoutes: RouterConfig = [
    {
       path: "users",
       component: userComponent,
       children: [
           {path: "new-user", component: newUserComponent}
       ]
    }

]
</code>```

This all worked very well. In the process of upgrading to Modules, I moved everything into their own individual routing files instead so now these two look more like this

```<code>const AdminRoutes: Routes = [
    {path: "admin", component: AdminComponent}
]

export const adminRouting = RouterModule.forChild(AdminRoutes)
</code>```

and

```<code>const UserRoutes: Routes = [
       path: "users",
       component: userComponent,
       children: [
           {path: "new-user", component: newUserComponent}
       ]
]

export const userRouting = RouterModule.forChild(UserRoutes)
</code>```

With all of that in place, I have a UsersModule which imports the userRouting, and then an AdminModule that imports the adminRoutes and the UsersModule. My thought was that since UsersModule is a child of AdminModule, the routing would work the way it used to. Unfortunately, it doesn't so I end up with a users route that is just

```<code>/users/new-user
</code>```

instead of

```<code>/admin/users/new-user
</code>```

Further, because of this, the new-user component isn't loaded into the router outlet of my admin component which throws off the styling and navigation of my application.

I can't for the life of me come up with how to reference the routes of my UserModule as children of my AdminModule. I've tried doing this the old way and get errors about the routes being in two Modules. Obviously since this is newly released, the documentation around some of these cases is a bit limited.

Any help anyone can provide would be greatly appreciated!

答:
I think 2.0.0 rc5 isn't interested now. But is is worked in Angular 4, may be early too.

```<code>@NgModule({
    imports: [
        RouterModule.forRoot([
                {path: "", redirectTo: "test-sample", pathMatch: "full"},
                {
                    path: "test-sample",
                    loadChildren: () => TestSampleModule
                }
        ])
    ],
    exports: [RouterModule],
    declarations: []
})
export class AppRoutingModule{}

@NgModule({
    imports: [
        RouterModule.forChild([{
                    path: "",
                    component: TestSampleComponent,
                    children: [
                        {path: "", redirectTo: "home", pathMatch: "full"},
                        {
                            path: "home",
                            loadChildren: () => HomeModule
                        },
                        {
                            path: "about",
                            loadChildren: () => AboutModule
                        }
                    ]
                }
        ])
    ],
    exports: [RouterModule],
    declarations: []
})
export class TestSampleRoutingModule {}

@NgModule({
    imports: [RouterModule.forChild([{
                    path: "",
                    component: AboutComponent
                }
    ])],
    exports: [RouterModule]
})
export class AboutRoutingModule {}
</code>```

Take in account  on loadChildren: () => {...}. It is not the lazy loading.

See for details feat: Support NgModules hierarchy sans Lazy Loading

Body:
I am in the process upgrading an application I'm working on to the latest Angular 2 release candidate. As part of this work I am attempting to use the NgModule spec and migrating all of the parts of my application to modules. For the most part, this has gone very well with the exception of an issue with routing.

"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/forms": "0.3.0",
"@angular/http": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-rc.1",

My app is built as a composition of modules, with several modules being glued together as children of a parent module. For example, I have an Admin Module that consists of a Notifications Module, a Users Module, and a Telphony Module (for example). The routes to these modules should look like...

/admin/notifications/my-notifications
/admin/users/new-user
/admin/telephony/whatever

In the earlier release of the router, this was easy to accomplish using "children"

export const AdminRoutes: RouterConfig = [
   {
      path: "Admin",
      component: AdminComponent,
      Children: [
         ...UserRoutes,
         ...TelephonyRoutes,
         ...NotificationRoutes
      ]
   }
]

In another file, as part of the sub-modules, I'd define the individual module routes as well i.e.

export const UserRoutes: RouterConfig = [
    {
       path: "users",
       component: userComponent,
       children: [
           {path: "new-user", component: newUserComponent}
       ]
    }

]

This all worked very well. In the process of upgrading to Modules, I moved everything into their own individual routing files instead so now these two look more like this

const AdminRoutes: Routes = [
    {path: "admin", component: AdminComponent}
]

export const adminRouting = RouterModule.forChild(AdminRoutes)

and

const UserRoutes: Routes = [
       path: "users",
       component: userComponent,
       children: [
           {path: "new-user", component: newUserComponent}
       ]
]

export const userRouting = RouterModule.forChild(UserRoutes)

With all of that in place, I have a UsersModule which imports the userRouting, and then an AdminModule that imports the adminRoutes and the UsersModule. My thought was that since UsersModule is a child of AdminModule, the routing would work the way it used to. Unfortunately, it doesn't so I end up with a users route that is just

/users/new-user

instead of

/admin/users/new-user

Further, because of this, the new-user component isn't loaded into the router outlet of my admin component which throws off the styling and navigation of my application.

I can't for the life of me come up with how to reference the routes of my UserModule as children of my AdminModule. I've tried doing this the old way and get errors about the routes being in two Modules. Obviously since this is newly released, the documentation around some of these cases is a bit limited.

Any help anyone can provide would be greatly appreciated!

Body:
I think 2.0.0 rc5 isn't interested now. But is is worked in Angular 4, may be early too.

@NgModule({
    imports: [
        RouterModule.forRoot([
                {path: "", redirectTo: "test-sample", pathMatch: "full"},
                {
                    path: "test-sample",
                    loadChildren: () => TestSampleModule
                }
        ])
    ],
    exports: [RouterModule],
    declarations: []
})
export class AppRoutingModule{}

@NgModule({
    imports: [
        RouterModule.forChild([{
                    path: "",
                    component: TestSampleComponent,
                    children: [
                        {path: "", redirectTo: "home", pathMatch: "full"},
                        {
                            path: "home",
                            loadChildren: () => HomeModule
                        },
                        {
                            path: "about",
                            loadChildren: () => AboutModule
                        }
                    ]
                }
        ])
    ],
    exports: [RouterModule],
    declarations: []
})
export class TestSampleRoutingModule {}

@NgModule({
    imports: [RouterModule.forChild([{
                    path: "",
                    component: AboutComponent
                }
    ])],
    exports: [RouterModule]
})
export class AboutRoutingModule {}

Take in account  on loadChildren: () => {...}. It is not the lazy loading.

See for details feat: Support NgModules hierarchy sans Lazy Loading


来源: stackexchange

问:
Vue.js: "attach" content to two different classes?
So, I have data in my vue.js file that I want to "attach" to two different classes without having to create another Vue.js component or repeating the content again in another component. For example:

```<code>var fullViewContent = new Vue({
  el: ".class-one",
  data: {
    name: 'Vue.js'
  },
  data: {
    items: [{
      content: "repeat this string in various places",

    },
   ]
 }
</code>```

First HTML Block

```<code>  <div class="class-one">
      <template v-for="(item, index) in items">
        <div class="container">
           <h2>{{ item.content }}</h2>
        </div>
      </template>
  </div><!-- end list view -->
</code>```

Second HTML Block

```<code>  <div class="different-html-block class-one">
      <template v-for="(item, index) in items">
        <div class="container">
           <h2>{{ item.content }}</h2>
        </div>
      </template>
  </div><!-- end list view -->
</code>```

So I want the same content from my component in each of these different html blocks. Is it enough to just attach the same class to it? Something else?

答:
You cannot apply a Vue to more than one element.

Instead, move the shared data into an object accessible to both Vues.

```<code>const shared = {
  items: [
    {
      content: "repeat this string in various places",
    },
    {
      content: "more data",
    },
   ]
}

var app1 = new Vue({
  el: "#app1",
  data: {
    name: 'Vue.js',
    items: shared.items
  },
})

var app2 = new Vue({
  el: "#app2",
  data: {
    name: 'Vue.js',
    items: shared.items
  }
})
</code>```

And the template

```<code><div id="app1">
  <div class="class-one">
      <template v-for="(item, index) in items">
        <div class="container">
           <h2>{{ item.content }}</h2>
        </div>
      </template>
  </div><!-- end list view -->
</div>

<div id="app2">
  <div class="different-html-block class-one">
      <template v-for="(item, index) in items">
        <div class="container">
           <h2>{{ item.content }}</h2>
        </div>
      </template>
  </div><!-- end list view -->
</div>
</code>```

Example.

If you want to avoid repeating code you can programmatically create your Vues.

```<code>each = Array.prototype.forEach;

const data = {
  name: "Vue.js",
  items: [
    {
      content: "repeat this string in various places",
    },
    {
      content: "more data",
    },
   ]
}

each.call(document.querySelectorAll(".class-one"), el => new Vue({el, data}))
</code>```

Example.

ContentLicense: CC BY-SA 3.0

Body:
So, I have data in my vue.js file that I want to "attach" to two different classes without having to create another Vue.js component or repeating the content again in another component. For example:

var fullViewContent = new Vue({
  el: ".class-one",
  data: {
    name: 'Vue.js'
  },
  data: {
    items: [{
      content: "repeat this string in various places",

    },
   ]
 }

First HTML Block

      <template v-for="(item, index) in items">

{{ item.content }}

      </template>

Second HTML Block

      <template v-for="(item, index) in items">

{{ item.content }}

      </template>

So I want the same content from my component in each of these different html blocks. Is it enough to just attach the same class to it? Something else?

Body:
You cannot apply a Vue to more than one element.

Instead, move the shared data into an object accessible to both Vues.

const shared = {
  items: [
    {
      content: "repeat this string in various places",
    },
    {
      content: "more data",
    },
   ]
}

var app1 = new Vue({
  el: "#app1",
  data: {
    name: 'Vue.js',
    items: shared.items
  },
})

var app2 = new Vue({
  el: "#app2",
  data: {
    name: 'Vue.js',
    items: shared.items
  }
})

And the template

<div id="app1">
  <div class="class-one">
      <template v-for="(item, index) in items">
        <div class="container">
           <h2>{{ item.content }}</h2>
        </div>
      </template>
  </div><!-- end list view -->
</div>

<div id="app2">
  <div class="different-html-block class-one">
      <template v-for="(item, index) in items">
        <div class="container">
           <h2>{{ item.content }}</h2>
        </div>
      </template>
  </div><!-- end list view -->
</div>

Example.

If you want to avoid repeating code you can programmatically create your Vues.

each = Array.prototype.forEach;

const data = {
  name: "Vue.js",
  items: [
    {
      content: "repeat this string in various places",
    },
    {
      content: "more data",
    },
   ]
}

each.call(document.querySelectorAll(".class-one"), el => new Vue({el, data}))

Example.


问:
Compilation errors while compiling WordCount.java
I keep getting an error which says 'cannot find symbol' while compiling WordCount.java. I tried importing the other libraries, but it only adds up to the list of errors. Am I missing some component that needs to be added? </p>

```<code>  javac -classpath /Documents/hadoop/hadoop-1.2.1/hadoop-core-1.2.1.jar:/Documents/hadoop/hadoop-1.2.1/lib/commons-cli-1.2.jar -d wordcount_classes WordCount.java

    WordCount.java:4: error: package org.apache.hadoop.fs does not exist
    import org.apache.hadoop.fs.Path;
                               ^
    WordCount.java:5: error: package org.apache.hadoop.io does not exist
    import org.apache.hadoop.io.*;
    ^
    WordCount.java:6: error: package org.apache.hadoop.mapred does not exist
    import org.apache.hadoop.mapred.*;
    ^
    WordCount.java:8: error: package org.apache.hadoop.mapred.lib.input does not exist
    import org.apache.hadoop.mapred.lib.input.FileInputFormat;
                                             ^
    WordCount.java:9: error: package org.apache.hadoop.mapred.lib.output does not exist
    import org.apache.hadoop.mapred.lib.output.FileOutputFormat;
                                          ^
    WordCount.java:10: error: package org.apache.hadoop.mapred.lib.input does not exist
    import org.apache.hadoop.mapred.lib.input.TextInputFormat;
                                         ^
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,    Text, Text, IntWritable> {
                                        ^
    symbol:   class MapReduceBase
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,   Text, Text, IntWritable> {
                                                                 ^
    symbol:   class Mapper
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,     Text, Text, IntWritable> {
                                                                        ^
    symbol:   class LongWritable
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
                                                                                ^
    symbol:   class Text
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,     Text, Text, IntWritable> {
                                                                                ^
    symbol:   class Text
    location: class WordCount
WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
                                                                                ^
    symbol:   class IntWritable
    location: class WordCount
    WordCount.java:16: error: cannot find symbol
          private final static IntWritable one = new IntWritable(1);
                               ^
    symbol:   class IntWritable
    location: class Map
    WordCount.java:17: error: cannot find symbol
          private Text word = new Text();
                  ^
    symbol:   class Text
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                          ^
    symbol:   class LongWritable
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable>   output, Reporter reporter) throws IOException {
                                            ^
    symbol:   class Text
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable>     output, Reporter reporter) throws IOException {
                                                        ^
    symbol:   class OutputCollector
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                        ^
  symbol:   class Text
  location: class Map
WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                              ^
  symbol:   class IntWritable
  location: class Map
WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class Reporter
  location: class Map
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                           ^
  symbol:   class MapReduceBase
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                    ^
  symbol:   class Reducer
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                            ^
  symbol:   class Text
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                                ^
  symbol:   class IntWritable
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                                ^
  symbol:   class Text
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                                ^
  symbol:   class IntWritable
  location: class WordCount
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                             ^
  symbol:   class Text
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                ^
  symbol:   class IntWritable
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                     ^
  symbol:   class OutputCollector
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class Text
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class IntWritable
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class Reporter
  location: class Reduce
WordCount.java:16: error: cannot find symbol
          private final static IntWritable one = new IntWritable(1);
                                                     ^
  symbol:   class IntWritable
  location: class Map
WordCount.java:17: error: cannot find symbol
          private Text word = new Text();
                                  ^
  symbol:   class Text
  location: class Map
WordCount.java:34: error: cannot find symbol
            output.collect(key, new IntWritable(sum));
                                    ^
  symbol:   class IntWritable
  location: class Reduce
WordCount.java:39: error: cannot find symbol
          JobConf conf = new JobConf(WordCount.class);
          ^
  symbol:   class JobConf
  location: class WordCount
WordCount.java:39: error: cannot find symbol
          JobConf conf = new JobConf(WordCount.class);
                             ^
  symbol:   class JobConf
  location: class WordCount
WordCount.java:42: error: cannot find symbol
          conf.setOutputKeyClass(Text.class);
                                 ^
  symbol:   class Text
  location: class WordCount
WordCount.java:43: error: cannot find symbol
          conf.setOutputValueClass(IntWritable.class);
                                   ^
  symbol:   class IntWritable
  location: class WordCount
WordCount.java:49: error: cannot find symbol
          conf.setInputFormat(TextInputFormat.class);
                              ^
  symbol:   class TextInputFormat
  location: class WordCount
WordCount.java:50: error: cannot find symbol
          conf.setOutputFormat(TextOutputFormat.class);
                               ^
  symbol:   class TextOutputFormat
  location: class WordCount
WordCount.java:52: error: cannot find symbol
          FileInputFormat.setInputPaths(conf, new Path(args[0]));
                                                  ^
  symbol:   class Path
  location: class WordCount
WordCount.java:52: error: cannot find symbol
          FileInputFormat.setInputPaths(conf, new Path(args[0]));
          ^
  symbol:   variable FileInputFormat
  location: class WordCount
WordCount.java:53: error: cannot find symbol
          FileOutputFormat.setOutputPath(conf, new Path(args[1]));
                                                   ^
  symbol:   class Path
  location: class WordCount
WordCount.java:53: error: cannot find symbol
          FileOutputFormat.setOutputPath(conf, new Path(args[1]));
          ^
  symbol:   variable FileOutputFormat
  location: class WordCount
WordCount.java:55: error: cannot find symbol
      JobClient.runJob(conf);
      ^
  symbol:   variable JobClient
  location: class WordCount
46 errors
</code>```

答:
It is because the necessary packages are not included in javac classpath.

For hadoop 2.7.3, adding 3 packages works for me:

```<code>javac -classpath $HADOOP_HOME$/share/hadoop/common/hadoop-common-2.7.3.jar:$HADOOP_HOME$/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.7.3.jar:$HADOOP_HOME$/share/hadoop/common/lib/commons-cli-1.2.jar
-d wordcount_classes WordCount.java
</code>```

Body:
I keep getting an error which says 'cannot find symbol' while compiling WordCount.java. I tried importing the other libraries, but it only adds up to the list of errors. Am I missing some component that needs to be added?

  javac -classpath /Documents/hadoop/hadoop-1.2.1/hadoop-core-1.2.1.jar:/Documents/hadoop/hadoop-1.2.1/lib/commons-cli-1.2.jar -d wordcount_classes WordCount.java

    WordCount.java:4: error: package org.apache.hadoop.fs does not exist
    import org.apache.hadoop.fs.Path;
                               ^
    WordCount.java:5: error: package org.apache.hadoop.io does not exist
    import org.apache.hadoop.io.*;
    ^
    WordCount.java:6: error: package org.apache.hadoop.mapred does not exist
    import org.apache.hadoop.mapred.*;
    ^
    WordCount.java:8: error: package org.apache.hadoop.mapred.lib.input does not exist
    import org.apache.hadoop.mapred.lib.input.FileInputFormat;
                                             ^
    WordCount.java:9: error: package org.apache.hadoop.mapred.lib.output does not exist
    import org.apache.hadoop.mapred.lib.output.FileOutputFormat;
                                          ^
    WordCount.java:10: error: package org.apache.hadoop.mapred.lib.input does not exist
    import org.apache.hadoop.mapred.lib.input.TextInputFormat;
                                         ^
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,    Text, Text, IntWritable> {
                                        ^
    symbol:   class MapReduceBase
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,   Text, Text, IntWritable> {
                                                                 ^
    symbol:   class Mapper
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,     Text, Text, IntWritable> {
                                                                        ^
    symbol:   class LongWritable
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
                                                                                ^
    symbol:   class Text
    location: class WordCount
    WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable,     Text, Text, IntWritable> {
                                                                                ^
    symbol:   class Text
    location: class WordCount
WordCount.java:15: error: cannot find symbol
        public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
                                                                                ^
    symbol:   class IntWritable
    location: class WordCount
    WordCount.java:16: error: cannot find symbol
          private final static IntWritable one = new IntWritable(1);
                               ^
    symbol:   class IntWritable
    location: class Map
    WordCount.java:17: error: cannot find symbol
          private Text word = new Text();
                  ^
    symbol:   class Text
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                          ^
    symbol:   class LongWritable
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable>   output, Reporter reporter) throws IOException {
                                            ^
    symbol:   class Text
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable>     output, Reporter reporter) throws IOException {
                                                        ^
    symbol:   class OutputCollector
    location: class Map
    WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                        ^
  symbol:   class Text
  location: class Map
WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                              ^
  symbol:   class IntWritable
  location: class Map
WordCount.java:19: error: cannot find symbol
          public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class Reporter
  location: class Map
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                           ^
  symbol:   class MapReduceBase
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                    ^
  symbol:   class Reducer
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                            ^
  symbol:   class Text
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                                ^
  symbol:   class IntWritable
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                                ^
  symbol:   class Text
  location: class WordCount
WordCount.java:28: error: cannot find symbol
        public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
                                                                                ^
  symbol:   class IntWritable
  location: class WordCount
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                             ^
  symbol:   class Text
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                ^
  symbol:   class IntWritable
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                     ^
  symbol:   class OutputCollector
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class Text
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class IntWritable
  location: class Reduce
WordCount.java:29: error: cannot find symbol
          public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
                                                                                ^
  symbol:   class Reporter
  location: class Reduce
WordCount.java:16: error: cannot find symbol
          private final static IntWritable one = new IntWritable(1);
                                                     ^
  symbol:   class IntWritable
  location: class Map
WordCount.java:17: error: cannot find symbol
          private Text word = new Text();
                                  ^
  symbol:   class Text
  location: class Map
WordCount.java:34: error: cannot find symbol
            output.collect(key, new IntWritable(sum));
                                    ^
  symbol:   class IntWritable
  location: class Reduce
WordCount.java:39: error: cannot find symbol
          JobConf conf = new JobConf(WordCount.class);
          ^
  symbol:   class JobConf
  location: class WordCount
WordCount.java:39: error: cannot find symbol
          JobConf conf = new JobConf(WordCount.class);
                             ^
  symbol:   class JobConf
  location: class WordCount
WordCount.java:42: error: cannot find symbol
          conf.setOutputKeyClass(Text.class);
                                 ^
  symbol:   class Text
  location: class WordCount
WordCount.java:43: error: cannot find symbol
          conf.setOutputValueClass(IntWritable.class);
                                   ^
  symbol:   class IntWritable
  location: class WordCount
WordCount.java:49: error: cannot find symbol
          conf.setInputFormat(TextInputFormat.class);
                              ^
  symbol:   class TextInputFormat
  location: class WordCount
WordCount.java:50: error: cannot find symbol
          conf.setOutputFormat(TextOutputFormat.class);
                               ^
  symbol:   class TextOutputFormat
  location: class WordCount
WordCount.java:52: error: cannot find symbol
          FileInputFormat.setInputPaths(conf, new Path(args[0]));
                                                  ^
  symbol:   class Path
  location: class WordCount
WordCount.java:52: error: cannot find symbol
          FileInputFormat.setInputPaths(conf, new Path(args[0]));
          ^
  symbol:   variable FileInputFormat
  location: class WordCount
WordCount.java:53: error: cannot find symbol
          FileOutputFormat.setOutputPath(conf, new Path(args[1]));
                                                   ^
  symbol:   class Path
  location: class WordCount
WordCount.java:53: error: cannot find symbol
          FileOutputFormat.setOutputPath(conf, new Path(args[1]));
          ^
  symbol:   variable FileOutputFormat
  location: class WordCount
WordCount.java:55: error: cannot find symbol
      JobClient.runJob(conf);
      ^
  symbol:   variable JobClient
  location: class WordCount
46 errors

Body:
It is because the necessary packages are not included in javac classpath.

For hadoop 2.7.3, adding 3 packages works for me:

javac -classpath $HADOOP_HOME$/share/hadoop/common/hadoop-common-2.7.3.jar:$HADOOP_HOME$/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.7.3.jar:$HADOOP_HOME$/share/hadoop/common/lib/commons-cli-1.2.jar
-d wordcount_classes WordCount.java


问:
How can I get a list of all the implementations of an interface programmatically in Java?
Can I do it with reflection or something like that?</p>

答: I ran into the same issue. My solution was to use reflection to examine all of the methods in an ObjectFactory class, eliminating those that were not createXXX() methods returning an instance of one of my bound POJOs. Each class so discovered is added to a Class[] array, which was then passed to the JAXBContext instantiation call. This performs well, needing only to load the ObjectFactory class, which was about to be needed anyway. I only need to maintain the ObjectFactory class, a task either performed by hand (in my case, because I started with POJOs and used schemagen), or can be generated as needed by xjc. Either way, it is performant, simple, and effective.</p>

OwnerDisplayName: damian

ContentLicense: CC BY-SA 2.5


问:
Looking for a short term fix for limiting record display number without :limit => 10
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.

In the mean time I am wanting to limit the display of records to a number like 10 but I don't want to do it in the controller through the :limit => 10 manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.

My view code is:

```<code><% @comments.each do |comment| %>
  <% if comment.workout.user_id == current_user.id %><br/>
    <%= link_to (comment.user.username), comment.user %> <br/>
    <%= time_ago_in_words(comment.created_at) %> <br/>
    <%= link_to (comment.workout.title), comment.workout %><br/>
    <%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
  <% end %>
<% end %>
</code>```

My controller is simply calling

```<code>@comments = Comment.all(:order => "created_at DESC")
</code>```

Body:
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.

In the mean time I am wanting to limit the display of records to a number like 10 but I don't want to do it in the controller through the :limit => 10 manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.

My view code is:

<% @comments.each do |comment| %>
  <% if comment.workout.user_id == current_user.id %>

    <%= link_to (comment.user.username), comment.user %>

    <%= time_ago_in_words(comment.created_at) %>

    <%= link_to (comment.workout.title), comment.workout %>

    <%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
  <% end %>
<% end %>

My controller is simply calling

@comments = Comment.all(:order => "created_at DESC")

Body:
@comments[0..9]

and

@comments[10..-1]


问:
Mongodb - find referred document and retrieve it with only one element in its inner array
So I have this data in mongodb:

Process document:

```<code>process: {
    procnumber: '1',
    person: {
        $ref: 'person',
        $id: ObjectId("5126bc054aed4daf9e2ab772")
    }
}
process: {
    procnumber: '2',
    person: {
        $ref: 'person',
        $id: ObjectId("5126bc054aed4daf9e2ab996")
    }
}
</code>```

Person document:

```<code>person: {
    _id: ObjectId("5126bc054aed4daf9e2ab772"),
    name:'person_1',
    obsarray:[{date:ISODate("2017-02-13"),obs:'1.this is one'},{date:ISODate("2017-02-20"),obs:'1.this is two'},{date:ISODate("2017-02-01"),obs:'1.this is three'}]
}
person: {
    _id: ObjectId("5126bc054aed4daf9e2ab996"),
    name:'person_2',
    obsarray:[{date:ISODate("2017-02-17"),obs:'2.this is one'},{date:ISODate("2017-02-27"),obs:'2.this is two'},{date:ISODate("2017-02-28"),obs:'2.this is three'}]
}
</code>```

And I want to query it so that the query returns fields from both Process and Person, and at the same time, have the "obsarray" only return the document with the most recent date.

Example of a desired output:

```<code>{
procnum:'1',
person: {
    name:'person_1',
    obsarray: {
        date:ISODate("2017-02-20"),
        obs:'1.this is two'
    }
}
</code>```

I've tried using aggregation, however I have failed to deal with the reference:

```<code>db.person.aggregate([
    {$match:{name:{$exists:true}}},
    {$unwind:'$obsarray' },
    {$sort:{'obsarray.date':-1}},
    {$group:{
        _id:'$_id',
        obsarray:{$first: '$obsarray.date'},
        name:{$first:'$name'}}
    }
])
</code>```

Is there any way of populating the 'Person' ref from 'Process' and then apply the aggregate so as to have the output with fields from both documents?

答:
You've to change DBRef to manual reference. Something like

```<code>var ProcessSchema = new mongoose.Schema({
    procnumber: String,
    person: {
     type: Schema.Types.ObjectId,
     ref: 'Person'
    }
});
</code>```

After updating your document should look like below.

```<code>process: {
    procnumber: '1',
    person: {
        _id: ObjectId("5126bc054aed4daf9e2ab772")
    }
}
</code>```

You can now use $lookup to get the information from other collection in aggregation query.

```<code>db.person.aggregate([
    {$match:{name:{$exists:true}}},
    {$lookup: {
        from: "process",
        localField: "_id",
        foreignField: "person._id",
        as: "person_process"}
    },
    {$unwind:'$person_process'},
    {$unwind:'$obsarray' },
    {$sort:{'obsarray.date':-1}},
    {$group:{
        _id:'$_id',
        obsarray:{$first: '$obsarray.date'},
        name:{$first:'$name'}},
        procnum:{$first:'$person_process.procnum'}}
    }
])
</code>```

Body:
So I have this data in mongodb:

Process document:

process: {
    procnumber: '1',
    person: {
        $ref: 'person',
        $id: ObjectId("5126bc054aed4daf9e2ab772")
    }
}
process: {
    procnumber: '2',
    person: {
        $ref: 'person',
        $id: ObjectId("5126bc054aed4daf9e2ab996")
    }
}

Person document:

person: {
    _id: ObjectId("5126bc054aed4daf9e2ab772"),
    name:'person_1',
    obsarray:[{date:ISODate("2017-02-13"),obs:'1.this is one'},{date:ISODate("2017-02-20"),obs:'1.this is two'},{date:ISODate("2017-02-01"),obs:'1.this is three'}]
}
person: {
    _id: ObjectId("5126bc054aed4daf9e2ab996"),
    name:'person_2',
    obsarray:[{date:ISODate("2017-02-17"),obs:'2.this is one'},{date:ISODate("2017-02-27"),obs:'2.this is two'},{date:ISODate("2017-02-28"),obs:'2.this is three'}]
}

And I want to query it so that the query returns fields from both Process and Person, and at the same time, have the "obsarray" only return the document with the most recent date.

Example of a desired output:

{
procnum:'1',
person: {
    name:'person_1',
    obsarray: {
        date:ISODate("2017-02-20"),
        obs:'1.this is two'
    }
}

I've tried using aggregation, however I have failed to deal with the reference:

db.person.aggregate([
    {$match:{name:{$exists:true}}},
    {$unwind:'$obsarray' },
    {$sort:{'obsarray.date':-1}},
    {$group:{
        _id:'$_id',
        obsarray:{$first: '$obsarray.date'},
        name:{$first:'$name'}}
    }
])

Is there any way of populating the 'Person' ref from 'Process' and then apply the aggregate so as to have the output with fields from both documents?

Body:
You've to change DBRef to manual reference. Something like

var ProcessSchema = new mongoose.Schema({
    procnumber: String,
    person: {
     type: Schema.Types.ObjectId,
     ref: 'Person'
    }
});

After updating your document should look like below.

process: {
    procnumber: '1',
    person: {
        _id: ObjectId("5126bc054aed4daf9e2ab772")
    }
}

You can now use $lookup to get the information from other collection in aggregation query.

db.person.aggregate([
    {$match:{name:{$exists:true}}},
    {$lookup: {
        from: "process",
        localField: "_id",
        foreignField: "person._id",
        as: "person_process"}
    },
    {$unwind:'$person_process'},
    {$unwind:'$obsarray' },
    {$sort:{'obsarray.date':-1}},
    {$group:{
        _id:'$_id',
        obsarray:{$first: '$obsarray.date'},
        name:{$first:'$name'}},
        procnum:{$first:'$person_process.procnum'}}
    }
])


问:
Force django-admin startproject if project folder already exists
I want to start new django project in already existing folder and obviously get

```<code>CommandError: '/home/user/projectfolder' already exists.
</code>```

Is there some way to force startproject command to create project in an existing folder? I have some important data in that folder and also git folder so I don't want to move it somewhere and then move it back.

答:
You can make too like this:

``` django-admin startproject name_project path_project ```

Example:

``` django-admin startproject example /tmp/example ```

Body:
I want to start new django project in already existing folder and obviously get

CommandError: '/home/user/projectfolder' already exists.

Is there some way to force startproject command to create project in an existing folder? I have some important data in that folder and also git folder so I don't want to move it somewhere and then move it back.

Body:
You can make too like this:

 django-admin startproject name_project path_project

Example:

 django-admin startproject example /tmp/example


问:
Multiple steps workflow in cucumber
I'm developing an application in rails with cucumber.

The application includes a workflow that have multiple steps.

Some steps are

A user import files (3 different files),

Other user make make some checks to date that was imported,

Other user input some parameter,

Other user apply the parameter to the data that was imported,

etc.

The steps must be executed in the correct order, and I is necessary to run all the previous steps in order to execute each one, for example to apply the parameter its necessary to have the data imported and the parameters defined.

My problem is how to build cucumber scenarios/features in this situation.
I know that a scenario is not suppose to call all the previous scenario.But the only other idea that I have is to create a very long scenario performing all this steps, and that make sense because it will be a scenario with more than 2 hundred steps.

Any thought on a pragmatical way of implementing cucumber in this kind of situation?

Many Tks

答:
It sounds as if you have to perform every thing every time.

Will every usage of your system include importing three files? Are there any cases where the user may only need to import two files? If the case is that there will always be three files imported, then you might abstract that step as

```<code>given the files are imported
</code>```

Things that always have to be done may be combined into some generic setup. As the setup never changes, the details may not be necessary to mention explicit.

My experience though, is that at the beginning it is hard to separate scenarios and try to do too much in a few scenarios with many steps. If you don't see any other way, start there. Look at your scenario and see if they possible to separate into perhaps two independent scenarios. It may be possible to separate it into two scenarios that are independent. Next step would be to see if these two new scenarios are possible to divide into two smaller, independent scenarios. It happens that it is possible.

It is obviously always possible that Cucumber is not the tool you need. It is possible that you would be better off with a unit test framework.

Title: Multiple steps workflow in cucumber

Body:
It sounds as if you have to perform every thing every time.

Will every usage of your system include importing three files? Are there any cases where the user may only need to import two files? If the case is that there will always be three files imported, then you might abstract that step as

given the files are imported

Things that always have to be done may be combined into some generic setup. As the setup never changes, the details may not be necessary to mention explicit.

My experience though, is that at the beginning it is hard to separate scenarios and try to do too much in a few scenarios with many steps. If you don't see any other way, start there. Look at your scenario and see if they possible to separate into perhaps two independent scenarios. It may be possible to separate it into two scenarios that are independent. Next step would be to see if these two new scenarios are possible to divide into two smaller, independent scenarios. It happens that it is possible.

It is obviously always possible that Cucumber is not the tool you need. It is possible that you would be better off with a unit test framework.


问:
formatting of prime factorization algorithm
suppose we have following script for  prime factorization

```<code> z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
</code>```

but output of this code is not formatted well,for instance

```<code> >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1
</code>```

how can i do  so  that i got

```<code>30=2^1*3^1*5^1?
</code>```

thanks in advance

答:
first of all thanks  everyone for your afford, here is my final solution

```<code> z=input('enter your number : ');
  string='';
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str =[num2str(ii) '^' num2str(s) ];

                   string=strcat(string,str);
                   string= strcat(string,'*');
             % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
    string=string(1:end-1);% remove last sign of multiplicaiton
fprintf('prime factorization is %s\n',string);
</code>```

here is  several examples

```<code>>> integer_factorization
enter your number : 30
prime factorization is 2^1*3^1*5^1
</code>```

another

```<code>>> integer_factorization
enter your number : 35
prime factorization is 5^1*7^1
</code>```

and  last one

```<code>>> integer_factorization
enter your number : 100
prime factorization is 2^2*5^2
</code>```

Body:
suppose we have following script for  prime factorization

 z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end

but output of this code is not formatted well,for instance

 >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1

how can i do  so  that i got

30=2^1*3^1*5^1?

thanks in advance

Body:
first of all thanks  everyone for your afford, here is my final solution

 z=input('enter your number : ');
  string='';
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str =[num2str(ii) '^' num2str(s) ];

                   string=strcat(string,str);
                   string= strcat(string,'*');
             % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
    string=string(1:end-1);% remove last sign of multiplicaiton
fprintf('prime factorization is %s\n',string);

here is  several examples

>> integer_factorization
enter your number : 30
prime factorization is 2^1*3^1*5^1

another

>> integer_factorization
enter your number : 35
prime factorization is 5^1*7^1

and  last one

>> integer_factorization
enter your number : 100
prime factorization is 2^2*5^2


问:
Check if there is a current active visual selection in Vim from a function invoked by a command
Situation #1: I have just selected a block of text. I then type ":Command", which invokes some function.

Situation #2: There is no current visual selection (though I may have made such a selection previously in the edit session). I type ":Command", which invokes (the same) function.

Is there a (robust) way to distinguish the above two situations from within the function? I tried mode(), but the problem is that in both cases I am in command mode, though in the first case I got into command mode from visual mode while in the second it was from normal mode. Maybe through inspection of a:firstline/a:lastline/v:count?

Update -- Use Case example: ":Sum". If there is a current visual selection, e.g., a column of numbers (block selection) or a range of lines containing just numbers, this command will echo the sum of the numbers. Otherwise, it expects a list of space-separated numbers as arguments, and will echo the sum of those numbers. Basic framework:

```<code>command! -nargs="*" -range Sum :call CalcSum(<f-args>)
function! CalcSum(...) range
   " 1. collect numbers from visual selection if there is a current active selection
   " 2. otherwise, if len(args) > 0, collect numbers from args
   " 3. other cases (i.e., no selection and no args or both selection and args) handled reasonably
   " 4. sum collection of numbers
   " 5. return/echo result
endfunction
</code>```

Steps (2)-(5) are straightforward. I'm having trouble with (1). I use the "<"/">" markers to recreate the collect the numbers from a visual selection. But I only want to do this if there is a visual selection currently highlighted/active.

Maybe my entire logic is wrong and there is a better way to design this functionality?

答:
If you need to use command, the only way I see is to inspect a:firstline/a:lastline:

```<code>" Assuming that you have passed -range=% when defining command
if a:firstline==1 && a:lastline==line('$')
    " Do something
endif
</code>```

but this does not hold the case when you selected the whole buffer. I suggest you use expression mappings:

```<code>function DoCommand()
    if mode()!~#"^[vV\<C-v>]"
        " Do something. For example, set global variable (and unset it in :Command)
    endif
    return ':Command'
endfunction
noremap <expr> {lhs} DoCommand()
</code>```

Update: Visual mode is never active in command mode. Never. Just because the command mode is not the visual mode. Using mappings is the only way to achieve what you want and here are two approaches: you use exactly the same expr mapping for all modes and check mode() somewhere in this expression or you define different mappings for different modes and use these differences to tell function from what mode it is called.

Body:
Situation #1: I have just selected a block of text. I then type ":Command", which invokes some function.

Situation #2: There is no current visual selection (though I may have made such a selection previously in the edit session). I type ":Command", which invokes (the same) function.

Is there a (robust) way to distinguish the above two situations from within the function? I tried mode(), but the problem is that in both cases I am in command mode, though in the first case I got into command mode from visual mode while in the second it was from normal mode. Maybe through inspection of a:firstline/a:lastline/v:count?

Update -- Use Case example: ":Sum". If there is a current visual selection, e.g., a column of numbers (block selection) or a range of lines containing just numbers, this command will echo the sum of the numbers. Otherwise, it expects a list of space-separated numbers as arguments, and will echo the sum of those numbers. Basic framework:

command! -nargs="*" -range Sum :call CalcSum(<f-args>)
function! CalcSum(...) range
   " 1. collect numbers from visual selection if there is a current active selection
   " 2. otherwise, if len(args) > 0, collect numbers from args
   " 3. other cases (i.e., no selection and no args or both selection and args) handled reasonably
   " 4. sum collection of numbers
   " 5. return/echo result
endfunction

Steps (2)-(5) are straightforward. I'm having trouble with (1). I use the "<"/">" markers to recreate the collect the numbers from a visual selection. But I only want to do this if there is a visual selection currently highlighted/active.

Maybe my entire logic is wrong and there is a better way to design this functionality?

Body:
If you need to use command, the only way I see is to inspect a:firstline/a:lastline:

" Assuming that you have passed -range=% when defining command
if a:firstline==1 && a:lastline==line('$')
    " Do something
endif

but this does not hold the case when you selected the whole buffer. I suggest you use expression mappings:

function DoCommand()
    if mode()!~#"^[vV\<C-v>]"
        " Do something. For example, set global variable (and unset it in :Command)
    endif
    return ':Command'
endfunction
noremap <expr> {lhs} DoCommand()

Update: Visual mode is never active in command mode. Never. Just because the command mode is not the visual mode. Using mappings is the only way to achieve what you want and here are two approaches: you use exactly the same expr mapping for all modes and check mode() somewhere in this expression or you define different mappings for different modes and use these differences to tell function from what mode it is called.


问:
How can I compare two lists of numpy vectors?
I have two lists of numpy vectors and wish to determine whether they represent approximately the same points (but possibly in a different order).

I've found methods such as numpy.testing.assert_allclose but it doesn't allow for possibly different orders. I have also found unittest.TestCase.assertCountEqual but that doesn't work with numpy arrays!

What is my best approach?

```<code>import unittest

import numpy as np

first = [np.array([20, 40]), np.array([20, 60])]
second = [np.array([19.8, 59.7]), np.array([20.1, 40.5])]

np.testing.assert_all_close(first, second, atol=2)  # Fails because the orders are different
unittest.TestCase.assertCountEqual(None, first, second)  # Fails because numpy comparisons evaluate element-wise; and because it doesn't allow a tolerance
</code>```

答:
A nice list iteration approach

```<code>In [1047]: res = []
In [1048]: for i in first:
      ...:     for j in second:
      ...:         diff = np.abs(i-j)
      ...:         if np.all(diff<2):
      ...:             res.append((i,j))
In [1049]: res
Out[1049]:
[(array([20, 40]), array([ 20.1,  40.5])),
 (array([20, 60]), array([ 19.8,  59.7]))]
</code>```

Length of res is the number of matches.

Or as list comprehension:

```<code>def match(i,j):
    diff = np.abs(i-j)
    return np.all(diff<2)

In [1051]: [(i,j) for i in first for j in second if match(i,j)]
Out[1051]:
[(array([20, 40]), array([ 20.1,  40.5])),
 (array([20, 60]), array([ 19.8,  59.7]))]
</code>```

or with the existing array test:

```<code>[(i,j) for i in first for j in second if np.allclose(i,j, atol=2)]
</code>```

Body:
I have two lists of numpy vectors and wish to determine whether they represent approximately the same points (but possibly in a different order).

I've found methods such as numpy.testing.assert_allclose but it doesn't allow for possibly different orders. I have also found unittest.TestCase.assertCountEqual but that doesn't work with numpy arrays!

What is my best approach?

import unittest

import numpy as np

first = [np.array([20, 40]), np.array([20, 60])]
second = [np.array([19.8, 59.7]), np.array([20.1, 40.5])]

np.testing.assert_all_close(first, second, atol=2)  # Fails because the orders are different
unittest.TestCase.assertCountEqual(None, first, second)  # Fails because numpy comparisons evaluate element-wise; and because it doesn't allow a tolerance

Body:
A nice list iteration approach

In [1047]: res = []
In [1048]: for i in first:
      ...:     for j in second:
      ...:         diff = np.abs(i-j)
      ...:         if np.all(diff<2):
      ...:             res.append((i,j))
In [1049]: res
Out[1049]:
[(array([20, 40]), array([ 20.1,  40.5])),
 (array([20, 60]), array([ 19.8,  59.7]))]

Length of res is the number of matches.

Or as list comprehension:

def match(i,j):
    diff = np.abs(i-j)
    return np.all(diff<2)

In [1051]: [(i,j) for i in first for j in second if match(i,j)]
Out[1051]:
[(array([20, 40]), array([ 20.1,  40.5])),
 (array([20, 60]), array([ 19.8,  59.7]))]

or with the existing array test:

[(i,j) for i in first for j in second if np.allclose(i,j, atol=2)]


问:
Image preloading techniques (for use as hover state CSS background images) don't seem to work on Chrome
I'm using the following technique to pre-load images that are applied as CSS background images when hovering buttons:

```<code>#preload_area {
  background-image:
    url(../images/image1.svg),
    url(../images/image2.svg);
  width: 0px;
  height: 0px;
  display: inline;
}
</code>```

Also tried to pre-load just one image, this way:

```<code>#preload_area {
  background: url(../images/image1.svg) -9999px -9999px no-repeat;
}
</code>```

None of this works: after hard refresh, when hovering my button the first time, I still see a blink (corresponding to loading the hover image). Obviously after that first time there's no blink any more.

Why is not working on Chrome? (it does work on Firefox)

答:
Why is it not working on Chrome? Because all browser vendors want the fastest browser. They will not load unnessecary assets.

You want a cross browser way to preload? Use a sprite, as [CBroe] suggested. This solution has been around for ages and is rock solid. Any other trick, rendering the image invisible, can work today but be broken tomorrow.

Body:
I'm using the following technique to pre-load images that are applied as CSS background images when hovering buttons:

#preload_area {
  background-image:
    url(../images/image1.svg),
    url(../images/image2.svg);
  width: 0px;
  height: 0px;
  display: inline;
}

Also tried to pre-load just one image, this way:

#preload_area {
  background: url(../images/image1.svg) -9999px -9999px no-repeat;
}

None of this works: after hard refresh, when hovering my button the first time, I still see a blink (corresponding to loading the hover image). Obviously after that first time there's no blink any more.

Why is not working on Chrome? (it does work on Firefox)


问:
XSLT-1.0: Create multiple records when child node has multiple values
Create multiple records when child has multiple values.

I have an XML with parent and child nodes. Child nodes do have multiple values. I am trying to create separate records for each child nodes such that the tags are in the order displayed in the output (Desired).

My XML input is:

```<code><Records count="65">
  <Record contentId="781435" levelId="17" levelGuid="33fceb92-9ee6-458f-81f6-5bd28e4af22e" moduleId="70" parentId="0">
    <Field id="15941" guid="75b528ad-2e19-42d6-9512-87b92bbf84d0" type="1">SPH0</Field>
    <Field id="15997" guid="90507e16-35a1-407e-8b27-586e3e091ac3" type="9">
      <Reference id="409826">Alberta</Reference>
    </Field>
  </Record>
  <Record contentId="783299" levelId="17" levelGuid="33fceb92-9ee6-458f-81f6-5bd28e4af22e" moduleId="70" parentId="0">
    <Field id="15941" guid="75b528ad-2e19-42d6-9512-87b92bbf84d0" type="1">SQV0</Field>
    <Field id="15997" guid="90507e16-35a1-407e-8b27-586e3e091ac3" type="9">
      <Reference id="409187">Ontario</Reference>
      <Reference id="409826">Quebec</Reference>
    </Field>
  </Record>
</Records>
</code>```

My XSLT code which I tried is:

```<code><?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/Records">
        <xsl:for-each select="Record">
            <ArcherRecord>
                <AppCode>
                    <xsl:value-of select="Field" />
                </AppCode>
                <xsl:for-each select="Field/Reference">
                    <Location>
                        <xsl:value-of select="." />
                    </Location>
                </xsl:for-each>
            </ArcherRecord>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

But the output I got is:

```<code><ArcherRecord>
    <AppCode>SPH0</AppCode>
    <Location>Alberta</Location>
</ArcherRecord>

<ArcherRecord>
    <AppCode>SQV0</AppCode>
    <Location>Ontario</Location>
    <Location>Quebec</Location>
</ArcherRecord>
</code>```

instead of the output I desire which would look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ArcherRecord>
    <AppCode>SPH0</AppCode>
    <Location>Alberta</Location>
</ArcherRecord>

<ArcherRecord>
    <AppCode>SQV0</AppCode>
    <Location>Ontario</Location>
</ArcherRecord>

<ArcherRecord>
    <AppCode>SQV0</AppCode>
    <Location>Quebec</Location>
</ArcherRecord>
</code>```

答:
Please try this:

```<code><?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/Records">
        <xsl:for-each select="Record/Field/Reference">
            <ArcherRecord>
                <AppCode>
                    <xsl:value-of select="../../Field[@type='1']" />
                </AppCode>
                    <Location>
                        <xsl:value-of select="." />
                    </Location>
            </ArcherRecord>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

The output is:

```<code><ArcherRecord>
   <AppCode>SPH0</AppCode>
   <Location>Alberta</Location>
</ArcherRecord>
<ArcherRecord>
   <AppCode>SQV0</AppCode>
   <Location>Ontario</Location>
</ArcherRecord>
<ArcherRecord>
   <AppCode>SQV0</AppCode>
   <Location>Quebec</Location>
</ArcherRecord>
</code>```

Body:
Create multiple records when child has multiple values.

I have an XML with parent and child nodes. Child nodes do have multiple values. I am trying to create separate records for each child nodes such that the tags are in the order displayed in the output (Desired).

My XML input is:

<Records count="65">
  <Record contentId="781435" levelId="17" levelGuid="33fceb92-9ee6-458f-81f6-5bd28e4af22e" moduleId="70" parentId="0">
    <Field id="15941" guid="75b528ad-2e19-42d6-9512-87b92bbf84d0" type="1">SPH0</Field>
    <Field id="15997" guid="90507e16-35a1-407e-8b27-586e3e091ac3" type="9">
      <Reference id="409826">Alberta</Reference>
    </Field>
  </Record>
  <Record contentId="783299" levelId="17" levelGuid="33fceb92-9ee6-458f-81f6-5bd28e4af22e" moduleId="70" parentId="0">
    <Field id="15941" guid="75b528ad-2e19-42d6-9512-87b92bbf84d0" type="1">SQV0</Field>
    <Field id="15997" guid="90507e16-35a1-407e-8b27-586e3e091ac3" type="9">
      <Reference id="409187">Ontario</Reference>
      <Reference id="409826">Quebec</Reference>
    </Field>
  </Record>
</Records>

My XSLT code which I tried is:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/Records">
        <xsl:for-each select="Record">
            <ArcherRecord>
                <AppCode>
                    <xsl:value-of select="Field" />
                </AppCode>
                <xsl:for-each select="Field/Reference">
                    <Location>
                        <xsl:value-of select="." />
                    </Location>
                </xsl:for-each>
            </ArcherRecord>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

But the output I got is:

<ArcherRecord>
    <AppCode>SPH0</AppCode>
    <Location>Alberta</Location>
</ArcherRecord>

<ArcherRecord>
    <AppCode>SQV0</AppCode>
    <Location>Ontario</Location>
    <Location>Quebec</Location>
</ArcherRecord>

instead of the output I desire which would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<ArcherRecord>
    <AppCode>SPH0</AppCode>
    <Location>Alberta</Location>
</ArcherRecord>

<ArcherRecord>
    <AppCode>SQV0</AppCode>
    <Location>Ontario</Location>
</ArcherRecord>

<ArcherRecord>
    <AppCode>SQV0</AppCode>
    <Location>Quebec</Location>
</ArcherRecord>

Body:
Please try this:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/Records">
        <xsl:for-each select="Record/Field/Reference">
            <ArcherRecord>
                <AppCode>
                    <xsl:value-of select="../../Field[@type='1']" />
                </AppCode>
                    <Location>
                        <xsl:value-of select="." />
                    </Location>
            </ArcherRecord>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

The output is:

<ArcherRecord>
   <AppCode>SPH0</AppCode>
   <Location>Alberta</Location>
</ArcherRecord>
<ArcherRecord>
   <AppCode>SQV0</AppCode>
   <Location>Ontario</Location>
</ArcherRecord>
<ArcherRecord>
   <AppCode>SQV0</AppCode>
   <Location>Quebec</Location>
</ArcherRecord>


问:
How to decide where to handle an exception - in scope of function it been thrown or in global one?
I`m writing client-server app for windows using WinSock and I have class for server.

while initialising server I have such code:

```<code>
class Server {
    static const int MaxClients = 10;
    std::vector connections;
    CRITICAL_SECTION cs;
    int port;
    SOCKET ServerSocket;
    sockaddr_in ServerAddress;
    void init();
public:
    Server(int Port);
    void addConnection(const Client& newClient);
    void closeConnection(int index);
    void Listen();
    int size();
    /*virtual void ClientService();
    virtual void SendMsg(const std::string& msg);*/
    virtual ~Server();
};

void Server::init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 2), &wsaData))
        throw Exception("WinSock init failed");
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
        throw Exception("Socket failed to create!");
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    ServerAddress.sin_port = htons(port);
    if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
    {
        throw Exception("Binding failed");
        closesocket(ServerSocket);
    }
}
</code>```

where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on?

答:
As for the question about catching the exception in the scope of the function where it's thrown (ie., in the init() function) - it seldom makes sense to catch an exception in the scope where it's thrown.  In essence that would mean that you've detected an error and know how to handle it (and are going to handle it), but that you're using an exception to perform nothing more than a transfer of control to another part of your function.

While there might be cases where this might make sense (though that would be a code smell that indicates the function is complex enough that it should be refactored), the logic for handling that error (since it is being handled) should use more common control flow techniques such as if statements or a break.  Even the wildly unpopular goto might be preferable to throwing an exception only to have it handled in the same function.

Body:
I`m writing client-server app for windows using WinSock and I have class for server.

while initialising server I have such code:

class Server {
    static const int MaxClients = 10;
    std::vector connections;
    CRITICAL_SECTION cs;
    int port;
    SOCKET ServerSocket;
    sockaddr_in ServerAddress;
    void init();
public:
    Server(int Port);
    void addConnection(const Client& newClient);
    void closeConnection(int index);
    void Listen();
    int size();
    /*virtual void ClientService();
    virtual void SendMsg(const std::string& msg);*/
    virtual ~Server();
};

void Server::init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 2), &wsaData))
        throw Exception("WinSock init failed");
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
        throw Exception("Socket failed to create!");
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    ServerAddress.sin_port = htons(port);
    if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
    {
        throw Exception("Binding failed");
        closesocket(ServerSocket);
    }
}

where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on?

OwnerDisplayName: Michael Burr


问:
C# public type alias?
What I want to do is write some classes in C# in a new namespace that act as wrapper classes for classes in another namespace.  Sometimes a wrapper class is not needed but I still want a corresponding class in the new namespace.  And I want an exact copy of the class.  Is there a way to define the class in the new namespace by referring to the definition of another class?  In other words I want an alias.

To clarify what I mean, if the existing namespace is named "Namespace1" and the new namespace is named "Namespace2", using code like this in Namespace2:

```<code>using Class1 = Namespace1.Class1;
</code>```

would not work because Namespace2.Class1 would not exist.  Class1 would only be aliased "private" to Namespace2 and not "public" to Namespace2.  If I could use Namepsace2.Class1 from outside the namespace, and if that would still refer to Namespace1.Class1, then that would be what I want.

I figured there might be a way to accomplish this with attributes or reflection maybe.  If there were some pre-processor directives or macros that could copy code that would work too, but obviously C# doesn't have anything like that.

答:
You could inherit the class:</p>

```<code>namespace N2
{
   public class Class1 : N1.Class1
   { }
}
</code>```

Title: C# public type alias?

Body:
What I want to do is write some classes in C# in a new namespace that act as wrapper classes for classes in another namespace.  Sometimes a wrapper class is not needed but I still want a corresponding class in the new namespace.  And I want an exact copy of the class.  Is there a way to define the class in the new namespace by referring to the definition of another class?  In other words I want an alias.

To clarify what I mean, if the existing namespace is named "Namespace1" and the new namespace is named "Namespace2", using code like this in Namespace2:

using Class1 = Namespace1.Class1;

would not work because Namespace2.Class1 would not exist.  Class1 would only be aliased "private" to Namespace2 and not "public" to Namespace2.  If I could use Namepsace2.Class1 from outside the namespace, and if that would still refer to Namespace1.Class1, then that would be what I want.

I figured there might be a way to accomplish this with attributes or reflection maybe.  If there were some pre-processor directives or macros that could copy code that would work too, but obviously C# doesn't have anything like that.

Body:
You could inherit the class:

namespace N2
{
   public class Class1 : N1.Class1
   { }
}


问:
Using variables in select (apostrophes needed)
psql (9.6.1, server 9.5.5)

employees

```<code>     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              |
 first_name     | character varying(20)       |                                                                 | extended |              |
 last_name      | character varying(25)       | not null                                                        | extended |              |
 email          | character varying(25)       | not null                                                        | extended |              |
 phone_number   | character varying(20)       |                                                                 | extended |              |
 hire_date      | timestamp without time zone | not null                                                        | plain    |              |
 job_id         | character varying(10)       | not null                                                        | extended |              |
 salary         | numeric(8,2)                |                                                                 | main     |              |
 commission_pct | numeric(2,2)                |                                                                 | main     |              |
 manager_id     | integer                     |                                                                 | plain    |              |
 department_id  | integer
</code>```

For self education I'd like to use a variable.

The result of this request would suit me:

```<code>hr=> select last_name, char_length(last_name) as Length from employees where substring(last_name from 1 for 1) = 'H' order by last_name;
 last_name | length
-----------+--------
 Hartstein |      9
 Higgins   |      7
 Hunold    |      6
(3 rows)
</code>```

But for self education I'd like to use a variable:

```<code>\set chosen_letter 'H'
hr=> select last_name, char_length(last_name) as Length from employees where substring(last_name from 1 for 1) = :chosen_letter order by last_name;
ERROR:  column "h" does not exist
LINE 1: ...ployees where substring(last_name from 1 for 1) = H order by...
                                                             ^
</code>```

Those apostrophes seems to ruin everything. And I can't cope with the problem.

Could you help me understand how to use variable to acquire the result as above?

答:
Try using:</p>

```<code>\set chosen_letter '''H'''
</code>```

Body:
psql (9.6.1, server 9.5.5)

employees

     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              |
 first_name     | character varying(20)       |                                                                 | extended |              |
 last_name      | character varying(25)       | not null                                                        | extended |              |
 email          | character varying(25)       | not null                                                        | extended |              |
 phone_number   | character varying(20)       |                                                                 | extended |              |
 hire_date      | timestamp without time zone | not null                                                        | plain    |              |
 job_id         | character varying(10)       | not null                                                        | extended |              |
 salary         | numeric(8,2)                |                                                                 | main     |              |
 commission_pct | numeric(2,2)                |                                                                 | main     |              |
 manager_id     | integer                     |                                                                 | plain    |              |
 department_id  | integer

For self education I'd like to use a variable.

The result of this request would suit me:

hr=> select last_name, char_length(last_name) as Length from employees where substring(last_name from 1 for 1) = 'H' order by last_name;
 last_name | length
-----------+--------
 Hartstein |      9
 Higgins   |      7
 Hunold    |      6
(3 rows)

But for self education I'd like to use a variable:

\set chosen_letter 'H'
hr=> select last_name, char_length(last_name) as Length from employees where substring(last_name from 1 for 1) = :chosen_letter order by last_name;
ERROR:  column "h" does not exist
LINE 1: ...ployees where substring(last_name from 1 for 1) = H order by...
                                                             ^

Those apostrophes seems to ruin everything. And I can't cope with the problem.

Could you help me understand how to use variable to acquire the result as above?

Body:
Try using:

\set chosen_letter '''H'''


问:
How can a static method provided by a component be shown in an UML component diagam?
Components can have a provided interface which could be shown with the ball notation or a realize dependency to an <<interface>>. But what if the component provides a static method?

Given a component MyComponent that provides its functionality via a public static mehtod `operation, would the following be a correct UML representation?

```<code>+---------------------+                  +---------------------------+
|    <<component>>    |   <<realize>>    |          AClass           |
|     MyComponent     |----------------->|---------------------------|
|                     |                  |+operation()    <<static>> |
+---------------------+                  +---------------------------+
</code>```

Or should AClass be marked with the <<interface>> stereotype even if it is not implemented as an interface in the programming language? There are languages without an interface construct after all.

答: Not every construct is governed by rules in UML. So you have quite a certain degree of freedom. Especially when modeling static programming languages (like you have in embedded systems with lots of C programming) you need to setup your own rules how to express things. So basically nothing is wrong with the way you showed it. You should simply describe this construct in the modeling rules for the domain where you intend to use this construct. Probably I would stereotype AClass as <<interface>> since the fact that you have some public method exposed counts more than the fact that it is realized as static.

Body:
Components can have a provided interface which could be shown with the ball notation or a realize dependency to an <<interface>>. But what if the component provides a static method?

Given a component MyComponent that provides its functionality via a public static mehtod `operation, would the following be a correct UML representation?

+---------------------+                  +---------------------------+
|    <<component>>    |   <<realize>>    |          AClass           |
|     MyComponent     |----------------->|---------------------------|
|                     |                  |+operation()    <<static>> |
+---------------------+                  +---------------------------+

Or should AClass be marked with the <<interface>> stereotype even if it is not implemented as an interface in the programming language? There are languages without an interface construct after all.


问:
Swift 3: UILabel not showing in custom UITableViewCell
I have a custom UITableViewCell called CCLineupTableViewCell that looks like this:

```<code>@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var artistValuationLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
</code>```

I access the cell in the cellForRowAt indexPath: IndexPath method like so:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! CCLineupTableViewCell
</code>```

My custom cell setup is like so:

As you can see it's setup right in the IB and in the code. The weird thing is that the first label, artistNameLabel, is accessible through cellForRowAt indexPath: IndexPath and works perfectly. The artistValuationLabel, however, never even shows up despite having default text via the storyboard.

Edit:

I've added a picture of the constraints from the nib. It's anchored to the right side, top, and bottom of the cell (as well as the aspect ratio).

答:
Your mistake is an error on the constraints you did set.

Add a Width constraint to make sure that artistValuationLabel will have space to appear.

Body:
I have a custom UITableViewCell called CCLineupTableViewCell that looks like this:

@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var artistValuationLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

I access the cell in the cellForRowAt indexPath: IndexPath method like so:

let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! CCLineupTableViewCell

My custom cell setup is like so:

As you can see it's setup right in the IB and in the code. The weird thing is that the first label, artistNameLabel, is accessible through cellForRowAt indexPath: IndexPath and works perfectly. The artistValuationLabel, however, never even shows up despite having default text via the storyboard.

Edit:

I've added a picture of the constraints from the nib. It's anchored to the right side, top, and bottom of the cell (as well as the aspect ratio).


问:
Deep combine NSDictionaries
I need to merge two NSDictionarys into one provided that if there are dictionaries within the dictionaries, they are also merged.

More or less like jQuery's extend function.

答:
Alexsander Akers works for me except the case where dict2 contains a dictionary that's missing from dict1 - it crashes.  I changed the logic to this:</p>

```<code>+ (NSDictionary *) dictionaryByMerging: (NSDictionary *) dict1 with: (NSDictionary *) dict2 {
    NSMutableDictionary * result = [NSMutableDictionary dictionaryWithDictionary:dict1];

    [dict2 enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
        if (![dict1 objectForKey:key]) {
            [result setObject: obj forKey: key];
        } else if ([obj isKindOfClass:[NSDictionary class]]) {
            NSDictionary * newVal = [[dict1 objectForKey: key] dictionaryByMergingWith: (NSDictionary *) obj];
            [result setObject: newVal forKey: key];
        }
    }];

    return (NSDictionary *) [result mutableCopy];
}
</code>```

Title: Deep combine NSDictionaries

Body:
Alexsander Akers works for me except the case where dict2 contains a dictionary that's missing from dict1 - it crashes.  I changed the logic to this:

+ (NSDictionary *) dictionaryByMerging: (NSDictionary *) dict1 with: (NSDictionary *) dict2 {
    NSMutableDictionary * result = [NSMutableDictionary dictionaryWithDictionary:dict1];

    [dict2 enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
        if (![dict1 objectForKey:key]) {
            [result setObject: obj forKey: key];
        } else if ([obj isKindOfClass:[NSDictionary class]]) {
            NSDictionary * newVal = [[dict1 objectForKey: key] dictionaryByMergingWith: (NSDictionary *) obj];
            [result setObject: newVal forKey: key];
        }
    }];

    return (NSDictionary *) [result mutableCopy];
}


问:
Android File IO Interface Class
I did some reading on the API for File IO and read the following blog post: http://techknock.blogspot.com/2008/05/file-hadling-in-android.html. His code works fine when everything is in the same activity. But what I am trying to do is create an IOInterface class that I can use to open multiple databases to populate multiple lists.

ListA.java

```<code>public class ListA
{
    public List<ClassA> list;
    private final String DBA = "dbA";
    private IOInterface database;

    public List()
    {
        list = new ArrayList<ClassA>();
        database = new IOInterface();
    }

    ...

    public void initListA() throws IOException
    {
        database.openForWriting(DBA);

        String myStr = new String("content");
        database.dos.writeBytes(myStr);
        database.dos.flush();
        database.dos.close();
    }
}
</code>```

IOInterface.java

```<code>public class IOInterface
{
    public DataOutputStream dos;
    private FileOutputStream fos;

    public void openForWriting(String database)
    {
        try {
            fos = openFileOutput(database, Content.MODE_PRIVATE);
            dos = new DataOutputStream(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Eclipse underlines fos = openFileOutput(database, Content.MODE_PRIVATE);. With the comment that openFileOutput() does not exist. The resolution to this is to extend the IOInteface class as an Activity. I suppose then openFileOutput() is a method of an activity class.

So my question is how do accomplish what I am trying to do? Standard Java file io such as:

```<code>File fp = new File("database");
FileOutputStream fos = new FileOutputStream(fp);
</code>```

does not work. It catches a FileNotFoundException. This has to be doable though. Any ideas?

Thanks,

答:
Method openFileOutput() is contained in the Context class, so you can pass an instance of this class to your method that opens files. And you should always use methods from Context when you want to work with files.

You can read about using the internal and external storages in the development guide.

Title: Android File IO Interface Class

Body:
I did some reading on the API for File IO and read the following blog post: http://techknock.blogspot.com/2008/05/file-hadling-in-android.html. His code works fine when everything is in the same activity. But what I am trying to do is create an IOInterface class that I can use to open multiple databases to populate multiple lists.

ListA.java

public class ListA
{
    public List<ClassA> list;
    private final String DBA = "dbA";
    private IOInterface database;

    public List()
    {
        list = new ArrayList<ClassA>();
        database = new IOInterface();
    }

    ...

    public void initListA() throws IOException
    {
        database.openForWriting(DBA);

        String myStr = new String("content");
        database.dos.writeBytes(myStr);
        database.dos.flush();
        database.dos.close();
    }
}

IOInterface.java

public class IOInterface
{
    public DataOutputStream dos;
    private FileOutputStream fos;

    public void openForWriting(String database)
    {
        try {
            fos = openFileOutput(database, Content.MODE_PRIVATE);
            dos = new DataOutputStream(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Eclipse underlines fos = openFileOutput(database, Content.MODE_PRIVATE);. With the comment that openFileOutput() does not exist. The resolution to this is to extend the IOInteface class as an Activity. I suppose then openFileOutput() is a method of an activity class.

So my question is how do accomplish what I am trying to do? Standard Java file io such as:

File fp = new File("database");
FileOutputStream fos = new FileOutputStream(fp);

does not work. It catches a FileNotFoundException. This has to be doable though. Any ideas?

Thanks,


问:
Using RegEx to grab all headings to build a ToC (Classic ASP)
i still try to develope a function that extract from an HTML text all Headings (h1,h2,h3,..) with a id specified to construct a Table of contents.

I've made a simple script using regex but for some strange reason it collect only 1 match (the last one)

here my sample code:

```<code>Function RegExResults(strTarget, strPattern)
    dim regEx
    Set regEx = New RegExp
    regEx.Pattern = strPattern
    regEx.Global = True
    regEx.IgnoreCase = True
    regEx.Multiline = True
    Set RegExResults = regEx.Execute(strTarget)
    Set regEx = Nothing
End Function

htmlstr = "<h1>Documentation</h1><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p><h3 id=""one"">How do you smurf a murf?</h3><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.</p><h3 id=""two"">How do many licks does a giraffe?</h3><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>"

regpattern = "<h([1-9]).*id=\""(.*)\"">(.*)</h[1-9]>"

set arrayresult = RegExResults(htmlstr,regpattern)
For each result in arrayresult
    response.write "count: " & arrayresult.count & "<br><hr>"
    response.write "0: " & result.Submatches(0) & "<br>"
    response.write "1: " & result.Submatches(1) & "<br>"
    response.write "2: " & result.Submatches(2) & "<br>"
Next
</code>```

I need to extract all headings plus for each one know what kind of heading  is (1..9) and the id value to use for jump to the right title paragraph (#ID_value).

I hope someone can help me to find out why this not working as intended.

Thank you

答:
The .*'s in the pattern are greedy but you need laziness to collect every possible match. Instead you should use .*?'s.

With some improvements, the pattern could be something like below.

regpattern = "<(h[1-9]).*?id=""(.*?)"">(.*?)</\1>"

' \1 means the same as the 1st group
' backslash (\) is redundant to escape double quotes, so removed it
```

I'd strongly recommend you to have a look at Repetition with Star and Plus. It's very useful article to understand lazy and greedy repetitions in Regex.

Oh, I almost forgot, You can't parse HTML with Regex, well you should not at least.

Body:
i still try to develope a function that extract from an HTML text all Headings (h1,h2,h3,..) with a id specified to construct a Table of contents.

I've made a simple script using regex but for some strange reason it collect only 1 match (the last one)

here my sample code:

Function RegExResults(strTarget, strPattern)
    dim regEx
    Set regEx = New RegExp
    regEx.Pattern = strPattern
    regEx.Global = True
    regEx.IgnoreCase = True
    regEx.Multiline = True
    Set RegExResults = regEx.Execute(strTarget)
    Set regEx = Nothing
End Function

htmlstr = "
Documentation

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

How do you smurf a murf?

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.

How do many licks does a giraffe?

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
"

regpattern = "<h([1-9]).*id=\""(.*)\"">(.*)</h[1-9]>"

set arrayresult = RegExResults(htmlstr,regpattern)
For each result in arrayresult
    response.write "count: " & arrayresult.count & "

"
    response.write "0: " & result.Submatches(0) & "
"
    response.write "1: " & result.Submatches(1) & "
"
    response.write "2: " & result.Submatches(2) & "
"
Next

I need to extract all headings plus for each one know what kind of heading  is (1..9) and the id value to use for jump to the right title paragraph (#ID_value).

I hope someone can help me to find out why this not working as intended.

Thank you

Body:
The .*'s in the pattern are greedy but you need laziness to collect every possible match. Instead you should use .*?'s.

With some improvements, the pattern could be something like below.

regpattern = "<(h[1-9]).*?id=""(.*?)"">(.*?)</\1>"

' \1 means the same as the 1st group
' backslash (\) is redundant to escape double quotes, so removed it

I'd strongly recommend you to have a look at Repetition with Star and Plus. It's very useful article to understand lazy and greedy repetitions in Regex.

Oh, I almost forgot, You can't parse HTML with Regex, well you should not at least.