问:
Interceptor not getting initialized and invoked with SpringBoot
I've a Spring-Boot application that is packaged as a war with tomcat dependency as provided (so I've both options - use the packaged .war to run within embedded container after launching it via java -jar command AND also to run on a standalone servlet container).

Below is my App main class

```<code>package com.mycompany.edsa.dgv.proxysvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import  org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.mycompany.edsa.dgv.proxysvc.interceptor.DGVProxySvcRequestInterceptor;

//import com.mycompany.edsa.dgv.proxysvc.config.ConfigExtension;

@SpringBootApplication
@ImportResource("classpath:dgv-proxy-svc-spring-ctx.xml")
//@Import(ConfigExtension.class)
public class DGVProxySvcAppMain extends SpringBootServletInitializer {

public static void main(String[] args) {
    SpringApplication.run(DGVProxySvcAppMain.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(DGVProxySvcAppMain.class);
}

@Bean
public DGVProxySvcRequestInterceptor dgvProxySvcRequestInterceptor() {
    DGVProxySvcRequestInterceptor dgvProxySvcReqInterceptor = new DGVProxySvcRequestInterceptor();
    return dgvProxySvcReqInterceptor;
}

@Bean
public WebMvcConfigurerAdapter adapter() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            System.out.println("Adding interceptors");
            registry.addInterceptor(dgvProxySvcRequestInterceptor()).addPathPatterns("/*");
            super.addInterceptors(registry);
        }
    };
}
</code>```

}

My Interceptor class below:

```<code>package com.mycompany.edsa.dgv.proxysvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class DGVProxySvcRequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /* Put in the code here to validate user principal before passing control to the controller */

        //BXPPrincipal principal = (BXPPrincipal)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //Map<String, ?> result = principal.getAttributes();
        System.out.println("Inside DGVProxySvcRequestInterceptor...");
        return super.preHandle(request, response, handler);
    }

}
</code>```

However, on launching the application (I launch through spring-boot:run maven goal and using Eclipse IDE), I do not see my interceptor getting registered in the console logs.
I tried launching it in debug mode with a breakpoint at the public void addInterceptors(InterceptorRegistry registry) method and I see that control comes at this point and the sysout message "Adding interceptors" get logged on console and also the registry contains my DGVProxySvcRequestInterceptor in its encapsulated ArrayList but not sure why there is no message on console mentioning anything about initialization of this interceptor bean.
Moreover, on invoking my service, I do not see sysout message "Inside DGVProxySvcRequestInterceptor..." that has been put into my interceptor class' preHandle method (which confirms that the interceptor didn't get invoked).

Can someone pls help me out in finding what configuration mistake I might be doing?

Pls note - I tried extending my main class with WebMvcConfigurerAdapter instead of SpringBootServletInitializer and overriden the addInterceptors method to add my interceptor. In that case my interceptor gets initialized well (I can see on console logs) and also gets invoked when I invoke my service uri.
So this tells me that something is not correct with my configuration when I try to use SpringBootServletInitializer (I've to use this initializer as I need to package my code as a war that can run on a standalone servlet container).

Thanks in advance for any suggestions/pointers !

答:
I had same issue.
@SpringBootApplication scans all the component from the current package only. In order to scan other package, we need to specify package in @ComponentScan.
For Example

```<code>package com.main;
@SpringBootApplication
public class Application {
     //Code goes here.
}
</code>```

Now i want interceptor to be register, which is neither in com.main not com.main.**, its available in com.test package.

```<code>package com.test.interceptor
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Autowired
    HeaderInterceptor headerInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(headerInterceptor);
    }
}
</code>```

In above case, Spring Boot won't register HeaderInterceptor in context. In order to register, we must explicitly scan that package.

```<code>package com.main;
@SpringBootApplication
@ComponentScan("com.*") //Which takes care all the package which starts with com.
@ComponentScan({"com.main.*","com.test.*"}) //For specific packages
public class Application {
     //Code goes here.
}
</code>```

Body:
I've a Spring-Boot application that is packaged as a war with tomcat dependency as provided (so I've both options - use the packaged .war to run within embedded container after launching it via java -jar command AND also to run on a standalone servlet container).

Below is my App main class

package com.mycompany.edsa.dgv.proxysvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import  org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.mycompany.edsa.dgv.proxysvc.interceptor.DGVProxySvcRequestInterceptor;

//import com.mycompany.edsa.dgv.proxysvc.config.ConfigExtension;

@SpringBootApplication
@ImportResource("classpath:dgv-proxy-svc-spring-ctx.xml")
//@Import(ConfigExtension.class)
public class DGVProxySvcAppMain extends SpringBootServletInitializer {

public static void main(String[] args) {
    SpringApplication.run(DGVProxySvcAppMain.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(DGVProxySvcAppMain.class);
}

@Bean
public DGVProxySvcRequestInterceptor dgvProxySvcRequestInterceptor() {
    DGVProxySvcRequestInterceptor dgvProxySvcReqInterceptor = new DGVProxySvcRequestInterceptor();
    return dgvProxySvcReqInterceptor;
}

@Bean
public WebMvcConfigurerAdapter adapter() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            System.out.println("Adding interceptors");
            registry.addInterceptor(dgvProxySvcRequestInterceptor()).addPathPatterns("/*");
            super.addInterceptors(registry);
        }
    };
}

}

My Interceptor class below:

package com.mycompany.edsa.dgv.proxysvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class DGVProxySvcRequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /* Put in the code here to validate user principal before passing control to the controller */

        //BXPPrincipal principal = (BXPPrincipal)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //Map<String, ?> result = principal.getAttributes();
        System.out.println("Inside DGVProxySvcRequestInterceptor...");
        return super.preHandle(request, response, handler);
    }

}

However, on launching the application (I launch through spring-boot:run maven goal and using Eclipse IDE), I do not see my interceptor getting registered in the console logs.
I tried launching it in debug mode with a breakpoint at the public void addInterceptors(InterceptorRegistry registry) method and I see that control comes at this point and the sysout message "Adding interceptors" get logged on console and also the registry contains my DGVProxySvcRequestInterceptor in its encapsulated ArrayList but not sure why there is no message on console mentioning anything about initialization of this interceptor bean.
Moreover, on invoking my service, I do not see sysout message "Inside DGVProxySvcRequestInterceptor..." that has been put into my interceptor class' preHandle method (which confirms that the interceptor didn't get invoked).

Can someone pls help me out in finding what configuration mistake I might be doing?

Pls note - I tried extending my main class with WebMvcConfigurerAdapter instead of SpringBootServletInitializer and overriden the addInterceptors method to add my interceptor. In that case my interceptor gets initialized well (I can see on console logs) and also gets invoked when I invoke my service uri.
So this tells me that something is not correct with my configuration when I try to use SpringBootServletInitializer (I've to use this initializer as I need to package my code as a war that can run on a standalone servlet container).

Thanks in advance for any suggestions/pointers !

Body:
I had same issue.
@SpringBootApplication scans all the component from the current package only. In order to scan other package, we need to specify package in @ComponentScan.
For Example

package com.main;
@SpringBootApplication
public class Application {
     //Code goes here.
}

Now i want interceptor to be register, which is neither in com.main not com.main.**, its available in com.test package.

package com.test.interceptor
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Autowired
    HeaderInterceptor headerInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(headerInterceptor);
    }
}

In above case, Spring Boot won't register HeaderInterceptor in context. In order to register, we must explicitly scan that package.

package com.main;
@SpringBootApplication
@ComponentScan("com.*") //Which takes care all the package which starts with com.
@ComponentScan({"com.main.*","com.test.*"}) //For specific packages
public class Application {
     //Code goes here.
}


来源: stackexchange

问:
Multi-Target and Multi-Class prediction
I am relatively new to machine learning as well as tensorflow. I would like to train the data so that predictions with 2 targets and multiple classes could be made. Is this something that can be done? I was able to implement the algorithm for 1 target but don't know how I need to do it for a second target as well.

An example dataset:
    DayOfYear Temperature Flow Visibility

```<code>316 8   1   4
285 -1  1   4
326 8   2   5
323 -1  0   3
10  7   3   6
62  8   0   3
56  8   1   4
347 7   2   5
363 7   0   3
77  7   3   6
1   7   1   4
308 -1  2   5
364 7   3   6
</code>```

