问:
SQL Column search.. then use that as table
Fairly rusty in my SQL.. what I am looking for is to start by searching all my tables for a given column

```<code>SELECT @myTables = TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myColumn%'
</code>```

Then I would like to use the results and run a search like so for every record

```<code>select * from @myTables[0]
select * from @myTables[1]
</code>```

....

and so on.. I hope I am clear in describing what I am looking for.

Thank you for your help.

答:
```<code>    SELECT 'SELECT * FROM '+ TABLE_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME LIKE '%myColumn%'
</code>```

This Query will return all select Queries you are expecting.

if you want to get the result of those select query:

```<code>    DECLARE @SQLQuery VARCHAR(MAX)

    SELECT @SQLQuery = COALESCE(@SQLQuery,'')+'SELECT * FROM '+ TABLE_NAME+';'
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME LIKE '%myColumn%'

    SELECT @SQLQuery

    EXEC (@SQLQuery)
</code>```

Body:
Fairly rusty in my SQL.. what I am looking for is to start by searching all my tables for a given column

SELECT @myTables = TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myColumn%'

Then I would like to use the results and run a search like so for every record

select * from @myTables[0]
select * from @myTables[1]

....

and so on.. I hope I am clear in describing what I am looking for.

Thank you for your help.

Body:
    SELECT 'SELECT * FROM '+ TABLE_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME LIKE '%myColumn%'

This Query will return all select Queries you are expecting.

if you want to get the result of those select query:

    DECLARE @SQLQuery VARCHAR(MAX)

    SELECT @SQLQuery = COALESCE(@SQLQuery,'')+'SELECT * FROM '+ TABLE_NAME+';'
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME LIKE '%myColumn%'

    SELECT @SQLQuery

    EXEC (@SQLQuery)


来源: stackexchange

问:
How to delete the last group in every line JAVA
If i have this group of lines:

```<code>812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100
</code>```

I want to delete the last group after the last space how can I do it.
I had code like this but it didn't work so I need help:

```<code> for(int i=0;i<=lines.length-1; i++){
    // get index of the last space
    int index = lines[i].lastIndexOf(" ");

    // remove everything after the last space
    lines[i] = lines[i].substring(0, index);
}
</code>```

The result should be like that:

```<code>812.12 135.14 646.17
812.12 135.14 646.18
812.12 135.14 646.19
812.12 135.14 646.20
812.12 135.14 646.21
812.12 135.14 646.22
</code>```

答:
```<code>import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

    String[] input=new String[2];
    input[0]="812.12 135.14 646.17 1";
    input[1]="812.12 135.14 646.21 100";

    String s;
    int x;

    for(int i=0;i<input.length;i++)
    {
        s=input[i];
        x=s.length();
        x=x-1;

        while(s.charAt(x)!=' ') /*Iterated from the last character of the string till we get a space*/
            x--;

        s=s.substring(0,x); /*Used the index of last space from above to cut out a substring from 0th index till the index of last space*/
        input[i]=s;
    }

    System.out.println(input[0]+"\n"+input[1]);

    }
}
</code>```

Here is the working demo of what you wanted. I have explained the code in comments, please read it to understand the code.

ContentLicense: CC BY-SA 3.0

Body:
If i have this group of lines:

812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100

I want to delete the last group after the last space how can I do it.
I had code like this but it didn't work so I need help:

 for(int i=0;i<=lines.length-1; i++){
    // get index of the last space
    int index = lines[i].lastIndexOf(" ");

    // remove everything after the last space
    lines[i] = lines[i].substring(0, index);
}

The result should be like that:

812.12 135.14 646.17
812.12 135.14 646.18
812.12 135.14 646.19
812.12 135.14 646.20
812.12 135.14 646.21
812.12 135.14 646.22

Body:
import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

    String[] input=new String[2];
    input[0]="812.12 135.14 646.17 1";
    input[1]="812.12 135.14 646.21 100";

    String s;
    int x;

    for(int i=0;i<input.length;i++)
    {
        s=input[i];
        x=s.length();
        x=x-1;

        while(s.charAt(x)!=' ') /*Iterated from the last character of the string till we get a space*/
            x--;

        s=s.substring(0,x); /*Used the index of last space from above to cut out a substring from 0th index till the index of last space*/
        input[i]=s;
    }

    System.out.println(input[0]+"\n"+input[1]);

    }
}

Here is the working demo of what you wanted. I have explained the code in comments, please read it to understand the code.


问:
Can I find the cursor's pixel position in a ContentEditable?
I mean finding the top/left pixel position of the cursor, rather than the character offset.

