问:
nan loss when training a deep neural network in tensorflow tutorial
I am trying to train a neural network with more than 1 hidden layer on the notMNIST. When I have one hidden layer it works fine, but when I add multiple hidden layers I start getting nan for the loss. Here is the code i am using

```<code>from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range

batch_size = 128
num_hidden = 1024
num_hidden2 = 300
num_hidden3 = 50
SEED = 1234567
keep_prob = 0.5

graph1 = tf.Graph()
with graph1.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  weights1 = tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden]))
  biases1 = tf.Variable(tf.zeros([num_hidden]))

  weights2 = tf.Variable(tf.truncated_normal([num_hidden, num_hidden2]))
  biases2 = tf.Variable(tf.zeros([num_hidden2]))

  weights3 = tf.Variable(tf.truncated_normal([num_hidden2, num_hidden3]))
  biases3 = tf.Variable(tf.zeros([num_hidden3]))

  weights4 = tf.Variable(tf.truncated_normal([num_hidden3, num_labels]))
  biases4 = tf.Variable(tf.zeros([num_labels]))

  # Training computation.
  l1 = tf.matmul(tf_train_dataset, weights1) + biases1
  h1 = tf.nn.relu(l1)
  h1 = tf.nn.dropout(h1, 0.5, seed=SEED)

  l2 = tf.matmul(h1, weights2) + biases2
  h2 = tf.nn.relu(l2)
  h2 = tf.nn.dropout(h2, 0.5, seed=SEED)

  l3 = tf.matmul(h2, weights3) + biases3
  h3 = tf.nn.relu(l3)
  h3 = tf.nn.dropout(h3, 0.5, seed=SEED)

  logits = tf.matmul(h3, weights4) + biases4

  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # L2 regularization for the fully connected parameters.
  regularizers = (tf.nn.l2_loss(weights1) + tf.nn.l2_loss(biases1) +
                  tf.nn.l2_loss(weights2) + tf.nn.l2_loss(biases2) +
                  tf.nn.l2_loss(weights3) + tf.nn.l2_loss(biases3) +
                  tf.nn.l2_loss(weights4) + tf.nn.l2_loss(biases4))
  # Add the regularization term to the loss.
  loss += 5e-4 * regularizers

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)

  v_l1 = tf.matmul(tf_valid_dataset, weights1) + biases1
  v_h1 = tf.nn.relu(v_l1)

  v_l2 = tf.matmul(v_h1, weights2) + biases2
  v_h2 = tf.nn.relu(v_l2)

  v_l3 = tf.matmul(v_h2, weights3) + biases3
  v_h3 = tf.nn.relu(v_l3)

  v_logits = tf.matmul(v_h3, weights4) + biases4
  valid_prediction = tf.nn.softmax(v_logits)

  t_l1 = tf.matmul(tf_test_dataset, weights1) + biases1
  t_h1 = tf.nn.relu(t_l1)

  t_l2 = tf.matmul(t_h1, weights2) + biases2
  t_h2 = tf.nn.relu(t_l2)

  t_l3 = tf.matmul(t_h2, weights3) + biases3
  t_h3 = tf.nn.relu(t_l3)

  t_logits = tf.matmul(t_h3, weights4) + biases4
  test_prediction = tf.nn.softmax(t_logits)

num_steps = 3001

with tf.Session(graph=graph1) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
</code>```

This is the output I get

```<code>Initialized
Minibatch loss at step 0: 48759.078125
Minibatch accuracy: 10.2%
Validation accuracy: 10.0%
Minibatch loss at step 500: nan
Minibatch accuracy: 9.4%
Validation accuracy: 10.0%
Minibatch loss at step 1000: nan
Minibatch accuracy: 8.6%
Validation accuracy: 10.0%
Minibatch loss at step 1500: nan
Minibatch accuracy: 11.7%
Validation accuracy: 10.0%
Minibatch loss at step 2000: nan
Minibatch accuracy: 6.2%
Validation accuracy: 10.0%
Minibatch loss at step 2500: nan
Minibatch accuracy: 10.2%
Validation accuracy: 10.0%
Minibatch loss at step 3000: nan
Minibatch accuracy: 7.8%
Validation accuracy: 10.0%
Test accuracy: 10.0%
</code>```

答: try lowering the standard deviation of the weights. The default is set to 1. It worked for me.</p>

Body:
I am trying to train a neural network with more than 1 hidden layer on the notMNIST. When I have one hidden layer it works fine, but when I add multiple hidden layers I start getting nan for the loss. Here is the code i am using

from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range

batch_size = 128
num_hidden = 1024
num_hidden2 = 300
num_hidden3 = 50
SEED = 1234567
keep_prob = 0.5

graph1 = tf.Graph()
with graph1.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  weights1 = tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden]))
  biases1 = tf.Variable(tf.zeros([num_hidden]))

  weights2 = tf.Variable(tf.truncated_normal([num_hidden, num_hidden2]))
  biases2 = tf.Variable(tf.zeros([num_hidden2]))

  weights3 = tf.Variable(tf.truncated_normal([num_hidden2, num_hidden3]))
  biases3 = tf.Variable(tf.zeros([num_hidden3]))

  weights4 = tf.Variable(tf.truncated_normal([num_hidden3, num_labels]))
  biases4 = tf.Variable(tf.zeros([num_labels]))

  # Training computation.
  l1 = tf.matmul(tf_train_dataset, weights1) + biases1
  h1 = tf.nn.relu(l1)
  h1 = tf.nn.dropout(h1, 0.5, seed=SEED)

  l2 = tf.matmul(h1, weights2) + biases2
  h2 = tf.nn.relu(l2)
  h2 = tf.nn.dropout(h2, 0.5, seed=SEED)

  l3 = tf.matmul(h2, weights3) + biases3
  h3 = tf.nn.relu(l3)
  h3 = tf.nn.dropout(h3, 0.5, seed=SEED)

  logits = tf.matmul(h3, weights4) + biases4

  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # L2 regularization for the fully connected parameters.
  regularizers = (tf.nn.l2_loss(weights1) + tf.nn.l2_loss(biases1) +
                  tf.nn.l2_loss(weights2) + tf.nn.l2_loss(biases2) +
                  tf.nn.l2_loss(weights3) + tf.nn.l2_loss(biases3) +
                  tf.nn.l2_loss(weights4) + tf.nn.l2_loss(biases4))
  # Add the regularization term to the loss.
  loss += 5e-4 * regularizers

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)

  v_l1 = tf.matmul(tf_valid_dataset, weights1) + biases1
  v_h1 = tf.nn.relu(v_l1)

  v_l2 = tf.matmul(v_h1, weights2) + biases2
  v_h2 = tf.nn.relu(v_l2)

  v_l3 = tf.matmul(v_h2, weights3) + biases3
  v_h3 = tf.nn.relu(v_l3)

  v_logits = tf.matmul(v_h3, weights4) + biases4
  valid_prediction = tf.nn.softmax(v_logits)

  t_l1 = tf.matmul(tf_test_dataset, weights1) + biases1
  t_h1 = tf.nn.relu(t_l1)

  t_l2 = tf.matmul(t_h1, weights2) + biases2
  t_h2 = tf.nn.relu(t_l2)

  t_l3 = tf.matmul(t_h2, weights3) + biases3
  t_h3 = tf.nn.relu(t_l3)

  t_logits = tf.matmul(t_h3, weights4) + biases4
  test_prediction = tf.nn.softmax(t_logits)

num_steps = 3001

with tf.Session(graph=graph1) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

This is the output I get

Initialized
Minibatch loss at step 0: 48759.078125
Minibatch accuracy: 10.2%
Validation accuracy: 10.0%
Minibatch loss at step 500: nan
Minibatch accuracy: 9.4%
Validation accuracy: 10.0%
Minibatch loss at step 1000: nan
Minibatch accuracy: 8.6%
Validation accuracy: 10.0%
Minibatch loss at step 1500: nan
Minibatch accuracy: 11.7%
Validation accuracy: 10.0%
Minibatch loss at step 2000: nan
Minibatch accuracy: 6.2%
Validation accuracy: 10.0%
Minibatch loss at step 2500: nan
Minibatch accuracy: 10.2%
Validation accuracy: 10.0%
Minibatch loss at step 3000: nan
Minibatch accuracy: 7.8%
Validation accuracy: 10.0%
Test accuracy: 10.0%


来源: stackexchange

问:
Reference a React Element before its declared in JSX
I am implementing react-native-zss-rich-text-editor in my project and am having a issue where the RichTextToolbar needs a function that returns a ref to a RichTextEditor component.

If I order the RichTextEditor before the RichTextToolbar it works fine

```<code><RichTextEditor
  ref={(r) => this.richtext = r}/>
<RichTextToolbar
    getEditor={() => this.richtext}/>
</code>```

But I would like to first render the RichTextToolbar and then the RichTextEditor which throws an exception

```<code>    <RichTextToolbar
        getEditor={() => this.richtext}/>  <-----
    <RichTextEditor
      ref={(r) => this.richtext = r}/>

</code>```

答:
Try this code:

```<code><RichTextToolbar
    getEditor={() => this.richtext ? this.richtext : <div/>}/>
<RichTextEditor
  ref={(r) => this.richtext = r}/>
</code>```

This solution is put something compatible with requirements of component RichTextToolbar to it. If div is not good - replace it with some else.

according to your comment try this:

```<code>{ this.richtext ?
  <RichTextToolbar
      getEditor={() => this.richtext}/>
  : null
}
<RichTextEditor
  ref={(r) => this.richtext = r}/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am implementing react-native-zss-rich-text-editor in my project and am having a issue where the RichTextToolbar needs a function that returns a ref to a RichTextEditor component.

If I order the RichTextEditor before the RichTextToolbar it works fine

<RichTextEditor
  ref={(r) => this.richtext = r}/>
<RichTextToolbar
    getEditor={() => this.richtext}/>

But I would like to first render the RichTextToolbar and then the RichTextEditor which throws an exception

    <RichTextToolbar
        getEditor={() => this.richtext}/>  <-----
    <RichTextEditor
      ref={(r) => this.richtext = r}/>

Body:
Try this code:

<RichTextToolbar
    getEditor={() => this.richtext ? this.richtext : <div/>}/>
<RichTextEditor
  ref={(r) => this.richtext = r}/>

This solution is put something compatible with requirements of component RichTextToolbar to it. If div is not good - replace it with some else.

according to your comment try this:

{ this.richtext ?
  <RichTextToolbar
      getEditor={() => this.richtext}/>
  : null
}
<RichTextEditor
  ref={(r) => this.richtext = r}/>

ContentLicense: CC BY-SA 3.0


问:
JavaScript - During recursion type of variable changes from object to number
I have a function that pushes the number "number" to "output" array with the given number of "times". For some reason, during recursive call of a function, the "output" array becomes a number, and hence, push method ceases to work. Could anybody explain to me why the type of "output" variable changes during recursion?

```<code>function replicate(times, number, output) {
  if (output == undefined) output = [];
  if (times < 0) {
    return [];
  } else if (times == 0) {
    return output;
  } else {
    console.log(output, typeof output);
    return replicate(times - 1, number, output.push(number));
  }
}

//logs
//[] 'object'
//1 'number'
</code>```

Regards

答:
Array.prototype.push() returns the array's new length, not the array. So you are passing a number as output to your function, which is what gets logged then.

The push() method adds one or more elements to the end of an array and returns the new length of the array.

You could use concat()

```<code>return replicate(times - 1, number, output.concat(number));
</code>```

instead, or push to the array first

```<code>else {
    output.push(number);
    return replicate(times - 1, number, output);
}
</code>```

Body:
I have a function that pushes the number "number" to "output" array with the given number of "times". For some reason, during recursive call of a function, the "output" array becomes a number, and hence, push method ceases to work. Could anybody explain to me why the type of "output" variable changes during recursion?

function replicate(times, number, output) {
  if (output == undefined) output = [];
  if (times < 0) {
    return [];
  } else if (times == 0) {
    return output;
  } else {
    console.log(output, typeof output);
    return replicate(times - 1, number, output.push(number));
  }
}

//logs
//[] 'object'
//1 'number'

Regards

Body:
Array.prototype.push() returns the array's new length, not the array. So you are passing a number as output to your function, which is what gets logged then.

The push() method adds one or more elements to the end of an array and returns the new length of the array.

You could use concat()

return replicate(times - 1, number, output.concat(number));

instead, or push to the array first

else {
    output.push(number);
    return replicate(times - 1, number, output);
}


问:
JavaFX Auto Open new Window
I have A.fxml and B.fxml. A runing with Java Application override start method. I want to every 40 min in loop(5 times) { open new stage B.fxml and wait stage.close, if stage close continue loop open new stage B fxml. Loop this five times. I try timer timertask i could not. I try JavaFX Service i could not. I create Mythread extend Thread object. This time i could not control loop for next stage. When for statement start opening 5 stage. But i want to loop wait for currentstage is close then go next loop.  This is my fail code;

```<code>public class Driver extends Application {

public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(View.SETTINGS));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.setTitle("Info Library");
    stage.setResizable(false);
    stage.show();
    RandomQuestionThread thread = new RandomQuestionThread();
    if (DBContext.settings.isAbbreviation() || DBContext.settings.isTranslation()) {
        thread.start();
    }
}

public static void main(String[] args) throws InterruptedException {
    DBContext.settings = DBContext.getInstance().settings().getSettings();

    launch(args);
    HibernateUtil.getSessionFactory().close();
}
</code>```

}

```<code>public class RandomQuestionThread extends Thread {
Thread randomThread = new Thread(this);
private String fxml;
private static String TITLE;

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(DBContext.settings.getAutoQuestionTime() * 6000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int i = 0; i<DBContext.settings.getAutoQuestionCount(); i++) {
            randomFxml();
            Platform.runLater(()->{
                Parent root = null;
                try {
                    root = new FXMLLoader(getClass().getResource(fxml)).load();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Stage stage = new Stage();
                stage.setScene(new Scene(root));
                stage.setTitle(TITLE);
                stage.show();
                System.out.println(currentThread().getName());
            });
        }
    }
}

private void randomFxml() {
    int start = 0;
    if (DBContext.settings.isTranslation() && DBContext.settings.isAbbreviation()) {
        start = new Random().nextInt(2);
    } else if (DBContext.settings.isTranslation()) {
        start = 1;
    }

    switch (start) {
    case 0:
        fxml = View.ABBREVIATION;
        break;
    case 1:
        fxml = View.TRANSLATION;
        break;

    default:
        break;
    }
    if (start == 0) {
        TITLE = "KISALTMA SORUSU";
    } else TITLE = "ÇEVİRİ SORUSU";
}
</code>```

}

I need to work more Java multi threads. But after fix this problem. Please explain where I'm doing wrong. In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.My brain gave blue screen error.

答:
I fix this. I used Timer and TimeTask in my main controller init method. And its work. But same code in app start method or in mian method stage didnt wait. I used stageshowandwait() method but thread didnt wait. But same code woked in main controller init method. Why i dont know.</p>

```<code>Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            Platform.runLater(()->{
                for (int i = 0; i<4; i++) {
                    Parent root = null;
                    try {
                        root = new FXMLLoader(getClass().getResource(View.ABBREVIATION)).load();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle("deneme");
                    stage.showAndWait();
                }
            });
        }
    };

    timer.schedule(timerTask, 6000);
</code>```

Title: JavaFX Auto Open new Window

Body:
I have A.fxml and B.fxml. A runing with Java Application override start method. I want to every 40 min in loop(5 times) { open new stage B.fxml and wait stage.close, if stage close continue loop open new stage B fxml. Loop this five times. I try timer timertask i could not. I try JavaFX Service i could not. I create Mythread extend Thread object. This time i could not control loop for next stage. When for statement start opening 5 stage. But i want to loop wait for currentstage is close then go next loop.  This is my fail code;

public class Driver extends Application {

public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(View.SETTINGS));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.setTitle("Info Library");
    stage.setResizable(false);
    stage.show();
    RandomQuestionThread thread = new RandomQuestionThread();
    if (DBContext.settings.isAbbreviation() || DBContext.settings.isTranslation()) {
        thread.start();
    }
}

public static void main(String[] args) throws InterruptedException {
    DBContext.settings = DBContext.getInstance().settings().getSettings();

    launch(args);
    HibernateUtil.getSessionFactory().close();
}

}

public class RandomQuestionThread extends Thread {
Thread randomThread = new Thread(this);
private String fxml;
private static String TITLE;

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(DBContext.settings.getAutoQuestionTime() * 6000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int i = 0; i<DBContext.settings.getAutoQuestionCount(); i++) {
            randomFxml();
            Platform.runLater(()->{
                Parent root = null;
                try {
                    root = new FXMLLoader(getClass().getResource(fxml)).load();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Stage stage = new Stage();
                stage.setScene(new Scene(root));
                stage.setTitle(TITLE);
                stage.show();
                System.out.println(currentThread().getName());
            });
        }
    }
}

private void randomFxml() {
    int start = 0;
    if (DBContext.settings.isTranslation() && DBContext.settings.isAbbreviation()) {
        start = new Random().nextInt(2);
    } else if (DBContext.settings.isTranslation()) {
        start = 1;
    }

    switch (start) {
    case 0:
        fxml = View.ABBREVIATION;
        break;
    case 1:
        fxml = View.TRANSLATION;
        break;

    default:
        break;
    }
    if (start == 0) {
        TITLE = "KISALTMA SORUSU";
    } else TITLE = "ÇEVİRİ SORUSU";
}

}

I need to work more Java multi threads. But after fix this problem. Please explain where I'm doing wrong. In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.My brain gave blue screen error.

Body:
I fix this. I used Timer and TimeTask in my main controller init method. And its work. But same code in app start method or in mian method stage didnt wait. I used stageshowandwait() method but thread didnt wait. But same code woked in main controller init method. Why i dont know.

Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            Platform.runLater(()->{
                for (int i = 0; i<4; i++) {
                    Parent root = null;
                    try {
                        root = new FXMLLoader(getClass().getResource(View.ABBREVIATION)).load();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle("deneme");
                    stage.showAndWait();
                }
            });
        }
    };

    timer.schedule(timerTask, 6000);


问:
UnsatisfiedDependencyException: Error creating bean with name 'welcomeController': Unsatisfied dependency expressed through field 'userValidator'
Ive been trying to get my head around this error for hours now with little success.

Im getting the following error -

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'welcomeController': Unsatisfied dependency expressed through field 'userValidator'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.config.UserValidator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

My WelcomeController has an AutoWired to UserValidator -

```<code>@Controller
@RequestMapping("/")
public class WelcomeController {

    @Autowired
    AuctionItemRepository aucRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserRoleRepository roleRepository;

    @Autowired
    UserValidator userValidator;

    @Autowired
    UserService userService;

    @Autowired
    SecurityService securityService;

// inject via application.properties
@Value("${welcome.message:test}")
private String message = "Hello World";

@RequestMapping(value = "/")
public String welcome(Map<String, Object> model) {
    model.put("message", this.message);
    return "welcome";
}

    Date getTime() {
        Timestamp time = new Timestamp(new Date().getTime());
        return time;
    }

    @RequestMapping(value = "/sell", method = RequestMethod.GET)
    public String addAuction(Model model, HttpServletRequest request) {

        model.addAttribute("newAuction", new AuctionItem());
        model.addAttribute("action", "sell");
        return "NewAuction";
    }