If I train (DayOfYear Temperature Flow) I can predict the Visibility quite well. But I need to predict Flow as well somehow. I am pretty sure that Flow will influence Visibility so I am not sure how to go with that.

This is the implementation that I have

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

import numpy as np
import tensorflow as tf

# Data sets
TRAINING = "/ml_baetterich_learn.csv"
TEST = "/ml_baetterich_test.csv"
VALIDATION = "/ml_baetterich_validation.csv"

def main():

  # Load datasets.
  training_set = tf.contrib.learn.datasets.base.load_csv_without_header(
      filename=TRAINING,
      target_dtype=np.int,
      features_dtype=np.int,
      target_column=-1)
  test_set = tf.contrib.learn.datasets.base.load_csv_without_header(
      filename=TEST,
      target_dtype=np.int,
      features_dtype=np.int,
      target_column=-1)
  validation_set = tf.contrib.learn.datasets.base.load_csv_without_header(
      filename=VALIDATION,
      target_dtype=np.int,
      features_dtype=np.int,
      target_column=-1)

  # Specify that all features have real-value data
  feature_columns = [tf.contrib.layers.real_valued_column("", dimension=3)]

  # Build 3 layer DNN with 10, 20, 10 units respectively.
  classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                              hidden_units=[10, 20, 10],
                                              n_classes=9,
                                              model_dir="/tmp/iris_model")
  # Define the training inputs
  def get_train_inputs():
    x = tf.constant(training_set.data)
    y = tf.constant(training_set.target)

    return x, y

  # Fit model.
  classifier.fit(input_fn=get_train_inputs, steps=4000)

  # Define the test inputs
  def get_test_inputs():
    x = tf.constant(test_set.data)
    y = tf.constant(test_set.target)

    return x, y

  # Define the test inputs
  def get_validation_inputs():
    x = tf.constant(validation_set.data)
    y = tf.constant(validation_set.target)

    return x, y

  # Evaluate accuracy.
  accuracy_test_score = classifier.evaluate(input_fn=get_test_inputs,
                                       steps=1)["accuracy"]

  accuracy_validation_score = classifier.evaluate(input_fn=get_validation_inputs,
                                       steps=1)["accuracy"]

  print ("\nValidation Accuracy: {0:0.2f}\nTest Accuracy: {1:0.2f}\n".format(accuracy_validation_score,accuracy_test_score))

  # Classify two new flower samples.
  def new_samples():
    return np.array(
      [[327,8,3],
       [47,8,0]], dtype=np.float32)

  predictions = list(classifier.predict_classes(input_fn=new_samples))

  print(
      "New Samples, Class Predictions:    {}\n"
      .format(predictions))

if __name__ == "__main__":
    main()
</code>```

答:
Option 1: multi-headed model

You could use a multi-headed DNNEstimator model. This treats Flow and Visibility as two separate softmax classification targets, each with their own set of classes. I had to modify the load_csv_without_header helper function to support multiple targets (which could be cleaner, but is not the point here - feel free to ignore its details).

import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
import csv
import collections

num_flow_classes = 4
num_visib_classes = 7

Dataset = collections.namedtuple('Dataset', ['data', 'target'])

def load_csv_without_header(fn, target_dtype, features_dtype, target_columns):
    with gfile.Open(fn) as csv_file:
        data_file = csv.reader(csv_file)
        data = []
        targets = {
            target_cols: []
            for target_cols in target_columns.keys()
        }
        for row in data_file:
            cols = sorted(target_columns.items(), key=lambda tup: tup[1], reverse=True)
            for target_col_name, target_col_i in cols:
                targets[target_col_name].append(row.pop(target_col_i))
            data.append(np.asarray(row, dtype=features_dtype))

        targets = {
            target_col_name: np.array(val, dtype=target_dtype)
            for target_col_name, val in targets.items()
        }
        data = np.array(data)
        return Dataset(data=data, target=targets)

feature_columns = [
    tf.contrib.layers.real_valued_column("", dimension=1),
    tf.contrib.layers.real_valued_column("", dimension=2),
]
head = tf.contrib.learn.multi_head([
    tf.contrib.learn.multi_class_head(
        num_flow_classes, label_name="Flow", head_name="Flow"),
    tf.contrib.learn.multi_class_head(
        num_visib_classes, label_name="Visibility", head_name="Visibility"),
])
classifier = tf.contrib.learn.DNNEstimator(
    feature_columns=feature_columns,
    hidden_units=[10, 20, 10],
    model_dir="iris_model",
    head=head,
)

def get_input_fn(filename):
    def input_fn():
        dataset = load_csv_without_header(
            fn=filename,
            target_dtype=np.int,
            features_dtype=np.int,
            target_columns={"Flow": 2, "Visibility": 3}
        )
        x = tf.constant(dataset.data)
        y = {k: tf.constant(v) for k, v in dataset.target.items()}
        return x, y
    return input_fn

classifier.fit(input_fn=get_input_fn("tmp_train.csv"), steps=4000)
res = classifier.evaluate(input_fn=get_input_fn("tmp_test.csv"), steps=1)

print("Validation:", res)
```

<h1>Option 2: multi-labeled head</h1>

<p>If you keep your CSV data separated by commas, and keep the last column for all the classes a row might have (separated by some token such as space), you can use the following code:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
import tensorflow as tf

all_classes = ["0", "1", "2", "3", "4", "5", "6"]

def k_hot(classes_col, all_classes, delimiter=' '):
    table = tf.contrib.lookup.index_table_from_tensor(
        mapping=tf.constant(all_classes)
    )
    classes = tf.string_split(classes_col, delimiter)
    ids = table.lookup(classes)
    num_items = tf.cast(tf.shape(ids)[0], tf.int64)
    num_entries = tf.shape(ids.indices)[0]

    y = tf.SparseTensor(
        indices=tf.stack([ids.indices[:, 0], ids.values], axis=1),
        values=tf.ones(shape=(num_entries,), dtype=tf.int32),
        dense_shape=(num_items, len(all_classes)),
    )
    y = tf.sparse_tensor_to_dense(y, validate_indices=False)
    return y

def feature_engineering_fn(features, labels):
    labels = k_hot(labels, all_classes)
    return features, labels

feature_columns = [
    tf.contrib.layers.real_valued_column("", dimension=1), # DayOfYear
    tf.contrib.layers.real_valued_column("", dimension=2), # Temperature
]
classifier = tf.contrib.learn.DNNEstimator(
    feature_columns=feature_columns,
    hidden_units=[10, 20, 10],
    model_dir="iris_model",
    head=tf.contrib.learn.multi_label_head(n_classes=len(all_classes)),
    feature_engineering_fn=feature_engineering_fn,
)

def get_input_fn(filename):
    def input_fn():
        dataset = tf.contrib.learn.datasets.base.load_csv_without_header(
            filename=filename,
            target_dtype="S100", # strings of length up to 100 characters
            features_dtype=np.int,
            target_column=-1
        )
        x = tf.constant(dataset.data)
        y = tf.constant(dataset.target)
        return x, y
    return input_fn

classifier.fit(input_fn=get_input_fn("tmp_train.csv"), steps=4000)
res = classifier.evaluate(input_fn=get_input_fn("tmp_test.csv"), steps=1)