The reason I want to do this is because I want to show a small tooltip-like div next to the cursor (think of the newer MS Word's floating formatting box) that follows the cursor as you type or click. I can use the mouse coordinates if the user clicks, but not sure how to do this for typing.

Is there a reliable way? If not for finding the top/left position of the cursor, then the alternative is to just find the top position for the line.

Sample code isn't 100% necessary, as long as the method works and is well-explained.

答:
try this

```<code>var cursorY = window.getSelection().getRangeAt(0).getBoundingClientRect().top;
</code>```

cursorY is the cursor Y position in window.

A Selection object represents the range of text selected by the
  user or the current position of the caret.

Selection.getRangeAt() return a range object representing one of
  the ranges currently selected.

ContentLicense: CC BY-SA 2.5

Body:
try this

var cursorY = window.getSelection().getRangeAt(0).getBoundingClientRect().top;

cursorY is the cursor Y position in window.

A Selection object represents the range of text selected by the
  user or the current position of the caret.

Selection.getRangeAt() return a range object representing one of
  the ranges currently selected.


问:
jQuery autocomplete - need to initiate only when a special character is typed
I'm sure you guys have seen this excellent plugin:

http://code.drewwilson.com/entry/autosuggest-jquery-plugin

I checked it out and could not find an option to initiate the autosuggest plugin only when a specific character is typed. In this case I need it to be the at sign '@'.

I see it has the option to set a minimum number of characters:
minChars: number (1 by default)

However, I need for the dropdown to NOT show until the @ sign is typed.

FYI, here are the options in jquery.autoSuggest.js

```<code>        var defaults = {
        asHtmlID: false,
        startText: "Enter Name Here",
        emptyText: "No Results Found",
        preFill: {},
        limitText: "No More Selections Are Allowed",
        selectedItemProp: "value", //name of object property
        selectedValuesProp: "value", //name of object property
        searchObjProps: "value", //comma separated list of object property names
        queryParam: "q",
        retrieveLimit: false, //number for 'limit' param on ajax request
        extraParams: "",
        matchCase: false,
        minChars: 1,
        keyDelay: 400,
        resultsHighlight: true,
        neverSubmit: false,
        selectionLimit: false,
        showResultList: true,
        start: function(){},
        selectionClick: function(elem){},
        selectionAdded: function(elem){},
        selectionRemoved: function(elem){ elem.remove(); },
        formatList: false, //callback function
        beforeRetrieve: function(string){ return string; },
        retrieveComplete: function(data){ return data; },
        resultClick: function(data){},
        resultsComplete: function(){}
    };
    var opts = $
</code>```

Thanks!

答:
I think you can play with beforeRetrieve:

```<code>beforeRetrieve: function(string){
 if (string.indexOf('@') == -1) return "";
 return string;
}
</code>```

From the doc:

beforeRetrieve: callback function - Custom function that is run right before the AJAX request is made, or before the local objected is searched. This is used to modify the search string before it is processed. So if a user entered "jim" into the AutoSuggest box, you can call this function to prepend their query with "guy_". Making the final query = "guy_jim". The search query is passed into this function. Example: beforeRetrieve: function(string){ return string; }

Body:
I'm sure you guys have seen this excellent plugin:

http://code.drewwilson.com/entry/autosuggest-jquery-plugin

I checked it out and could not find an option to initiate the autosuggest plugin only when a specific character is typed. In this case I need it to be the at sign '@'.

I see it has the option to set a minimum number of characters:
minChars: number (1 by default)

However, I need for the dropdown to NOT show until the @ sign is typed.

FYI, here are the options in jquery.autoSuggest.js

        var defaults = {
        asHtmlID: false,
        startText: "Enter Name Here",
        emptyText: "No Results Found",
        preFill: {},
        limitText: "No More Selections Are Allowed",
        selectedItemProp: "value", //name of object property
        selectedValuesProp: "value", //name of object property
        searchObjProps: "value", //comma separated list of object property names
        queryParam: "q",
        retrieveLimit: false, //number for 'limit' param on ajax request
        extraParams: "",
        matchCase: false,
        minChars: 1,
        keyDelay: 400,
        resultsHighlight: true,
        neverSubmit: false,
        selectionLimit: false,
        showResultList: true,
        start: function(){},
        selectionClick: function(elem){},
        selectionAdded: function(elem){},
        selectionRemoved: function(elem){ elem.remove(); },
        formatList: false, //callback function
        beforeRetrieve: function(string){ return string; },
        retrieveComplete: function(data){ return data; },
        resultClick: function(data){},
        resultsComplete: function(){}
    };
    var opts = $

Thanks!

Body:
I think you can play with beforeRetrieve:

beforeRetrieve: function(string){
 if (string.indexOf('@') == -1) return "";
 return string;
}

From the doc:

beforeRetrieve: callback function - Custom function that is run right before the AJAX request is made, or before the local objected is searched. This is used to modify the search string before it is processed. So if a user entered "jim" into the AutoSuggest box, you can call this function to prepend their query with "guy_". Making the final query = "guy_jim". The search query is passed into this function. Example: beforeRetrieve: function(string){ return string; }


问:
Unable to save and restore a trained TensorFlow Model
I just read the Deep MNIST for Experts tutorial and modified the  mnist_deep.py code to save the trained model using
saver = tf.train.Saver() before creating the session and
saver.save(sess, './mnist_deep_model', global_step=2000) after the for loop training the model. It appears to be correctly saved since I got the four following files in my working folder:

checkpoint

mnist_deep_model-2000.data-00000-of-00001

mnist_deep_model-2000.indexs

mnist_deep_model-2000.meta

I also modified the mnist_deep.py adding the two following functions to be able to test the model on individual test images, one by one:

```<code>def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)
</code>```

I also added at the end of the main function a loop in which I randomly choose one test image in the test set and try to apply the trained model to each of them with this function. It seems to work since I get the same accuracy in this test loop: 99.2%

Then I wrote a second program: mnist_deep_restore_trained_model.py (also based on the mnist_deep.py source code) trying to restore the previously saved trained model and apply test images to it expecting to get the same accuracy.

Of course, I removed of this program all the code required to create, train and test the model (the deepnn() function and all related functions, tensors creation: x = tf.placeholder(tf.float32, [None, 784]), y_conv, keep_prob = deepnn(x), loss, optimizer, and accuracy stuff...) and I simply restored the saved model this way: (once the session is open)

```<code>saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
</code>```

I also removed the global variables initialization at the beginning of the session since the values of the global variables should have been restored from the trained model:

But, to be able to apply the model in order to identify the digit of a given test image (cf function identifyDigitInImage(sess, x, y_conv, keep_prob, image)), I still need to get the Tensor variables x, y_conv and keep_prob. So I added the following lines after having restored the model from disk:

```<code>graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
y_conv = graph.get_tensor_by_name("y_conv:0")
</code>```

Finally, I also added at the end of this second program the same test loop as in the mnist_deep.py expecting to get the same results from this restored model...

Unfortunately, I get an exception on the first call to get_tensor_by_name():

```<code>x = graph.get_tensor_by_name("x:0")
KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."
</code>```

The other get_tensor_by_name() calls would also raise this same exception.

What am I doing wrong ? Why is that not possible to get these Tensors this way ?

Here is my full mnist_deep.py source code:

```<code># Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

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

import argparse
import sys
import tempfile
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  #graph_location = tempfile.mkdtemp()
  #print('Saving graph to: %s' % graph_location)
  #train_writer = tf.summary.FileWriter(graph_location)
  #train_writer.add_graph(tf.get_default_graph())

  # Prepare a saver to save the trained model:
  saver = tf.train.Saver()

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Save the untrained model:
    saver.save(sess, './mnist_deep_model')

    # Train the model:
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    # Save the trained model:
    saver.save(sess, './mnist_deep_model', global_step=2000)

    # Display the test accuracy:
    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
        # Choosing a test image index:
        test_image_index = random.randint(0, len(mnist.test.images) - 1)
        test_image = mnist.test.images[test_image_index]

        # Applying the trained model to identify the digit from the test image:
        identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

        # Display the identified digit:
        print("The written digit on the given image has been identified as a {}".format(identified_digit))

        # Check the expected_digit from the test label of the choosen test image:
        expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

        # Display the expected digit:
        print("Actually, the digit is a {}".format(expected_digit))

        # Count the correctly identified digits:
        if identified_digit == expected_digit:
            ok_count += 1

        # Stop the loop after 10000 iterations
        count += 1
        stop = count == 10000

        # Display the measured accuracy during the test loop:
    print("2nd Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

And here my full mnist_deep_restore_trained_model.py source code:

```<code># Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

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

import argparse
import sys
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  with tf.Session() as sess:

    # Restoring the trained model previously saved:
    saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # Trying to get back some required tensors variables from the restored graph:
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("x:0")
    # This call fails with the following exception:
    # KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."
    keep_prob = graph.get_tensor_by_name("keep_prob:0")
    y_conv = graph.get_tensor_by_name("y_conv:0")

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
      # Choosing a test image index:
      test_image_index = random.randint(0, len(mnist.test.images) - 1)
      test_image = mnist.test.images[test_image_index]

      # Applying the trained model to identify the digit from the test image:
      identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

      # Display the identified digit:
      print("The written digit on the given image has been identified as a {}".format(identified_digit))

      # Check the expected_digit from the test label of the choosen test image:
      expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

      # Display the expected digit:
      print("Actually, the digit is a {}".format(expected_digit))

      # Count the correctly identified digits:
      if identified_digit == expected_digit:
        ok_count += 1

      # Stop the loop after 10000 iterations
      count += 1
      stop = count == 10000

    # Display the measured accuracy during the test loop:
    print("Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

答:
You didn't give explicit names to your placeholders:

# Create the model
x = tf.placeholder(tf.float32, [None, 784])

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
```

<p>... as a result, they are named <code>Placeholder</code> and <code>Placeholder_1</code> in the saved graph, hence the error. Change this code to:</p>

<pre class="lang-py prettyprint-override"><code># Create the model
x = tf.placeholder(tf.float32, [None, 784], name='x')

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10], name='y')
</code>```

... and likewise for keep_prob and y_conv (use tf.add to give a name to the + op). By the way, it's always a good idea to name all your variables and key operations and also use scopes. After you retrain the model, your mnist_deep_restore_trained_model.py should work.

Body:
I just read the Deep MNIST for Experts tutorial and modified the  mnist_deep.py code to save the trained model using
saver = tf.train.Saver() before creating the session and
saver.save(sess, './mnist_deep_model', global_step=2000) after the for loop training the model. It appears to be correctly saved since I got the four following files in my working folder:

checkpoint

mnist_deep_model-2000.data-00000-of-00001

mnist_deep_model-2000.indexs

mnist_deep_model-2000.meta

I also modified the mnist_deep.py adding the two following functions to be able to test the model on individual test images, one by one:

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

I also added at the end of the main function a loop in which I randomly choose one test image in the test set and try to apply the trained model to each of them with this function. It seems to work since I get the same accuracy in this test loop: 99.2%

Then I wrote a second program: mnist_deep_restore_trained_model.py (also based on the mnist_deep.py source code) trying to restore the previously saved trained model and apply test images to it expecting to get the same accuracy.

Of course, I removed of this program all the code required to create, train and test the model (the deepnn() function and all related functions, tensors creation: x = tf.placeholder(tf.float32, [None, 784]), y_conv, keep_prob = deepnn(x), loss, optimizer, and accuracy stuff...) and I simply restored the saved model this way: (once the session is open)

saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))