    @RequestMapping(value = "/sell", method = RequestMethod.POST)
    public String saveAuction(@ModelAttribute("AuctionItem")AuctionItem auction, BindingResult result, ModelMap model){
        if(result.hasErrors()){
            return "error";
        }
 //           User user = (User) userRepository.findByUsername(getUser());
        auction.setAucStartTime(getTime());

        aucRepository.save(auction);
//            AuctionItem ai = aucRepository.findByOwnerAndStartTime(user, auction.getaStart());
        return "redirect:/aucConfirm";
    }

    @RequestMapping(value = "/aucConfirm", method = RequestMethod.GET)
    public String confirmAuction(Model model, HttpServletRequest request) {

        return "aucConfirm";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        model.addAttribute("userForm", new User());
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
        userValidator.validate(userForm, bindingResult);

        if (bindingResult.hasErrors()) {
            return "register";
        }

        userService.save(userForm);

        securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());

        return "redirect:/";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, String error, String logout) {
        if (error != null)
            model.addAttribute("error", "Your username and password is invalid.");

        if (logout != null)
            model.addAttribute("message", "You have been logged out successfully.");

        return "login";
    }
</code>```

}

UserValidator Class -

```<code>public class UserValidator implements Validator{
@Autowired
private UserService userService;

@Override
public boolean supports(Class<?> aClass) {
    return User.class.equals(aClass);
}

@Override
public void validate(Object o, Errors errors) {
            User user = (User) o;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
    if (user.getUsername().length() < 6 || user.getUsername().length() > 32) {
        errors.rejectValue("username", "Size.userForm.username");
    }
    if (userService.findByUsername(user.getUsername()) != null) {
        errors.rejectValue("username", "Duplicate.userForm.username");
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
    if (user.getPass().length() < 8 || user.getPass().length() > 32) {
        errors.rejectValue("password", "Size.userForm.password");
    }

    if (!user.getPasswordConfirm().equals(user.getPass())) {
        errors.rejectValue("passwordConfirm", "Diff.userForm.passwordConfirm");
    }
}

}
</code>```

Both these classes as well as my Spring Boot Configuration and WebSecurityConfig are in the package com.config

Any ideas?

答:
You need use @Component stereotype annotation for your UserValidator class, otherwise, Spring container will not instantiate that class & therefore will not be able to inject it as a dependency inside WelcomeController.

```<code>@Component
public class UserValidator implements Validator{
 //add current code
}
</code>```

Body:
Ive been trying to get my head around this error for hours now with little success.

Im getting the following error -

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'welcomeController': Unsatisfied dependency expressed through field 'userValidator'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.config.UserValidator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

My WelcomeController has an AutoWired to UserValidator -

@Controller
@RequestMapping("/")
public class WelcomeController {

    @Autowired
    AuctionItemRepository aucRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserRoleRepository roleRepository;

    @Autowired
    UserValidator userValidator;

    @Autowired
    UserService userService;

    @Autowired
    SecurityService securityService;

// inject via application.properties
@Value("${welcome.message:test}")
private String message = "Hello World";

@RequestMapping(value = "/")
public String welcome(Map<String, Object> model) {
    model.put("message", this.message);
    return "welcome";
}

    Date getTime() {
        Timestamp time = new Timestamp(new Date().getTime());
        return time;
    }

    @RequestMapping(value = "/sell", method = RequestMethod.GET)
    public String addAuction(Model model, HttpServletRequest request) {

        model.addAttribute("newAuction", new AuctionItem());
        model.addAttribute("action", "sell");
        return "NewAuction";
    }

    @RequestMapping(value = "/sell", method = RequestMethod.POST)
    public String saveAuction(@ModelAttribute("AuctionItem")AuctionItem auction, BindingResult result, ModelMap model){
        if(result.hasErrors()){
            return "error";
        }
 //           User user = (User) userRepository.findByUsername(getUser());
        auction.setAucStartTime(getTime());

        aucRepository.save(auction);
//            AuctionItem ai = aucRepository.findByOwnerAndStartTime(user, auction.getaStart());
        return "redirect:/aucConfirm";
    }

    @RequestMapping(value = "/aucConfirm", method = RequestMethod.GET)
    public String confirmAuction(Model model, HttpServletRequest request) {

        return "aucConfirm";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        model.addAttribute("userForm", new User());
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
        userValidator.validate(userForm, bindingResult);

        if (bindingResult.hasErrors()) {
            return "register";
        }

        userService.save(userForm);

        securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());

        return "redirect:/";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, String error, String logout) {
        if (error != null)
            model.addAttribute("error", "Your username and password is invalid.");

        if (logout != null)
            model.addAttribute("message", "You have been logged out successfully.");

        return "login";
    }

}

UserValidator Class -

public class UserValidator implements Validator{
@Autowired
private UserService userService;

@Override
public boolean supports(Class<?> aClass) {
    return User.class.equals(aClass);
}

@Override
public void validate(Object o, Errors errors) {
            User user = (User) o;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
    if (user.getUsername().length() < 6 || user.getUsername().length() > 32) {
        errors.rejectValue("username", "Size.userForm.username");
    }
    if (userService.findByUsername(user.getUsername()) != null) {
        errors.rejectValue("username", "Duplicate.userForm.username");
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
    if (user.getPass().length() < 8 || user.getPass().length() > 32) {
        errors.rejectValue("password", "Size.userForm.password");
    }

    if (!user.getPasswordConfirm().equals(user.getPass())) {
        errors.rejectValue("passwordConfirm", "Diff.userForm.passwordConfirm");
    }
}

}

Both these classes as well as my Spring Boot Configuration and WebSecurityConfig are in the package com.config

Any ideas?

Body:
You need use @Component stereotype annotation for your UserValidator class, otherwise, Spring container will not instantiate that class & therefore will not be able to inject it as a dependency inside WelcomeController.

@Component
public class UserValidator implements Validator{
 //add current code
}


问:
I can't put a CSS class on a template
I'm reading a book about Angular 2 and one of the chapters is about Forms. I'm using Semantic UI Framework and when I put a class, specify the "error" class the div is disappear. Is very very strange I don't know what happened. I have to mention what works perfectly if I replace "error" class with another like "negative" for instead.</p>

```<code>import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <form [formGroup]="myForm"
      (ngSubmit)="onSubmit(myForm.value)"
      class="ui form">

      <div class="field"
        [class.error]="!sku.valid && sku.touched">
        <label for="skuInput">SKU</label>
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [formControl]="myForm.controls['sku']">
        <div *ngIf="!sku.valid"
          class="ui error message">SKU is invalid</div>
        <div *ngIf="!sku.hasError('required')"
          class="ui error message">SKU is required</div>
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {
  myForm: FormGroup;
  sku: AbstractControl;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });

    this.sku = this.myForm.controls['sku'];
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}
</code>```

答:
Fixed. by default, semantic UI hides these unless the whole form is in the same state. You can create an another css called styles.css for example and use this:</p>

```<code>.ui.form .error.message,
.ui.form .success.message,
.ui.form .warning.message {
  display: block;
}
</code>```

Title: I can't put a CSS class on a template

Body:
I'm reading a book about Angular 2 and one of the chapters is about Forms. I'm using Semantic UI Framework and when I put a class, specify the "error" class the div is disappear. Is very very strange I don't know what happened. I have to mention what works perfectly if I replace "error" class with another like "negative" for instead.

import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `

Demo Form: Sku with Builder

    <form [formGroup]="myForm"
      (ngSubmit)="onSubmit(myForm.value)"
      class="ui form">

        SKU
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [formControl]="myForm.controls['sku']">

SKU is invalid

SKU is required

    <button type="submit" class="ui button">Submit</button>
    </form>

  `
})
export class DemoFormSkuBuilder {
  myForm: FormGroup;
  sku: AbstractControl;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });

    this.sku = this.myForm.controls['sku'];
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}

Body:
Fixed. by default, semantic UI hides these unless the whole form is in the same state. You can create an another css called styles.css for example and use this:

.ui.form .error.message,
.ui.form .success.message,
.ui.form .warning.message {
  display: block;
}


问:
Change Android BottomBar Icon on Select
Is there an easy way to change the icon for the Android BottomBar navigation (https://github.com/roughike/BottomBar). I have seen a number of ways to set this icon, but I would like to change the icon when the user selects it. Currently I have an icon, with outline, and I would like to display a filled icon when they select it. Any help would be great.

答:
It looks like the guys at BottomBar decided to incorporate this. They added the ability in 2.2.0:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_myicon_selected" android:state_selected="true" />
    <item android:drawable="@drawable/ic_myicon_default" android:state_selected="false" />
</selector>
</code>```

You can find the reference here.

Title: Change Android BottomBar Icon on Select

Body:
It looks like the guys at BottomBar decided to incorporate this. They added the ability in 2.2.0:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_myicon_selected" android:state_selected="true" />
    <item android:drawable="@drawable/ic_myicon_default" android:state_selected="false" />
</selector>

You can find the reference here.


问:
Pick Place Error - Google Places API
I'm getting this error with my code and I have followed the google tutorial instructions step by step.

```<code>Pick Place error: The operation couldn’t be completed. The Places API could not find the user's location. This may be because the user has not allowed the application to access location information.
</code>```

I have added the relevant information to the info.plist and my code looks like this -