print("Validation:", res)
</code>```

We are using DNNEstimator with a multi_label_head, which uses sigmoid crossentropy rather than softmax crossentropy as a loss function. This means that each of the output units/logits are passed through the sigmoid function, which gives the likelihood of the data point belonging to that class, i.e. the classes are computed independently and are not mutually exclusive as they are with softmax crossentropy. This means that you could have between 0 and len(all_classes) classes set for each row in the training set and final predictions.

Also notice that the classes are represented as strings (and k_hot makes the conversion to token indices), so that you could use arbitrary class identifiers such as category UUIDs in e-commerce settings. If the categories in the 3rd and 4th column are different (Flow ID 1 != Visibility ID 1), you could prepend the column name to each class ID, e.g.

316,8,flow1 visibility4
285,-1,flow1 visibility4
326,8,flow2 visibility5

For a description of how k_hot works, see my other SO answer. I decided to use k_hot as a separate function (rather than define it directly in feature_engineering_fn because it's a distinct piece of functionality, and probably TensorFlow will soon have a similar utility function.

Note that if you're now using the first two columns to predict the last two columns, your accuraccy will certainly go down, as the last two columns are highly correlated and using one of them will give you a lot of information about the other. Actually, your code was using only the 3rd column, which was kind of a cheat anyway if the goal is to predict the 3rd and 4th columns.

ContentLicense: CC BY-SA 3.0

Title: Multi-Target and Multi-Class prediction

Body:
I am relatively new to machine learning as well as tensorflow. I would like to train the data so that predictions with 2 targets and multiple classes could be made. Is this something that can be done? I was able to implement the algorithm for 1 target but don't know how I need to do it for a second target as well.

An example dataset:
    DayOfYear Temperature Flow Visibility

316 8   1   4
285 -1  1   4
326 8   2   5
323 -1  0   3
10  7   3   6
62  8   0   3
56  8   1   4
347 7   2   5
363 7   0   3
77  7   3   6
1   7   1   4
308 -1  2   5
364 7   3   6

If I train (DayOfYear Temperature Flow) I can predict the Visibility quite well. But I need to predict Flow as well somehow. I am pretty sure that Flow will influence Visibility so I am not sure how to go with that.

This is the implementation that I have

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

import numpy as np
import tensorflow as tf

# Data sets
TRAINING = "/ml_baetterich_learn.csv"
TEST = "/ml_baetterich_test.csv"
VALIDATION = "/ml_baetterich_validation.csv"

def main():

  # Load datasets.
  training_set = tf.contrib.learn.datasets.base.load_csv_without_header(
      filename=TRAINING,
      target_dtype=np.int,
      features_dtype=np.int,
      target_column=-1)
  test_set = tf.contrib.learn.datasets.base.load_csv_without_header(
      filename=TEST,
      target_dtype=np.int,
      features_dtype=np.int,
      target_column=-1)
  validation_set = tf.contrib.learn.datasets.base.load_csv_without_header(
      filename=VALIDATION,
      target_dtype=np.int,
      features_dtype=np.int,
      target_column=-1)

  # Specify that all features have real-value data
  feature_columns = [tf.contrib.layers.real_valued_column("", dimension=3)]

  # Build 3 layer DNN with 10, 20, 10 units respectively.
  classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                              hidden_units=[10, 20, 10],
                                              n_classes=9,
                                              model_dir="/tmp/iris_model")
  # Define the training inputs
  def get_train_inputs():
    x = tf.constant(training_set.data)
    y = tf.constant(training_set.target)

    return x, y

  # Fit model.
  classifier.fit(input_fn=get_train_inputs, steps=4000)

  # Define the test inputs
  def get_test_inputs():
    x = tf.constant(test_set.data)
    y = tf.constant(test_set.target)

    return x, y

  # Define the test inputs
  def get_validation_inputs():
    x = tf.constant(validation_set.data)
    y = tf.constant(validation_set.target)

    return x, y

  # Evaluate accuracy.
  accuracy_test_score = classifier.evaluate(input_fn=get_test_inputs,
                                       steps=1)["accuracy"]

  accuracy_validation_score = classifier.evaluate(input_fn=get_validation_inputs,
                                       steps=1)["accuracy"]

  print ("\nValidation Accuracy: {0:0.2f}\nTest Accuracy: {1:0.2f}\n".format(accuracy_validation_score,accuracy_test_score))

  # Classify two new flower samples.
  def new_samples():
    return np.array(
      [[327,8,3],
       [47,8,0]], dtype=np.float32)

  predictions = list(classifier.predict_classes(input_fn=new_samples))

  print(
      "New Samples, Class Predictions:    {}\n"
      .format(predictions))

if __name__ == "__main__":
    main()

Body:
Option 1: multi-headed model

You could use a multi-headed DNNEstimator model. This treats Flow and Visibility as two separate softmax classification targets, each with their own set of classes. I had to modify the load_csv_without_header helper function to support multiple targets (which could be cleaner, but is not the point here - feel free to ignore its details).

import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
import csv
import collections

num_flow_classes = 4
num_visib_classes = 7

Dataset = collections.namedtuple('Dataset', ['data', 'target'])

def load_csv_without_header(fn, target_dtype, features_dtype, target_columns):
    with gfile.Open(fn) as csv_file:
        data_file = csv.reader(csv_file)
        data = []
        targets = {
            target_cols: []
            for target_cols in target_columns.keys()
        }
        for row in data_file:
            cols = sorted(target_columns.items(), key=lambda tup: tup[1], reverse=True)
            for target_col_name, target_col_i in cols:
                targets[target_col_name].append(row.pop(target_col_i))
            data.append(np.asarray(row, dtype=features_dtype))

        targets = {
            target_col_name: np.array(val, dtype=target_dtype)
            for target_col_name, val in targets.items()
        }
        data = np.array(data)
        return Dataset(data=data, target=targets)

feature_columns = [
    tf.contrib.layers.real_valued_column("", dimension=1),
    tf.contrib.layers.real_valued_column("", dimension=2),
]
head = tf.contrib.learn.multi_head([
    tf.contrib.learn.multi_class_head(
        num_flow_classes, label_name="Flow", head_name="Flow"),
    tf.contrib.learn.multi_class_head(
        num_visib_classes, label_name="Visibility", head_name="Visibility"),
])
classifier = tf.contrib.learn.DNNEstimator(
    feature_columns=feature_columns,
    hidden_units=[10, 20, 10],
    model_dir="iris_model",
    head=head,
)

def get_input_fn(filename):
    def input_fn():
        dataset = load_csv_without_header(
            fn=filename,
            target_dtype=np.int,
            features_dtype=np.int,
            target_columns={"Flow": 2, "Visibility": 3}
        )
        x = tf.constant(dataset.data)
        y = {k: tf.constant(v) for k, v in dataset.target.items()}
        return x, y
    return input_fn

classifier.fit(input_fn=get_input_fn("tmp_train.csv"), steps=4000)
res = classifier.evaluate(input_fn=get_input_fn("tmp_test.csv"), steps=1)

print("Validation:", res)

Option 2: multi-labeled head

If you keep your CSV data separated by commas, and keep the last column for all the classes a row might have (separated by some token such as space), you can use the following code:

import numpy as np
import tensorflow as tf

all_classes = ["0", "1", "2", "3", "4", "5", "6"]

def k_hot(classes_col, all_classes, delimiter=' '):
    table = tf.contrib.lookup.index_table_from_tensor(
        mapping=tf.constant(all_classes)
    )
    classes = tf.string_split(classes_col, delimiter)
    ids = table.lookup(classes)
    num_items = tf.cast(tf.shape(ids)[0], tf.int64)
    num_entries = tf.shape(ids.indices)[0]

    y = tf.SparseTensor(
        indices=tf.stack([ids.indices[:, 0], ids.values], axis=1),
        values=tf.ones(shape=(num_entries,), dtype=tf.int32),
        dense_shape=(num_items, len(all_classes)),
    )
    y = tf.sparse_tensor_to_dense(y, validate_indices=False)
    return y

def feature_engineering_fn(features, labels):
    labels = k_hot(labels, all_classes)
    return features, labels

feature_columns = [
    tf.contrib.layers.real_valued_column("", dimension=1), # DayOfYear
    tf.contrib.layers.real_valued_column("", dimension=2), # Temperature
]
classifier = tf.contrib.learn.DNNEstimator(
    feature_columns=feature_columns,
    hidden_units=[10, 20, 10],
    model_dir="iris_model",
    head=tf.contrib.learn.multi_label_head(n_classes=len(all_classes)),
    feature_engineering_fn=feature_engineering_fn,
)

def get_input_fn(filename):
    def input_fn():
        dataset = tf.contrib.learn.datasets.base.load_csv_without_header(
            filename=filename,
            target_dtype="S100", # strings of length up to 100 characters
            features_dtype=np.int,
            target_column=-1
        )
        x = tf.constant(dataset.data)
        y = tf.constant(dataset.target)
        return x, y
    return input_fn

classifier.fit(input_fn=get_input_fn("tmp_train.csv"), steps=4000)
res = classifier.evaluate(input_fn=get_input_fn("tmp_test.csv"), steps=1)

print("Validation:", res)

We are using DNNEstimator with a multi_label_head, which uses sigmoid crossentropy rather than softmax crossentropy as a loss function. This means that each of the output units/logits are passed through the sigmoid function, which gives the likelihood of the data point belonging to that class, i.e. the classes are computed independently and are not mutually exclusive as they are with softmax crossentropy. This means that you could have between 0 and len(all_classes) classes set for each row in the training set and final predictions.

Also notice that the classes are represented as strings (and k_hot makes the conversion to token indices), so that you could use arbitrary class identifiers such as category UUIDs in e-commerce settings. If the categories in the 3rd and 4th column are different (Flow ID 1 != Visibility ID 1), you could prepend the column name to each class ID, e.g.

316,8,flow1 visibility4
285,-1,flow1 visibility4
326,8,flow2 visibility5

For a description of how k_hot works, see my other SO answer. I decided to use k_hot as a separate function (rather than define it directly in feature_engineering_fn because it's a distinct piece of functionality, and probably TensorFlow will soon have a similar utility function.

Note that if you're now using the first two columns to predict the last two columns, your accuraccy will certainly go down, as the last two columns are highly correlated and using one of them will give you a lot of information about the other. Actually, your code was using only the 3rd column, which was kind of a cheat anyway if the goal is to predict the 3rd and 4th columns.


问:
Can I catch the value by using bourne shell script?
When I type some command in openwrt, the result is like this.

```<code>Security  Signal(%)     Mode
WPA2      86            on
WPA2      42            on
</code>```

In this result, I want to catch the signal value(86) in first column.
How can i catch the value by using bourne shell script?

Plus, luci.sys.call function is only used in cbi file for making Luci, isn't it?

答:
Try also

```<code>HereYourCommand | awk 'NR==2 { print $2 }'
</code>```

The awk program prints the second field (aka column) of the second record (aka line).

Body:
When I type some command in openwrt, the result is like this.

Security  Signal(%)     Mode
WPA2      86            on
WPA2      42            on

In this result, I want to catch the signal value(86) in first column.
How can i catch the value by using bourne shell script?

Plus, luci.sys.call function is only used in cbi file for making Luci, isn't it?

Body:
Try also

HereYourCommand | awk 'NR==2 { print $2 }'

The awk program prints the second field (aka column) of the second record (aka line).


问:
Cannot read property 'ObjectTracker' of undefined
I'm still new to Angular development, I'm trying to use https://trackingjs.com/ in my typescript angular app, I have included the type definitions but getting the

MonitorComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot
  read property 'ObjectTracker' of undefined

my code

```<code>import { Component, OnInit } from '@angular/core';
import { tracking } from 'tracking';