I also removed the global variables initialization at the beginning of the session since the values of the global variables should have been restored from the trained model:

But, to be able to apply the model in order to identify the digit of a given test image (cf function identifyDigitInImage(sess, x, y_conv, keep_prob, image)), I still need to get the Tensor variables x, y_conv and keep_prob. So I added the following lines after having restored the model from disk:

graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
y_conv = graph.get_tensor_by_name("y_conv:0")

Finally, I also added at the end of this second program the same test loop as in the mnist_deep.py expecting to get the same results from this restored model...

Unfortunately, I get an exception on the first call to get_tensor_by_name():

x = graph.get_tensor_by_name("x:0")
KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."

The other get_tensor_by_name() calls would also raise this same exception.

What am I doing wrong ? Why is that not possible to get these Tensors this way ?

Here is my full mnist_deep.py source code:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

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

import argparse
import sys
import tempfile
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  #graph_location = tempfile.mkdtemp()
  #print('Saving graph to: %s' % graph_location)
  #train_writer = tf.summary.FileWriter(graph_location)
  #train_writer.add_graph(tf.get_default_graph())

  # Prepare a saver to save the trained model:
  saver = tf.train.Saver()

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Save the untrained model:
    saver.save(sess, './mnist_deep_model')

    # Train the model:
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    # Save the trained model:
    saver.save(sess, './mnist_deep_model', global_step=2000)

    # Display the test accuracy:
    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
        # Choosing a test image index:
        test_image_index = random.randint(0, len(mnist.test.images) - 1)
        test_image = mnist.test.images[test_image_index]

        # Applying the trained model to identify the digit from the test image:
        identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

        # Display the identified digit:
        print("The written digit on the given image has been identified as a {}".format(identified_digit))

        # Check the expected_digit from the test label of the choosen test image:
        expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

        # Display the expected digit:
        print("Actually, the digit is a {}".format(expected_digit))

        # Count the correctly identified digits:
        if identified_digit == expected_digit:
            ok_count += 1

        # Stop the loop after 10000 iterations
        count += 1
        stop = count == 10000

        # Display the measured accuracy during the test loop:
    print("2nd Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

And here my full mnist_deep_restore_trained_model.py source code:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

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

import argparse
import sys
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  with tf.Session() as sess:

    # Restoring the trained model previously saved:
    saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # Trying to get back some required tensors variables from the restored graph:
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("x:0")
    # This call fails with the following exception:
    # KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."
    keep_prob = graph.get_tensor_by_name("keep_prob:0")
    y_conv = graph.get_tensor_by_name("y_conv:0")

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
      # Choosing a test image index:
      test_image_index = random.randint(0, len(mnist.test.images) - 1)
      test_image = mnist.test.images[test_image_index]

      # Applying the trained model to identify the digit from the test image:
      identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

      # Display the identified digit:
      print("The written digit on the given image has been identified as a {}".format(identified_digit))

      # Check the expected_digit from the test label of the choosen test image:
      expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

      # Display the expected digit:
      print("Actually, the digit is a {}".format(expected_digit))

      # Count the correctly identified digits:
      if identified_digit == expected_digit:
        ok_count += 1

      # Stop the loop after 10000 iterations
      count += 1
      stop = count == 10000

    # Display the measured accuracy during the test loop:
    print("Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Body:
You didn't give explicit names to your placeholders:

# Create the model
x = tf.placeholder(tf.float32, [None, 784])

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])

... as a result, they are named Placeholder and Placeholder_1 in the saved graph, hence the error. Change this code to:

# Create the model
x = tf.placeholder(tf.float32, [None, 784], name='x')

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10], name='y')

... and likewise for keep_prob and y_conv (use tf.add to give a name to the + op). By the way, it's always a good idea to name all your variables and key operations and also use scopes. After you retrain the model, your mnist_deep_restore_trained_model.py should work.


问:
Switch Case statement for Regex matching in JavaScript
So I have a bunch of regexes and I try to see if they match with another string using this If statement:

if (samplestring.match(regex1)) {
  console.log("regex1");
} else if (samplestring.match(regex2)) {
  console.log("regex2");
} else if (samplestring.match(regex3)) {
  console.log("regex3");
}
```
<p>But as soon as I need to use more regexes this gets quite ugly so I want to use a switch case statement like this:</p>
<pre class="lang-js prettyprint-override"><code>switch(samplestring) {
  case samplestring.match(regex1): console.log("regex1");
  case samplestring.match(regex2): console.log("regex2");
  case samplestring.match(regex3): console.log("regex3");
}
</code>```

The problem is it doesn't work like I did it in the example above.
Any Ideas on how it could work like that?

答:
You need to use a different check, not with String#match, that returns an array or null which is not usable with strict comparison like in a switch statement.

You may use RegExp#test and check with true:

var regex1 = /a/,
    regex2 = /b/,
    regex3 = /c/,
    samplestring = 'b';