```<code>import UIKit
import GooglePlaces

class ViewController: UIViewController {

    var placesClient: GMSPlacesClient!

    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var addressLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        let locationManager = CLLocationManager()
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        placesClient = GMSPlacesClient.shared()
    }

    @IBAction func getCurrentPlace(_ sender: UIButton) {

        placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
            if let error = error {
                print("Pick Place error: \(error.localizedDescription)")
                return
            }

            self.nameLabel.text = "No current place"
            self.addressLabel.text = ""

            if let placeLikelihoodList = placeLikelihoodList {
                let place = placeLikelihoodList.likelihoods.first?.place
                if let place = place {
                    self.nameLabel.text = place.name
                    self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
                        .joined(separator: "\n")
                }
            }
            }
        )
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

The location window with allow/deny disappears too quickly and even when I press allow nothing happens, I have no idea how to solve this as I'm just following the google doc.

Additionally this error appears -

```<code>2017-03-26 14:38:27.472739 Restaurant[26616:2797750] subsystem: com.apple.BackBoardServices.fence, category: Observer, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
</code>```

答: you need to check the request limit on https://console.developers.google.com , free version its only for 1000 per day, i have to create another project and new key for keep testing. </p>

Title: Pick Place Error - Google Places API

Body:
I'm getting this error with my code and I have followed the google tutorial instructions step by step.

Pick Place error: The operation couldn’t be completed. The Places API could not find the user's location. This may be because the user has not allowed the application to access location information.

I have added the relevant information to the info.plist and my code looks like this -

import UIKit
import GooglePlaces

class ViewController: UIViewController {

    var placesClient: GMSPlacesClient!

    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var addressLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        let locationManager = CLLocationManager()
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        placesClient = GMSPlacesClient.shared()
    }

    @IBAction func getCurrentPlace(_ sender: UIButton) {

        placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
            if let error = error {
                print("Pick Place error: \(error.localizedDescription)")
                return
            }

            self.nameLabel.text = "No current place"
            self.addressLabel.text = ""

            if let placeLikelihoodList = placeLikelihoodList {
                let place = placeLikelihoodList.likelihoods.first?.place
                if let place = place {
                    self.nameLabel.text = place.name
                    self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
                        .joined(separator: "\n")
                }
            }
            }
        )
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

The location window with allow/deny disappears too quickly and even when I press allow nothing happens, I have no idea how to solve this as I'm just following the google doc.

Additionally this error appears -

2017-03-26 14:38:27.472739 Restaurant[26616:2797750] subsystem: com.apple.BackBoardServices.fence, category: Observer, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0


问:
Forming new object with array of objects
From the object 1, I am trying to form another object 2. I have written this below piece of code but I dono is this the right approach to achieve object 2.

```<code>var arr = [];
    object1.filter(function(value) {
                                return value.hasOwnProperty("This Year"); // Get only elements, which have such a key
                                    }).map(function(value) {
                                arr.push({value:value["This Year"]}); // Extract the values only
                                    });
</code>```

Object 1

```<code>var obj=[
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]
</code>```

Object 2 - Desired Result

```<code>var dataset = [
        {
            "seriesname": "Last Year",
            "data": [
                {
                    "value": "10000"
                },
                {
                    "value": "11500"
                },
                {
                    "value": "12500"
                },
                {
                    "value": "15000"
                }
            ]
        },
        {
            "seriesname": "This Year",
            "data": [
                {
                    "value": "25400"
                },
                {
                    "value": "29800"
                }
            ]
        }
    ]
</code>```

If anyone can help me with better approach. In my code I am hard coding the key name of object 1. Is it possible in any other way?

答:
To avoid hard coding the year entries, you could use RegExp to look for a key containing the year word.

var arr = [{sno:1,"Last Year":1e4},{sno:2,"Last Year":11500},{sno:3,"Last Year":12500},{sno:4,"This Year":25400},{sno:5,"Last Year":15e3},{sno:6,"This Year":29800}],
    res = [...new Set(arr.map(v => Object.keys(v).find(z => /year/i.test(z))))]
          .map(c => ({seriesname: c, data: arr.filter(x => x[c]).map(a => ({value: a[c]}))}));

console.log(res);```

Body:
From the object 1, I am trying to form another object 2. I have written this below piece of code but I dono is this the right approach to achieve object 2.

var arr = [];
    object1.filter(function(value) {
                                return value.hasOwnProperty("This Year"); // Get only elements, which have such a key
                                    }).map(function(value) {
                                arr.push({value:value["This Year"]}); // Extract the values only
                                    });

Object 1

var obj=[
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]

Object 2 - Desired Result

var dataset = [
        {
            "seriesname": "Last Year",
            "data": [
                {
                    "value": "10000"
                },
                {
                    "value": "11500"
                },
                {
                    "value": "12500"
                },
                {
                    "value": "15000"
                }
            ]
        },
        {
            "seriesname": "This Year",
            "data": [
                {
                    "value": "25400"
                },
                {
                    "value": "29800"
                }
            ]
        }
    ]

If anyone can help me with better approach. In my code I am hard coding the key name of object 1. Is it possible in any other way?


问:
Django REST Framework: define fields in nested object?
I got events that happen at locations:

```<code>class Event(models.Model):
    title = models.CharField(max_length=200)
    date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    date_start = models.DateTimeField('start date')
    date_end = models.DateTimeField('end date')
    def __unicode__(self):
        return self.title
    description = models.TextField()
    price = models.IntegerField(null=True, blank=True)
    tags = TaggableManager()
    location = models.ForeignKey(Location, blank=False)

class Location(models.Model):
    location_title = models.CharField(max_length=200)
    location_date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    location_latitude = models.CharField(max_length=200)
    location_longitude = models.CharField(max_length=200)
    location_address = models.CharField(max_length=200)
    location_city = models.CharField(max_length=200)
    location_zipcode = models.CharField(max_length=200)
    location_state = models.CharField(max_length=200)
    location_country = models.CharField(max_length=200)
    location_description = models.TextField()
    def __unicode__(self):
        return u'%s' % (self.location_title)
</code>```

I can get the results of all via:

```<code>class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    class Meta:
        model = Event
        depth = 2
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
</code>```

Which outputs:

```<code> {
            "url": "http://localhost:8000/api/event/3/",
            "id": 3,
            "title": "Testing",
            "date_start": "2013-03-10T20:19:00Z",
            "date_end": "2013-03-10T20:19:00Z",
            "description": "fgdgdfg",
            "price": 10,
            "location": {
                "id": 2,
                "location_title": "Mighty",
                "location_date_published": "2013-03-10T20:16:00Z",
                "location_latitude": "37.767475",
                "location_longitude": "-122.406878",
                "location_address": "119 Utah St, San Francisco, CA 94103, USA",
                "location_city": "San Francisco",
                "location_zipcode": "94103",
                "location_state": "California",
                "location_country": "United States",
                "location_description": "Some place"
            }
        },
</code>```

However, I don't want it to grab all fields, as I don't need all of them. How can I define what fields should be retrieved from my nested object? Thanks!

答:
I found this question when I was trying to figure out how to exclude certain fields from a serializer only when it was being nested. Looks like Tasawer Nawaz had that question as well. You can do that by overriding get_field_names. Here's an example based on Tom Christie's answer:

```<code>class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = (...)
        exclude_when_nested = {'location_title', 'location_date_published'}  # not an official DRF meta attribute ...

    def get_field_names(self, *args, **kwargs):
        field_names = super(LinkUserSerializer, self).get_field_names(*args, **kwargs)
        if self.parent:
            field_names = [i for i in field_names if i not in self.Meta.exclude_when_nested]
        return field_names

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    location = LocationSerializer()

    class Meta:
        model = Event
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')
</code>```

Body:
I got events that happen at locations:

class Event(models.Model):
    title = models.CharField(max_length=200)
    date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    date_start = models.DateTimeField('start date')
    date_end = models.DateTimeField('end date')
    def __unicode__(self):
        return self.title
    description = models.TextField()
    price = models.IntegerField(null=True, blank=True)
    tags = TaggableManager()
    location = models.ForeignKey(Location, blank=False)

class Location(models.Model):
    location_title = models.CharField(max_length=200)
    location_date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    location_latitude = models.CharField(max_length=200)
    location_longitude = models.CharField(max_length=200)
    location_address = models.CharField(max_length=200)
    location_city = models.CharField(max_length=200)
    location_zipcode = models.CharField(max_length=200)
    location_state = models.CharField(max_length=200)
    location_country = models.CharField(max_length=200)
    location_description = models.TextField()
    def __unicode__(self):
        return u'%s' % (self.location_title)

I can get the results of all via:

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    class Meta:
        model = Event
        depth = 2
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')

Which outputs:

 {
            "url": "http://localhost:8000/api/event/3/",
            "id": 3,
            "title": "Testing",
            "date_start": "2013-03-10T20:19:00Z",
            "date_end": "2013-03-10T20:19:00Z",
            "description": "fgdgdfg",
            "price": 10,
            "location": {
                "id": 2,
                "location_title": "Mighty",
                "location_date_published": "2013-03-10T20:16:00Z",
                "location_latitude": "37.767475",
                "location_longitude": "-122.406878",
                "location_address": "119 Utah St, San Francisco, CA 94103, USA",
                "location_city": "San Francisco",
                "location_zipcode": "94103",
                "location_state": "California",
                "location_country": "United States",
                "location_description": "Some place"
            }
        },

However, I don't want it to grab all fields, as I don't need all of them. How can I define what fields should be retrieved from my nested object? Thanks!

Body:
I found this question when I was trying to figure out how to exclude certain fields from a serializer only when it was being nested. Looks like Tasawer Nawaz had that question as well. You can do that by overriding get_field_names. Here's an example based on Tom Christie's answer:

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = (...)
        exclude_when_nested = {'location_title', 'location_date_published'}  # not an official DRF meta attribute ...

    def get_field_names(self, *args, **kwargs):
        field_names = super(LinkUserSerializer, self).get_field_names(*args, **kwargs)
        if self.parent:
            field_names = [i for i in field_names if i not in self.Meta.exclude_when_nested]
        return field_names

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    location = LocationSerializer()

    class Meta:
        model = Event
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')


问:
wavesurfer.js destroy() causes Uncaught (in promise) DOMException: Cannot close a context that is being closed or has already been closed
I'm using wavesurfer to show song waveforms on my web page. I'm using the following code -