@Component({
 selector: 'monitor',
 templateUrl: './monitor.component.html',
 styleUrls: ['./monitor.component.css']
})
export class MonitorComponent implements OnInit {

constructor() { }

ngOnInit() {
    var video = document.getElementById('video');
    var canvas = <HTMLCanvasElement>document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var tracker = new tracking.ObjectTracker(['face']);

    tracking.track('#video', tracker);

    tracker.on('track', function (event) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        event.data.forEach(function (rect) {
            context.strokeStyle = '#a64ceb';
            context.strokeRect(rect.x, rect.y, rect.width, rect.height);
            context.font = '11px Helvetica';
            context.fillStyle = "#fff";
            context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
            context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
        });
    });
}

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

HTML

```<code>   <div class="demo-frame">
                    <div class="demo-container">
                        <video id="video" width="320" height="240" preload autoplay loop muted></video>
                        <canvas id="canvas" width="320" height="240"></canvas>
                    </div>
                </div>
</code>```

typedefinition edit

```<code> declare namespace tracking {
  export class ColorTracker extends Tracker {
    constructor(colours: string[]);

    static registerColor(name: string, predicate: (r: number, g: number, b:
    number) => boolean): void;
  }

  export class ObjectTracker extends Tracker {
    constructor(objects: string[]);
  }

  class Tracker {
    constructor(target: string);
    on(eventName: string, callback: (event: TrackEvent) => void): void;
  }

  interface TrackEvent {
    data: TrackRect[];
  }

   interface TrackRect {
    x: number;
    y: number;
    height: number;
    width: number;
    color: string;
  }

  interface TrackerTask {
    stop(): void;
    run(): void;
  }

  export function track(selector: string, tracker: tracking.Tracker):
TrackerTask;
}
</code>```

Any assistance and code improvements would be appreciated.

答:
Since the library does not provide a format that can be consumed by NodeJS (see https://github.com/eduardolundgren/tracking.js/issues/177 mentioned by @Und3rTow)

You cannot use import statements that import a variable for it.

Alternatively, you can use import 'tracking' to tell TypeScript to import the package, which it will declare the tracking variable at the global namespace.

It is the same as doing require('tracking') in NodeJS with JavaScript.

After that, you can use the tracking variable as is.

Body:
I'm still new to Angular development, I'm trying to use https://trackingjs.com/ in my typescript angular app, I have included the type definitions but getting the

MonitorComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot
  read property 'ObjectTracker' of undefined

my code

import { Component, OnInit } from '@angular/core';
import { tracking } from 'tracking';

@Component({
 selector: 'monitor',
 templateUrl: './monitor.component.html',
 styleUrls: ['./monitor.component.css']
})
export class MonitorComponent implements OnInit {

constructor() { }

ngOnInit() {
    var video = document.getElementById('video');
    var canvas = <HTMLCanvasElement>document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var tracker = new tracking.ObjectTracker(['face']);

    tracking.track('#video', tracker);

    tracker.on('track', function (event) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        event.data.forEach(function (rect) {
            context.strokeStyle = '#a64ceb';
            context.strokeRect(rect.x, rect.y, rect.width, rect.height);
            context.font = '11px Helvetica';
            context.fillStyle = "#fff";
            context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
            context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
        });
    });
}

}   });
    }

HTML

                        <video id="video" width="320" height="240" preload autoplay loop muted></video>
                        <canvas id="canvas" width="320" height="240"></canvas>

typedefinition edit

 declare namespace tracking {
  export class ColorTracker extends Tracker {
    constructor(colours: string[]);

    static registerColor(name: string, predicate: (r: number, g: number, b:
    number) => boolean): void;
  }

  export class ObjectTracker extends Tracker {
    constructor(objects: string[]);
  }

  class Tracker {
    constructor(target: string);
    on(eventName: string, callback: (event: TrackEvent) => void): void;
  }

  interface TrackEvent {
    data: TrackRect[];
  }

   interface TrackRect {
    x: number;
    y: number;
    height: number;
    width: number;
    color: string;
  }

  interface TrackerTask {
    stop(): void;
    run(): void;
  }

  export function track(selector: string, tracker: tracking.Tracker):
TrackerTask;
}

Any assistance and code improvements would be appreciated.


问:
Conditional callback with request sub domain. is it possible?
I tried something like this

```<code>class SomeController < ApplicationController
  before_action :something, if: request.subdomain == "specific"

end
</code>```

but here i could not access request object and it throwing error.

```<code>undefined local variable or method `request' for SomeController:Class
</code>```

Can someone suggest me how i can achieve this?

答:
Use proc,</p>

```<code>class SomeController < ApplicationController
  before_action :something, if: proc { |c| c.request.subdomain == "specific" }

end
</code>```

Body:
I tried something like this

class SomeController < ApplicationController
  before_action :something, if: request.subdomain == "specific"

end

but here i could not access request object and it throwing error.

undefined local variable or method `request' for SomeController:Class

Can someone suggest me how i can achieve this?

Body:
Use proc,

class SomeController < ApplicationController
  before_action :something, if: proc { |c| c.request.subdomain == "specific" }

end


问:
how call function in domain Ono2many field odoo 8
message Error:

TypeError: old_api() takes at least 3 arguments (1 given)

code py:

```<code>@api.model
def domain_users(self):
        if self.env.user.login=="bendjeddou.o":
            domain=[('exp_P','>',0)]
        else:
            domain=[]
        return domain
o2m_materiels fields.One2many('gmat.journaleline','rapJor_ids',string='Materiel',domain=domain_users)
</code>```

class py:

```<code>class Journaleline(models.Model):
    _name = 'gmat.journaleline'
    _description    =   'Detail materiel'

   rapJor_ids = fields.Many2one('gmat.rapporjournal',string='num')
   exp_P = fields.Float(string='Panne(H)',default=0)
</code>```

答:
Try this:

# remove the decorator
def domain_users(self):
        domain = False
        if self.env.user.login=="bendjeddou.o":
            domain=[('exp_P','>',0)]
        else:
            domain=[]
        return domain