switch (true) {
    case regex1.test(samplestring):
        console.log("regex1");
        break;
    case regex2.test(samplestring):
        console.log("regex2");
        break;
    case regex3.test(samplestring):
        console.log("regex3");
        break;
}```

ContentLicense: CC BY-SA 4.0

Body:
So I have a bunch of regexes and I try to see if they match with another string using this If statement:

if (samplestring.match(regex1)) {
  console.log("regex1");
} else if (samplestring.match(regex2)) {
  console.log("regex2");
} else if (samplestring.match(regex3)) {
  console.log("regex3");
}

But as soon as I need to use more regexes this gets quite ugly so I want to use a switch case statement like this:

switch(samplestring) {
  case samplestring.match(regex1): console.log("regex1");
  case samplestring.match(regex2): console.log("regex2");
  case samplestring.match(regex3): console.log("regex3");
}

The problem is it doesn't work like I did it in the example above.
Any Ideas on how it could work like that?


问:
Get Folder Size from Windows Command Line
Is it possible in Windows to get a folder's size from the command line without using any 3rd party tool?

I want the same result as you would get when right clicking the folder in the windows explorer → properties.

答:
Try:

```<code>SET FOLDERSIZE=0
FOR /F "tokens=3" %A IN ('DIR "C:\Program Files" /a /-c /s ^| FINDSTR /C:" bytes" ^| FINDSTR /V /C:" bytes free"') DO SET FOLDERSIZE=%A
</code>```

Change C:\Program Files to whatever folder you want and change %A to %%A if using in a batch file

It returns the size of the whole folder, including subfolders and hidden and system files, and works with folders over 2GB

It does write to the screen, so you'll have to use an interim file if you don't want that.

Body:
Try:

SET FOLDERSIZE=0
FOR /F "tokens=3" %A IN ('DIR "C:\Program Files" /a /-c /s ^| FINDSTR /C:" bytes" ^| FINDSTR /V /C:" bytes free"') DO SET FOLDERSIZE=%A

Change C:\Program Files to whatever folder you want and change %A to %%A if using in a batch file

It returns the size of the whole folder, including subfolders and hidden and system files, and works with folders over 2GB

It does write to the screen, so you'll have to use an interim file if you don't want that.


问:
loading javascript function on start using javascript
I have this javascript function here for example:

```<code><script type="text/javascript">
  function onLoadFunctions() {
        //some funcitons here...
  }
</script>
</code>```

And I wanted to load this function when the page loads using only javascript.
Can anyone help me. thanks in advance.

答:
You have several options to do this:

You can add the event listener in Javascript.

```<code>window.addEventListener('load',myOnLoadFunction);
</code>```

Or if you want you can add the event listener at the html tag.

```<code><body onload="onLoadFunctions();">
</code>```

Update

You can read more about addEventListener here.

Body:
I have this javascript function here for example:

And I wanted to load this function when the page loads using only javascript.
Can anyone help me. thanks in advance.

Body:
You have several options to do this:

You can add the event listener in Javascript.

window.addEventListener('load',myOnLoadFunction);

Or if you want you can add the event listener at the html tag.

<body onload="onLoadFunctions();">

Update

You can read more about addEventListener here.


问:
Slick returns empty list when it should return an object
I have an ApiCall table. I am trying to ensure that for each api call, the appropriate token was used. In plain english, what I think I'm doing here is filtering on ApiCall by apiCallId, then taking headOption (there should only be one b/c apiCallId is unique), then mapping on that. For some reason though, this function returns an empty List()...

```<code>def apiCallMatchesToken(apiCallId: ApiCallId, token: String): Future[Boolean] = {

val tableQuery = ApiCalls.filter(_.apiCallId === apiCallId).result.headOption

database.tryRun(tableQuery).map({
  case (a: ApiCallRow) => if (a.token == token) { true } else { false }
  case _ => false
})

}
</code>```

I have double-checked that the apiCallId exists in my database. What's the issue?

答:
The most probable answer is that your Option[ApiCallRow] is wrapped into something added by tryRun function - it may be Try[Option[ApiCallRow]] or Future[Option[ApiCallRow]]. Try using using aflatMap` instead of a map or matching on an Option here:

database.tryRun(tableQuery).flatMap({
  case Some(a: ApiCallRow) => return Future.successful(a.token == token)
  case _ => Future.successful(false)
})

Body:
I have an ApiCall table. I am trying to ensure that for each api call, the appropriate token was used. In plain english, what I think I'm doing here is filtering on ApiCall by apiCallId, then taking headOption (there should only be one b/c apiCallId is unique), then mapping on that. For some reason though, this function returns an empty List()...

def apiCallMatchesToken(apiCallId: ApiCallId, token: String): Future[Boolean] = {

val tableQuery = ApiCalls.filter(_.apiCallId === apiCallId).result.headOption

database.tryRun(tableQuery).map({
  case (a: ApiCallRow) => if (a.token == token) { true } else { false }
  case _ => false
})

}

I have double-checked that the apiCallId exists in my database. What's the issue?


问:
AppSettings get value from .config file
I'm not able to access values in configuration file.

```<code>Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var clientsFilePath = config.AppSettings.Settings["ClientsFilePath"].Value;
// the second line gets a NullReferenceException
</code>```

.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>

    <add key="ClientsFilePath" value="filepath"/>

  </appSettings>
</configuration>
```

Do you have any suggestion what should I do?

答:
You can simply type:

```<code>string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];
</code>```

because key is an object and AppSettings takes a string

Title: AppSettings get value from .config file

Body:
I'm not able to access values in configuration file.

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var clientsFilePath = config.AppSettings.Settings["ClientsFilePath"].Value;
// the second line gets a NullReferenceException

.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>

    <add key="ClientsFilePath" value="filepath"/>

  </appSettings>
</configuration>

Do you have any suggestion what should I do?

Body:
You can simply type:

string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];

because key is an object and AppSettings takes a string


问:
How to get event target/this without putting the event listener in the HTML tag?
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use

$(document).ready(function(){})

I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?

//$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}</code>```

<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>```

Thanks in advance!

PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.

PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D

PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)

答:
This should work.</p>

```<code>//$(document).ready(function() {
  window.onload = startup();
  function startup() {
   console.log("window loaded");
    $("img").hide();
    $("button").click(function() {showImage(this)});
  }
  function showImage(e) {
    console.log("onside eras");
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});
</code>```

Body:
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use

$(document).ready(function(){})

I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?

//$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});

body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}

<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>

Thanks in advance!

PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.

PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D

PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)

Body:
This should work.

//$(document).ready(function() {
  window.onload = startup();
  function startup() {
   console.log("window loaded");
    $("img").hide();
    $("button").click(function() {showImage(this)});
  }
  function showImage(e) {
    console.log("onside eras");
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});


问:
OpenWrap vs NuGet
What is the difference between OpenWrap and NuGet. And what you prefer ?</p>

答:
Just wanted to chime in with some thoughts from the NuGet side of things. Seb leaves out a few details that are worth pointing out.

While our primary UI is VS based, the core NuGet assembly doesn't have any ties to VS. The ASP.NET Web Pages product has a web-based package manager. I wrote a blog post showing one example of using NuGet to build a website that updates itself at runtime. http://haacked.com/archive/2011/01/15/building-a-self-updating-site-using-nuget.aspx

NuGet provides a powerful PowerShell console. NuGet packages can add new commands to the console. See http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/. As before, this is one client to NuGet and NuGet core doesn't require it.

NuGet is available for install via the VS Extension Gallery and is very easy to get started with immediately.

NuGet supports pointing the client at a directory (or network share) containing a set of packages and automatically treats it as a repository. So if you don't want to deal with OData, you don't have to. But we also include an implementation of our gallery so there's no need to manually deal with OData/XML in any case.

NuGet doesn't require you to deploy any part of NuGet as part of your application. It stays hands off and is focused on automating the steps you would take without NuGet to acquire and deploy your dependencies. To be clear, as Seb points out, neither does OpenWrap. I just wanted to make it clear that NuGet doesn't require this as well.

Title: OpenWrap vs NuGet


问:
Input checked state does not affect css selector
So I've been trying to trigger my CSS selector via the checkbox state as you can see below but I've had no luck getting it to trigger. What should happen on click is the tick should simply disappear.

```<code>.i-cb input[type="checkbox"]:checked + label::before {
   display: none;
   width:0px;
   height: 0px;
}
</code>```

JSFiddle : https://jsfiddle.net/7tnepc8r/4/

答:
It's a problem with order.

You should change order your HTML.

The + selector is used to select elements that is placed immediately after(not inside) the first specified element.

.i-cb input[type=checkbox] {
  visibility: hidden;
}

.i-cb label {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 44px;
  border: 4px solid #48c8f1;
  border-radius: 50%;
  border-top-color: transparent;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  z-index: 0;
}

.i-cb label::before {
  content: "";
  position: absolute;
  width: 6px;
  height: 45px;
  background-color: #93c83d;
  left: 22px;
  top: -15px;
  z-index: 1;
}

.i-cb label::after {
  content: "";
  position: absolute;
  width: 18px;
  height: 6px;
  background-color: #93c83d;
  left: 10px;
  top: 24px;
  z-index: 1;
}

.i-cb input[type=checkbox]:checked + label::after {
  display: none !important;
  width: 0px !important;
  height: 0px !important;
}

.i-cb input[type=checkbox]:checked + label::before {
  display: none;
  width: 0px;
  height: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="i-cb">
  <input id="check" type="checkbox" />
  <label for="check"></label>
</div></code>```