```<code>function setupSongwaves(songJson) {
    var songwaveid = '#song-waveform' + songJson.songid;

    var wavesurfer = WaveSurfer.create({
        container: songwaveid,
        height : 80,
        barWidth : 4,
        cursorWidth : 2,
        waveColor: 'blue',
        cursorColor: 'white',
        progressColor: 'red'
    });

    wavesurfer.on('ready', function () {
        console.log('ready');
        // wavesurfer.play();

        setTimeout(function () {
            destroyCurrentSongwaves()
        },2000);
    });

    $(document).on("destroy-songwaves", function () {
        wavesurfer.destroy();
    });

    // Hard coding song for now
    wavesurfer.load('../assets/song1.mp3');
}

function destroyCurrentSongwaves() {
    $.event.trigger({
        type: "destroy-songwaves"
    });
}
</code>```

As soon as wavesurfer.destroy() is called I get the following error message in my console -

Uncaught (in promise) DOMException: Cannot close a context that is
  being closed or has already been closed.

Things appear to be working fine, but I get this error every time and I can't figure out what seems to be the problem. Any help would be appreciated!

答: try to upgrade Wavesurfer to the current latest version 1.3.7, it should resolve the problem.</p>

Body:
I'm using wavesurfer to show song waveforms on my web page. I'm using the following code -

function setupSongwaves(songJson) {
    var songwaveid = '#song-waveform' + songJson.songid;

    var wavesurfer = WaveSurfer.create({
        container: songwaveid,
        height : 80,
        barWidth : 4,
        cursorWidth : 2,
        waveColor: 'blue',
        cursorColor: 'white',
        progressColor: 'red'
    });

    wavesurfer.on('ready', function () {
        console.log('ready');
        // wavesurfer.play();

        setTimeout(function () {
            destroyCurrentSongwaves()
        },2000);
    });

    $(document).on("destroy-songwaves", function () {
        wavesurfer.destroy();
    });

    // Hard coding song for now
    wavesurfer.load('../assets/song1.mp3');
}

function destroyCurrentSongwaves() {
    $.event.trigger({
        type: "destroy-songwaves"
    });
}

As soon as wavesurfer.destroy() is called I get the following error message in my console -

Uncaught (in promise) DOMException: Cannot close a context that is
  being closed or has already been closed.

Things appear to be working fine, but I get this error every time and I can't figure out what seems to be the problem. Any help would be appreciated!


问:
Responsive search field layout while avoiding position absolute
I have this specific layout problem.

Where I want to get 3 containers in one row, where left and right are with fixed width and middle one is responsive. And inside there is a input field and submit button, where the input field is the responsive one. Example:

What I tried to do, is to use a div-wrapper, that contains the padding and fake-styling for input. And then inside this wrapper there is width: 100%; input field. Sadly, my approach is not working no matter how hard I tried:

#general_before {display: inline-block; background: rgba(34, 43, 34, 0.5); width: 100px;}
#general_wrapper {display: inline-block; width: 100%; border: 2px solid black;}
#field_wrapper {padding: 5px; background: rgba(45, 65, 78, 0.5);}
#field {width: 100%;}
#submit {float: right;}
#general_after {display: inline-block; background: rgba(45, 87, 56, 0.5); width: 100px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="general_before">BEFORE</div>
<div id="general_wrapper">
<input id="submit" type="submit" value="GO" />
<div id="field_wrapper"><input id="field" type="text" name="" placeholder="Enter your search term here.." value="" /></div>
</div>
<div id="general_after">AFTER</div></code>```

I don't even have a solution for the 3 containers in a row, except using position absolute position: absolute; left: 200px; right: 200; on the middle container. But this feels wrong approach to this problem.

答:
Try Flexboxes:

#container, #general_wrapper {display: flex;}
#general_wrapper, #field_wrapper {flex-grow: 1;}
#field { width: 100%;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="general_before">BEFORE</div>
<div id="general_wrapper">
<input id="submit" type="submit" value="GO" />
<div id="field_wrapper"><input id="field" type="text" name="" placeholder="Enter your search term here.." value="" /></div>
</div>
<div id="general_after">AFTER</div></code>```

Update for IE support

#container , #general_wrapper { display: table; width: 100%;}
#general_before, #general_after, #submit, #field_wrapper { display: table-cell;}