o2m_materiels = fields.One2many('gmat.journaleline',
                                'rapJor_ids',
                                string='Materiel',
                                domain=lambda self: self.domain_users())
```

<p>or for less typing</p>

<pre class="lang-py prettyprint-override"><code># no need to define method
o2m_materiels = fields.One2many('gmat.journaleline',
                        'rapJor_ids',
                        string='Materiel',
                        domain = lambda self:  self.env.user.login == "bendjedou.o" and [('exp_P','>',0)] or [])
</code>```

EDITS:
ok for some reason i think the signature of the method
must be in old api try this:

    # or this
    # def domain_users(self, cr, uid, ids, context=None):
    def domain_users(self, cr, uid, context=None):
            domain = False
            user = self.pool.get('res.users').browse(cr, uid, uid, context).
            if user.login == "bendjeddou.o":
                domain=[('exp_P','>',0)]
            else:
                domain=[]
            return domain

    o2m_materiels = fields.One2many('gmat.journaleline',
                                    'rapJor_ids',
                                    string='Materiel',
                                    domain=domain_users)
```

May because your model is created using osv.Model not model.Model

Body:
message Error:

TypeError: old_api() takes at least 3 arguments (1 given)

code py:

@api.model
def domain_users(self):
        if self.env.user.login=="bendjeddou.o":
            domain=[('exp_P','>',0)]
        else:
            domain=[]
        return domain
o2m_materiels fields.One2many('gmat.journaleline','rapJor_ids',string='Materiel',domain=domain_users)

class py:

class Journaleline(models.Model):
    _name = 'gmat.journaleline'
    _description    =   'Detail materiel'

   rapJor_ids = fields.Many2one('gmat.rapporjournal',string='num')
   exp_P = fields.Float(string='Panne(H)',default=0)

Body:
Try this:

# remove the decorator
def domain_users(self):
        domain = False
        if self.env.user.login=="bendjeddou.o":
            domain=[('exp_P','>',0)]
        else:
            domain=[]
        return domain

o2m_materiels = fields.One2many('gmat.journaleline',
                                'rapJor_ids',
                                string='Materiel',
                                domain=lambda self: self.domain_users())

or for less typing

# no need to define method
o2m_materiels = fields.One2many('gmat.journaleline',
                        'rapJor_ids',
                        string='Materiel',
                        domain = lambda self:  self.env.user.login == "bendjedou.o" and [('exp_P','>',0)] or [])

EDITS:
ok for some reason i think the signature of the method
must be in old api try this:

    # or this
    # def domain_users(self, cr, uid, ids, context=None):
    def domain_users(self, cr, uid, context=None):
            domain = False
            user = self.pool.get('res.users').browse(cr, uid, uid, context).
            if user.login == "bendjeddou.o":
                domain=[('exp_P','>',0)]
            else:
                domain=[]
            return domain

    o2m_materiels = fields.One2many('gmat.journaleline',
                                    'rapJor_ids',
                                    string='Materiel',
                                    domain=domain_users)

May because your model is created using osv.Model not model.Model


问:
Trying to read and write parquet files from s3 with local spark
I'm trying to read and write parquet files from my local machine to S3 using spark. But I can't seem to configure my spark session properly to do so.  Obviously there are configurations to be made, but I could not find a clear reference on how to do it.

Currently my spark session reads local parquet mocks and is defined as such:

```<code>val sparkSession = SparkSession.builder.master("local").appName("spark session example").getOrCreate()
</code>```

答:
I'm going to have to correct the post by himanshuIIITian slightly, (sorry).

Use the s3a connector, not the older, obsolete, unmaintained, s3n. S3A is: faster, works with the newer S3 clusters (Seoul, Frankfurt, London, ...), scales better. S3N has fundamental performance issues which have only been fixed in the latest version of Hadoop by deleting that connector entirely. Move on.

You cannot safely use s3 as a direct destination of a Spark query., not with the classic "FileSystem" committers available today. Write to your local file:// and then copy up the data afterwards, using the AWS CLI interface. You'll get better performance as well as the guarantees of reliable writing which you would normally expect from IO

Body:
I'm trying to read and write parquet files from my local machine to S3 using spark. But I can't seem to configure my spark session properly to do so.  Obviously there are configurations to be made, but I could not find a clear reference on how to do it.

Currently my spark session reads local parquet mocks and is defined as such:

val sparkSession = SparkSession.builder.master("local").appName("spark session example").getOrCreate()


问:
Distinct and group by at the same time in LINQ?
Let say I have the following classes:

```<code>Product { ID, Name }

Meta { ID, Object, Key, Value }

Category { ID, Name }

Relation {ID, ChildID, ParentID } (Child = Product, Parent = Category)
</code>```

and some sample data:

Product:

```<code>ID   Name

1    Chair
2    Table
</code>```

Meta

```<code>ID   Object  Key     Value

1      1     Color   "Red"
2      1     Size    "Large"
3      2     Color   "Blue"
4      2     Size    "Small"
</code>```

Category

```<code>ID   Name

1    Indoor
2    Outdoor
</code>```

Relation

```<code>ID   ChildID   ParentID

1       1         1
2       1         2
3       2         1
</code>```

Can we use Distinct and Group by to produce the following format (ProductDetail)

```<code>ID=1,
Name=Chair,
Parent=
{
  { ID=1, Name="Indoor" },
  { ID=2, Name="Outdoor" }
},
Properties { Color="Red", Size="Large" }

ID=2,
Name=Table,
Parent=
{
  { ID=1, Name="Indoor"}
},
Properties { Color = "Blue", Size = "Small" }
</code>```

which we can get the "Color" value of the first item by using

```<code>ProductDetails[0].Properties.Color
</code>```

Any helps would be appreciated!

答:
No, you can't do this based on what you've said - because "Color" and "Size" are part of the data, rather than part of the model. They're only known at execution time, so unless you use dynamic typing, you're not going to be able to access it by Properties.Color.

You could, however, use Properties["Color"] potentially:

```<code>var query = from product in db.Products
            join meta in db.Meta
                on product.ID equals meta.Object
                into properties
            select new { Product = product,
                         Properties = properties.ToDictionary(m => m.Key,
                                                              m => m.Value) };
</code>```

So for each product, you'll have a dictionary of properties. That works logically, but you may need to tweak it to get it to work in the entity framework - I don't know how well that supports ToDictionary.

EDIT: Okay, I'll leave the above up as the "ideal" solution, but if EF doesn't support ToDictionary, you'd have to do that part in-process:

```<code>var query = (from product in db.Products
             join meta in db.Meta
                 on product.ID equals meta.Object
                 into properties
             select new { product, properties })
            .AsEnumerable()
            .Select(p => new {
                    Product = p.product,
                    Properties = p.properties.ToDictionary(m => m.Key,
                                                           m => m.Value) });
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let say I have the following classes:

Product { ID, Name }

Meta { ID, Object, Key, Value }

Category { ID, Name }

Relation {ID, ChildID, ParentID } (Child = Product, Parent = Category)

and some sample data:

Product:

ID   Name

1    Chair
2    Table

Meta

ID   Object  Key     Value

1      1     Color   "Red"
2      1     Size    "Large"
3      2     Color   "Blue"
4      2     Size    "Small"

Category

ID   Name

1    Indoor
2    Outdoor

Relation

ID   ChildID   ParentID

1       1         1
2       1         2
3       2         1

Can we use Distinct and Group by to produce the following format (ProductDetail)

ID=1,
Name=Chair,
Parent=
{
  { ID=1, Name="Indoor" },
  { ID=2, Name="Outdoor" }
},
Properties { Color="Red", Size="Large" }

ID=2,
Name=Table,
Parent=
{
  { ID=1, Name="Indoor"}
},
Properties { Color = "Blue", Size = "Small" }

which we can get the "Color" value of the first item by using

ProductDetails[0].Properties.Color

Any helps would be appreciated!

Body:
No, you can't do this based on what you've said - because "Color" and "Size" are part of the data, rather than part of the model. They're only known at execution time, so unless you use dynamic typing, you're not going to be able to access it by Properties.Color.

You could, however, use Properties["Color"] potentially:

var query = from product in db.Products
            join meta in db.Meta
                on product.ID equals meta.Object
                into properties
            select new { Product = product,
                         Properties = properties.ToDictionary(m => m.Key,
                                                              m => m.Value) };