Body:
So I've been trying to trigger my CSS selector via the checkbox state as you can see below but I've had no luck getting it to trigger. What should happen on click is the tick should simply disappear.

.i-cb input[type="checkbox"]:checked + label::before {
   display: none;
   width:0px;
   height: 0px;
}

JSFiddle : https://jsfiddle.net/7tnepc8r/4/

Body:
It's a problem with order.

You should change order your HTML.

The + selector is used to select elements that is placed immediately after(not inside) the first specified element.

.i-cb input[type=checkbox] {
  visibility: hidden;
}

.i-cb label {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 44px;
  border: 4px solid #48c8f1;
  border-radius: 50%;
  border-top-color: transparent;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  z-index: 0;
}

.i-cb label::before {
  content: "";
  position: absolute;
  width: 6px;
  height: 45px;
  background-color: #93c83d;
  left: 22px;
  top: -15px;
  z-index: 1;
}

.i-cb label::after {
  content: "";
  position: absolute;
  width: 18px;
  height: 6px;
  background-color: #93c83d;
  left: 10px;
  top: 24px;
  z-index: 1;
}

.i-cb input[type=checkbox]:checked + label::after {
  display: none !important;
  width: 0px !important;
  height: 0px !important;
}

.i-cb input[type=checkbox]:checked + label::before {
  display: none;
  width: 0px;
  height: 0px;
}

<div class="i-cb">
  <input id="check" type="checkbox" />
  <label for="check"></label>
</div>


问:
Call a method from a child view
I'm trying to make some changes to the code a colleague made.

So, I have a ShellView that loads documents (and shows them as its content) with a method defined in its ViewModel, and the child view, a StatusBarView which holds the path navigated in the documents and some other infos.

```<code>public class ShellViewModel
{
    public StatusBarViewModel StatusBar { get; }

    public ShellViewModel(StatusBarViewModel statusBarViewModel, ...)
    {
        StatusBar = statusBarViewModel;

        var keymap = new Keymap();
        keymap.Map("F2", new SimpleCommand("open-file",
                                           "Shows the open file dialog",
                                            param => OpenFile());

    }

    private void OpenFile()
    {
        // Logic to open the file that uses other methods
        // inside this VM to validate the file
    }
}
</code>```

At the moment you can load a new pack of documents pressing a key, I'd like to do the same with a button in the Status Bar and calling that method.

What is the proper way to call a method existing in the parent view from the child view?

答:
In your child view Define an event Handler

```<code>public EventHandler OpenFileHandler
</code>```

On the click of the button of your Status Bar view do this:

```<code>public Btn_Click(object sender, RoutedEventArgs e)
 {
   OpenFileHandler(this, e);
 }
</code>```

in your parent view, when you create your status bar view, define the delegate

```<code>statusbar.OpenFileHandler+= delegate
{
   ShellViewModel instance = this.DataContext as ShellViewModel;
   instance.OpenFile();
}
</code>```

statusbar is the name i gave to your status bar view, but it represent the instance of it

Title: Call a method from a child view

Body:
I'm trying to make some changes to the code a colleague made.

So, I have a ShellView that loads documents (and shows them as its content) with a method defined in its ViewModel, and the child view, a StatusBarView which holds the path navigated in the documents and some other infos.

public class ShellViewModel
{
    public StatusBarViewModel StatusBar { get; }

