问:
Keras InvalidArgumentError: You must feed a value for placeholder tensor
I'm stuck on this problem since days. here's my simple code: I'm trying to sample a 3D tensor into a 2D tensor with a lambda layer but every time i get an error from tensorflow backend. here's my code, reduced to the point where the error occours:

```<code>import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.layers import Lambda, Input
from keras.models import Model

def sampling(x):
    def get_sample(preds, temperature=1.0):
        # helper function to sample an index from a probability array
        preds = K.log(preds) / temperature
        exp_preds = K.exp(preds)
        preds = exp_preds / K.sum(exp_preds)
        probas = np.random.multinomial(1, K.eval(preds), 1)
        return K.expand_dims(K.variable(np.argmax(probas)))

    b = K.int_shape(x)[1]
    for i in range(1):
        result = get_sample(x[i, 0, :])
        for j in range(b):
            if j == 0:
                continue
            c = get_sample(x[i, j, :])
            result = K.concatenate([result, c], axis=0)

    return result

if __name__ == '__main__':
    # model definition
    inp = Input(shape=(15, 38))
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
    model = Model(inputs=inp, outputs=exa)
    model.summary()

    # test input
    noise = K.random_uniform(shape=(2, 15, 38), maxval=1, minval=0, dtype="float32", seed=42)

    print(model.predict_on_batch(noise))
</code>```

here's the error dump

```<code>2017-11-15 11:44:58.285872: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX
Traceback (most recent call last):
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 37, in <module>
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
  File "/usr/lib/python2.7/site-packages/keras/engine/topology.py", line 603, in __call__
    output = self.call(inputs, **kwargs)
  File "/usr/lib/python2.7/site-packages/keras/layers/core.py", line 651, in call
    return self.function(inputs, **arguments)
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 37, in <lambda>
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 24, in sampling
    result = get_sample(x[i, 0, :])
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 19, in get_sample
    probas = np.random.multinomial(1, K.eval(preds), 1)
  File "/usr/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 644, in eval
    return to_dense(x).eval(session=get_session())
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 570, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 4455, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1120, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1317, in _do_run
    options, run_metadata)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1336, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,15,38]
     [[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[?,15,38], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op u'input_1', defined at:
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 36, in <module>
    inp = Input(shape=(15, 38))
  File "/usr/lib/python2.7/site-packages/keras/engine/topology.py", line 1439, in Input
    input_tensor=tensor)
  File "/usr/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/keras/engine/topology.py", line 1348, in __init__
    name=self.name)
  File "/usr/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 488, in placeholder
    x = tf.placeholder(dtype, shape=shape, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 1599, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3091, in _placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2956, in create_op
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1470, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,15,38]
     [[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[?,15,38], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
</code>```

if I feed a tensor to the input layer like this:

```<code>if __name__ == '__main__':
    tens = K.zeros(shape=(2, 15, 38), dtype="float32")
    inp = Input(shape=(15, 38), tensor=tens)
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
    model = Model(inputs=inp, outputs=exa)
    model.summary()

    noise = K.random_uniform(shape=(2, 15, 38), maxval=1, minval=0, dtype="float32", seed=42)

    print(model.predict_on_batch(noise))
</code>```

I the model works but using the zeroes tensor I gave to the input layer, returning an array of 1.

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 15, 38)            0
_________________________________________________________________
lambda_1 (Lambda)            (None, 15)                0
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________
[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
</code>```

If I try to put a K.placeholder object I get the same error as well. How can I resolve this?
I already tried setting the learning phase to 0 or 1 but nothing changes.

答:
The solution was very simple: do not use numpy during tensor manipulation, only Keras backend functions and clearly I did not understand how lambda layers work.
here's the corrected code if anyone else get stuck by this problem.

```<code>import numpy as np
from keras import backend as K
from keras.layers import Input
from keras.layers import Lambda
from keras.models import Model

def sampling(preds, temperature=1.0):
    preds = K.log(preds) / temperature
    exp_preds = K.exp(preds)
    preds = exp_preds / K.sum(exp_preds)
    return K.argmax(preds, axis=2)

if __name__ == '__main__':
    batch_size = 10

    ########### MODEL
    inp = Input(shape=(15, 38))
    exa = Lambda(lambda x: sampling(x), output_shape=(15,))(inp)
    model = Model(inputs=inp, outputs=exa)
    model.summary()

    noise = np.random.uniform(0, 1, size=(batch_size, 15, 38))
    print("NOISE INPUT")
    print(noise)
    decoded = model.predict_on_batch(noise)
    print("\n\nSAMPLED OUTPUT")
    print(decoded)
    #################
</code>```

and here's the expected output

```<code>Using TensorFlow backend.
2017-11-16 18:26:51.398569: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 15, 38)            0
_________________________________________________________________
lambda_1 (Lambda)            (None, 15)                0
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________
NOISE INPUT
[[[ 0.30891316  0.15221787  0.5038829  ...,  0.8848083   0.08956024
    0.3606536 ]
  [ 0.44807492  0.23133616  0.70644087 ...,  0.27361268  0.65620316
    0.85804126]
  [ 0.72102694  0.09523426  0.16791966 ...,  0.66441456  0.80056542
    0.86870569]
  ...,
  [ 0.98217747  0.77091951  0.59332161 ...,  0.79585449  0.73915857
    0.46059018]
  [ 0.88017517  0.17193309  0.51066406 ...,  0.78946729  0.88111187
    0.26728708]
  [ 0.34269771  0.62430603  0.84418251 ...,  0.80441201  0.54334108
    0.98493448]]

 [[ 0.8669257   0.82135396  0.10069927 ...,  0.90542972  0.67465482
    0.55842347]
  [ 0.72956178  0.08731971  0.95467123 ...,  0.95472095  0.88684042
    0.37218502]
  [ 0.46721374  0.96649476  0.1933913  ...,  0.06071162  0.14450657
    0.90962683]
  ...,
  [ 0.12344553  0.96051246  0.68679955 ...,  0.99269888  0.20232171
    0.67095509]
  [ 0.68686574  0.94280854  0.80347876 ...,  0.04743072  0.95419244
    0.85568141]
  [ 0.38312468  0.51157601  0.71631078 ...,  0.26982261  0.94738435
    0.01725109]]

 [[ 0.60993944  0.78323704  0.44851841 ...,  0.88221101  0.32755589
    0.82010709]
  [ 0.83341658  0.55235978  0.03581224 ...,  0.03711514  0.82935275
    0.1729678 ]
  [ 0.78978104  0.2181397   0.49759489 ...,  0.20598122  0.87555217
    0.1310053 ]
  ...,
  [ 0.0136351   0.1470119   0.55496631 ...,  0.93888501  0.29122596
    0.73619966]
  [ 0.15711732  0.99471253  0.35647437 ...,  0.90060837  0.75228682
    0.3414452 ]
  [ 0.35007325  0.54940108  0.60591077 ...,  0.90813329  0.04030722
    0.09562064]]

 ...,
 [[ 0.02168732  0.95698804  0.09280446 ...,  0.71586791  0.00920231
    0.38907889]
  [ 0.76853587  0.25528251  0.61563489 ...,  0.97880311  0.88628481
    0.30254836]
  [ 0.75778522  0.27014167  0.86857289 ...,  0.7196309   0.47614798
    0.50452127]
  ...,
  [ 0.38104386  0.95507951  0.8337219  ...,  0.86317049  0.56698557
    0.67915409]
  [ 0.2014119   0.18607705  0.11220879 ...,  0.11445029  0.54958169
    0.332358  ]
  [ 0.26280992  0.73237823  0.72684251 ...,  0.43947476  0.56091593
    0.32524556]]

 [[ 0.96829533  0.68190408  0.3739879  ...,  0.9606717   0.22280759
    0.3031305 ]
  [ 0.82955492  0.04815685  0.43250177 ...,  0.58623864  0.37036309
    0.23000677]
  [ 0.47910544  0.44406259  0.22996476 ...,  0.05613431  0.77214874
    0.95063867]
  ...,
  [ 0.60491445  0.33447544  0.22093127 ...,  0.82935465  0.08349322
    0.2298346 ]
  [ 0.81513182  0.27917361  0.34890291 ...,  0.4860525   0.72408671
    0.91163499]
  [ 0.87716181  0.90365287  0.12285839 ...,  0.9010089   0.05510581
    0.61629317]]

 [[ 0.80663206  0.35334483  0.81901437 ...,  0.55569487  0.15872563
    0.71420715]
  [ 0.78043711  0.37595655  0.7021172  ...,  0.57781578  0.68621989
    0.0617801 ]
  [ 0.74502178  0.51097854  0.35836054 ...,  0.39165413  0.63403207
    0.1674981 ]
  ...,
  [ 0.87651597  0.34229628  0.99998675 ...,  0.64886858  0.87177124
    0.83341321]
  [ 0.037897    0.00723697  0.05077544 ...,  0.54169736  0.18409638
    0.1442172 ]
  [ 0.10817155  0.82998391  0.1356064  ...,  0.89285585  0.7613262
    0.33972169]]]