So for each product, you'll have a dictionary of properties. That works logically, but you may need to tweak it to get it to work in the entity framework - I don't know how well that supports ToDictionary.

EDIT: Okay, I'll leave the above up as the "ideal" solution, but if EF doesn't support ToDictionary, you'd have to do that part in-process:

var query = (from product in db.Products
             join meta in db.Meta
                 on product.ID equals meta.Object
                 into properties
             select new { product, properties })
            .AsEnumerable()
            .Select(p => new {
                    Product = p.product,
                    Properties = p.properties.ToDictionary(m => m.Key,
                                                           m => m.Value) });


问:
Using jquery.when in an object literal
I've got a javascript/jQuery function called addLocation, which is a method of an object literal:

```<code>addLocation: function(latLng, address=false, elevation=false, pan=false)
{

    $.when(geographic.getAddress(latLng), geographic.getElevation(latLng), geographic.getMagneticDeclination(latLng))
        .done(function(data){

            if (data.status != 'OK') {
                window.alert(data.message);
            }

            if (pan) {
                flyityourself.map.panTo(latLng);
                flyityourself.map.setZoom(16);
            }

            flyityourself.addWaypoint(latLng, data);

            flyityourself.addMarker(latLng, data);
        })
        .fail(function(msg) {
            window.alert(msg);
        }
    );
},
</code>```

The three functions getAddress, getElevation and getMagneticDeclination are all methods of a second object literal named 'geographic'.

But the code is failing.

In the debugger, I have checked all four functions.

Each of getAddress, getElevation and getMagneticDeclination create  $.Deferred objects and return $.Deferred.promise objects as they should.

Each of getAddress, getElevation and getMagneticDeclination are retrieving the right data and are all reaching their respective resolve() statements.

But in addLocation(), the data parameter only contains the data returned from getAddress.

Previously,  only the three methods getAddress, getElevation and getMagneticDeclination were in the object literal 'geographic'. addLocation was in a flat .js file. In this case the code worked.

But since changing my code to put addLocation inside an object literal, the code has started to fail.

Does $.when work differently in object literals or have I forgotten to qualify something?

Regards.
Chris B.

答:
A. Wolff is right in the comment they made - you need 3 params in your done callback, one for each promise handled by when.

Here's a simple example, supplying a mock geographic object to make your code work in a stand-alone fiddle:

https://jsfiddle.net/tmLrn4gc/1/

```<code>// Mock geographic object for testing
geographic = {
  // Return a promise, and a second later, resolve that promise with some
  // dummy data.
  getAddress: function() {
    var dfd = $.Deferred();
    window.setTimeout(function() {
      dfd.resolve("address:lat1,lng1")
    }, 1000);
    return dfd.promise();
  },
  getElevation: function() {
    var dfd = $.Deferred();
    window.setTimeout(function() {
      dfd.resolve("elevation:meters")
    }, 1000);
    return dfd.promise();
  },
  getMagneticDeclination: function() {
    var dfd = $.Deferred();
    window.setTimeout(function() {
      dfd.resolve("declination:degrees")
    }, 1000);
    return dfd.promise();
  }
};

// A simplified location manager, showing the 3 promises and a done method.
// The console output in the fiddle shows the 3 promises are resolved as
// desired.
LocationManager = {
  addLocation: function(latLng, address=false, elevation=false, pan=false) {
    $.when(
      geographic.getAddress(latLng),
      geographic.getElevation(latLng),
      geographic.getMagneticDeclination(latLng)
    ).done(function(d1, d2, d3) {
        console.log("Done", d1, d2, d3);
    })
  }
}

// Make it all happen!
LocationManager.addLocation();
</code>```

Title: Using jquery.when in an object literal

Body:
I've got a javascript/jQuery function called addLocation, which is a method of an object literal:

addLocation: function(latLng, address=false, elevation=false, pan=false)
{

    $.when(geographic.getAddress(latLng), geographic.getElevation(latLng), geographic.getMagneticDeclination(latLng))
        .done(function(data){

            if (data.status != 'OK') {
                window.alert(data.message);
            }

            if (pan) {
                flyityourself.map.panTo(latLng);
                flyityourself.map.setZoom(16);
            }

            flyityourself.addWaypoint(latLng, data);

            flyityourself.addMarker(latLng, data);
        })
        .fail(function(msg) {
            window.alert(msg);
        }
    );
},

The three functions getAddress, getElevation and getMagneticDeclination are all methods of a second object literal named 'geographic'.

But the code is failing.

In the debugger, I have checked all four functions.

Each of getAddress, getElevation and getMagneticDeclination create  $.Deferred objects and return $.Deferred.promise objects as they should.

Each of getAddress, getElevation and getMagneticDeclination are retrieving the right data and are all reaching their respective resolve() statements.

But in addLocation(), the data parameter only contains the data returned from getAddress.

Previously,  only the three methods getAddress, getElevation and getMagneticDeclination were in the object literal 'geographic'. addLocation was in a flat .js file. In this case the code worked.

But since changing my code to put addLocation inside an object literal, the code has started to fail.

Does $.when work differently in object literals or have I forgotten to qualify something?

Regards.
Chris B.

Body:
A. Wolff is right in the comment they made - you need 3 params in your done callback, one for each promise handled by when.

Here's a simple example, supplying a mock geographic object to make your code work in a stand-alone fiddle:

https://jsfiddle.net/tmLrn4gc/1/

// Mock geographic object for testing
geographic = {
  // Return a promise, and a second later, resolve that promise with some
  // dummy data.
  getAddress: function() {
    var dfd = $.Deferred();
    window.setTimeout(function() {
      dfd.resolve("address:lat1,lng1")
    }, 1000);
    return dfd.promise();
  },
  getElevation: function() {
    var dfd = $.Deferred();
    window.setTimeout(function() {
      dfd.resolve("elevation:meters")
    }, 1000);
    return dfd.promise();
  },
  getMagneticDeclination: function() {
    var dfd = $.Deferred();
    window.setTimeout(function() {
      dfd.resolve("declination:degrees")
    }, 1000);
    return dfd.promise();
  }
};

// A simplified location manager, showing the 3 promises and a done method.
// The console output in the fiddle shows the 3 promises are resolved as
// desired.
LocationManager = {
  addLocation: function(latLng, address=false, elevation=false, pan=false) {
    $.when(
      geographic.getAddress(latLng),
      geographic.getElevation(latLng),
      geographic.getMagneticDeclination(latLng)
    ).done(function(d1, d2, d3) {
        console.log("Done", d1, d2, d3);
    })
  }
}

// Make it all happen!
LocationManager.addLocation();


问:
Continuous Execution in Jenkins
How to execute the same build again and again in Jenkins(Say I want to execute the build for 10 times continuously). After each execution the reports have to copied.

Don't say create 10 jobs and make use of Downstream/Upstream.

答:
You can use pretty simple solution by using Build Periodically, from Build Triggers, such as:

H/15 * * * *

This triggers job in every fifteen minutes (perhaps at :07, :22, :37, :52). So, this will not trigger the next execution immediately, but you can schedule it in this way.

ContentLicense: CC BY-SA 4.0

Title: Continuous Execution in Jenkins


问:
Count CSV columns without using Excel API
Is there any method/code/reference to count the number of columns of every each row of records in a CSV file by maybe using PowerShell Get-Content and without using any Excel API as the records in the CSV file are extremely large (1GB+). Using Excel API such as Import-Csv or New-Object -ComObject Excel.Application will take extremely long periods of time to process.

The following image is the example of records in a CSV file.

And the following image is the same CSV open in Notepad++. As you can see there is only one delimiter in row 4. Hence this row counted as 2 columns while others are 4 columns.

I would like create a script that can check every row of CSV data with short time taken and can detect the columns are missing if the delimiter is not same as the header(as shown in row 4 with 2 columns but in row 1 header with 4 columns). So the final result would be like this:

Row 2  4 Columns Pass

  Row 3  4 Columns Pass

  Row 4  2 Columns Fail

I'm currently using COMAPI in my completed script, but I want to switch to using Get-Content. However, the quoted comma leads to an incorrect result.

```<code># sample testing code snippet
$path = "testing.csv"
$delimiter = ","
Get-Content $path | ForEach-Object {($_.Split($delimiter)).Count}
</code>```