    public ShellViewModel(StatusBarViewModel statusBarViewModel, ...)
    {
        StatusBar = statusBarViewModel;

        var keymap = new Keymap();
        keymap.Map("F2", new SimpleCommand("open-file",
                                           "Shows the open file dialog",
                                            param => OpenFile());

    }

    private void OpenFile()
    {
        // Logic to open the file that uses other methods
        // inside this VM to validate the file
    }
}

At the moment you can load a new pack of documents pressing a key, I'd like to do the same with a button in the Status Bar and calling that method.

What is the proper way to call a method existing in the parent view from the child view?

Body:
In your child view Define an event Handler

public EventHandler OpenFileHandler

On the click of the button of your Status Bar view do this:

public Btn_Click(object sender, RoutedEventArgs e)
 {
   OpenFileHandler(this, e);
 }

in your parent view, when you create your status bar view, define the delegate

statusbar.OpenFileHandler+= delegate
{
   ShellViewModel instance = this.DataContext as ShellViewModel;
   instance.OpenFile();
}

statusbar is the name i gave to your status bar view, but it represent the instance of it


问:
malformed config.xml error in phonegap
I am new at using phonegap build.
So I tried to take a built by watching videos.
And I take malformed config.wml eror.
I checked the config file but I couldt solve problem and sometimes I take another eror message ('Error - Your package has a file or directory name that is invalid. Please view the build logs to see which file is causing this error)

I will be thankful if someone can give any advice and any help to me.

<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" xmlns:gap="http://schemas.android.com/apk/res/android"  "http://schemas.android.com/apk/res/android" id="com.razzmatazzist.myapp" version="1.0.0.1">

 <name>AOR</name>
 <description>Adventure of Ruzgar</description>
 <author></author>

 <icon src="icon-128.png" width="128" height="128" />
 <icon src="icon-256.png" width="256" height="256" gap:role="default" />

 <preference name="permissions" value="none"/>
 <preference name="android-targetSdkVersion" value="21" />

 <feature name="http://api.phonegap.com/1.0/network"/>

<plugin name="cordova-build-architecture" spec="https://github.com/MBuchalik/cordova-build-architecture.git#v1.0.1" source="git" />

<gap:config-file platform="android" parent="/manifest" mode="delete"> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> </gap:config-file>

 <preference name="orientation" value="default" />
 <preference name="fullscreen" value="true" />
 <gap:config-file platform="ios" parent="UIStatusBarHidden"><true/></gap:config-file>
 <gap:config-file platform="ios" parent="UIViewControllerBasedStatusBarAppearance"><false/></gap:config-file>
 <plugin name="cordova-plugin-crosswalk-webview" source="npm" />

 <plugin name="cordova-plugin-wkwebview-engine" />
 <plugin name="cordova-plugin-file" />
 <plugin name="cordova-plugin-httpd" />

 <plugin name="cordova-plugin-whitelist" source="npm" />
 <access origin="*" />

</widget>```

enter image description here

答:
Your Config.xml is not proper/valid. Please go through following</p>

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="io.ionic.startewwr" version="0.0.5" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>AOR</name>
    <description>Adventure of Ruzgar</description>
    <author></author>
    <icon src="icon-128.png" width="128" height="128" />
    <icon src="icon-256.png" width="256" height="256" />
    <preference name="permissions" value="none" />
    <preference name="android-targetSdkVersion" value="21" />
    <feature name="http://api.phonegap.com/1.0/network" />
    <plugin name="cordova-build-architecture" spec="https://github.com/MBuchalik/cordova-build-architecture.git#v1.0.1" source="git" />
    <preference name="orientation" value="default" />
    <preference name="fullscreen" value="true" />
    <plugin name="cordova-plugin-crosswalk-webview" source="npm" />
    <plugin name="cordova-plugin-wkwebview-engine" />
    <plugin name="cordova-plugin-file" />
    <plugin name="cordova-plugin-httpd" />
    <plugin name="cordova-plugin-whitelist" source="npm" />
    <access origin="*" />
</widget>
</code>```

Title: malformed config.xml error in phonegap

Body:
I am new at using phonegap build.
So I tried to take a built by watching videos.
And I take malformed config.wml eror.
I checked the config file but I couldt solve problem and sometimes I take another eror message ('Error - Your package has a file or directory name that is invalid. Please view the build logs to see which file is causing this error)

I will be thankful if someone can give any advice and any help to me.

<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" xmlns:gap="http://schemas.android.com/apk/res/android"  "http://schemas.android.com/apk/res/android" id="com.razzmatazzist.myapp" version="1.0.0.1">

 <name>AOR</name>
 <description>Adventure of Ruzgar</description>
 <author></author>

 <icon src="icon-128.png" width="128" height="128" />
 <icon src="icon-256.png" width="256" height="256" gap:role="default" />

 <preference name="permissions" value="none"/>
 <preference name="android-targetSdkVersion" value="21" />

 <feature name="http://api.phonegap.com/1.0/network"/>

<plugin name="cordova-build-architecture" spec="https://github.com/MBuchalik/cordova-build-architecture.git#v1.0.1" source="git" />

<gap:config-file platform="android" parent="/manifest" mode="delete"> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> </gap:config-file>

 <preference name="orientation" value="default" />
 <preference name="fullscreen" value="true" />
 <gap:config-file platform="ios" parent="UIStatusBarHidden"><true/></gap:config-file>
 <gap:config-file platform="ios" parent="UIViewControllerBasedStatusBarAppearance"><false/></gap:config-file>
 <plugin name="cordova-plugin-crosswalk-webview" source="npm" />

 <plugin name="cordova-plugin-wkwebview-engine" />
 <plugin name="cordova-plugin-file" />
 <plugin name="cordova-plugin-httpd" />

 <plugin name="cordova-plugin-whitelist" source="npm" />
 <access origin="*" />

</widget>

enter image description here

Body:
Your Config.xml is not proper/valid. Please go through following

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.ionic.startewwr" version="0.0.5" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>AOR</name>
    <description>Adventure of Ruzgar</description>
    <author></author>
    <icon src="icon-128.png" width="128" height="128" />
    <icon src="icon-256.png" width="256" height="256" />
    <preference name="permissions" value="none" />
    <preference name="android-targetSdkVersion" value="21" />
    <feature name="http://api.phonegap.com/1.0/network" />
    <plugin name="cordova-build-architecture" spec="https://github.com/MBuchalik/cordova-build-architecture.git#v1.0.1" source="git" />
    <preference name="orientation" value="default" />
    <preference name="fullscreen" value="true" />
    <plugin name="cordova-plugin-crosswalk-webview" source="npm" />
    <plugin name="cordova-plugin-wkwebview-engine" />
    <plugin name="cordova-plugin-file" />
    <plugin name="cordova-plugin-httpd" />
    <plugin name="cordova-plugin-whitelist" source="npm" />
    <access origin="*" />
</widget>


问:
How to copy elements of an array in superclass into an array in subclass in java?
Eg:

```<code>class A
{
    int array[] = {1,2,3,4,5}
}
class B extends A
{
    int new_array[];
}
</code>```

Now here, I want to that new_array in class B should be containing the same elements as array in class A.

NOTE :
I want to copy, but want to take care of that case where when we do any change in the copied array then the change should "not" be reflected in the original array.

答:
After studying and surfing the web, I finally managed learned how to copy an array without using loops.
The solution is as follows :

```<code>class A
{
    int array[] = {1, 2, 3, 4, 5};
}
class B extends A
{
    int copyArray[] = array.clone();
}
</code>```

I found this clone() method really helpful!

Body:
Eg:

class A
{
    int array[] = {1,2,3,4,5}
}
class B extends A
{
    int new_array[];
}

Now here, I want to that new_array in class B should be containing the same elements as array in class A.

NOTE :
I want to copy, but want to take care of that case where when we do any change in the copied array then the change should "not" be reflected in the original array.

Body:
After studying and surfing the web, I finally managed learned how to copy an array without using loops.
The solution is as follows :

class A
{
    int array[] = {1, 2, 3, 4, 5};
}
class B extends A
{
    int copyArray[] = array.clone();
}

I found this clone() method really helpful!


问:
How to run a Perl (or any CGI script) with a Wordpress installation
I have a simple wordpress website. I would like to run some perl programs from the cgi-bin folder. But the wordpress install gives a page not found when I put the link into my browser.

I put a simple "hello world" program in the cgi-bin folder, changed the permissions, then tried to execute it with a link.

It seems that wordpress is overriding any links to the cgi folder and presenting a wordpress 404 page. I have no problem running cgi programs on any other website on the same server.

答: Okay, as suggested by the scarcity of responses, this is not a wordpress issue. In fact the cgi-bin folder had the wrong permissions, which triggered the wordpress page not found response.</p>


问:
Where does Xcode store .m files of a framework?
In Xcode there are many frameworks (like mkmapkit.framework).

This framework contains only .h (header) files. Where can I find the corresponding .m (implementation) files.

答:
The only way to see the implementation is to decompile the frameworks static library with tools like those described in this question:

Decompiling Objective-C libraries

Since the frameworks you are probably interested in will generally have symbols stripped, it will be a bit of a task understanding what is going on but you can glean some things from tools like these.


问:
Swift Error - Cannot load underlying module for 'MessageKit'
I've been trying to create a Chat Apps using MessageKit, but when creating the ViewController and import the MessageKit, I get an error as below

Cannot load underlying module for 'MessageKit'

this is my PodFile

```<code>platform :ios, '11.0'

target 'GanChat' do
use_frameworks!

pod 'Firebase/Core'
pod 'Firebase/Storage'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'MessageKit'

end
</code>```

and this is my ViewController

```<code>import UIKit
import MessageKit

class ChatViewController: MessagesViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    senderId = "1234"
    senderDisplayName = "Heri"
}

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

答: According to the OP, the fix for the issue was to clean the project with (Cmd + Shift + K) before building the project.</p>

Body:
I've been trying to create a Chat Apps using MessageKit, but when creating the ViewController and import the MessageKit, I get an error as below

Cannot load underlying module for 'MessageKit'

this is my PodFile

platform :ios, '11.0'

target 'GanChat' do
use_frameworks!

pod 'Firebase/Core'
pod 'Firebase/Storage'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'MessageKit'

end

and this is my ViewController

import UIKit
import MessageKit

class ChatViewController: MessagesViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    senderId = "1234"
    senderDisplayName = "Heri"
}

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


问:
Export Access VBA Recordset To Single Row In Excel
I am trying to write some VBA to export a recordset from Access to Excel.  I have finally come down to the below export process, but it exports to columns A and B, and I want all of the data to be exported to row 2.

What would be the proper protocol/syntax to export to row 2?

```<code>Do While Not rsone.EOF
   columnNum = 1
   rowNum = rowNum + 1
   For Each fieldsss In rsone.Fields
       newExcelApp.Cells(rowNum, columnNum) = fieldsss.Value
     columnNum = columnNum + 1
   Next fieldsss
   rsone.MoveNext
Loop
</code>```

答:
kurtz's answer was nearly right, but he forgot to stop resetting the column number, making each next record overwrite the previous one.

Use this:

columnNum = 1
Do While Not rsone.EOF
   For Each fieldsss In rsone.Fields
       newExcelApp.Cells(2, columnNum).Value = fieldsss
     columnNum = columnNum + 1
   Next fieldsss
   rsone.MoveNext
Loop
```

Body:
I am trying to write some VBA to export a recordset from Access to Excel.  I have finally come down to the below export process, but it exports to columns A and B, and I want all of the data to be exported to row 2.

What would be the proper protocol/syntax to export to row 2?

Do While Not rsone.EOF
   columnNum = 1
   rowNum = rowNum + 1
   For Each fieldsss In rsone.Fields
       newExcelApp.Cells(rowNum, columnNum) = fieldsss.Value
     columnNum = columnNum + 1
   Next fieldsss
   rsone.MoveNext
Loop


问:
webpack import only variable value
I'm compiling code that needs the version value from package.json:

```<code>import {version} from '../package.json';
export default {version};
</code>```

and when I look at the .js file that webpack outputs I see the whole package.json there!

How can I avoid this?

My setup is:

```<code>plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }),
    new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.(js|css)$/,
        threshold: 10240,
        minRatio: 0.8
    }),
]
</code>```

My webpack version is 3.8.1

答:
What I usually do is take advantage of the DefinePlugin

```<code>// webpack.config.js
// getting the version
const package = require("./package.json");
const version = package.version;

plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"',
        'process.env.VERSION': version,
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }),
    new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.(js|css)$/,
        threshold: 10240,
        minRatio: 0.8
    }),
]
</code>```

Now in your code all you gotta do is use process.env.VERSION and you it will output your packages version.

Hope it helped

Title: webpack import only variable value

Body:
I'm compiling code that needs the version value from package.json:

import {version} from '../package.json';
export default {version};

and when I look at the .js file that webpack outputs I see the whole package.json there!

How can I avoid this?

My setup is:

plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }),
    new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.(js|css)$/,
        threshold: 10240,
        minRatio: 0.8
    }),
]