SAMPLED OUTPUT
[[18 12 30  3 15  9 28 36 29 14 15  5 33  4 28]
 [ 3 35  5 10 23 16 10 11  3 15  6  1 29 30 23]
 [27 17 11 32 14 19  4 20  7 20 29 19 29  1 26]
 [ 3 27  5 11 21 21 11 27  0 21 21 34 15 24  0]
 [ 5  5 21  0  1 10 21  5 19 19 13 25 37 28 33]
 [ 7 34 11  3 18 24 18 32 11 21  5 32 25  0 16]
 [ 0 25 29 21 15 15 35 23  0 18  6 27  4 11 21]
 [27 35 29 10 11 11 18  6 29 35 36 29 34 21 33]
 [ 0 29  8 11 30 21 32 27 15 10 16 15 13 34 27]
 [17 26  3 20 10 13 27 35  4 10 10 20  2 15 34]]
</code>```

Body:
I'm stuck on this problem since days. here's my simple code: I'm trying to sample a 3D tensor into a 2D tensor with a lambda layer but every time i get an error from tensorflow backend. here's my code, reduced to the point where the error occours:

import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.layers import Lambda, Input
from keras.models import Model

def sampling(x):
    def get_sample(preds, temperature=1.0):
        # helper function to sample an index from a probability array
        preds = K.log(preds) / temperature
        exp_preds = K.exp(preds)
        preds = exp_preds / K.sum(exp_preds)
        probas = np.random.multinomial(1, K.eval(preds), 1)
        return K.expand_dims(K.variable(np.argmax(probas)))

    b = K.int_shape(x)[1]
    for i in range(1):
        result = get_sample(x[i, 0, :])
        for j in range(b):
            if j == 0:
                continue
            c = get_sample(x[i, j, :])
            result = K.concatenate([result, c], axis=0)

    return result

if __name__ == '__main__':
    # model definition
    inp = Input(shape=(15, 38))
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
    model = Model(inputs=inp, outputs=exa)
    model.summary()

    # test input
    noise = K.random_uniform(shape=(2, 15, 38), maxval=1, minval=0, dtype="float32", seed=42)

    print(model.predict_on_batch(noise))

here's the error dump

2017-11-15 11:44:58.285872: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX
Traceback (most recent call last):
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 37, in <module>
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
  File "/usr/lib/python2.7/site-packages/keras/engine/topology.py", line 603, in __call__
    output = self.call(inputs, **kwargs)
  File "/usr/lib/python2.7/site-packages/keras/layers/core.py", line 651, in call
    return self.function(inputs, **arguments)
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 37, in <lambda>
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 24, in sampling
    result = get_sample(x[i, 0, :])
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 19, in get_sample
    probas = np.random.multinomial(1, K.eval(preds), 1)
  File "/usr/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 644, in eval
    return to_dense(x).eval(session=get_session())
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 570, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 4455, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1120, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1317, in _do_run
    options, run_metadata)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1336, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,15,38]
     [[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[?,15,38], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op u'input_1', defined at:
  File "/home/archeffect/PycharmProjects/adversarial_DGA/sample_layer.py", line 36, in <module>
    inp = Input(shape=(15, 38))
  File "/usr/lib/python2.7/site-packages/keras/engine/topology.py", line 1439, in Input
    input_tensor=tensor)
  File "/usr/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/keras/engine/topology.py", line 1348, in __init__
    name=self.name)
  File "/usr/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 488, in placeholder
    x = tf.placeholder(dtype, shape=shape, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 1599, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3091, in _placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2956, in create_op
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1470, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,15,38]
     [[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[?,15,38], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

if I feed a tensor to the input layer like this:

if __name__ == '__main__':
    tens = K.zeros(shape=(2, 15, 38), dtype="float32")
    inp = Input(shape=(15, 38), tensor=tens)
    exa = Lambda(lambda x: sampling(x), input_shape=(15, 38), output_shape=(15,))(inp)
    model = Model(inputs=inp, outputs=exa)
    model.summary()

    noise = K.random_uniform(shape=(2, 15, 38), maxval=1, minval=0, dtype="float32", seed=42)

    print(model.predict_on_batch(noise))

I the model works but using the zeroes tensor I gave to the input layer, returning an array of 1.

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 15, 38)            0
_________________________________________________________________
lambda_1 (Lambda)            (None, 15)                0
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________
[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

If I try to put a K.placeholder object I get the same error as well. How can I resolve this?
I already tried setting the learning phase to 0 or 1 but nothing changes.

Body:
The solution was very simple: do not use numpy during tensor manipulation, only Keras backend functions and clearly I did not understand how lambda layers work.
here's the corrected code if anyone else get stuck by this problem.

import numpy as np
from keras import backend as K
from keras.layers import Input
from keras.layers import Lambda
from keras.models import Model

def sampling(preds, temperature=1.0):
    preds = K.log(preds) / temperature
    exp_preds = K.exp(preds)
    preds = exp_preds / K.sum(exp_preds)
    return K.argmax(preds, axis=2)

if __name__ == '__main__':
    batch_size = 10

    ########### MODEL
    inp = Input(shape=(15, 38))
    exa = Lambda(lambda x: sampling(x), output_shape=(15,))(inp)
    model = Model(inputs=inp, outputs=exa)
    model.summary()

    noise = np.random.uniform(0, 1, size=(batch_size, 15, 38))
    print("NOISE INPUT")
    print(noise)
    decoded = model.predict_on_batch(noise)
    print("\n\nSAMPLED OUTPUT")
    print(decoded)
    #################

and here's the expected output

Using TensorFlow backend.
2017-11-16 18:26:51.398569: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 15, 38)            0
_________________________________________________________________
lambda_1 (Lambda)            (None, 15)                0
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________
NOISE INPUT
[[[ 0.30891316  0.15221787  0.5038829  ...,  0.8848083   0.08956024
    0.3606536 ]
  [ 0.44807492  0.23133616  0.70644087 ...,  0.27361268  0.65620316
    0.85804126]
  [ 0.72102694  0.09523426  0.16791966 ...,  0.66441456  0.80056542
    0.86870569]
  ...,
  [ 0.98217747  0.77091951  0.59332161 ...,  0.79585449  0.73915857
    0.46059018]
  [ 0.88017517  0.17193309  0.51066406 ...,  0.78946729  0.88111187
    0.26728708]
  [ 0.34269771  0.62430603  0.84418251 ...,  0.80441201  0.54334108
    0.98493448]]

 [[ 0.8669257   0.82135396  0.10069927 ...,  0.90542972  0.67465482
    0.55842347]
  [ 0.72956178  0.08731971  0.95467123 ...,  0.95472095  0.88684042
    0.37218502]
  [ 0.46721374  0.96649476  0.1933913  ...,  0.06071162  0.14450657
    0.90962683]
  ...,
  [ 0.12344553  0.96051246  0.68679955 ...,  0.99269888  0.20232171
    0.67095509]
  [ 0.68686574  0.94280854  0.80347876 ...,  0.04743072  0.95419244
    0.85568141]
  [ 0.38312468  0.51157601  0.71631078 ...,  0.26982261  0.94738435
    0.01725109]]

 [[ 0.60993944  0.78323704  0.44851841 ...,  0.88221101  0.32755589
    0.82010709]
  [ 0.83341658  0.55235978  0.03581224 ...,  0.03711514  0.82935275
    0.1729678 ]
  [ 0.78978104  0.2181397   0.49759489 ...,  0.20598122  0.87555217
    0.1310053 ]
  ...,
  [ 0.0136351   0.1470119   0.55496631 ...,  0.93888501  0.29122596
    0.73619966]
  [ 0.15711732  0.99471253  0.35647437 ...,  0.90060837  0.75228682
    0.3414452 ]
  [ 0.35007325  0.54940108  0.60591077 ...,  0.90813329  0.04030722
    0.09562064]]

 ...,
 [[ 0.02168732  0.95698804  0.09280446 ...,  0.71586791  0.00920231
    0.38907889]
  [ 0.76853587  0.25528251  0.61563489 ...,  0.97880311  0.88628481
    0.30254836]
  [ 0.75778522  0.27014167  0.86857289 ...,  0.7196309   0.47614798
    0.50452127]
  ...,
  [ 0.38104386  0.95507951  0.8337219  ...,  0.86317049  0.56698557
    0.67915409]
  [ 0.2014119   0.18607705  0.11220879 ...,  0.11445029  0.54958169
    0.332358  ]
  [ 0.26280992  0.73237823  0.72684251 ...,  0.43947476  0.56091593
    0.32524556]]

 [[ 0.96829533  0.68190408  0.3739879  ...,  0.9606717   0.22280759
    0.3031305 ]
  [ 0.82955492  0.04815685  0.43250177 ...,  0.58623864  0.37036309
    0.23000677]
  [ 0.47910544  0.44406259  0.22996476 ...,  0.05613431  0.77214874
    0.95063867]
  ...,
  [ 0.60491445  0.33447544  0.22093127 ...,  0.82935465  0.08349322
    0.2298346 ]
  [ 0.81513182  0.27917361  0.34890291 ...,  0.4860525   0.72408671
    0.91163499]
  [ 0.87716181  0.90365287  0.12285839 ...,  0.9010089   0.05510581
    0.61629317]]

 [[ 0.80663206  0.35334483  0.81901437 ...,  0.55569487  0.15872563
    0.71420715]
  [ 0.78043711  0.37595655  0.7021172  ...,  0.57781578  0.68621989
    0.0617801 ]
  [ 0.74502178  0.51097854  0.35836054 ...,  0.39165413  0.63403207
    0.1674981 ]
  ...,
  [ 0.87651597  0.34229628  0.99998675 ...,  0.64886858  0.87177124
    0.83341321]
  [ 0.037897    0.00723697  0.05077544 ...,  0.54169736  0.18409638
    0.1442172 ]
  [ 0.10817155  0.82998391  0.1356064  ...,  0.89285585  0.7613262
    0.33972169]]]

SAMPLED OUTPUT
[[18 12 30  3 15  9 28 36 29 14 15  5 33  4 28]
 [ 3 35  5 10 23 16 10 11  3 15  6  1 29 30 23]
 [27 17 11 32 14 19  4 20  7 20 29 19 29  1 26]
 [ 3 27  5 11 21 21 11 27  0 21 21 34 15 24  0]
 [ 5  5 21  0  1 10 21  5 19 19 13 25 37 28 33]
 [ 7 34 11  3 18 24 18 32 11 21  5 32 25  0 16]
 [ 0 25 29 21 15 15 35 23  0 18  6 27  4 11 21]
 [27 35 29 10 11 11 18  6 29 35 36 29 34 21 33]
 [ 0 29  8 11 30 21 32 27 15 10 16 15 13 34 27]
 [17 26  3 20 10 13 27 35  4 10 10 20  2 15 34]]


来源: stackexchange

问:
opencv cascade.detectMultiScale creates error: (-215) !empty()
I am following this tutorial to understand haar features. While writing following code:

```<code>import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('Sachin.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
</code>```

getting following error:

```<code>File "<ipython-input-6-0b479e459b0f>", line 1, in <module>
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
</code>```

(Sachin is the image i downloaded from google, of size (237,237,3) and after converting gray it is (237,237) with min=23, max=210. I am using opencv 3.1.0 with python 3.6, installed using command conda install -c menpo opencv3. i am trying for this solution but unable to find xml file in my desktop. How to solve problem.

答: You should be in the same directory as the xml file . Hope this helps!</p>

ContentLicense: CC BY-SA 3.0

Body:
I am following this tutorial to understand haar features. While writing following code:

import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('Sachin.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

getting following error:

File "<ipython-input-6-0b479e459b0f>", line 1, in <module>
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale

(Sachin is the image i downloaded from google, of size (237,237,3) and after converting gray it is (237,237) with min=23, max=210. I am using opencv 3.1.0 with python 3.6, installed using command conda install -c menpo opencv3. i am trying for this solution but unable to find xml file in my desktop. How to solve problem.


问:
Iterate in list and get nearest values
How can I loop in the list below and set the values of the  as a class on the input? But it cannot iterate over the .liBrand list item.

```<code><ul>
    <li class="liModelFilter liMultipleSelectionFilter">
        <ul>
             <li class="liBrand"><b>Mini</b></li>
             <li>
                 <input type="checkbox" value="1090" id="ModelIds">
                 <span>Cooper</span>
             </li>
             <li>
                 <input type="checkbox" value="1092" id="ModelIds">
                 <span>One</span>
             </li>
        </ul>
    </li>
 </ul>
</code>```

Required result:

```<code><li>
    <input class="Cooper" type="checkbox" value="1090" id="ModelIds">
    <span>Cooper</span>
</li>
</code>```

I need this because I have to create a custom checkbox - each checkbox has to have to logo of the type (Cooper, One,...).

I already tried something like this:

```<code>jQuery($('.liModelFilter ul li:not(.liBrand)')).each(function() {
    console.log($('.liModelFilter ul li:not(.liBrand)')).html();
});
</code>```

答:
The simplest way to do this would be to call addClass() on the input elements, and provide a function which returns the text content of the sibling span, something like this:

$('.liModelFilter :checkbox').addClass(function() {
  return $(this).next('span').text();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="liModelFilter liMultipleSelectionFilter">
    <ul>
      <li class="liBrand"><b>Mini</b></li>
      <li>
        <input type="checkbox" value="1090" class="ModelIds">
        <span>Cooper</span>
      </li>
      <li>
        <input type="checkbox" value="1092" class="ModelIds">
        <span>One</span>
      </li>
    </ul>
  </li>
</ul></code>```

Also note that I changed the id="ModelIds" to a class, as you cannot have duplicate id attributes within the DOM.

Title: Iterate in list and get nearest values

Body:
How can I loop in the list below and set the values of the  as a class on the input? But it cannot iterate over the .liBrand list item.

Mini

                 <input type="checkbox" value="1090" id="ModelIds">
                 Cooper

                 <input type="checkbox" value="1092" id="ModelIds">
                 One

Required result:

    <input class="Cooper" type="checkbox" value="1090" id="ModelIds">
    Cooper

I need this because I have to create a custom checkbox - each checkbox has to have to logo of the type (Cooper, One,...).

I already tried something like this:

jQuery($('.liModelFilter ul li:not(.liBrand)')).each(function() {
    console.log($('.liModelFilter ul li:not(.liBrand)')).html();
});

Body:
The simplest way to do this would be to call addClass() on the input elements, and provide a function which returns the text content of the sibling span, something like this:

$('.liModelFilter :checkbox').addClass(function() {
  return $(this).next('span').text();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="liModelFilter liMultipleSelectionFilter">
    <ul>
      <li class="liBrand"><b>Mini</b></li>
      <li>
        <input type="checkbox" value="1090" class="ModelIds">
        <span>Cooper</span>
      </li>
      <li>
        <input type="checkbox" value="1092" class="ModelIds">
        <span>One</span>
      </li>
    </ul>
  </li>
</ul>

Also note that I changed the id="ModelIds" to a class, as you cannot have duplicate id attributes within the DOM.


问:
Process API is not returning the all instances of a ms word process
I'm checking word process instances, I have open more then one instances of word instance but it returns only the first instance of word and return process.Count 1 ,  When I use notepad as process then it works but with winword it didn't works.   </p>

```<code>For Each a In p
    If Not pName.Equals("") And I <= p.Count Then
        Console.WriteLine(a)
        Console.WriteLine(p.Count)
        pName = p(I).MainWindowTitle.ToString
        File.WriteLine("Word Process Name : {0} is started on time {1}", pName, p(I).StartTime)
        fullPath = Path.GetFullPath(pName)
        File.WriteLine("Path Of the file is  : {0}", fullPath(0))
    End If
Next
</code>```

答:
I have solved This problem with Word.Application API you can add it form reference add. </p>

```<code>Dim wordApp As Microsoft.Office.Interop.Word.Application
wordApp = Marshal.GetActiveObject("Word.Application")
For Each f In wordApp.Documents
          pName = Path.GetFileName(f.FullName).ToString()
           pPath = f.Path.ToString()
           File.WriteLine("Word Process Name : {0}  ", pName)
           File.WriteLine("File Path is: {0} ", pPath)
           File.WriteLine("File Starting Time is {0}", pTime)
Next
</code>```

Body:
I'm checking word process instances, I have open more then one instances of word instance but it returns only the first instance of word and return process.Count 1 ,  When I use notepad as process then it works but with winword it didn't works.

For Each a In p
    If Not pName.Equals("") And I <= p.Count Then
        Console.WriteLine(a)
        Console.WriteLine(p.Count)
        pName = p(I).MainWindowTitle.ToString
        File.WriteLine("Word Process Name : {0} is started on time {1}", pName, p(I).StartTime)
        fullPath = Path.GetFullPath(pName)
        File.WriteLine("Path Of the file is  : {0}", fullPath(0))
    End If
Next

Body:
I have solved This problem with Word.Application API you can add it form reference add.

Dim wordApp As Microsoft.Office.Interop.Word.Application
wordApp = Marshal.GetActiveObject("Word.Application")
For Each f In wordApp.Documents
          pName = Path.GetFileName(f.FullName).ToString()
           pPath = f.Path.ToString()
           File.WriteLine("Word Process Name : {0}  ", pName)
           File.WriteLine("File Path is: {0} ", pPath)
           File.WriteLine("File Starting Time is {0}", pTime)
Next


问:
Is there a Firefox 3 addon similar to View Source Chart?
Before I upgraded to Firefox 3 I used to constantly use the View Source Chart Firefox Addon which shows the source HTML in a very organized, graphical form. Unfortunately, this addon is only for Firefox 2 and the beta version for Firefox 3 now costs $10 on the author's site.

Anyone know of a similar addon that works for Firefox 3?

(of course, I might indeed pay $10 for this, but first want to ask around if there isn't anything better and free, as the version for Firefox 2 had its limitations and I don't really want to pay $10 for something in beta that I can't test out before paying for it.)

答: View formatted source is kinda similar. It uses tree controls rather than pretty colour blocks, though.</p>

OwnerDisplayName: Edward Tanguay

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Oli

OwnerDisplayName: Cheekysoft


问:
Pass path with spaces as parameter to bat file
I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?

In my code i have the following

```<code>:READ_PWA_PATH
    if "%1" == "" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
            IF ERRORLEVEL ==2 GOTO CANCEL
            IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
    )
</code>```

If I simply call the script I get the following error:

```<code>C:\Projects\Setup>install.cmd "C:\program files (x86)"

-----------------
SETUP SCRIPT
-----------------

files was unexpected at this time.
C:\Projects\Setup>
</code>```

答:
Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found  that out.

Body:
I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?

In my code i have the following

:READ_PWA_PATH
    if "%1" == "" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
            IF ERRORLEVEL ==2 GOTO CANCEL
            IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
    )

If I simply call the script I get the following error:

C:\Projects\Setup>install.cmd "C:\program files (x86)"

-----------------
SETUP SCRIPT
-----------------

files was unexpected at this time.
C:\Projects\Setup>

OwnerDisplayName: VardhanDotNet


问:
Lync error in Silverlight: Client not trusted
When I try to load my Lync Controls in a Silverlight application I get the error: Client is not trusted. This error doesn't appear when I debug the Silverlight application without the corresponding web project.

This is the code that generates the error:

```<code>LyncClient l = LyncClient.GetClient();
</code>```

This is the error:

```<code>AutomationServerException was unhandled by user code
Client is not trusted
</code>```

What must I do?

答:
This error usually happens because the web site that your Silverlight application is running under isn't in the "Trusted Sites" browser zone. Adding to Trusted Sites should fix it.

Edit: The walkthrough here states:

Security settings for Microsoft Lync
  2010 SDK applications require that the
  host URL for Lync Control Silverlight
  applications be added to the Trusted
  sites list in Microsoft Internet
  Explorer. For information about adding
  to the Trusted sites list, see Working with Internet Explorer 6 Security Settings.

Body:
When I try to load my Lync Controls in a Silverlight application I get the error: Client is not trusted. This error doesn't appear when I debug the Silverlight application without the corresponding web project.

This is the code that generates the error:

LyncClient l = LyncClient.GetClient();

This is the error:

AutomationServerException was unhandled by user code
Client is not trusted

What must I do?


问:
Example of standalone Apache Qpid (amqp) Junit Test
Does anyone have an example of using Apache Qpid within a standalone junit test.

Ideally I want to be able to create a queue on the fly which I can put/get msgs within my test.
So I'm not testing QPid within my test, I'll use integration tests for that, however be very useful to test methods handling msgs with having to mock out a load of services.

答:
My solution on qpid-broker @ 6.1.1, add below to pom.xml

```<code><dependency>
    <groupId>org.apache.qpid</groupId>
    <artifactId>qpid-broker</artifactId>
    <version>6.1.1</version>
    <scope>test</scope>
</dependency>
</code>```

qpid config file as:

```<code>{
  "name" : "${broker.name}",
  "modelVersion" : "6.1",
  "defaultVirtualHost" : "default",
  "authenticationproviders" : [ {
    "name" : "anonymous",
    "type" : "Anonymous"
  } ],
  "ports" : [ {
    "name" : "AMQP",
    "port" : "${qpid.amqp_port}",
    "authenticationProvider" : "anonymous",
    "virtualhostaliases" : [ {
      "name" : "defaultAlias",
      "type" : "defaultAlias"
    } ]
  } ],
  "virtualhostnodes" : [ {
    "name" : "default",
    "type" : "JSON",
    "defaultVirtualHostNode" : "true",
    "virtualHostInitialConfiguration" : "{ \"type\" : \"Memory\" }"
  } ]
}
</code>```

code to start the qpid server

```<code>Broker broker = new Broker();
BrokerOptions brokerOptions = new BrokerOptions();
// I use fix port number
brokerOptions.setConfigProperty("qpid.amqp_port", "20179");
brokerOptions.setConfigurationStoreType("Memory");
// work_dir for qpid's log, configs, persist data
System.setProperty("qpid.work_dir", "/tmp/qpidworktmp");
// init config of qpid. Relative path for classloader resource or absolute path for non-resource
System.setProperty("qpid.initialConfigurationLocation", "qpid/qpid-config.json");
brokerOptions.setStartupLoggedToSystemOut(false);
broker.startup(brokerOptions);
</code>```

code to stop qpid server

```<code>broker.shutdown();
</code>```

Since I use anonymouse mode, client should do like:

```<code>SaslConfig saslConfig = new SaslConfig() {
    public SaslMechanism getSaslMechanism(String[] mechanisms) {
        return new SaslMechanism() {
            public String getName() {
                return "ANONYMOUS";
            }

            public LongString handleChallenge(LongString challenge, String username, String password) {
                return LongStringHelper.asLongString("");
            }
        };
    }
};
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(20179);
factory.setSaslConfig(saslConfig);

Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
</code>```

That's all.
A little more on how to do it on other version.

You can download qpid-broker binary package from official site. After download and unzip, you can run it to test as server against your case. After your case connected server well, using commandline to generate or just copy the initial config file in QPID_WORK, remove useless id filed and use it for embedded server like above.

The most complicated thing is the authentication. You can choose PLAIN mode but you have to add the username and password in initial config. I choose anonymous mode which need a little code when connecting. For other authentication mode you have specify the password file or key/cert store, which I didnt try.

If it still not working, you can read the qpid-borker doc and Main class code in qpid-broker artifact which show how command line works for each settings.

Body:
My solution on qpid-broker @ 6.1.1, add below to pom.xml

<dependency>
    <groupId>org.apache.qpid</groupId>
    <artifactId>qpid-broker</artifactId>
    <version>6.1.1</version>
    <scope>test</scope>
</dependency>

qpid config file as:

{
  "name" : "${broker.name}",
  "modelVersion" : "6.1",
  "defaultVirtualHost" : "default",
  "authenticationproviders" : [ {
    "name" : "anonymous",
    "type" : "Anonymous"
  } ],
  "ports" : [ {
    "name" : "AMQP",
    "port" : "${qpid.amqp_port}",
    "authenticationProvider" : "anonymous",
    "virtualhostaliases" : [ {
      "name" : "defaultAlias",
      "type" : "defaultAlias"
    } ]
  } ],
  "virtualhostnodes" : [ {
    "name" : "default",
    "type" : "JSON",
    "defaultVirtualHostNode" : "true",
    "virtualHostInitialConfiguration" : "{ \"type\" : \"Memory\" }"
  } ]
}

code to start the qpid server

Broker broker = new Broker();
BrokerOptions brokerOptions = new BrokerOptions();
// I use fix port number
brokerOptions.setConfigProperty("qpid.amqp_port", "20179");
brokerOptions.setConfigurationStoreType("Memory");
// work_dir for qpid's log, configs, persist data
System.setProperty("qpid.work_dir", "/tmp/qpidworktmp");
// init config of qpid. Relative path for classloader resource or absolute path for non-resource
System.setProperty("qpid.initialConfigurationLocation", "qpid/qpid-config.json");
brokerOptions.setStartupLoggedToSystemOut(false);
broker.startup(brokerOptions);

code to stop qpid server

broker.shutdown();

Since I use anonymouse mode, client should do like:

SaslConfig saslConfig = new SaslConfig() {
    public SaslMechanism getSaslMechanism(String[] mechanisms) {
        return new SaslMechanism() {
            public String getName() {
                return "ANONYMOUS";
            }

            public LongString handleChallenge(LongString challenge, String username, String password) {
                return LongStringHelper.asLongString("");
            }
        };
    }
};
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(20179);
factory.setSaslConfig(saslConfig);

Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

That's all.
A little more on how to do it on other version.

You can download qpid-broker binary package from official site. After download and unzip, you can run it to test as server against your case. After your case connected server well, using commandline to generate or just copy the initial config file in QPID_WORK, remove useless id filed and use it for embedded server like above.

The most complicated thing is the authentication. You can choose PLAIN mode but you have to add the username and password in initial config. I choose anonymous mode which need a little code when connecting. For other authentication mode you have specify the password file or key/cert store, which I didnt try.

If it still not working, you can read the qpid-borker doc and Main class code in qpid-broker artifact which show how command line works for each settings.


问:
Extract version number from a comment
I have a CSS (or HTML or JS) file with a comment /* Version: 1.2.1 */ near the beginning of the file.

Using PHP/regex, how do I get a string containing '1.2.1'?

I apologise for not RTFM but I can't find an answer on the Google. Any direction on learning regex would be great!

答:
```<code>$str = '/* Version 1.2.1 */';
preg_match('/version\s(.*)\s\*/i',$str,$matches);

print_r($matches[1]);
</code>```

its very simple to grap, \s(.*)\s capture anything in between
  spaces as first group. display first captured group $matches[1]

if you are curious that how it works or wanna learn yourself ? you can dive directly into it from here i found this very helpful for beginner.

Regular Expressions!

DIY

Title: Extract version number from a comment

Body:
$str = '/* Version 1.2.1 */';
preg_match('/version\s(.*)\s\*/i',$str,$matches);

print_r($matches[1]);

its very simple to grap, \s(.*)\s capture anything in between
  spaces as first group. display first captured group $matches[1]

if you are curious that how it works or wanna learn yourself ? you can dive directly into it from here i found this very helpful for beginner.

Regular Expressions!

DIY


问:
Check if key exists in an array and replace its value
CLIENT CODE

I am sending an id of a client from the client side using

```<code>var socket = io.connect('http://localhost:8080?token='+userID);
</code>```

and getting it on the server in my io.on('connection')
function using

SERVER CODE

```<code>let token = socket.handshake.query.token;
</code>```

so now I have the userID stored in the variable token.

Also I am getting the connected socket id and storing it like

```<code>var id = socket.id;
</code>```

Then I am storing the userID and the socketID in an array as key value pair.

```<code>var item = {};
item[token] = id;
</code>```

This is an array I am pushing it into(the array is declared outside the on connection function)

```<code>keyPairArray.push(item);
</code>```

So I am getting an array like this when two people are connected.

```<code>[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' } ]
</code>```

But when any user reloads the page the array gets like

```<code>[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' },
  { '1456': 'tIhvkxFbSSAQEckWAAAC' } ]
</code>```

Same user Id but different socket id's.

The socket id changes every time the user reloads the page or opens the page in another tab and the same UserID is appended into the array with a different socket id.

I don't want to insert the same user again. If the user reloads the page, I want it to check the userId which is the key in the array and replace the old socket id with the newly generated one.

This is the code that I tried with no luck

```<code>var checkKeyPair = keyPairArray.some(function(item){
    return item[token] === id;
});

if(checkKeyPair){
    console.log("Hello");
}else{
    keyPairArray.push(item);
    console.log(keyPairArray);
}
</code>```

答:
Try this (if ES6 is not a problem):

let token = socket.handshake.query.token;
var id = socket.id;
var item = { [token]: id };
var index = keyPairArray.findIndex(it => Object.keys(it)[0] === token);
if (index === -1) {
    keyPairArray.push(item);
} else {
    keyPairArray[index] = item;
}
```

Body:
CLIENT CODE

I am sending an id of a client from the client side using

var socket = io.connect('http://localhost:8080?token='+userID);

and getting it on the server in my io.on('connection')
function using

SERVER CODE

let token = socket.handshake.query.token;

so now I have the userID stored in the variable token.

Also I am getting the connected socket id and storing it like

var id = socket.id;

Then I am storing the userID and the socketID in an array as key value pair.

var item = {};
item[token] = id;

This is an array I am pushing it into(the array is declared outside the on connection function)

keyPairArray.push(item);

So I am getting an array like this when two people are connected.

[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' } ]

But when any user reloads the page the array gets like

[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' },
  { '1456': 'tIhvkxFbSSAQEckWAAAC' } ]

Same user Id but different socket id's.

The socket id changes every time the user reloads the page or opens the page in another tab and the same UserID is appended into the array with a different socket id.

I don't want to insert the same user again. If the user reloads the page, I want it to check the userId which is the key in the array and replace the old socket id with the newly generated one.

This is the code that I tried with no luck

var checkKeyPair = keyPairArray.some(function(item){
    return item[token] === id;
});

if(checkKeyPair){
    console.log("Hello");
}else{
    keyPairArray.push(item);
    console.log(keyPairArray);
}


问:
How to change a specific (this) button class when click on. Using Vue.js 2.0
When clicked the any of the buttons they are all turns active. So what i want is just the clicked one should be changed.

var vm = new Vue({
 el: '#toolBtns',
 data: {
  isActive: false
 },
 computed: {
  activeClass: function () {
   return {
    active: this.isActive
   };
  }
 }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn-group" role="group" id="toolBtns">
  <button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn1</button>
  <button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn2</button>
  <button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn3</button></div></code>```

答:
You don't need to set 'isActive: false', and you don't need to bind isActive to each of the items. you can do as follows: 1, declare an array, called 'candidates', then each item clicked will be pushed into candidates.  2, declare a function, called 'contains()' which checks if an item is in the candidates array. 3, bind contains() to each item. 4, in CSS, give 'clicked' some style.

html code:

```<code><body>
    <div id="toolBtns">
        <button v-for="item in buttons" v-on:click="provide(item)" v-bind:class="{clicked: contains(candidates, item)}" type="button">{{ item.name }}
        </button>
    </div>
</body>
</code>```

javascript code:

```<code>var toolBtns = new Vue({
el: '#toolBtns',
data:
{
    buttons: [
        {name: 'Btn1'},
        {name: 'Btn2'},
        {name: 'Btn3'},
    ],
    candidates: [],
},
methods:
{
    provide: function(item)
    {
        if(this.candidates.indexOf(item) == -1)
        {
            this.candidates.push(item);
        }
        else
        {
             this.candidates.splice(this.candidates.indexOf(item), 1);
        }
    },
    contains: function(arr, item)
    {
        return arr.indexOf(item) != -1;
    },
}
});
</code>```

CSS code

```<code>.clicked{
    background-color: red;
}
</code>```

here is the jsfiddle example https://jsfiddle.net/JoyAndBrave/anzdzq4L/6/

Body:
When clicked the any of the buttons they are all turns active. So what i want is just the clicked one should be changed.

var vm = new Vue({
 el: '#toolBtns',
 data: {
  isActive: false
 },
 computed: {
  activeClass: function () {
   return {
    active: this.isActive
   };
  }
 }
});

  <button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn1</button>
  <button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn2</button>
  <button class="btn" type="button" @click="isActive = !isActive" :class="activeClass">Btn3</button>

Body:
You don't need to set 'isActive: false', and you don't need to bind isActive to each of the items. you can do as follows: 1, declare an array, called 'candidates', then each item clicked will be pushed into candidates.  2, declare a function, called 'contains()' which checks if an item is in the candidates array. 3, bind contains() to each item. 4, in CSS, give 'clicked' some style.

html code:

<body>
    <div id="toolBtns">
        <button v-for="item in buttons" v-on:click="provide(item)" v-bind:class="{clicked: contains(candidates, item)}" type="button">{{ item.name }}
        </button>
    </div>
</body>

javascript code:

var toolBtns = new Vue({
el: '#toolBtns',
data:
{
    buttons: [
        {name: 'Btn1'},
        {name: 'Btn2'},
        {name: 'Btn3'},
    ],
    candidates: [],
},
methods:
{
    provide: function(item)
    {
        if(this.candidates.indexOf(item) == -1)
        {
            this.candidates.push(item);
        }
        else
        {
             this.candidates.splice(this.candidates.indexOf(item), 1);
        }
    },
    contains: function(arr, item)
    {
        return arr.indexOf(item) != -1;
    },
}
});

CSS code

.clicked{
    background-color: red;
}

here is the jsfiddle example https://jsfiddle.net/JoyAndBrave/anzdzq4L/6/


问:
WCF 4.0 REST Upload MS-Excel File
I am trying to upload MS-Excel file through WCF-REST Service.
I used the solution given in below post:-
RESTful WCF service image upload problem
My POST Method is declared as:

```<code>  [OperationContract]
                [WebInvoke(Method = "POST", UriTemplate = "/RFQ")]
                [WebContentType("application/octet-stream")]
                void UploadRFQDoc(Stream fileContents);
</code>```

When I debug, stream content is fine till the call goes, and when I attach service to debug,  Stream fileContents  parameter becomes null , and service returns with [Bad Request]. I am not sending large file (it is just 50 KB). I am using HttpClient to call the Post.
Here are the client code(RestClient is HttpClient).

```<code> protected void Post(string uri, Stream stream, int length)
        {
            var content = HttpContent.Create(output => CopyToStream(stream, output, length), "application/octet-stream", length);
            Uri relativeUri = new Uri(uri, UriKind.Relative);

            var resp = RestClient.Post(relativeUri, content);

            ProcessResponse(resp);
        }

        void CopyToStream(Stream input, Stream output, int length)
        {
            var buffer = new byte[length];
            var read = input.Read(buffer, 0, Convert.ToInt32 (length));

            output.Write(buffer, 0, read);
        }
</code>```

Any clue what else can go wrong.
Many Thanks.

答: [WebContentType("application/octet-stream")] attribute was unnecessary here. I commented it out, and all worked fine :).</p>

Title: WCF 4.0 REST Upload MS-Excel File

Body:
I am trying to upload MS-Excel file through WCF-REST Service.
I used the solution given in below post:-
RESTful WCF service image upload problem
My POST Method is declared as:

  [OperationContract]
                [WebInvoke(Method = "POST", UriTemplate = "/RFQ")]
                [WebContentType("application/octet-stream")]
                void UploadRFQDoc(Stream fileContents);

When I debug, stream content is fine till the call goes, and when I attach service to debug,  Stream fileContents  parameter becomes null , and service returns with [Bad Request]. I am not sending large file (it is just 50 KB). I am using HttpClient to call the Post.
Here are the client code(RestClient is HttpClient).

 protected void Post(string uri, Stream stream, int length)
        {
            var content = HttpContent.Create(output => CopyToStream(stream, output, length), "application/octet-stream", length);
            Uri relativeUri = new Uri(uri, UriKind.Relative);

            var resp = RestClient.Post(relativeUri, content);

            ProcessResponse(resp);
        }

        void CopyToStream(Stream input, Stream output, int length)
        {
            var buffer = new byte[length];
            var read = input.Read(buffer, 0, Convert.ToInt32 (length));

            output.Write(buffer, 0, read);
        }

Any clue what else can go wrong.
Many Thanks.


问:
Custom attribute mapping of object in Javascript
Would I be able to send a metadata in a POST request? I'm able to send Bulk amount of data inside a POST request but if need to group data's together inside a POST method and send it to a REST API, do I have to manipulate the values inside the body?

I'm able to send like this:

Example:

```<code>{
"name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc",
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"
}
</code>```

But I need to send data like this:

Example:

```<code>{
"User":{"name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc"},``
"Project":{
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"}
}
</code>```

答:
If you want to create a new object from your current metadata object, you can initialize your new object like this:

```<code>var res = {
  User: {},
  Project: {}
};
</code>```

Then you can use Object.keys() to loop over the object keys, and popluate the result object:

```<code>Object.keys(obj).forEach(function(key) {
  if (key === "name" || key === "version" || key === "author")
    res.User[key] = obj[key];
  else
    res.Project[key] = obj[key];
});
</code>```

Demo:

var obj = {
  "name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc",
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"
};

var res = {
  User: {},
  Project: {}
};
Object.keys(obj).forEach(function(key) {
  if (key === "name" || key === "version" || key === "author")
    res.User[key] = obj[key];
  else
    res.Project[key] = obj[key];
});
console.log(res);```

Body:
Would I be able to send a metadata in a POST request? I'm able to send Bulk amount of data inside a POST request but if need to group data's together inside a POST method and send it to a REST API, do I have to manipulate the values inside the body?

I'm able to send like this:

Example:

{
"name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc",
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"
}

But I need to send data like this:

Example:

{
"User":{"name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc"},``
"Project":{
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"}
}

Body:
If you want to create a new object from your current metadata object, you can initialize your new object like this:

var res = {
  User: {},
  Project: {}
};

Then you can use Object.keys() to loop over the object keys, and popluate the result object:

Object.keys(obj).forEach(function(key) {
  if (key === "name" || key === "version" || key === "author")
    res.User[key] = obj[key];
  else
    res.Project[key] = obj[key];
});

Demo:

var obj = {
  "name": "puppetlabs-ntp",
  "version": "6.1.0",
  "author": "Puppet Inc",
  "summary": "Installs, configures, and manages the NTP service.",
  "license": "Apache-2.0",
  "source": "https://github.com/puppetlabs/puppetlabs-ntp",
  "project_page": "https://github.com/puppetlabs/puppetlabs-ntp",
  "issues_url": "https://tickets.puppetlabs.com/browse/MODULES"
};

var res = {
  User: {},
  Project: {}
};
Object.keys(obj).forEach(function(key) {
  if (key === "name" || key === "version" || key === "author")
    res.User[key] = obj[key];
  else
    res.Project[key] = obj[key];
});
console.log(res);


问:
Unable to Inspect elements in Java Website (IE Browser)
I want to verify the installed version of java by navigating to this

URL: https://www.java.com/en/download/installed.jsp in IE browser

When I click on Agree and continue button, it will display the java version.

I want to get the text of the java version displayed to verify it with my value, But I couldn't inspect on the block which displays the java version

I tried looking hmtl,the version value is not available in HTML as well.

Can anyone address this issue?

答:
An Image to view the source code and the Xpath:

.//span[@id='results_upgrade_block_user_jre']

In IE11 it seems equals:


问:
Different values in different instances of the same usercontrol in WPF
I am working on creating a map for an application, which I need to present in two different ways. One mini-map and one regular map, they are both made up of one single UserControl. My issue is that I am trying to find a smooth way of displaying the regular-sized map with area names, and the mini-map without. I have been looking into DependencyProperties as a possible way of doing this, or at least a way to illustrate my train of thought. What I have so far is this.

```<code>    public bool MiniMap
    {
        get { return (bool)GetValue(MiniMapProperty); }
        set { SetValue(MiniMapProperty, value); }
    }

    public static DependencyProperty MiniMapProperty =
        DependencyProperty.Register("MiniMap",
        typeof(bool),
        typeof(myMap),
        new PropertyMetadata());
</code>```

I then have all the TextBlocks with the right labels in the UserControl, and are currently trying to remove the Text property if the MiniMap property is set as true, and let them be if it is false. Currently I am just doing it on the title of the map, but I can loop through them all once I get this one to work.

```<code>    if (MiniMap == true)
        {
            this.Title.Text = "";
        }
</code>```

I am then instantiating this UserControl in a different View twice, with the MiniMap property set as true in one case, and false in the other.

```<code>    <map:myMap x:Name="myMap" Visibility="Collapsed" MiniMap="False"/>
    <map:myMap x:Name="miniMap" Visibility="Visible" MiniMap="True"/>
</code>```

The idea here is that once you click the Map button, the big map comes up (changes Visibility to Visible) and since the MiniMap property is set to false in this instance, then TextBlock(s) should be empty, or removed preferably - but that is a different issue. My problem here tho is that no matter what I do both instances of my UserControl always seems to have the same value for the MiniMap property, so I can only turn the TextBlock either on in both cases, or off in both. Anyone have any idea how I can get this to work, or have another solution better suited for my problem?

答:
Try to use a propertychanged callback</p>

```<code>public static DependencyProperty MiniMapProperty =
    DependencyProperty.Register("MiniMap",
    typeof(bool),
    typeof(myMap),
    new PropertyMetadata(new PropertyChangedCallback(OnMiniMapPropertyChanged)));

private static void OnMiniMapPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var control = sender as myMap;
            if (control != null && (bool)e.NewValue == true)
                control.Title.Text = "";
        }
</code>```

Body:
I am working on creating a map for an application, which I need to present in two different ways. One mini-map and one regular map, they are both made up of one single UserControl. My issue is that I am trying to find a smooth way of displaying the regular-sized map with area names, and the mini-map without. I have been looking into DependencyProperties as a possible way of doing this, or at least a way to illustrate my train of thought. What I have so far is this.

    public bool MiniMap
    {
        get { return (bool)GetValue(MiniMapProperty); }
        set { SetValue(MiniMapProperty, value); }
    }

    public static DependencyProperty MiniMapProperty =
        DependencyProperty.Register("MiniMap",
        typeof(bool),
        typeof(myMap),
        new PropertyMetadata());

I then have all the TextBlocks with the right labels in the UserControl, and are currently trying to remove the Text property if the MiniMap property is set as true, and let them be if it is false. Currently I am just doing it on the title of the map, but I can loop through them all once I get this one to work.

    if (MiniMap == true)
        {
            this.Title.Text = "";
        }

I am then instantiating this UserControl in a different View twice, with the MiniMap property set as true in one case, and false in the other.

    <map:myMap x:Name="myMap" Visibility="Collapsed" MiniMap="False"/>
    <map:myMap x:Name="miniMap" Visibility="Visible" MiniMap="True"/>

The idea here is that once you click the Map button, the big map comes up (changes Visibility to Visible) and since the MiniMap property is set to false in this instance, then TextBlock(s) should be empty, or removed preferably - but that is a different issue. My problem here tho is that no matter what I do both instances of my UserControl always seems to have the same value for the MiniMap property, so I can only turn the TextBlock either on in both cases, or off in both. Anyone have any idea how I can get this to work, or have another solution better suited for my problem?

Body:
Try to use a propertychanged callback

public static DependencyProperty MiniMapProperty =
    DependencyProperty.Register("MiniMap",
    typeof(bool),
    typeof(myMap),
    new PropertyMetadata(new PropertyChangedCallback(OnMiniMapPropertyChanged)));

private static void OnMiniMapPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var control = sender as myMap;
            if (control != null && (bool)e.NewValue == true)
                control.Title.Text = "";
        }


问:
remove array object from nested array if element is undefined using javascript
Raw array

```<code>myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]
</code>```

Expected array,

```<code> myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]
</code>```

i want to remove undefined element with index  in result array,

答:
Try map and filter

```<code>myArr.map( s => (s.values = s.values.filter( p => JSON.stringify(p) != "{}" ), s ) );
</code>```

Demo

var myArr = [
{name:'abcd',values:[{undefined},{quarter: "Q2-2016", koordinaten: 119},
{quarter: "Q3-2016", koordinaten: 129},{undefined}]},
{name:'abcd',values:[{undefined},{undefined},{quarter: "Q4-2016", koordinaten: 19},{undefined}]}
];

var output = myArr.map(s => (s.values = s.values.filter(p => JSON.stringify(p) != "{}"), s));

console.log(output);```