And the result from the same CSV file will be like this:

4

  4

  4

  3

答:
If you Import-Csv, every item value ($_.PSObject.Properties.Value) is converted to a string, unless the whole item is missing from the column, the .Value property will be set to $Null.

If your csv file includes a header row, it is presumed that the number of headers are at least the same as the maximum number of columns in a row:

```<code>Import-Csv .\testing.csv | ForEach {@($_.PSObject.Properties | Where {$_.Value -ne $Null}).Count}
</code>```

In case your csv file doesn't include a header row, you might add a large number of headers yourself:

```<code>Import-Csv .\testing.csv -Header @(0..99) | ForEach {@($_.PSObject.Properties | Where {$_.Value -ne $Null}).Count}
</code>```

Body:
Is there any method/code/reference to count the number of columns of every each row of records in a CSV file by maybe using PowerShell Get-Content and without using any Excel API as the records in the CSV file are extremely large (1GB+). Using Excel API such as Import-Csv or New-Object -ComObject Excel.Application will take extremely long periods of time to process.

The following image is the example of records in a CSV file.

And the following image is the same CSV open in Notepad++. As you can see there is only one delimiter in row 4. Hence this row counted as 2 columns while others are 4 columns.

I would like create a script that can check every row of CSV data with short time taken and can detect the columns are missing if the delimiter is not same as the header(as shown in row 4 with 2 columns but in row 1 header with 4 columns). So the final result would be like this:

Row 2  4 Columns Pass

  Row 3  4 Columns Pass

  Row 4  2 Columns Fail

I'm currently using COMAPI in my completed script, but I want to switch to using Get-Content. However, the quoted comma leads to an incorrect result.

# sample testing code snippet
$path = "testing.csv"
$delimiter = ","
Get-Content $path | ForEach-Object {($_.Split($delimiter)).Count}

And the result from the same CSV file will be like this:

4

  4

  4

  3

Body:
If you Import-Csv, every item value ($_.PSObject.Properties.Value) is converted to a string, unless the whole item is missing from the column, the .Value property will be set to $Null.

If your csv file includes a header row, it is presumed that the number of headers are at least the same as the maximum number of columns in a row:

Import-Csv .\testing.csv | ForEach {@($_.PSObject.Properties | Where {$_.Value -ne $Null}).Count}

In case your csv file doesn't include a header row, you might add a large number of headers yourself:

Import-Csv .\testing.csv -Header @(0..99) | ForEach {@($_.PSObject.Properties | Where {$_.Value -ne $Null}).Count}


问:
Updating a Tab view text
I am beginning with Android and I have a NavigationView along with Tabular layout. I want to change the values in the tabs fragments based on the selection made in the navigation view. Here is my code-

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Context mainActivityContext;
    Intent serviceIntent;

    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private String valSelected = "";
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editor  = sharedPref.edit();

        mainActivityContext = this;

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.sel1) {

            valSelected = "First";
            NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);

            fragment_obj.updateView();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);

             textView.setText("HELLO");
            return rootView;
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            if(position == 0) {
                return new NotificationFragment();

            }
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {

            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab1";
                case 1:
                    return "Tab2";
                case 2:
                    return "Tab3";
                case 3:
                    return "Tab4";

            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            if (object instanceof NotificationFragment) {
                ((NotificationFragment)object).updateView();
            }
            return super.getItemPosition(object);
        }
    }
}
</code>```

This is my NotificationFragment
NotificationFragment.java

```<code>public class NotificationFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.notification_layout, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.title_notification);

        textView.setText(MainActivity.coinSelected.toUpperCase());
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void updateView(){
        TextView text = (TextView) this.getView().findViewById(R.id.title_notification);
        text.setText(MainActivity.valSelected);
    }

}
</code>```

But when I try to update the value in my MainActivity using

```<code>NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);
</code>```

it gives me null.

Edit
Here is the notification layout file:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/title_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BTC/USD"
        android:textSize="26dp"/>

</LinearLayout>
</code>```

答:
in your code
NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);
R.id.title_notification must be the id of fragment,but in your xml,it's a textview</p>

Title: Updating a Tab view text

Body:
I am beginning with Android and I have a NavigationView along with Tabular layout. I want to change the values in the tabs fragments based on the selection made in the navigation view. Here is my code-

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Context mainActivityContext;
    Intent serviceIntent;

    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private String valSelected = "";
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editor  = sharedPref.edit();

        mainActivityContext = this;

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.sel1) {

            valSelected = "First";
            NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);

            fragment_obj.updateView();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);

             textView.setText("HELLO");
            return rootView;
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            if(position == 0) {
                return new NotificationFragment();

            }
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {

            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab1";
                case 1:
                    return "Tab2";
                case 2:
                    return "Tab3";
                case 3:
                    return "Tab4";

            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            if (object instanceof NotificationFragment) {
                ((NotificationFragment)object).updateView();
            }
            return super.getItemPosition(object);
        }
    }
}

This is my NotificationFragment
NotificationFragment.java

public class NotificationFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.notification_layout, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.title_notification);

        textView.setText(MainActivity.coinSelected.toUpperCase());
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void updateView(){
        TextView text = (TextView) this.getView().findViewById(R.id.title_notification);
        text.setText(MainActivity.valSelected);
    }

}

But when I try to update the value in my MainActivity using

NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);

it gives me null.

Edit
Here is the notification layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/title_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BTC/USD"
        android:textSize="26dp"/>

</LinearLayout>


问:
How can i join two tables after filtering
How can i join two tables after filtering each table with some condition and on getting the result of filter, join both the results.

Tried code but showing syntax error

```<code>SELECT *
FROM Table1
WHERE flag1 = 0
JOIN SELECT *
     FROM TABLE2
     where flag2 = 0 on Table1.email = TABLE2.email
</code>```

答:
```<code>SELECT *
FROM Table1 as t1
join Table2 as t2 on t1.orderlist_email = t2.email
where flag1 = 0
and flag2 = 0
</code>```

<p>Correct join will be like this. </p>

Body:
How can i join two tables after filtering each table with some condition and on getting the result of filter, join both the results.

Tried code but showing syntax error

SELECT *
FROM Table1
WHERE flag1 = 0
JOIN SELECT *
     FROM TABLE2
     where flag2 = 0 on Table1.email = TABLE2.email

Body:
SELECT *
FROM Table1 as t1
join Table2 as t2 on t1.orderlist_email = t2.email
where flag1 = 0
and flag2 = 0

Correct join will be like this.


问:
Better to use DQL for getting Column Count or Get Collection Then Count?
I am quite sure that DQL will be the way to go, but I am wondering if Doctrine, i am using Doctrine 2, has someway to return the row count. I won't be using the rows itself, I just want the count.</p>

答:
I'm new to Doctrine2 but it looks like you can simply do this:

```<code>$query = $em->createQuery('SELECT COUNT(u.id) FROM Entities\User u');
$count = $query->getSingleScalarResult();
</code>```

Source (Using Agregate Functions): http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#dql-select-examples

Allowed aggregate functions: http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#aggregate-functions

Body:
I'm new to Doctrine2 but it looks like you can simply do this:

$query = $em->createQuery('SELECT COUNT(u.id) FROM Entities\User u');
$count = $query->getSingleScalarResult();

Source (Using Agregate Functions): http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#dql-select-examples

Allowed aggregate functions: http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#aggregate-functions


问:
How to enlarge and widen the photo as it can in ms word?
my program :

produce a picture that is extracting data from excel .

Paste it in word and make the page setting as Landscape .

However ,the picture generated is small and the setting of page become custom.

the photo is so wide .I don't want to enlarge by myself everytimes.

How can I add this setting in vba ?Make it as large and wide as it can .

Secondly , it is pleasure that the data extracted can be pasted as table format.

my codes :