My webpack version is 3.8.1

Body:
What I usually do is take advantage of the DefinePlugin

// webpack.config.js
// getting the version
const package = require("./package.json");
const version = package.version;

plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"',
        'process.env.VERSION': version,
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }),
    new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.(js|css)$/,
        threshold: 10240,
        minRatio: 0.8
    }),
]

Now in your code all you gotta do is use process.env.VERSION and you it will output your packages version.

Hope it helped


问:
What shared library does contain android_init_namespaces?
When I wrote my own dynamic loader for android shared libraries I got such issue: in library libnativeloader.so there is such plt entry android_init_namespaces@plt, but there is no symbol android_init_namespaces. I've found such code in bionic:

```<code>LIBC {
  global:
    android_dlopen_ext;
    dl_iterate_phdr;
    dladdr;
    dlclose;
    dlerror;
    dlopen;
    dlsym;
  local:
    *;
};

LIBC_N {
  global:
    android_init_namespaces;
    android_create_namespace;
    dlvsym;
} LIBC;

LIBC_PLATFORM {
 global:
    android_get_application_target_sdk_version;
    android_set_application_target_sdk_version;
    android_get_LD_LIBRARY_PATH;
    android_update_LD_LIBRARY_PATH;
} LIBC_N;
</code>```

In such case it seems that this symbol is in libc.so. But there is no such symbol in libc.so.
Can anybody help with this issue ?

答:
I guess you are talking about Android N. Everything below is based on that assumption.

Those symbols are not from any shared library, they are implemented in linker, and exported via a handcrafted soinfo in source code.

```<code>static ElfW(Sym) g_libdl_symtab[] = {
  // Total length of libdl_info.strtab, including trailing 0.
  // This is actually the STH_UNDEF entry. Technically, it's
  // supposed to have st_name == 0, but instead, it points to an index
  // in the strtab with a \0 to make iterating through the symtab easier.
  ELFW(SYM_INITIALIZER)(sizeof(ANDROID_LIBDL_STRTAB) - 1, nullptr, 0),
  ELFW(SYM_INITIALIZER)(  0, &dlopen, 1),
  ELFW(SYM_INITIALIZER)(  7, &dlclose, 1),
  ELFW(SYM_INITIALIZER)( 15, &dlsym, 1),
  ELFW(SYM_INITIALIZER)( 21, &dlerror, 1),
  ELFW(SYM_INITIALIZER)( 29, &dladdr, 1),
  ELFW(SYM_INITIALIZER)( 36, &android_update_LD_LIBRARY_PATH, 1),
  ELFW(SYM_INITIALIZER)( 67, &android_get_LD_LIBRARY_PATH, 1),
  ELFW(SYM_INITIALIZER)( 95, &dl_iterate_phdr, 1),
  ELFW(SYM_INITIALIZER)(111, &android_dlopen_ext, 1),
  ELFW(SYM_INITIALIZER)(130, &android_set_application_target_sdk_version, 1),
  ELFW(SYM_INITIALIZER)(173, &android_get_application_target_sdk_version, 1),
  ELFW(SYM_INITIALIZER)(216, &android_init_namespaces, 1),
  ELFW(SYM_INITIALIZER)(240, &android_create_namespace, 1),
  ELFW(SYM_INITIALIZER)(265, &dlvsym, 1),
  ELFW(SYM_INITIALIZER)(272, &android_dlwarning, 1),
#if defined(__arm__)
  ELFW(SYM_INITIALIZER)(290, &dl_unwind_find_exidx, 1),
#endif
};

// This is used by the dynamic linker. Every process gets these symbols for free.
soinfo* get_libdl_info() {
  if (__libdl_info == nullptr) {
    __libdl_info = new (__libdl_info_buf) soinfo(&g_default_namespace, "libdl.so", nullptr, 0, RTLD_GLOBAL);
    __libdl_info->flags_ |= FLAG_LINKED;
    __libdl_info->strtab_ = ANDROID_LIBDL_STRTAB;
    __libdl_info->symtab_ = g_libdl_symtab;
    __libdl_info->nbucket_ = sizeof(g_libdl_buckets)/sizeof(unsigned);
    __libdl_info->nchain_ = sizeof(g_libdl_chains)/sizeof(unsigned);
    __libdl_info->bucket_ = g_libdl_buckets;
    __libdl_info->chain_ = g_libdl_chains;
    __libdl_info->ref_count_ = 1;
    __libdl_info->strtab_size_ = sizeof(ANDROID_LIBDL_STRTAB);
    __libdl_info->local_group_root_ = __libdl_info;
    __libdl_info->soname_ = "libdl.so";
    __libdl_info->target_sdk_version_ = __ANDROID_API__;
    __libdl_info->generate_handle();
#if defined(__work_around_b_24465209__)
    strlcpy(__libdl_info->old_name_, __libdl_info->soname_, sizeof(__libdl_info->old_name_));
#endif
  }
</code>```