Body:
Raw array

myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]

Expected array,

 myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]

i want to remove undefined element with index  in result array,

Body:
Try map and filter

myArr.map( s => (s.values = s.values.filter( p => JSON.stringify(p) != "{}" ), s ) );

Demo

var myArr = [
{name:'abcd',values:[{undefined},{quarter: "Q2-2016", koordinaten: 119},
{quarter: "Q3-2016", koordinaten: 129},{undefined}]},
{name:'abcd',values:[{undefined},{undefined},{quarter: "Q4-2016", koordinaten: 19},{undefined}]}
];

var output = myArr.map(s => (s.values = s.values.filter(p => JSON.stringify(p) != "{}"), s));

console.log(output);


问:
Show/hide not working during AJAX request
I have a function that requests data using ajax. I would like to display a busy spinner but hide/show do not change the elements visibility.

```<code>function RequestDataFromServer(stuff, url) {
    var result;

    $.ajax({
        url: url,
        data: { stuff: Stuff},
        async: false,
        beforeSend: function () {
            $("#divOverlay").show();
            console.log("Starting...");
        },
        complete: function () {
            $("#divOverlay").hide();
            console.log("Complete!");
            result = true;
        },
        success: function (data) {
            AddDataToCache(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            result = false;
        }
    });

    return result;
}
</code>```