```<code>   Private Sub CommandButton1_Click()

    Dim tbl0 As Excel.RANGE
    Dim Tbl As Excel.RANGE
    Dim tbl2 As Excel.RANGE

    Dim wordApp As Word.Application
    Dim myDoc As Word.Document
    Dim WordTable As Word.Table
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("17-18")             ' Change e.g. sheet9.Name
    'Optimize Code
    Application.ScreenUpdating = False
    Application.EnableEvents = False

Value1 = Me.TextBox1.Value
Value2 = Me.TextBox2.Value
    ws.Rows("84:89").EntireRow.Hidden = True 'ADJUST AS APPROPRIATE

    'Copy Range from Excel
    'Set tbl0 = ws.RANGE("A78:I83")
    Set Tbl = ws.RANGE("A78:I92")

    ' Set tbl2 = ws.Range("A90:I92")

    'Create an Instance of MS Word
    On Error Resume Next

    'Is MS Word already opened?
    Set wordApp = GetObject(Class:="Word.Application")

    'Clear the error between errors
    Err.Clear

    'If MS Word is not already open then open MS Word
    If wordApp Is Nothing Then Set wordApp = CreateObject(Class:="Word.Application")

    'Handle if the Word Application is not found
    If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
    End If

    On Error GoTo 0

    'Make MS Word Visible and Active
    wordApp.Visible = True
    wordApp.Activate

    'Create a New Document
    Set myDoc = wordApp.Documents.Add

    'Trigger copy separately for each table + paste for each table

    Tbl.CopyPicture Appearance:=xlScreen, Format:=xlPicture

    wordApp.Selection.Paste
    wordApp.Selection.TypeParagraph

    wordApp.Selection.PageSetup.Orientation = wdOrientLandscape

    resize_all_images_to_page_width myDoc

EndRoutine:
    'Optimize Code
    Application.ScreenUpdating = True
    Application.EnableEvents = True

    'Clear The Clipboard
    Application.CutCopyMode = False

End Sub
</code>```

答:
Although I don't fiddle with Word but Excel only it might give you an idea...

The code of my XmasPrep excel sucks in a bunch of pictures in order to produce a catalog, listing the pictures to select from.

For each line, i.e. each picture, the code

assigns an Excel cell range and then resizes the range ROW height and width
as well as the range height itself

assigns the picture object thisPic = .Parent.Pictures.Insert(picFileName) and then resizes that according to the cell range's coordinates and size:

```<code>thisPic.Top = .Top + 1
thisPic.Left = .Left + 1
thisPic.Width = .Width - 2
thisPic.Height = .Height - 2
</code>```

So, if you're able to grab the picture object (thisPic) in Word you might be able to resize it to your needs as well. Hope it helps.

```<code>    :
    Const MaxHeight = 50
    Const MaxWidth = 14
    Dim picFileName         As String
    Dim i, j, k             As Long
    Dim col_Filenames       As Long
    Dim col_Pictures        As Long
    Dim range_PicCell       As Range
    Dim thisPic             As Picture
    :

    picFileName = filesPath & select2order.Cells(i, col_Filenames).Value
    Set range_PicCell = select2order.Cells(i, col_Pictures)
    range_PicCell.RowHeight = MaxHeight
    range_PicCell.ColumnWidth = MaxWidth
    With range_PicCell
        .Height = MaxHeight
        Set thisPic = .Parent.Pictures.Insert(picFileName)
        thisPic.Top = .Top + 1
        thisPic.Left = .Left + 1
        thisPic.Width = .Width - 2
        thisPic.Height = .Height - 2
    End With
    :
</code>```

Body:
my program :

produce a picture that is extracting data from excel .

Paste it in word and make the page setting as Landscape .

However ,the picture generated is small and the setting of page become custom.

the photo is so wide .I don't want to enlarge by myself everytimes.

How can I add this setting in vba ?Make it as large and wide as it can .

Secondly , it is pleasure that the data extracted can be pasted as table format.

my codes :

   Private Sub CommandButton1_Click()

    Dim tbl0 As Excel.RANGE
    Dim Tbl As Excel.RANGE
    Dim tbl2 As Excel.RANGE

    Dim wordApp As Word.Application
    Dim myDoc As Word.Document
    Dim WordTable As Word.Table
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("17-18")             ' Change e.g. sheet9.Name
    'Optimize Code
    Application.ScreenUpdating = False
    Application.EnableEvents = False

Value1 = Me.TextBox1.Value
Value2 = Me.TextBox2.Value
    ws.Rows("84:89").EntireRow.Hidden = True 'ADJUST AS APPROPRIATE

    'Copy Range from Excel
    'Set tbl0 = ws.RANGE("A78:I83")
    Set Tbl = ws.RANGE("A78:I92")

    ' Set tbl2 = ws.Range("A90:I92")

    'Create an Instance of MS Word
    On Error Resume Next

    'Is MS Word already opened?
    Set wordApp = GetObject(Class:="Word.Application")

    'Clear the error between errors
    Err.Clear

    'If MS Word is not already open then open MS Word
    If wordApp Is Nothing Then Set wordApp = CreateObject(Class:="Word.Application")

    'Handle if the Word Application is not found
    If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
    End If

    On Error GoTo 0

    'Make MS Word Visible and Active
    wordApp.Visible = True
    wordApp.Activate

    'Create a New Document
    Set myDoc = wordApp.Documents.Add

    'Trigger copy separately for each table + paste for each table

    Tbl.CopyPicture Appearance:=xlScreen, Format:=xlPicture

    wordApp.Selection.Paste
    wordApp.Selection.TypeParagraph

    wordApp.Selection.PageSetup.Orientation = wdOrientLandscape

    resize_all_images_to_page_width myDoc

EndRoutine:
    'Optimize Code
    Application.ScreenUpdating = True
    Application.EnableEvents = True

    'Clear The Clipboard
    Application.CutCopyMode = False

End Sub

Body:
Although I don't fiddle with Word but Excel only it might give you an idea...

The code of my XmasPrep excel sucks in a bunch of pictures in order to produce a catalog, listing the pictures to select from.

For each line, i.e. each picture, the code

assigns an Excel cell range and then resizes the range ROW height and width
as well as the range height itself

assigns the picture object thisPic = .Parent.Pictures.Insert(picFileName) and then resizes that according to the cell range's coordinates and size:

thisPic.Top = .Top + 1
thisPic.Left = .Left + 1
thisPic.Width = .Width - 2
thisPic.Height = .Height - 2

So, if you're able to grab the picture object (thisPic) in Word you might be able to resize it to your needs as well. Hope it helps.

    :
    Const MaxHeight = 50
    Const MaxWidth = 14
    Dim picFileName         As String
    Dim i, j, k             As Long
    Dim col_Filenames       As Long
    Dim col_Pictures        As Long
    Dim range_PicCell       As Range
    Dim thisPic             As Picture
    :

    picFileName = filesPath & select2order.Cells(i, col_Filenames).Value
    Set range_PicCell = select2order.Cells(i, col_Pictures)
    range_PicCell.RowHeight = MaxHeight
    range_PicCell.ColumnWidth = MaxWidth
    With range_PicCell
        .Height = MaxHeight
        Set thisPic = .Parent.Pictures.Insert(picFileName)
        thisPic.Top = .Top + 1
        thisPic.Left = .Left + 1
        thisPic.Width = .Width - 2
        thisPic.Height = .Height - 2
    End With
    :


问:
Forced Non-blocking refresh of Cache
I want a cache refresh policy where if cache values become stale after 5 minutes, I need to trigger refresh for the value at say 4th minute so that the new value is available at 5th minute and any request that tries to fetch data at 5th minute neither has to wait for the load nor gets stale data.

With Guava if I use refreshAfterWrite(4, Minute) and expireAfterWrite(5, Minute) together I can solve this problem for keys that are frequently queried. However I have few keys that are very rarely queried and for them the request might have to wait for load.

Is there a solution to this problem?

答:
The documentation explains that the cache doesn't do any work in the background for you (and that this is actually a feature). So if your cache is not high-throughput enough to ensure all desired keys are always recent, you should create a task (e.g. using ScheduledExecutorService) which occasionally refreshes all your keys.

This might look like:

```<code>scheduler.scheduleAtFixedRate(
    () -> cache.asMap().keys().stream().forEach(cache::refresh), 4, 4, TimeUnit.MINUTES);
</code>```

Title: Forced Non-blocking refresh of Cache

Body:
The documentation explains that the cache doesn't do any work in the background for you (and that this is actually a feature). So if your cache is not high-throughput enough to ensure all desired keys are always recent, you should create a task (e.g. using ScheduledExecutorService) which occasionally refreshes all your keys.

This might look like:

scheduler.scheduleAtFixedRate(
    () -> cache.asMap().keys().stream().forEach(cache::refresh), 4, 4, TimeUnit.MINUTES);