check https://android.googlesource.com/platform/bionic/+/android-7.0.0_r1/linker/dlfcn.cpp for more details.

Body:
When I wrote my own dynamic loader for android shared libraries I got such issue: in library libnativeloader.so there is such plt entry android_init_namespaces@plt, but there is no symbol android_init_namespaces. I've found such code in bionic:

LIBC {
  global:
    android_dlopen_ext;
    dl_iterate_phdr;
    dladdr;
    dlclose;
    dlerror;
    dlopen;
    dlsym;
  local:
    *;
};

LIBC_N {
  global:
    android_init_namespaces;
    android_create_namespace;
    dlvsym;
} LIBC;

LIBC_PLATFORM {
 global:
    android_get_application_target_sdk_version;
    android_set_application_target_sdk_version;
    android_get_LD_LIBRARY_PATH;
    android_update_LD_LIBRARY_PATH;
} LIBC_N;

In such case it seems that this symbol is in libc.so. But there is no such symbol in libc.so.
Can anybody help with this issue ?

Body:
I guess you are talking about Android N. Everything below is based on that assumption.

Those symbols are not from any shared library, they are implemented in linker, and exported via a handcrafted soinfo in source code.

static ElfW(Sym) g_libdl_symtab[] = {
  // Total length of libdl_info.strtab, including trailing 0.
  // This is actually the STH_UNDEF entry. Technically, it's
  // supposed to have st_name == 0, but instead, it points to an index
  // in the strtab with a \0 to make iterating through the symtab easier.
  ELFW(SYM_INITIALIZER)(sizeof(ANDROID_LIBDL_STRTAB) - 1, nullptr, 0),
  ELFW(SYM_INITIALIZER)(  0, &dlopen, 1),
  ELFW(SYM_INITIALIZER)(  7, &dlclose, 1),
  ELFW(SYM_INITIALIZER)( 15, &dlsym, 1),
  ELFW(SYM_INITIALIZER)( 21, &dlerror, 1),
  ELFW(SYM_INITIALIZER)( 29, &dladdr, 1),
  ELFW(SYM_INITIALIZER)( 36, &android_update_LD_LIBRARY_PATH, 1),
  ELFW(SYM_INITIALIZER)( 67, &android_get_LD_LIBRARY_PATH, 1),
  ELFW(SYM_INITIALIZER)( 95, &dl_iterate_phdr, 1),
  ELFW(SYM_INITIALIZER)(111, &android_dlopen_ext, 1),
  ELFW(SYM_INITIALIZER)(130, &android_set_application_target_sdk_version, 1),
  ELFW(SYM_INITIALIZER)(173, &android_get_application_target_sdk_version, 1),
  ELFW(SYM_INITIALIZER)(216, &android_init_namespaces, 1),
  ELFW(SYM_INITIALIZER)(240, &android_create_namespace, 1),
  ELFW(SYM_INITIALIZER)(265, &dlvsym, 1),
  ELFW(SYM_INITIALIZER)(272, &android_dlwarning, 1),
#if defined(__arm__)
  ELFW(SYM_INITIALIZER)(290, &dl_unwind_find_exidx, 1),
#endif
};

// This is used by the dynamic linker. Every process gets these symbols for free.
soinfo* get_libdl_info() {
  if (__libdl_info == nullptr) {
    __libdl_info = new (__libdl_info_buf) soinfo(&g_default_namespace, "libdl.so", nullptr, 0, RTLD_GLOBAL);
    __libdl_info->flags_ |= FLAG_LINKED;
    __libdl_info->strtab_ = ANDROID_LIBDL_STRTAB;
    __libdl_info->symtab_ = g_libdl_symtab;
    __libdl_info->nbucket_ = sizeof(g_libdl_buckets)/sizeof(unsigned);
    __libdl_info->nchain_ = sizeof(g_libdl_chains)/sizeof(unsigned);
    __libdl_info->bucket_ = g_libdl_buckets;
    __libdl_info->chain_ = g_libdl_chains;
    __libdl_info->ref_count_ = 1;
    __libdl_info->strtab_size_ = sizeof(ANDROID_LIBDL_STRTAB);
    __libdl_info->local_group_root_ = __libdl_info;
    __libdl_info->soname_ = "libdl.so";
    __libdl_info->target_sdk_version_ = __ANDROID_API__;
    __libdl_info->generate_handle();
#if defined(__work_around_b_24465209__)
    strlcpy(__libdl_info->old_name_, __libdl_info->soname_, sizeof(__libdl_info->old_name_));
#endif
  }

check https://android.googlesource.com/platform/bionic/+/android-7.0.0_r1/linker/dlfcn.cpp for more details.


问:
Easier way to dynamically create Javascript using PHP
I'm currently using PHP to dynamically create a javascript which will be echoed on the page.

Sample Code:

```<code>$JS .= '<script>';

if($condition == true) {
    $JS .= 'alert("Yo its true omg!");
}

$JS .= "</script>";
</code>```

As you can see, this will eventually get messy with ll the ' quotes and escaping of single quotes within the double quotes...

Is there a better way to do this?

答:
If the static javscript code amount is more than your dinamically created javascript code amount, you can simply write javascript code as usual and then inject php where needed.

Example of a hypothetical index.php:

```<code><?php

    $message = "Yo its true omg!";

?>

<html><head>

    <script>
        alert("<?php echo $message; ?>");
    </script>

</head><body>

    ...

</body></html>
</code>```

Body:
I'm currently using PHP to dynamically create a javascript which will be echoed on the page.

Sample Code:

$JS .= '";

As you can see, this will eventually get messy with ll the ' quotes and escaping of single quotes within the double quotes...

Is there a better way to do this?

Body:
If the static javscript code amount is more than your dinamically created javascript code amount, you can simply write javascript code as usual and then inject php where needed.

Example of a hypothetical index.php:

<?php

    $message = "Yo its true omg!";

?>

<html><head>

    <script>
        alert("<?php echo $message; ?>");
    </script>

</head><body>

    ...

</body></html>


问:
How can I show an image using Javascript starting with a jpg-encoded string?
An annoying API that I have to deal with provides an image as a jpg, but it is a JSON-encoded string within a larger JSON object, rather than just making the jpg available at some url. I have code to access this api with javascript, but then how do I get the image to show up on the page?

update: The API providing the image is accessed from javascript rather than a server, so ideal would be a pure javascript solution. I don't have to support IE6 but I do have to support IE7, Firefox, and Chrome. The jpg isn't base64 encoded but I could base64 encode it in javascript.

答:
If the JSON string is base 64 encoded then you can output it as a Data URI, e.g.

```<code><img src="data:image/jpeg;base64,...." />
</code>```

This also works (without the base64 tag) if the string is URL encoded (e.g. mostly ASCII, and %xx format for non-printing and non-HTML-safe characters).

Body:
If the JSON string is base 64 encoded then you can output it as a Data URI, e.g.

<img src="data:image/jpeg;base64,...." />

This also works (without the base64 tag) if the string is URL encoded (e.g. mostly ASCII, and %xx format for non-printing and non-HTML-safe characters).