I know the show/hide syntax is correct because it works when I attach it to buttons. I have also tried using :

```<code>$(document).ajaxStart(function(){
    $("#divOverlay").show();
})
</code>```

With no affect (however if I step thru this event in Chrome it does show and hide the elements). I've also tried show/hide in a function that calls the RequestDataFromServer function... still nothing. I'm out of ideas.

答: I had the same issue , it worked when async:true. Still don't know the cause but it worked.</p>

Body:
I have a function that requests data using ajax. I would like to display a busy spinner but hide/show do not change the elements visibility.

function RequestDataFromServer(stuff, url) {
    var result;

    $.ajax({
        url: url,
        data: { stuff: Stuff},
        async: false,
        beforeSend: function () {
            $("#divOverlay").show();
            console.log("Starting...");
        },
        complete: function () {
            $("#divOverlay").hide();
            console.log("Complete!");
            result = true;
        },
        success: function (data) {
            AddDataToCache(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            result = false;
        }
    });

    return result;
}

I know the show/hide syntax is correct because it works when I attach it to buttons. I have also tried using :

$(document).ajaxStart(function(){
    $("#divOverlay").show();
})

With no affect (however if I step thru this event in Chrome it does show and hide the elements). I've also tried show/hide in a function that calls the RequestDataFromServer function... still nothing. I'm out of ideas.


问:
Hide browser address bar on BlackBerry OS6
I'm currently developing HTML 5 mobile web apps. If you add such an app to your homescreen on an iPhone, it pretty much looks like a native app since I am able to hide the mobile safari's address bar. This can be achieved by using some meta-tags within my HTML code.

Now I was wondering if hiding the address bar is also possible on the Blackberry OS 6? Does anyone have an idea if and how this could be achieved? Is there a Blackberry-specific meta-tag?

答:
There is no meta tag available for BlackBerry.

Try to use the window.scrollTo (0,1) function while loading the content into the browser.


问:
Angular 4 - Adding router param before url
Just wondering whether there is a way to create a angular route with parameter before of in-between a url,

```<code>{path: ':param/test/list'} or {path: 'web/:param/list'}
</code>```

and reference it in routerLink directive,

```<code>[routerLink]="['test/list', paramValue]"
</code>```

Thee parameter value is always getting appended to the end of the url.

答:
You should put parameter segment in same position to route. Something similar:

```<code>path: { ':parameter/test/list' }
[routerLink]="[paramValeu, 'test', 'list']"
</code>```

Edit:

Separate segments in Route link.

Body:
Just wondering whether there is a way to create a angular route with parameter before of in-between a url,

{path: ':param/test/list'} or {path: 'web/:param/list'}

and reference it in routerLink directive,

[routerLink]="['test/list', paramValue]"

Thee parameter value is always getting appended to the end of the url.

Body:
You should put parameter segment in same position to route. Something similar:

path: { ':parameter/test/list' }
[routerLink]="[paramValeu, 'test', 'list']"

Edit:

Separate segments in Route link.


问:
C segfaults on string operation
I'm writing a little programme to remove a word from a string. C segfaults in the for-loop inside the removeWord function (the third printf is never executed). What can the reason be? I'm an absolute newbee in C. When I try to print str[j] as %s inside the for loop, the compiler complains about str being an integer, not a string. Why is that?</p>

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

void removeWord(char * str, char * toRemove)
{
    int i, j, k, stringLen, toRemoveLen;
    stringLen   = strlen(str);      // Length of string
    toRemoveLen = strlen(toRemove); // Length of word to remove
// ...(code for finding the word)...
        printf ("str='%s' StrLen=%d ToRem=%d i=%d j=%d\n",str, stringLen, toRemoveLen, i, j);
        for(j=i; j<=stringLen - toRemoveLen; j++)
        {
            printf ("j=%d\n", j);
            str[j] = str[j + toRemoveLen];
        }
        printf ("i=%d j=%d\n", i, j);
}

int main(void)
{
    char * term = "from the ";
    removeWord(term, "from");
    return 0;
}
</code>```

答:
It's string literal. You can't modify it. As a result you get a segfault trying to modify it.(Actually it's undefined behavior).

What you can do is

```<code>char  term[] = "from the ";
</code>```

that will help you modify it, which is what you want.

Even you can take a char* and allocate memory in it and copy the string but that's an overkill for this task.

From the standard it can be quoted that §6.4.5

It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

In your case temp basically holds the address of the string literal which is non-modifiable. If you copy it and then that will be modifiable.

Title: C segfaults on string operation

Body:
I'm writing a little programme to remove a word from a string. C segfaults in the for-loop inside the removeWord function (the third printf is never executed). What can the reason be? I'm an absolute newbee in C. When I try to print str[j] as %s inside the for loop, the compiler complains about str being an integer, not a string. Why is that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeWord(char * str, char * toRemove)
{
    int i, j, k, stringLen, toRemoveLen;
    stringLen   = strlen(str);      // Length of string
    toRemoveLen = strlen(toRemove); // Length of word to remove
// ...(code for finding the word)...
        printf ("str='%s' StrLen=%d ToRem=%d i=%d j=%d\n",str, stringLen, toRemoveLen, i, j);
        for(j=i; j<=stringLen - toRemoveLen; j++)
        {
            printf ("j=%d\n", j);
            str[j] = str[j + toRemoveLen];
        }
        printf ("i=%d j=%d\n", i, j);
}

int main(void)
{
    char * term = "from the ";
    removeWord(term, "from");
    return 0;
}

Body:
It's string literal. You can't modify it. As a result you get a segfault trying to modify it.(Actually it's undefined behavior).

What you can do is

char  term[] = "from the ";

that will help you modify it, which is what you want.

Even you can take a char* and allocate memory in it and copy the string but that's an overkill for this task.

From the standard it can be quoted that §6.4.5

It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

In your case temp basically holds the address of the string literal which is non-modifiable. If you copy it and then that will be modifiable.