#field_wrapper, #field_wrapper input  { width: 100%;}
#general_before, #general_after, #submit {width: 100px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="general_before">BEFORE</div>
<div id="general_wrapper">
<input id="submit" type="submit" value="GO" />
<div id="field_wrapper"><input id="field" type="text" name="" placeholder="Enter your search term here.." value="" /></div>
</div>
<div id="general_after">AFTER</div></code>```

Body:
I have this specific layout problem.

Where I want to get 3 containers in one row, where left and right are with fixed width and middle one is responsive. And inside there is a input field and submit button, where the input field is the responsive one. Example:

What I tried to do, is to use a div-wrapper, that contains the padding and fake-styling for input. And then inside this wrapper there is width: 100%; input field. Sadly, my approach is not working no matter how hard I tried:

#general_before {display: inline-block; background: rgba(34, 43, 34, 0.5); width: 100px;}
#general_wrapper {display: inline-block; width: 100%; border: 2px solid black;}
#field_wrapper {padding: 5px; background: rgba(45, 65, 78, 0.5);}
#field {width: 100%;}
#submit {float: right;}
#general_after {display: inline-block; background: rgba(45, 87, 56, 0.5); width: 100px;}

BEFORE

<input id="submit" type="submit" value="GO" />

<input id="field" type="text" name="" placeholder="Enter your search term here.." value="" />

AFTER

I don't even have a solution for the 3 containers in a row, except using position absolute position: absolute; left: 200px; right: 200; on the middle container. But this feels wrong approach to this problem.

Body:
Try Flexboxes:

#container, #general_wrapper {display: flex;}
#general_wrapper, #field_wrapper {flex-grow: 1;}
#field { width: 100%;}

<div id="general_before">BEFORE</div>
<div id="general_wrapper">
<input id="submit" type="submit" value="GO" />
<div id="field_wrapper"><input id="field" type="text" name="" placeholder="Enter your search term here.." value="" /></div>
</div>
<div id="general_after">AFTER</div>

Update for IE support

#container , #general_wrapper { display: table; width: 100%;}
#general_before, #general_after, #submit, #field_wrapper { display: table-cell;}

#field_wrapper, #field_wrapper input  { width: 100%;}
#general_before, #general_after, #submit {width: 100px;}

<div id="general_before">BEFORE</div>
<div id="general_wrapper">
<input id="submit" type="submit" value="GO" />
<div id="field_wrapper"><input id="field" type="text" name="" placeholder="Enter your search term here.." value="" /></div>
</div>
<div id="general_after">AFTER</div>


问:
Commons-Io Duplicate Entry Error Using Robospice and Android Studio
I've been working on the following issue for several hours, but haven't come up with a way to solve my problem.  I've tried the following fixes from Stack Overflow (Android Studio update to 1.0 corrupts MultiDex and Duplicate Zip Entry after Gradle Plugin v0.13.1) but neither one of them worked.

I am getting the following error when trying to build my program:

```<code>Execution failed for task ':app:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
</code>```

The error seems to indicate that commons-io is being included twice in the build process

I am using Android Studio and Gradle to include multiple Robospice dependencies.  This is the dependencies section of my Gradle build file:

```<code>dependencies {
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:support-v4:21.0.3'
    compile 'com.google.android.gms:play-services:6.5.87'

    compile'com.google.api-client:google-api-client-android:1.19.0'

    // You must install or update the Google Repository through the SDK manager to use this dependency.
    // The Google Repository (separate from the corresponding library) can be found in the Extras category.
    //compile 'com.google.android.gms:play-services:4.3.23'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.jakewharton:butterknife:${butterknifeVersion}"
    compile 'com.sun.jersey:jersey-bundle:1.8'
    compile 'com.google.code.gson:gson:2.3'
    compile 'org.codehaus.jackson:jackson-core-asl:1.9.0'
    compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.0'

    compile ('com.octo.android.robospice:robospice:1.4.14'){
        exclude module: 'commons-io'
        exclude group: 'commons-io'
    }

    compile ('com.octo.android.robospice:robospice-spring-android:1.4.14'){
        exclude group: 'org.apache.commons', module: 'commons-io'
    }

    compile 'com.squareup.okhttp:okhttp:2.1.0'

    compile ('com.octo.android.robospice:robospice-google-http-client:1.4.14'){
        exclude module: 'xpp3'
        exclude group: 'stax'
    }

    compile 'org.scribe:scribe:1.3.5'
    compile files("$buildDir/native-libs/native-libs.jar")

}
</code>```

Using the "gradlew -q dependencies app:dependencies" command  to view the project's dependency tree indicates that com.octo.android.robospice:robospice:1.4.14 is dependent on the commons-io library.  Here is the relevant snippet of the project dependency tree:

```<code>+--- com.octo.android.robospice:robospice:1.4.14
|    \--- com.octo.android.robospice:robospice-cache:1.4.14
|         +--- org.apache.commons:commons-lang3:3.3.2
|         \--- org.apache.commons:commons-io:1.3.2
|              \--- commons-io:commons-io:1.3.2
</code>```

The dependency is still listed even though I excluded commons-io from all Robospice related dependencies in the gradle build file.  I also tried changing the group name from commons-io to org.apache.commons, and that did not work either.

My project is at a standstill until I get this resolved, and I would appreciate any help I can get.

答:
I guess this question needs a structured approach towards solving the issue which both of the above answers fail to provide.

Step 1: Find out which external library is causing duplicate zip entry. Run following command from terminal of Android Studio.
gradlew -q dependencies app:dependencies

In my case, image picking library ('net.yazeed44.imagepicker:imagepicker:1.3.0') was causing the duplicate entry.

Step 2: Add code to exclude commons-io only for that library

```<code>compile ('net.yazeed44.imagepicker:imagepicker:1.3.0'){
        exclude group: 'org.apache.commons', module: 'commons-io'
}
</code>```

Step 3: Include updated commons-io library.
compile 'commons-io:commons-io:1.3.2'

Now you are set to go.

Body:
I've been working on the following issue for several hours, but haven't come up with a way to solve my problem.  I've tried the following fixes from Stack Overflow (Android Studio update to 1.0 corrupts MultiDex and Duplicate Zip Entry after Gradle Plugin v0.13.1) but neither one of them worked.

I am getting the following error when trying to build my program:

Execution failed for task ':app:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class

The error seems to indicate that commons-io is being included twice in the build process

I am using Android Studio and Gradle to include multiple Robospice dependencies.  This is the dependencies section of my Gradle build file:

dependencies {
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:support-v4:21.0.3'
    compile 'com.google.android.gms:play-services:6.5.87'

    compile'com.google.api-client:google-api-client-android:1.19.0'

    // You must install or update the Google Repository through the SDK manager to use this dependency.
    // The Google Repository (separate from the corresponding library) can be found in the Extras category.
    //compile 'com.google.android.gms:play-services:4.3.23'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.jakewharton:butterknife:${butterknifeVersion}"
    compile 'com.sun.jersey:jersey-bundle:1.8'
    compile 'com.google.code.gson:gson:2.3'
    compile 'org.codehaus.jackson:jackson-core-asl:1.9.0'
    compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.0'

    compile ('com.octo.android.robospice:robospice:1.4.14'){
        exclude module: 'commons-io'
        exclude group: 'commons-io'
    }

    compile ('com.octo.android.robospice:robospice-spring-android:1.4.14'){
        exclude group: 'org.apache.commons', module: 'commons-io'
    }

    compile 'com.squareup.okhttp:okhttp:2.1.0'

    compile ('com.octo.android.robospice:robospice-google-http-client:1.4.14'){
        exclude module: 'xpp3'
        exclude group: 'stax'
    }

    compile 'org.scribe:scribe:1.3.5'
    compile files("$buildDir/native-libs/native-libs.jar")

}

Using the "gradlew -q dependencies app:dependencies" command  to view the project's dependency tree indicates that com.octo.android.robospice:robospice:1.4.14 is dependent on the commons-io library.  Here is the relevant snippet of the project dependency tree:

+--- com.octo.android.robospice:robospice:1.4.14
|    \--- com.octo.android.robospice:robospice-cache:1.4.14
|         +--- org.apache.commons:commons-lang3:3.3.2
|         \--- org.apache.commons:commons-io:1.3.2
|              \--- commons-io:commons-io:1.3.2

The dependency is still listed even though I excluded commons-io from all Robospice related dependencies in the gradle build file.  I also tried changing the group name from commons-io to org.apache.commons, and that did not work either.

My project is at a standstill until I get this resolved, and I would appreciate any help I can get.

Body:
I guess this question needs a structured approach towards solving the issue which both of the above answers fail to provide.

Step 1: Find out which external library is causing duplicate zip entry. Run following command from terminal of Android Studio.
gradlew -q dependencies app:dependencies

In my case, image picking library ('net.yazeed44.imagepicker:imagepicker:1.3.0') was causing the duplicate entry.

Step 2: Add code to exclude commons-io only for that library

compile ('net.yazeed44.imagepicker:imagepicker:1.3.0'){
        exclude group: 'org.apache.commons', module: 'commons-io'
}

Step 3: Include updated commons-io library.
compile 'commons-io:commons-io:1.3.2'

Now you are set to go.


问:
Navigator and window type error with TypeScript and Angular 2
I am trying to use ng2-translate in my Ionic 2 app, with:

```<code>this.translateService.setDefaultLang('en');
            if (this.platform.is('cordova')) {
                if (navigator.globalization) {
                    navigator.globalization.getPreferredLanguage(function (language) {
</code>```

but I get this error

```<code>Typescript Error
Property 'globalization' does not exist on type 'Navigator'.
src/app/app.component.ts
if (this.platform.is('cordova')) {
    if (navigator.globalization) {
</code>```

And I have the same type of error with window.cordovain this line of code:

```<code>if (this.platform.is('cordova') && window.cordova.plugins.Keyboard) {
</code>```

Should I declare navigator type or something ?

答:
You're missing Typescript typing information for that navigator object. Basically, the error you're seeing is the Typescript compiler saying that, based on the type definitions you have supplied so far, there is no information stating that the navigator object has a globalization property.

The solution is to add the typing information for that navigator object.

I'm honestly not sure which package contains those type definitions, but from Typescript v2 (or v2.1... can't remember which), npm stores type definitions for Typescript libraries under the @types namespace.

So, you want to

```<code>npm install --save-dev @types/<some package>
</code>```

to add the type definitions into your project.

I'd take a guess at starting with:

```<code>@npm install --save-dev @types/cordova-ionic
</code>```

Body:
I am trying to use ng2-translate in my Ionic 2 app, with:

this.translateService.setDefaultLang('en');
            if (this.platform.is('cordova')) {
                if (navigator.globalization) {
                    navigator.globalization.getPreferredLanguage(function (language) {

but I get this error

Typescript Error
Property 'globalization' does not exist on type 'Navigator'.
src/app/app.component.ts
if (this.platform.is('cordova')) {
    if (navigator.globalization) {

And I have the same type of error with window.cordovain this line of code:

if (this.platform.is('cordova') && window.cordova.plugins.Keyboard) {

Should I declare navigator type or something ?

Body:
You're missing Typescript typing information for that navigator object. Basically, the error you're seeing is the Typescript compiler saying that, based on the type definitions you have supplied so far, there is no information stating that the navigator object has a globalization property.

The solution is to add the typing information for that navigator object.

I'm honestly not sure which package contains those type definitions, but from Typescript v2 (or v2.1... can't remember which), npm stores type definitions for Typescript libraries under the @types namespace.

So, you want to

npm install --save-dev @types/<some package>

to add the type definitions into your project.

I'd take a guess at starting with:

@npm install --save-dev @types/cordova-ionic


问:
What context name should be passed to Glide method?
In order to load image when using viewholder and fragment, I don't know context object name I should pass. Below is my glide code:

```<code>Glide.with(activity).load(cheeses.getImageView()).fitCenter().into(mImageView);
</code>```

Error:

```<code>at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1555)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
at com.bumptech.glide.manager.RequestManagerRetriever.getSupportRequestManagerFragment(RequestManagerRetriever.java:187)
at com.bumptech.glide.manager.RequestManagerRetriever.supportFragmentGet(RequestManagerRetriever.java:195)
at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:104)
at com.bumptech.glide.Glide.with(Glide.java:644)
at com.support.android.designlibdemo.ViewHolderClass.ViewHolder.bindToCheese(ViewHolder.java:42)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:112)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:93)
</code>```

答: In the ViewHolder use getActivity, not MainActivity mainActvity;</p>

Body:
In order to load image when using viewholder and fragment, I don't know context object name I should pass. Below is my glide code:

Glide.with(activity).load(cheeses.getImageView()).fitCenter().into(mImageView);

Error:

at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1555)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
at com.bumptech.glide.manager.RequestManagerRetriever.getSupportRequestManagerFragment(RequestManagerRetriever.java:187)
at com.bumptech.glide.manager.RequestManagerRetriever.supportFragmentGet(RequestManagerRetriever.java:195)
at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:104)
at com.bumptech.glide.Glide.with(Glide.java:644)
at com.support.android.designlibdemo.ViewHolderClass.ViewHolder.bindToCheese(ViewHolder.java:42)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:112)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:93)


答:
This is because the return type of push method on array is its length! never ever do this! that should be like this:</p>

```<code>function replicate(times, number, output) {
  if (output == undefined) output = [];
  if (times < 0) {
    return [];
  } else if (times == 0) {
    return output;
  } else {
    console.log(output, typeof output);
    output.push(number);
    return replicate(times - 1, number, output);
  }
}
</code>```

Title: JavaScript - During recursion type of variable changes from object to number

Body:
I have a function that pushes the number "number" to "output" array with the given number of "times". For some reason, during recursive call of a function, the "output" array becomes a number, and hence, push method ceases to work. Could anybody explain to me why the type of "output" variable changes during recursion?

function replicate(times, number, output) {
  if (output == undefined) output = [];
  if (times < 0) {
    return [];
  } else if (times == 0) {
    return output;
  } else {
    console.log(output, typeof output);
    return replicate(times - 1, number, output.push(number));
  }
}

//logs
//[] 'object'
//1 'number'

Regards

Body:
This is because the return type of push method on array is its length! never ever do this! that should be like this:

function replicate(times, number, output) {
  if (output == undefined) output = [];
  if (times < 0) {
    return [];
  } else if (times == 0) {
    return output;
  } else {
    console.log(output, typeof output);
    output.push(number);
    return replicate(times - 1, number, output);
  }
}


问:
cmake + swig + dependicies
Today I tried to use combination of "cmake + swig" to generate bindings for my code. Basically it works:

```<code>set(SWIG_EXECUTABLE "/usr/bin/swig")
find_package(SWIG REQUIRED)
include(${CMAKE_CURRENT_SOURCE_DIR}/UseSWIG.cmake)

set(CMAKE_SWIG_FLAGS -package example)
set(CMAKE_SWIG_OUTDIR "${CMAKE_CURRENT_SOURCE_DIR}/example")
set_source_files_properties(native.i PROPERTIES CPLUSPLUS ON)
SWIG_ADD_MODULE(core Java native.i lib.cpp)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
</code>```

with such native.i:

```<code>%module native
%include "lib.hpp"
%{
#include "lib.hpp"
  %}
</code>```

But if I change lib.hpp build system cmake build not call swig to regenerate code. So I have to touch native.i to get it works, this is very annoying.

I found -M option of swig to generate dependencies,
Is any idea how use it to fix UseSWIG.cmake?

UseSWIG.cmake just uses add_custom_command for generation,
so I need somehow add_custom_command depend on dynamic set of files,
not static?

答:
I believe that I have found a solution to your request.

I am currently using a solution, where all relevant dependencies are added such that SWIG re-generates the interface, whenever any of the headers parsed are modified.

The idea is to make a custom target, which touch a dummy file in addition to deleting the generated interface file. I have put the solution below for a project named fnm with a wrapper swig_fnm.

```<code># Method to make swig_fnm.i depend on input headers
execute_process(COMMAND swig -M -python -c++  -I${CMAKE_CURRENT_BINARY_DIR}/.. -I${CMAKE_CURRENT_SOURCE_DIR}/.. swig_fnm.i
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  OUTPUT_VARIABLE swig_deps
  INPUT_FILE swig_fnm.i)
# Match all lines except the first one until " \"
string(REGEX MATCHALL "\n  [^ ]+" temp ${swig_deps})

# Valid dependency extensions
set(valid_ext .h .hpp)

# Dependency list
set(swig_deps_actual)
foreach(t ${temp})
  string(STRIP "${t}" t)

  # Add to dependency list
  if (EXISTS "${t}")
    set(filter)
    get_filename_component(filter "${t}" EXT)
    if (";${valid_ext};" MATCHES ";${filter};")
      set(swig_deps_actual ${swig_deps_actual} "${t}")
    endif()
  endif()
endforeach()

# This makes configure run again, but does not regenerate the SWIG interface.
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${swig_deps_actual})

# All headers except for the single .i file are ignored
swig_add_module(swig_fnm python swig_fnm.i ${swig_fnm_HEADERS} ${swig_deps_actual})

# Removes generated file (if any of the dependent files are changed)
add_custom_command(
  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/swig.stamp
  COMMAND ${CMAKE_COMMAND} -E remove ${swig_generated_file_fullname}
  COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/swig.stamp
  DEPENDS ${swig_deps_actual} # The dependent files
  COMMENT "Removing old SWIG generated file" VERBATIM)

# Custom target for establishing dependency
add_custom_target(
  swigtrick
  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/swig.stamp)

# Dependency
add_dependencies(_swig_fnm swigtrick)
</code>```

Title: cmake + swig + dependicies

Body:
Today I tried to use combination of "cmake + swig" to generate bindings for my code. Basically it works:

set(SWIG_EXECUTABLE "/usr/bin/swig")
find_package(SWIG REQUIRED)
include(${CMAKE_CURRENT_SOURCE_DIR}/UseSWIG.cmake)

set(CMAKE_SWIG_FLAGS -package example)
set(CMAKE_SWIG_OUTDIR "${CMAKE_CURRENT_SOURCE_DIR}/example")
set_source_files_properties(native.i PROPERTIES CPLUSPLUS ON)
SWIG_ADD_MODULE(core Java native.i lib.cpp)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})

with such native.i:

%module native
%include "lib.hpp"
%{
#include "lib.hpp"
  %}

But if I change lib.hpp build system cmake build not call swig to regenerate code. So I have to touch native.i to get it works, this is very annoying.

I found -M option of swig to generate dependencies,
Is any idea how use it to fix UseSWIG.cmake?

UseSWIG.cmake just uses add_custom_command for generation,
so I need somehow add_custom_command depend on dynamic set of files,
not static?

Body:
I believe that I have found a solution to your request.

I am currently using a solution, where all relevant dependencies are added such that SWIG re-generates the interface, whenever any of the headers parsed are modified.

The idea is to make a custom target, which touch a dummy file in addition to deleting the generated interface file. I have put the solution below for a project named fnm with a wrapper swig_fnm.

# Method to make swig_fnm.i depend on input headers
execute_process(COMMAND swig -M -python -c++  -I${CMAKE_CURRENT_BINARY_DIR}/.. -I${CMAKE_CURRENT_SOURCE_DIR}/.. swig_fnm.i
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  OUTPUT_VARIABLE swig_deps
  INPUT_FILE swig_fnm.i)
# Match all lines except the first one until " \"
string(REGEX MATCHALL "\n  [^ ]+" temp ${swig_deps})

# Valid dependency extensions
set(valid_ext .h .hpp)

# Dependency list
set(swig_deps_actual)
foreach(t ${temp})
  string(STRIP "${t}" t)

  # Add to dependency list
  if (EXISTS "${t}")
    set(filter)
    get_filename_component(filter "${t}" EXT)
    if (";${valid_ext};" MATCHES ";${filter};")
      set(swig_deps_actual ${swig_deps_actual} "${t}")
    endif()
  endif()
endforeach()

# This makes configure run again, but does not regenerate the SWIG interface.
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${swig_deps_actual})

# All headers except for the single .i file are ignored
swig_add_module(swig_fnm python swig_fnm.i ${swig_fnm_HEADERS} ${swig_deps_actual})

# Removes generated file (if any of the dependent files are changed)
add_custom_command(
  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/swig.stamp
  COMMAND ${CMAKE_COMMAND} -E remove ${swig_generated_file_fullname}
  COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/swig.stamp
  DEPENDS ${swig_deps_actual} # The dependent files
  COMMENT "Removing old SWIG generated file" VERBATIM)

# Custom target for establishing dependency
add_custom_target(
  swigtrick
  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/swig.stamp)

# Dependency
add_dependencies(_swig_fnm swigtrick)


答:
You can try with something like this </p>

```<code>select m.OrderId, sum(m.amount)
from master m
join detail d
on m.OrderId = d.OrderId
join tempDetail td
on m.OrderId = td.OrderId
where m.ItemQty = 3
group by m.OrderId
having sum(d.Qty * d.Price) = sum(td.Qty * td.Price)
</code>```

Title: SQL Server - Master / Detail - get extract exact detail item match

Body:
I need help to extract the exact item match from two table. I want from Detail Table  all the order that exists in Temp Detail and Master and Temp Master itemQty are the same.

example: in this case I need the sum of master.Amount for all the order which ItemQty is 3 and the detail table has the exact same value of temp Detail.

Master

OrderId|      Amount   | ItemQty |Status
------------------------------------------
125    |       36.75   |    3    |  A    |
------------------------------------------
128    |       11.95   |    5    |  A    |
------------------------------------------

Detail contain lot of order detail

------------------------------------------
OrderId|  ItemId    |  Qty  | Price      |
------------------------------------------
125    |     12345 |  1   |  11.00      |
------------------------------------------
125    |     23456 |  1   |  12.75      |
------------------------------------------
125    |     34567 |  1   |  13.00      |
------------------------------------------

Temp Master

------------------------------------------
|OrderId|      Amount   | ItemQty |Status
------------------------------------------
|9999   |       36.75   |    3    |  A   |
------------------------------------------

Temp Detail

------------------------------------------
|OrderId |  ItemId  |  Qty | Price       |
------------------------------------------
| 9999   |   12345 |    1 |   11.00      |
------------------------------------------
| 9999   |   23456 |    1 |   12.75      |
------------------------------------------
| 9999   |   34567 |    1 |   13.00      |
------------------------------------------

thank you in advance

Body:
You can try with something like this

select m.OrderId, sum(m.amount)
from master m
join detail d
on m.OrderId = d.OrderId
join tempDetail td
on m.OrderId = td.OrderId
where m.ItemQty = 3
group by m.OrderId
having sum(d.Qty * d.Price) = sum(td.Qty * td.Price)


问:
How to merge two arrays using PHP
I am really confused about merging two arrays, if this is really called merging or recursive mode. I have seen some examples before, but I didn't really understand how to get the results i needed.

```<code>$arrays = array('A1','A2','A3');
$result = array('B1','B2','B3');
</code>```

I wanted to get something like A1 B1, A1 B2, A1 B3. Then A2 B1, A2 B2, A2 B3, then A3 B1, A3 B2, A3 B3, but i don't really seem to understand how this is supposed to be done.
I found this code online

```<code>function get_combinations($arrays) {
    $result = array(array());
    foreach ($arrays as $property => $property_values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($property_values as $property_key => $property_value) {
                $tmp[] = $result_item + array($property_key => $property_value);
            }
        }
        $result = $tmp;
    }
    return $result;
}
</code>```

I tried changing some values in it, but it didn't work for me, because i don't know how to make something like this in the example. Please forgive me if there is a duplicate somewhere, I just don't know how to make it work. Any help will be appreciated.

Answer:
Ok guys, thanks to you all, I was really able to make it work. I wasn't able to Answer it in a normal way due to some limitations in my account. Thanks to chris85 for his example. It works great. I was able to store these values into an array. This is my code:

```<code>$arrays = array('A1','A2','A3');
$result = array('B1','B2','B3');
$myarray = array();

    foreach($arrays as $value) {
    foreach($result as $value2){
    $myarray[] = $value . $value2;
         }
    }
        print_r ($myarray);
</code>```

答:
```<code><?php

$array1 = array('A1','A2','A3');
$array2 = array('B1','B2','B3');
foreach($array1 as $val1) {
    foreach($array2 as $val2)echo $val1.$val2. " ";
    echo "\n";
}

Output:

A1B1 A1B2 A1B3
A2B1 A2B2 A2B3
A3B1 A3B2 A3B3
</code>```

Title: How to merge two arrays using PHP

Body:
I am really confused about merging two arrays, if this is really called merging or recursive mode. I have seen some examples before, but I didn't really understand how to get the results i needed.

$arrays = array('A1','A2','A3');
$result = array('B1','B2','B3');

I wanted to get something like A1 B1, A1 B2, A1 B3. Then A2 B1, A2 B2, A2 B3, then A3 B1, A3 B2, A3 B3, but i don't really seem to understand how this is supposed to be done.
I found this code online

function get_combinations($arrays) {
    $result = array(array());
    foreach ($arrays as $property => $property_values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($property_values as $property_key => $property_value) {
                $tmp[] = $result_item + array($property_key => $property_value);
            }
        }
        $result = $tmp;
    }
    return $result;
}

I tried changing some values in it, but it didn't work for me, because i don't know how to make something like this in the example. Please forgive me if there is a duplicate somewhere, I just don't know how to make it work. Any help will be appreciated.

Answer:
Ok guys, thanks to you all, I was really able to make it work. I wasn't able to Answer it in a normal way due to some limitations in my account. Thanks to chris85 for his example. It works great. I was able to store these values into an array. This is my code:

$arrays = array('A1','A2','A3');
$result = array('B1','B2','B3');
$myarray = array();

    foreach($arrays as $value) {
    foreach($result as $value2){
    $myarray[] = $value . $value2;
         }
    }
        print_r ($myarray);


问:
Microsoft Hololens Spatial Mapping Surface Differentiation
I am wondering about the capabilities of the HoloLens to differentiate between surfaces. More specifically, I would like to know what type of surface the user is gazing at, be it a horizontal surface (i.e. a table top, floor, ceiling) or a vertical surface (i.e. walls). I am wondering if there is any built in function in detecting this or how I can go about implementing one -which I am not too sure of where to start. (I have been googling for quite a while now to no avail.)</p>

答:
The other ideas will work, but are missing the point of what Microsoft has provided.  You should use either the HoloToolkit (Direct3d / C++) or the HoloToolkit for Unity (Unity3d / C#).

https://github.com/microsoft/HoloToolkit

https://github.com/microsoft/HoloToolkit-Unity

Each of these have the concepts of

SpatialMapping + PlaneFinding:

https://github.com/Microsoft/HoloToolkit-Unity/tree/master/Assets/HoloToolkit/SpatialMapping

https://github.com/Microsoft/HoloToolkit/tree/master/SpatialMapping/PlaneFinding

and

SpatialMapping + SpatialUnderstanding:

https://github.com/Microsoft/HoloToolkit-Unity/tree/master/Assets/HoloToolkit/SpatialUnderstanding

https://github.com/Microsoft/HoloToolkit/tree/master/SpatialUnderstanding/Src

Plane Finding will do what you are looking for, but Spatial Understanding may provide a level of sophistication that helps you better accomplish your goals. Either way, work smart and use the SDK's Microsoft has provided.


问:
WPF Toolkit Pie Chart Not Displaying
I am trying to display a Pie Chart in WPF using the WPF Toolkit (System.Windows.Controls.DataVisualization.Toolkit.dll)

The Chart itself is created by doind this in my XAML:

```<code><DVC:Chart BorderThickness="0" Title="Arbeitsverteilung" Grid.Column="0" Grid.Row="0" Background="Teal" x:Name="workDist" >
  <DVC:Chart.Series>
    <DVC:PieSeries
      IndependentValuePath="Key"
      DependentValuePath="Value"
      VerticalAlignment="Top"
      HorizontalAlignment="Stretch"/>
  </DVC:Chart.Series>
</DVC:Chart>
</code>```

and I set the DataSource with the following Method:

```<code>private void LoadData()
{
  ((PieSeries)workDist.Series[0]).ItemsSource =
    new KeyValuePair<string, int>[] {
      new KeyValuePair<string, int> ("Mario", 12),
      new KeyValuePair<string, int> ("Ahner", 14)};
}
</code>```

That seems to work pretty well with one problem:
It only displays the legend for the chart but not the chart itself:

I've already read a few tutorials but everyone did it exactly like I did and it worked fine.

Would be nice if someone could help me!

答:
Take out the top vertical alignment:

```<code>    <DVC:Chart BorderThickness="0" Title="Arbeitsverteilung" Grid.Column="0" Grid.Row="0" Background="Teal" x:Name="workDist" >
        <DVC:Chart.Series>
            <DVC:PieSeries
                IndependentValuePath="Key"
                DependentValuePath="Value"
                HorizontalAlignment="Stretch"
                />
        </DVC:Chart.Series>
    </DVC:Chart>
</code>```

Title: WPF Toolkit Pie Chart Not Displaying

Body:
I am trying to display a Pie Chart in WPF using the WPF Toolkit (System.Windows.Controls.DataVisualization.Toolkit.dll)

The Chart itself is created by doind this in my XAML:

<DVC:Chart BorderThickness="0" Title="Arbeitsverteilung" Grid.Column="0" Grid.Row="0" Background="Teal" x:Name="workDist" >
  <DVC:Chart.Series>
    <DVC:PieSeries
      IndependentValuePath="Key"
      DependentValuePath="Value"
      VerticalAlignment="Top"
      HorizontalAlignment="Stretch"/>
  </DVC:Chart.Series>
</DVC:Chart>

and I set the DataSource with the following Method:

private void LoadData()
{
  ((PieSeries)workDist.Series[0]).ItemsSource =
    new KeyValuePair<string, int>[] {
      new KeyValuePair<string, int> ("Mario", 12),
      new KeyValuePair<string, int> ("Ahner", 14)};
}

That seems to work pretty well with one problem:
It only displays the legend for the chart but not the chart itself:

I've already read a few tutorials but everyone did it exactly like I did and it worked fine.

Would be nice if someone could help me!

Body:
Take out the top vertical alignment:

    <DVC:Chart BorderThickness="0" Title="Arbeitsverteilung" Grid.Column="0" Grid.Row="0" Background="Teal" x:Name="workDist" >
        <DVC:Chart.Series>
            <DVC:PieSeries
                IndependentValuePath="Key"
                DependentValuePath="Value"
                HorizontalAlignment="Stretch"
                />
        </DVC:Chart.Series>
    </DVC:Chart>


答:
Your purpose is not suitable for 1-dimensional array. You must use pairs or 2-dimensional array as result. Your desired operation is really Cartesian product.</p>

```<code>$arrays = array('A1','A2','A3');
$result = array('B1','B2','B3');
$i=0;
foreach($arrays as $value1)
  foreach($result as $value2)
    {
    $final[$i][1]=$value1;
    $final[$i][2]=$value2;
    $i++;
    }
</code>```

Title: How to merge two arrays using PHP

Body:
Your purpose is not suitable for 1-dimensional array. You must use pairs or 2-dimensional array as result. Your desired operation is really Cartesian product.

$arrays = array('A1','A2','A3');
$result = array('B1','B2','B3');
$i=0;
foreach($arrays as $value1)
  foreach($result as $value2)
    {
    $final[$i][1]=$value1;
    $final[$i][2]=$value2;
    $i++;
    }


问:
Using list comprehension to store the maximum seen value
Is it possible to do the below with list comprehension? Trying to store the maximum value that has been seen at any given point through the loop.</p>

```<code>def test(input):
    a = input[0]
    b = []
    for i in input:
        a = max(i,a)
        b.append(a)
    return b

print test([-5,6,19,4,5,20,1,30])

# returns [-5, 6, 19, 19, 19, 20, 20, 30]
</code>```

答:
If using NumPy is permitted, then you can use NumPy:</p>

```<code>import numpy as np
np.maximum.accumulate([-5,6,19,4,5,20,1,30])
# array([-5,  6, 19, 19, 19, 20, 20, 30])
</code>```

Body:
Is it possible to do the below with list comprehension? Trying to store the maximum value that has been seen at any given point through the loop.

def test(input):
    a = input[0]
    b = []
    for i in input:
        a = max(i,a)
        b.append(a)
    return b

print test([-5,6,19,4,5,20,1,30])

# returns [-5, 6, 19, 19, 19, 20, 20, 30]

Body:
If using NumPy is permitted, then you can use NumPy:

import numpy as np
np.maximum.accumulate([-5,6,19,4,5,20,1,30])
# array([-5,  6, 19, 19, 19, 20, 20, 30])


问:
jQuery .submit problem
I'm having a little problem with jQuery:
I'm having .submit() defined on a form, when I submit the form by clicking the submit button, the even triggers and things works smoothly, however, when I use document.forms[0].submit(), the event doesn't get triggered, but the form submits!! Is there any reason why? How can I overcome that?

答: There are some of us out here that are forced to use code from legacy systems. These systems are non-compliant, and in my case awaiting to be upgraded. But when several thousands of people are using the system, it's just not possible to go in and change code to baseline packages. So, we are forced to find workarounds. In my case, the forms do not have IDs or names, so using document.forms[0].submit() is one of the only options.

ContentLicense: CC BY-SA 2.5

Title: jQuery .submit problem


答:
You can use itertools.accumulate with the max builtin in Python 3:

```<code>from itertools import accumulate

lst = [-5,6,19,4,5,20,1,30]
r = list(accumulate(lst, max)) #[i for i in accumulate(lst, max)]
print(r)
# [-5, 6, 19, 19, 19, 20, 20, 30]
</code>```

Title: Using list comprehension to store the maximum seen value

Body:
You can use itertools.accumulate with the max builtin in Python 3:

from itertools import accumulate

lst = [-5,6,19,4,5,20,1,30]
r = list(accumulate(lst, max)) #[i for i in accumulate(lst, max)]
print(r)
# [-5, 6, 19, 19, 19, 20, 20, 30]


问:
Run JavaScript command on website
I have a home automation system which has a small Linux server and an app to control my lighting system. The problem is that this system is too limited for my use, so I wanted to create a desktop app (Java or C#) to send my own data to the server.

When I log into the webpage, I can just use FireFox' JavaScript console to send the commands. But my question is how I can log into a webpage and send JavaScript data to it programmatically.

I also tried sending the data through a WebSocket or TcpClient, but I have no idea how that works.

答: You just have to perform the same requests than the browser when you are on the website, that is (most probably) HTTP GET and HTTP POST. It is possible to send the request with any programming language, including JavaScript.</p>

Title: Run JavaScript command on website