问:
Siamese Model with LSTM network fails to train using tensorflow
Dataset Description

The dataset contains a set of question pairs and a label which tells if the questions are same. e.g.

"How do I read and find my YouTube comments?" , "How can I see all my
  Youtube comments?" , "1"

The goal of the model is to identify if the given question pair is same or different.

Approach

I have created a Siamese network to identify if two questions are same. Following is the model:

```<code>graph = tf.Graph()

with graph.as_default():
    embedding_placeholder = tf.placeholder(tf.float32, shape=embedding_matrix.shape, name='embedding_placeholder')
    with tf.variable_scope('siamese_network') as scope:
        labels = tf.placeholder(tf.int32, [batch_size, None], name='labels')
        keep_prob = tf.placeholder(tf.float32, name='question1_keep_prob')

        with tf.name_scope('question1') as question1_scope:
            question1_inputs = tf.placeholder(tf.int32, [batch_size, seq_len], name='question1_inputs')

            question1_embedding = tf.get_variable(name='embedding', initializer=embedding_placeholder, trainable=False)
            question1_embed = tf.nn.embedding_lookup(question1_embedding, question1_inputs)

            question1_lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
            question1_drop = tf.contrib.rnn.DropoutWrapper(question1_lstm, output_keep_prob=keep_prob)
            question1_multi_lstm = tf.contrib.rnn.MultiRNNCell([question1_drop] * lstm_layers)

            q1_initial_state = question1_multi_lstm.zero_state(batch_size, tf.float32)

            question1_outputs, question1_final_state = tf.nn.dynamic_rnn(question1_multi_lstm, question1_embed, initial_state=q1_initial_state)

        scope.reuse_variables()

        with tf.name_scope('question2') as question2_scope:
            question2_inputs = tf.placeholder(tf.int32, [batch_size, seq_len], name='question2_inputs')

            question2_embedding = question1_embedding
            question2_embed = tf.nn.embedding_lookup(question2_embedding, question2_inputs)

            question2_lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
            question2_drop = tf.contrib.rnn.DropoutWrapper(question2_lstm, output_keep_prob=keep_prob)
            question2_multi_lstm = tf.contrib.rnn.MultiRNNCell([question2_drop] * lstm_layers)

            q2_initial_state = question2_multi_lstm.zero_state(batch_size, tf.float32)

            question2_outputs, question2_final_state = tf.nn.dynamic_rnn(question2_multi_lstm, question2_embed, initial_state=q2_initial_state)
</code>```

Calculate the cosine distance using the RNN outputs:

```<code>with graph.as_default():
    diff = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(question1_outputs[:, -1, :], question2_outputs[:, -1, :])), reduction_indices=1))

    margin = tf.constant(1.)
    labels = tf.to_float(labels)
    match_loss = tf.expand_dims(tf.square(diff, 'match_term'), 0)
    mismatch_loss = tf.expand_dims(tf.maximum(0., tf.subtract(margin, tf.square(diff)), 'mismatch_term'), 0)

    loss = tf.add(tf.matmul(labels, match_loss), tf.matmul((1 - labels), mismatch_loss), 'loss_add')
    distance = tf.reduce_mean(loss)

    optimizer = tf.train.AdamOptimizer(learning_rate).minimize(distance)
</code>```

Following is the code to train the model:

```<code>with graph.as_default():
    saver = tf.train.Saver()

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer(), feed_dict={embedding_placeholder: embedding_matrix})

    iteration = 1
    for e in range(epochs):
        summary_writer = tf.summary.FileWriter('/Users/mithun/projects/kaggle/quora_question_pairs/logs', sess.graph)
        summary_writer.add_graph(sess.graph)

        for ii, (x1, x2, y) in enumerate(get_batches(question1_train, question2_train, label_train, batch_size), 1):
            feed = {question1_inputs: x1,
                    question2_inputs: x2,
                    labels: y[:, None],
                    keep_prob: 0.9
                   }
            loss1 = sess.run([distance], feed_dict=feed)

            if iteration%5==0:
                print("Epoch: {}/{}".format(e, epochs),
                      "Iteration: {}".format(iteration),
                      "Train loss: {:.3f}".format(loss1))

            if iteration%50==0:
                val_acc = []
                for x1, x2, y in get_batches(question1_val, question2_val, label_val, batch_size):
                    feed = {question1_inputs: x1,
                            question2_inputs: x2,
                            labels: y[:, None],
                            keep_prob: 1
                           }
                    batch_acc = sess.run([accuracy], feed_dict=feed)
                    val_acc.append(batch_acc)
                print("Val acc: {:.3f}".format(np.mean(val_acc)))
            iteration +=1

    saver.save(sess, "checkpoints/quora_pairs.ckpt")
</code>```

I have trained the above model with about 10,000 labeled data. But, the accuracy is stagnant at around 0.630 and strangely the validation accuracy is same across all the iterations.

```<code>lstm_size = 64
lstm_layers = 1
batch_size = 128
learning_rate = 0.001
</code>```

Is there anything wrong with the way I have created the model?

答: This is a common problem with imbalanced datasets like the recently released Quora dataset which you are using. Since the Quora dataset is imbalanced (~63% negative and ~37% positive examples) you need proper initialization of weights. Without weight initialization your solution will be stuck in a local minima and it will train to predict only the negative class. Hence the 63% accuracy, because that is the percentage of 'not similar' questions in your validation data. If you check the results obtained on your validation set you will notice that it predicts all zeros. A truncated normal distribution proposed in He et al., http://arxiv.org/abs/1502.01852 is a good alternate for initializing the weights.</p>

Body:
Dataset Description

The dataset contains a set of question pairs and a label which tells if the questions are same. e.g.

"How do I read and find my YouTube comments?" , "How can I see all my
  Youtube comments?" , "1"

The goal of the model is to identify if the given question pair is same or different.

Approach

I have created a Siamese network to identify if two questions are same. Following is the model:

graph = tf.Graph()

with graph.as_default():
    embedding_placeholder = tf.placeholder(tf.float32, shape=embedding_matrix.shape, name='embedding_placeholder')
    with tf.variable_scope('siamese_network') as scope:
        labels = tf.placeholder(tf.int32, [batch_size, None], name='labels')
        keep_prob = tf.placeholder(tf.float32, name='question1_keep_prob')

        with tf.name_scope('question1') as question1_scope:
            question1_inputs = tf.placeholder(tf.int32, [batch_size, seq_len], name='question1_inputs')

            question1_embedding = tf.get_variable(name='embedding', initializer=embedding_placeholder, trainable=False)
            question1_embed = tf.nn.embedding_lookup(question1_embedding, question1_inputs)

            question1_lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
            question1_drop = tf.contrib.rnn.DropoutWrapper(question1_lstm, output_keep_prob=keep_prob)
            question1_multi_lstm = tf.contrib.rnn.MultiRNNCell([question1_drop] * lstm_layers)

            q1_initial_state = question1_multi_lstm.zero_state(batch_size, tf.float32)

            question1_outputs, question1_final_state = tf.nn.dynamic_rnn(question1_multi_lstm, question1_embed, initial_state=q1_initial_state)

        scope.reuse_variables()

        with tf.name_scope('question2') as question2_scope:
            question2_inputs = tf.placeholder(tf.int32, [batch_size, seq_len], name='question2_inputs')

            question2_embedding = question1_embedding
            question2_embed = tf.nn.embedding_lookup(question2_embedding, question2_inputs)

            question2_lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
            question2_drop = tf.contrib.rnn.DropoutWrapper(question2_lstm, output_keep_prob=keep_prob)
            question2_multi_lstm = tf.contrib.rnn.MultiRNNCell([question2_drop] * lstm_layers)

            q2_initial_state = question2_multi_lstm.zero_state(batch_size, tf.float32)

            question2_outputs, question2_final_state = tf.nn.dynamic_rnn(question2_multi_lstm, question2_embed, initial_state=q2_initial_state)

Calculate the cosine distance using the RNN outputs:

with graph.as_default():
    diff = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(question1_outputs[:, -1, :], question2_outputs[:, -1, :])), reduction_indices=1))

    margin = tf.constant(1.)
    labels = tf.to_float(labels)
    match_loss = tf.expand_dims(tf.square(diff, 'match_term'), 0)
    mismatch_loss = tf.expand_dims(tf.maximum(0., tf.subtract(margin, tf.square(diff)), 'mismatch_term'), 0)

    loss = tf.add(tf.matmul(labels, match_loss), tf.matmul((1 - labels), mismatch_loss), 'loss_add')
    distance = tf.reduce_mean(loss)

    optimizer = tf.train.AdamOptimizer(learning_rate).minimize(distance)

Following is the code to train the model:

with graph.as_default():
    saver = tf.train.Saver()

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer(), feed_dict={embedding_placeholder: embedding_matrix})

    iteration = 1
    for e in range(epochs):
        summary_writer = tf.summary.FileWriter('/Users/mithun/projects/kaggle/quora_question_pairs/logs', sess.graph)
        summary_writer.add_graph(sess.graph)

        for ii, (x1, x2, y) in enumerate(get_batches(question1_train, question2_train, label_train, batch_size), 1):
            feed = {question1_inputs: x1,
                    question2_inputs: x2,
                    labels: y[:, None],
                    keep_prob: 0.9
                   }
            loss1 = sess.run([distance], feed_dict=feed)

            if iteration%5==0:
                print("Epoch: {}/{}".format(e, epochs),
                      "Iteration: {}".format(iteration),
                      "Train loss: {:.3f}".format(loss1))

            if iteration%50==0:
                val_acc = []
                for x1, x2, y in get_batches(question1_val, question2_val, label_val, batch_size):
                    feed = {question1_inputs: x1,
                            question2_inputs: x2,
                            labels: y[:, None],
                            keep_prob: 1
                           }
                    batch_acc = sess.run([accuracy], feed_dict=feed)
                    val_acc.append(batch_acc)
                print("Val acc: {:.3f}".format(np.mean(val_acc)))
            iteration +=1

    saver.save(sess, "checkpoints/quora_pairs.ckpt")

I have trained the above model with about 10,000 labeled data. But, the accuracy is stagnant at around 0.630 and strangely the validation accuracy is same across all the iterations.

lstm_size = 64
lstm_layers = 1
batch_size = 128
learning_rate = 0.001

Is there anything wrong with the way I have created the model?


来源: stackexchange

问:
Error when building veins_inet subproject
I have imported the veins_inet subproject when importing the veins 4.5 project (by selecting the "Search for nested projects") in Omnet++.
I have built veins and can run the Erlangen example.

However, I cannot build the veins_inet project.
The sources can be found here: https://github.com/sommer/veins/tree/master/subprojects/veins_inet

I get the following error:

```<code>make MODE=debug all
make[1]: Entering directory '/home/XX/omnetpp-5.1.1/samples/veins/subprojects/veins_inet/src'
veins_inet/VeinsInetManager.cc
veins_inet/VeinsInetManager.cc:21:41: fatal error: veins_inet/VeinsInetManager.h: No such file or directory
compilation terminated.
Makefile:97: recipe for target '../out/gcc-debug/src/veins_inet/VeinsInetManager.o' failed
make[1]: Leaving directory '/home/XX/omnetpp-5.1.1/samples/veins/subprojects/veins_inet/src'
Makefile:12: recipe for target 'all' failed
make[1]: *** [../out/gcc-debug/src/veins_inet/VeinsInetManager.o] Error 1
make: *** [all] Error 2
</code>```

It seems like the header files have failed to be included.

I can bypass the "No such file or directory" errors by manually copying all necessary *.h files into the veins_inet/src/veins_inet folder and editing the *.cc and *.h files, such that the compiler finds the required header files.

I guess the issue lies in the Makefiles, or rather in the configure file, which generates the Makefiles.

veins_inet/configure:

```<code>#!/usr/bin/env python

"""
Creates Makefile(s) for building Veins_INET.
"""

import os
import sys
import subprocess
from logging import warning, error
from optparse import OptionParser

# Option handling
parser = OptionParser()
parser.add_option("--with-veins", dest="veins", help="link Veins_INET with a version of Veins installed in PATH [default: do not link with Veins]", metavar="PATH", default="../..")
parser.add_option("--with-inet", dest="inet", help="link Veins_INET with a version of the INET Framework installed in PATH [default: do not link with INET]", metavar="PATH", default="../../../inet")
(options, args) = parser.parse_args()

if args:
    warning("Superfluous command line arguments: \"%s\"" % " ".join(args))

# Start with default flags
makemake_flags = ['-f', '--deep', '--no-deep-includes', '--make-so', '-I', '.', '-o', 'veins_inet', '-O', 'out']
run_libs = [os.path.join('src', 'veins_inet')]
run_neds = [os.path.join('src', 'veins_inet')]

# Add flags for Veins
if options.veins:
    check_fname = os.path.join(options.veins, 'src/veins/package.ned')
    expect_version = '4'
    if not os.path.isfile(check_fname):
        error('Could not find Veins (by looking for %s). Check the path to Veins (--with-veins=... option) and the Veins version (should be version %s)' % (check_fname, expect_version))
        sys.exit(1)

    veins_header_dirs = [os.path.join(os.path.relpath(options.veins, 'src'), 'src')]
    veins_includes = ['-I' + s for s in veins_header_dirs]
    veins_link = ["-L" + os.path.join(os.path.relpath(options.veins, 'src'), 'src'), "-lveins"]
    veins_defs = []

    makemake_flags += veins_includes + veins_link + veins_defs
    run_libs = [os.path.relpath(os.path.join(options.veins, 'src', 'veins'))] + run_libs
    run_neds = [os.path.relpath(os.path.join(options.veins, 'src', 'veins'))] + run_neds

# Add flags for INET
if options.inet:
    fname = os.path.join(options.inet, '_scripts/get_version')
    expect_version = '3.4.0'
    try:
        print 'Running "%s" to determine INET version.' % fname
        version = subprocess.check_output(fname).strip()
        if not version == expect_version:
            warning('Unsupported INET Version. Expecting %s, found "%s"' % (expect_version, version))
        else:
            print 'Found INET version "%s". Okay.' % version
    except OSError as e:
        error('Could not determine INET Version (by running %s): %s. Check the path to INET (--with-inet=... option) and the INET version (should be version %s)' % (fname, e, expect_version))
        sys.exit(1)

    inet_header_dirs = [os.path.join(os.path.relpath(options.inet, 'src'), 'src')]
    inet_includes = ['-I' + s for s in inet_header_dirs]
    inet_link = ["-L" + os.path.join(os.path.relpath(options.inet, 'src'), 'src'), "-lINET"]
    inet_defs = ["-DINET_IMPORT"]

    makemake_flags += inet_includes + inet_link + inet_defs
    run_libs = [os.path.relpath(os.path.join(options.inet, 'src', 'INET'))] + run_libs
    run_neds = [os.path.relpath(os.path.join(options.inet, 'src'))] + run_neds

# Start creating files
if not os.path.isdir('out'):
    os.mkdir('out')

f = open(os.path.join('out', 'config.py'), 'w')
f.write('run_libs = %s\n' % repr(run_libs))
f.write('run_neds = %s\n' % repr(run_neds))
f.close()

subprocess.check_call(['env', 'opp_makemake'] + makemake_flags, cwd='src')

print 'Configure done. You can now run "make".'
</code>```

veins_inet/Makefile

```<code>.PHONY: all makefiles clean cleanall doxy

# if out/config.py exists, we can also create command line scripts for running simulations
ADDL_TARGETS =
ifeq ($(wildcard out/config.py),)
else
    ADDL_TARGETS += run debug memcheck
endif

# default target
all: src/Makefile $(ADDL_TARGETS)
    @cd src && $(MAKE)

# command line scripts
run debug memcheck: % : src/scripts/%.in.py out/config.py
    @echo "Creating script \"./$@\""
    @head -n1 "$<" > "$@"
    @cat out/config.py >> "$@"
    @tail -n+2 "$<" >> "$@"
    @chmod a+x "$@"

# legacy
makefiles:
    @echo
    @echo '====================================================================='
    @echo 'Warning: make makefiles has been deprecated in favor of ./configure'
    @echo '====================================================================='
    @echo
    ./configure
    @echo
    @echo '====================================================================='
    @echo 'Warning: make makefiles has been deprecated in favor of ./configure'
    @echo '====================================================================='
    @echo

clean: src/Makefile
    cd src && $(MAKE) clean
    rm -f run debug memcheck

cleanall: src/Makefile
    cd src && $(MAKE) MODE=release clean
    cd src && $(MAKE) MODE=debug clean
    rm -f src/Makefile
    rm -f run debug memcheck

src/Makefile:
    @echo
    @echo '====================================================================='
    @echo '$@ does not exist.'
    @echo 'Please run "./configure" or use the OMNeT++ IDE to generate it.'
    @echo '====================================================================='
    @echo
    @exit 1

out/config.py:
    @echo
    @echo '====================================================================='
    @echo '$@ does not exist.'
    @echo 'Please run "./configure" to generate it.'
    @echo '====================================================================='
    @echo
    @exit 1

# autogenerated documentation
doxy:
    doxygen doxy.cfg

doxyshow: doxy
    xdg-open doc/doxy/index.html
</code>```

veins_inet/src/Makefile

```<code>#
# OMNeT++/OMNEST Makefile for $(LIB_PREFIX)veins_inet
#
# This file was generated with the command:
#  opp_makemake --make-so -f --deep -KINET_PROJ=../../../../inet -KVEINS_PROJ=../../.. -L$$\(INET_PROJ\)/out/$$\(CONFIGNAME\)/src -L$$\(VEINS_PROJ\)/out/$$\(CONFIGNAME\)/src -lINET -lveins
#

# Name of target to be created (-o option)
TARGET = $(LIB_PREFIX)veins_inet$(SHARED_LIB_SUFFIX)

# C++ include paths (with -I)
INCLUDE_PATH =

# Additional object and library files to link with
EXTRA_OBJS =

# Additional libraries (-L, -l options)
LIBS = $(LDFLAG_LIBPATH)$(INET_PROJ)/out/$(CONFIGNAME)/src $(LDFLAG_LIBPATH)$(VEINS_PROJ)/out/$(CONFIGNAME)/src  -lINET -lveins

# Output directory
PROJECT_OUTPUT_DIR = ../out
PROJECTRELATIVE_PATH = src
O = $(PROJECT_OUTPUT_DIR)/$(CONFIGNAME)/$(PROJECTRELATIVE_PATH)

# Object files for local .cc, .msg and .sm files
OBJS = $O/veins_inet/VeinsInetManager.o $O/veins_inet/VeinsInetMobility.o

# Message files
MSGFILES =

# SM files
SMFILES =

# Other makefile variables (-K)
INET_PROJ=../../../../inet
VEINS_PROJ=../../..

#------------------------------------------------------------------------------

# Pull in OMNeT++ configuration (Makefile.inc)

ifneq ("$(OMNETPP_CONFIGFILE)","")
CONFIGFILE = $(OMNETPP_CONFIGFILE)
else
ifneq ("$(OMNETPP_ROOT)","")
CONFIGFILE = $(OMNETPP_ROOT)/Makefile.inc
else
CONFIGFILE = $(shell opp_configfilepath)
endif
endif

ifeq ("$(wildcard $(CONFIGFILE))","")
$(error Config file '$(CONFIGFILE)' does not exist -- add the OMNeT++ bin directory to the path so that opp_configfilepath can be found, or set the OMNETPP_CONFIGFILE variable to point to Makefile.inc)
endif

include $(CONFIGFILE)

# Simulation kernel and user interface libraries
OMNETPP_LIBS = -loppenvir$D $(KERNEL_LIBS) $(SYS_LIBS)
ifneq ($(TOOLCHAIN_NAME),clangc2)
LIBS += -Wl,-rpath,$(abspath $(INET_PROJ)/out/$(CONFIGNAME)/src) -Wl,-rpath,$(abspath $(VEINS_PROJ)/out/$(CONFIGNAME)/src)
endif

COPTS = $(CFLAGS) $(IMPORT_DEFINES)  $(INCLUDE_PATH) -I$(OMNETPP_INCL_DIR)
MSGCOPTS = $(INCLUDE_PATH)
SMCOPTS =

# we want to recompile everything if COPTS changes,
# so we store COPTS into $COPTS_FILE and have object
# files depend on it (except when "make depend" was called)
COPTS_FILE = $O/.last-copts
ifneq ("$(COPTS)","$(shell cat $(COPTS_FILE) 2>/dev/null || echo '')")
$(shell $(MKPATH) "$O" && echo "$(COPTS)" >$(COPTS_FILE))
endif

#------------------------------------------------------------------------------
# User-supplied makefile fragment(s)
# >>>
# <<<
#------------------------------------------------------------------------------

# Main target
all: $O/$(TARGET)
    $(Q)$(LN) $O/$(TARGET) .

$O/$(TARGET): $(OBJS)  $(wildcard $(EXTRA_OBJS)) Makefile $(CONFIGFILE)
    @$(MKPATH) $O
    @echo Creating shared library: $@
    $(Q)$(SHLIB_LD) -o $O/$(TARGET) $(OBJS) $(EXTRA_OBJS) $(AS_NEEDED_OFF) $(WHOLE_ARCHIVE_ON) $(LIBS) $(WHOLE_ARCHIVE_OFF) $(OMNETPP_LIBS) $(LDFLAGS)
    $(Q)$(SHLIB_POSTPROCESS) $O/$(TARGET)

.PHONY: all clean cleanall depend msgheaders smheaders

.SUFFIXES: .cc

$O/%.o: %.cc $(COPTS_FILE) | msgheaders smheaders
    @$(MKPATH) $(dir $@)
    $(qecho) "$<"
    $(Q)$(CXX) -c $(CXXFLAGS) $(COPTS) -o $@ $<

%_m.cc %_m.h: %.msg
    $(qecho) MSGC: $<
    $(Q)$(MSGC) -s _m.cc $(MSGCOPTS) $?

%_sm.cc %_sm.h: %.sm
    $(qecho) SMC: $<
    $(Q)$(SMC) -c++ -suffix cc $(SMCOPTS) $?

msgheaders: $(MSGFILES:.msg=_m.h)

smheaders: $(SMFILES:.sm=_sm.h)

clean:
    $(qecho) Cleaning...
    $(Q)-rm -rf $O
    $(Q)-rm -f $(TARGET)
    $(Q)-rm -f $(call opp_rwildcard, . , *_m.cc *_m.h *_sm.cc *_sm.h)

cleanall: clean
    $(Q)-rm -rf $(PROJECT_OUTPUT_DIR)

# include all dependencies
-include $(OBJS:%.o=%.d)
</code>```

Has anybody solved the issue ?

答:
To solve the problem I had to add missing "Include Paths" to the project properties:

1. Select your veins_inet project and click Project>>Properties in Omnet++

2. In the new window expand the OMNeT++ entry and select Makemake

3. select src:makemake(deep,recurse)-->veins_inet(dynamic lib)

4. Click on the Options... button

It should look like this: Properties for veins_inet window

5. Go to the Compile tab in the window that opens

6. Enter the missing include directories:

```<code>[workspace]/veins/subprojects/veins_inet/src
[workspace]/veins/src
[workspace]/inet/src
</code>```

You should end up with something similar: Makemake Options window

7. Click OK in both windows

8. You should be able to build the veins_inet project without errors

ContentLicense: CC BY-SA 3.0

Body:
I have imported the veins_inet subproject when importing the veins 4.5 project (by selecting the "Search for nested projects") in Omnet++.
I have built veins and can run the Erlangen example.

However, I cannot build the veins_inet project.
The sources can be found here: https://github.com/sommer/veins/tree/master/subprojects/veins_inet

I get the following error:

make MODE=debug all
make[1]: Entering directory '/home/XX/omnetpp-5.1.1/samples/veins/subprojects/veins_inet/src'
veins_inet/VeinsInetManager.cc
veins_inet/VeinsInetManager.cc:21:41: fatal error: veins_inet/VeinsInetManager.h: No such file or directory
compilation terminated.
Makefile:97: recipe for target '../out/gcc-debug/src/veins_inet/VeinsInetManager.o' failed
make[1]: Leaving directory '/home/XX/omnetpp-5.1.1/samples/veins/subprojects/veins_inet/src'
Makefile:12: recipe for target 'all' failed
make[1]: *** [../out/gcc-debug/src/veins_inet/VeinsInetManager.o] Error 1
make: *** [all] Error 2

It seems like the header files have failed to be included.

I can bypass the "No such file or directory" errors by manually copying all necessary *.h files into the veins_inet/src/veins_inet folder and editing the *.cc and *.h files, such that the compiler finds the required header files.

I guess the issue lies in the Makefiles, or rather in the configure file, which generates the Makefiles.

veins_inet/configure:

#!/usr/bin/env python

"""
Creates Makefile(s) for building Veins_INET.
"""

import os
import sys
import subprocess
from logging import warning, error
from optparse import OptionParser

# Option handling
parser = OptionParser()
parser.add_option("--with-veins", dest="veins", help="link Veins_INET with a version of Veins installed in PATH [default: do not link with Veins]", metavar="PATH", default="../..")
parser.add_option("--with-inet", dest="inet", help="link Veins_INET with a version of the INET Framework installed in PATH [default: do not link with INET]", metavar="PATH", default="../../../inet")
(options, args) = parser.parse_args()

if args:
    warning("Superfluous command line arguments: \"%s\"" % " ".join(args))

# Start with default flags
makemake_flags = ['-f', '--deep', '--no-deep-includes', '--make-so', '-I', '.', '-o', 'veins_inet', '-O', 'out']
run_libs = [os.path.join('src', 'veins_inet')]
run_neds = [os.path.join('src', 'veins_inet')]

# Add flags for Veins
if options.veins:
    check_fname = os.path.join(options.veins, 'src/veins/package.ned')
    expect_version = '4'
    if not os.path.isfile(check_fname):
        error('Could not find Veins (by looking for %s). Check the path to Veins (--with-veins=... option) and the Veins version (should be version %s)' % (check_fname, expect_version))
        sys.exit(1)

    veins_header_dirs = [os.path.join(os.path.relpath(options.veins, 'src'), 'src')]
    veins_includes = ['-I' + s for s in veins_header_dirs]
    veins_link = ["-L" + os.path.join(os.path.relpath(options.veins, 'src'), 'src'), "-lveins"]
    veins_defs = []

    makemake_flags += veins_includes + veins_link + veins_defs
    run_libs = [os.path.relpath(os.path.join(options.veins, 'src', 'veins'))] + run_libs
    run_neds = [os.path.relpath(os.path.join(options.veins, 'src', 'veins'))] + run_neds

# Add flags for INET
if options.inet:
    fname = os.path.join(options.inet, '_scripts/get_version')
    expect_version = '3.4.0'
    try:
        print 'Running "%s" to determine INET version.' % fname
        version = subprocess.check_output(fname).strip()
        if not version == expect_version:
            warning('Unsupported INET Version. Expecting %s, found "%s"' % (expect_version, version))
        else:
            print 'Found INET version "%s". Okay.' % version
    except OSError as e:
        error('Could not determine INET Version (by running %s): %s. Check the path to INET (--with-inet=... option) and the INET version (should be version %s)' % (fname, e, expect_version))
        sys.exit(1)

    inet_header_dirs = [os.path.join(os.path.relpath(options.inet, 'src'), 'src')]
    inet_includes = ['-I' + s for s in inet_header_dirs]
    inet_link = ["-L" + os.path.join(os.path.relpath(options.inet, 'src'), 'src'), "-lINET"]
    inet_defs = ["-DINET_IMPORT"]

    makemake_flags += inet_includes + inet_link + inet_defs
    run_libs = [os.path.relpath(os.path.join(options.inet, 'src', 'INET'))] + run_libs
    run_neds = [os.path.relpath(os.path.join(options.inet, 'src'))] + run_neds

# Start creating files
if not os.path.isdir('out'):
    os.mkdir('out')

f = open(os.path.join('out', 'config.py'), 'w')
f.write('run_libs = %s\n' % repr(run_libs))
f.write('run_neds = %s\n' % repr(run_neds))
f.close()

subprocess.check_call(['env', 'opp_makemake'] + makemake_flags, cwd='src')

print 'Configure done. You can now run "make".'

veins_inet/Makefile

.PHONY: all makefiles clean cleanall doxy

# if out/config.py exists, we can also create command line scripts for running simulations
ADDL_TARGETS =
ifeq ($(wildcard out/config.py),)
else
    ADDL_TARGETS += run debug memcheck
endif

# default target
all: src/Makefile $(ADDL_TARGETS)
    @cd src && $(MAKE)

# command line scripts
run debug memcheck: % : src/scripts/%.in.py out/config.py
    @echo "Creating script \"./$@\""
    @head -n1 "$<" > "$@"
    @cat out/config.py >> "$@"
    @tail -n+2 "$<" >> "$@"
    @chmod a+x "$@"

# legacy
makefiles:
    @echo
    @echo '====================================================================='
    @echo 'Warning: make makefiles has been deprecated in favor of ./configure'
    @echo '====================================================================='
    @echo
    ./configure
    @echo
    @echo '====================================================================='
    @echo 'Warning: make makefiles has been deprecated in favor of ./configure'
    @echo '====================================================================='
    @echo

clean: src/Makefile
    cd src && $(MAKE) clean
    rm -f run debug memcheck

cleanall: src/Makefile
    cd src && $(MAKE) MODE=release clean
    cd src && $(MAKE) MODE=debug clean
    rm -f src/Makefile
    rm -f run debug memcheck

src/Makefile:
    @echo
    @echo '====================================================================='
    @echo '$@ does not exist.'
    @echo 'Please run "./configure" or use the OMNeT++ IDE to generate it.'
    @echo '====================================================================='
    @echo
    @exit 1

out/config.py:
    @echo
    @echo '====================================================================='
    @echo '$@ does not exist.'
    @echo 'Please run "./configure" to generate it.'
    @echo '====================================================================='
    @echo
    @exit 1

# autogenerated documentation
doxy:
    doxygen doxy.cfg

doxyshow: doxy
    xdg-open doc/doxy/index.html

veins_inet/src/Makefile

#
# OMNeT++/OMNEST Makefile for $(LIB_PREFIX)veins_inet
#
# This file was generated with the command:
#  opp_makemake --make-so -f --deep -KINET_PROJ=../../../../inet -KVEINS_PROJ=../../.. -L$$\(INET_PROJ\)/out/$$\(CONFIGNAME\)/src -L$$\(VEINS_PROJ\)/out/$$\(CONFIGNAME\)/src -lINET -lveins
#

# Name of target to be created (-o option)
TARGET = $(LIB_PREFIX)veins_inet$(SHARED_LIB_SUFFIX)

# C++ include paths (with -I)
INCLUDE_PATH =

# Additional object and library files to link with
EXTRA_OBJS =

# Additional libraries (-L, -l options)
LIBS = $(LDFLAG_LIBPATH)$(INET_PROJ)/out/$(CONFIGNAME)/src $(LDFLAG_LIBPATH)$(VEINS_PROJ)/out/$(CONFIGNAME)/src  -lINET -lveins

# Output directory
PROJECT_OUTPUT_DIR = ../out
PROJECTRELATIVE_PATH = src
O = $(PROJECT_OUTPUT_DIR)/$(CONFIGNAME)/$(PROJECTRELATIVE_PATH)

# Object files for local .cc, .msg and .sm files
OBJS = $O/veins_inet/VeinsInetManager.o $O/veins_inet/VeinsInetMobility.o

# Message files
MSGFILES =

# SM files
SMFILES =

# Other makefile variables (-K)
INET_PROJ=../../../../inet
VEINS_PROJ=../../..

#------------------------------------------------------------------------------

# Pull in OMNeT++ configuration (Makefile.inc)

ifneq ("$(OMNETPP_CONFIGFILE)","")
CONFIGFILE = $(OMNETPP_CONFIGFILE)
else
ifneq ("$(OMNETPP_ROOT)","")
CONFIGFILE = $(OMNETPP_ROOT)/Makefile.inc
else
CONFIGFILE = $(shell opp_configfilepath)
endif
endif

ifeq ("$(wildcard $(CONFIGFILE))","")
$(error Config file '$(CONFIGFILE)' does not exist -- add the OMNeT++ bin directory to the path so that opp_configfilepath can be found, or set the OMNETPP_CONFIGFILE variable to point to Makefile.inc)
endif

include $(CONFIGFILE)

# Simulation kernel and user interface libraries
OMNETPP_LIBS = -loppenvir$D $(KERNEL_LIBS) $(SYS_LIBS)
ifneq ($(TOOLCHAIN_NAME),clangc2)
LIBS += -Wl,-rpath,$(abspath $(INET_PROJ)/out/$(CONFIGNAME)/src) -Wl,-rpath,$(abspath $(VEINS_PROJ)/out/$(CONFIGNAME)/src)
endif

COPTS = $(CFLAGS) $(IMPORT_DEFINES)  $(INCLUDE_PATH) -I$(OMNETPP_INCL_DIR)
MSGCOPTS = $(INCLUDE_PATH)
SMCOPTS =

# we want to recompile everything if COPTS changes,
# so we store COPTS into $COPTS_FILE and have object
# files depend on it (except when "make depend" was called)
COPTS_FILE = $O/.last-copts
ifneq ("$(COPTS)","$(shell cat $(COPTS_FILE) 2>/dev/null || echo '')")
$(shell $(MKPATH) "$O" && echo "$(COPTS)" >$(COPTS_FILE))
endif

#------------------------------------------------------------------------------
# User-supplied makefile fragment(s)
# >>>
# <<<
#------------------------------------------------------------------------------

# Main target
all: $O/$(TARGET)
    $(Q)$(LN) $O/$(TARGET) .

$O/$(TARGET): $(OBJS)  $(wildcard $(EXTRA_OBJS)) Makefile $(CONFIGFILE)
    @$(MKPATH) $O
    @echo Creating shared library: $@
    $(Q)$(SHLIB_LD) -o $O/$(TARGET) $(OBJS) $(EXTRA_OBJS) $(AS_NEEDED_OFF) $(WHOLE_ARCHIVE_ON) $(LIBS) $(WHOLE_ARCHIVE_OFF) $(OMNETPP_LIBS) $(LDFLAGS)
    $(Q)$(SHLIB_POSTPROCESS) $O/$(TARGET)

.PHONY: all clean cleanall depend msgheaders smheaders

.SUFFIXES: .cc

$O/%.o: %.cc $(COPTS_FILE) | msgheaders smheaders
    @$(MKPATH) $(dir $@)
    $(qecho) "$<"
    $(Q)$(CXX) -c $(CXXFLAGS) $(COPTS) -o $@ $<

%_m.cc %_m.h: %.msg
    $(qecho) MSGC: $<
    $(Q)$(MSGC) -s _m.cc $(MSGCOPTS) $?

%_sm.cc %_sm.h: %.sm
    $(qecho) SMC: $<
    $(Q)$(SMC) -c++ -suffix cc $(SMCOPTS) $?

msgheaders: $(MSGFILES:.msg=_m.h)

smheaders: $(SMFILES:.sm=_sm.h)

clean:
    $(qecho) Cleaning...
    $(Q)-rm -rf $O
    $(Q)-rm -f $(TARGET)
    $(Q)-rm -f $(call opp_rwildcard, . , *_m.cc *_m.h *_sm.cc *_sm.h)

cleanall: clean
    $(Q)-rm -rf $(PROJECT_OUTPUT_DIR)

# include all dependencies
-include $(OBJS:%.o=%.d)

Has anybody solved the issue ?

Body:
To solve the problem I had to add missing "Include Paths" to the project properties:

1. Select your veins_inet project and click Project>>Properties in Omnet++

2. In the new window expand the OMNeT++ entry and select Makemake

3. select src:makemake(deep,recurse)-->veins_inet(dynamic lib)

4. Click on the Options... button

It should look like this: Properties for veins_inet window

5. Go to the Compile tab in the window that opens

6. Enter the missing include directories:

[workspace]/veins/subprojects/veins_inet/src
[workspace]/veins/src
[workspace]/inet/src

You should end up with something similar: Makemake Options window

7. Click OK in both windows

8. You should be able to build the veins_inet project without errors


问:
When do items in HTML5 local storage expire?
For how long is data stored in localStorage (as part of DOM Storage in HTML5) available? Can I set an expiration time for the data which I put into local storage?

答:
Here highly recommended to use sessionStorage

it is same as localStorage but destroy when session destroyed / browser close

also localStorage can share between tabs while sessionStorage can use in current tab only, but value does not change on refresh page or change the page

sessionStorage is also useful to reduce network traffic against cookie

for set value use

```<code>sessionStorage.setItem("key","my value");
</code>```

for get value use

```<code>var value = sessionStorage.getItem("key");
</code>```

click here for view api

all ways for set are

```<code>  sessionStorage.key = "my val";
  sessionStorage["key"] = "my val";
  sessionStorage.setItem("key","my value");
</code>```

all ways for get are

```<code>  var value = sessionStorage.key;
  var value = sessionStorage["key"];
  var value = sessionStorage.getItem("key");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here highly recommended to use sessionStorage

it is same as localStorage but destroy when session destroyed / browser close

also localStorage can share between tabs while sessionStorage can use in current tab only, but value does not change on refresh page or change the page

sessionStorage is also useful to reduce network traffic against cookie

for set value use

sessionStorage.setItem("key","my value");

for get value use

var value = sessionStorage.getItem("key");

click here for view api

all ways for set are

  sessionStorage.key = "my val";
  sessionStorage["key"] = "my val";
  sessionStorage.setItem("key","my value");

all ways for get are

  var value = sessionStorage.key;
  var value = sessionStorage["key"];
  var value = sessionStorage.getItem("key");


问:
Lack of practical insights into using Play+Scala vs. JavaScript
We (my team) is starting on a cloud-hosted web based application. We embarked upon Scala+Play as the server side web application. Since no one knew Scala in my team (previous experience in Java/Java Script/Python/C++) all of us are experiencing a steep learning curve. After spending a few weeks on learning basics of Scala, we started with play-scala-starter example as a basis. It took a few days of time for a team member to create a prototype GET+POST API handler accessing mysql DB.
Given significant efforts and the time spent on Scala, a team member for the sake of comparison built the same prototype functionality using node.js in just half-a-day (4-5 hours). That was a revelation for all of us. To add to that the Internet is replete with node.js success stories used in enterprise grade applications (note that for front-end anyway we are going to use JS based framework e.g. Angular, React, etc.).
Now as a team we are debating on next approach - play+scala or node.js. We don't want to take a decision based on short-term gains or to avoid initial struggle in ramping-up. That's why posting this question here to get real-world insights. If this is a wrong-place to ask such questions then please suggest appropriate one. Most likely this question will be closed as it is of 'discussion' type.
NOTE: This post is not to criticize any of the approaches. So apologies in advance. </p>

答:
This is what you should expect when you "take a quick look into Scala and build a prototype". Scala is a long-term investment. If you want to get all the benefits of its type system, expressiveness and functional programming concepts, it will take much more that a few weeks (I've been doing it for almost three years now and am still learning all the time).

I work at a successful startup which started out with its backend being written in NodeJS because of the same reasoning as you described, but now they are doing all their new stuff in Scala (not Play, but a more FP-oriented framework Finch; however I've been working with Play at my previous two jobs and it's definitely if not the most widespread Scala web framework, then definitely out there near the top). So don't worry, it's really heavily used in production. For example, my favourite chess portal is fully done in Play stack. There were many others three years ago and the list is surely much bigger by now (and of course, these are just the most popular ones; also note that this is the list for those who have specifically declared to be using Play framework, because list for Scala in general would include many other giants, such as Twitter, Coursera, Soundcloud, Spotify, Foursquare, Netflix, AirBnB, Quora, Tumblr, eBay etc.).

When done right, functional programming (oh yes btw, I'm not even considering OOP-style Scala) gives you a lot of safety and security. You know that old saying - "I used to feel like an expert in JS and nothing worked. Now I feel like an amateur in Haskell, but everything works". But compared to Haskell, I feel that Scala has a lot more traction. I understand your worries when you google something related to NodeJS and then the same for Scala, but trust me, once you get going you will realize that Scala has a big community, a lot of material on various blogs/forums/stackoverflow and a huge ecosystem.

As far as NodeJS itself is concerned, you will notice a lot of similarities with Play, both being asynchronous event-driven frameworks. But talking about JS as a language, if you invest time into Scala to become proficient enough with it, you will be asking yourself how could you ever have lived without certain aspects of it, most notably its type system (TypeScript sucks btw).

I'm aware that I'm being subjective, but it's an opinion-based question. It should (and probably will) be marked as too broad / non-constructive / off-topic / unclear, but instead of just flagging it, I decided to try to encourage you guys into making a good long-term decision. Find some extra time, go through a good introductory book, enroll into the Coursera course (started yesterday) and this time next month you will be feeling much more confident with it. Of course, one month is a long time if you need a prototype tomorrow, but if timing is really that critical, then I would always advise to go with the technology you're most comfortable with and leave experimenting for a more relaxed project. Otherwise you will not only be frustrated, but deliver a poor product.


问:
how optimize this mysql query?
i have written this mysql query:

```<code>SELECT * , 1 AS haschild
       FROM table2
       WHERE parentid = '0'
             AND pid IN ( SELECT parentid FROM table2 )
UNION
SELECT * , 0
       FROM table2
       WHERE parentid = '0'
             AND pid NOT IN ( SELECT parentid FROM table2 )
ORDER BY pid
</code>```

but i think it is so silly query !!
hope you can get my meaning of this query and guide me to write a better one.

thanks.

答:
Try :</p>

```<code>SELECT * , CASE WHEN pid IN ( SELECT parentid FROM table2 ) THEN 1 ELSE 0 END AS haschild
       FROM table2
       WHERE parentid = '0'
ORDER BY pid
</code>```

ContentLicense: CC BY-SA 2.5

Title: how optimize this mysql query?

Body:
i have written this mysql query:

SELECT * , 1 AS haschild
       FROM table2
       WHERE parentid = '0'
             AND pid IN ( SELECT parentid FROM table2 )
UNION
SELECT * , 0
       FROM table2
       WHERE parentid = '0'
             AND pid NOT IN ( SELECT parentid FROM table2 )
ORDER BY pid

but i think it is so silly query !!
hope you can get my meaning of this query and guide me to write a better one.

thanks.

Body:
Try :

SELECT * , CASE WHEN pid IN ( SELECT parentid FROM table2 ) THEN 1 ELSE 0 END AS haschild
       FROM table2
       WHERE parentid = '0'
ORDER BY pid


问:
Link cannot appear as a descendant of a link
A React.js app gives the warning

```<code>Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.
See Element > a > ... > a.
</code>```

What does that mean? How can you prevent it? Are nested links illegal in HTML, HTML5 or React.js?

答:
You can use a function instead of a tag:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { Link, withRouter } from 'react-router';

class SomeClass extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.redirect = this.redirect.bind(this);
  }

  redirect(target) {
    this.context.router.push("/path");
  }

  render() {
    return (
      <div>
        <p onClick={this.redirect}>Link</p>
      </div>
    );
  }
}

SomeClass.contextTypes = {
  router: PropTypes.object
};

export default SomeClass;
</code>```

Be careful to use a context.
I'm using a context for routing only.

```<code>class SomeClass extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.redirect = this.redirect.bind(this);
  }
}
</code>```

Body:
A React.js app gives the warning

Warning: validateDOMNesting(...):  cannot appear as a descendant of .
See Element > a > ... > a.

What does that mean? How can you prevent it? Are nested links illegal in HTML, HTML5 or React.js?

Body:
You can use a function instead of a tag:

import React from 'react';
import PropTypes from 'prop-types';
import { Link, withRouter } from 'react-router';

class SomeClass extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.redirect = this.redirect.bind(this);
  }

  redirect(target) {
    this.context.router.push("/path");
  }

  render() {
    return (
      <div>
        <p onClick={this.redirect}>Link</p>
      </div>
    );
  }
}

SomeClass.contextTypes = {
  router: PropTypes.object
};

export default SomeClass;

Be careful to use a context.
I'm using a context for routing only.

class SomeClass extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.redirect = this.redirect.bind(this);
  }
}


问:
C# .NET web api return from post request
I am making a POST request to a route which is returning JSON data.

```<code>    [HttpPost("api/v1/testGetAll")]
    public object Test([FromBody]object filteringOptions)
    {
        return myService.GetLogs(filteringOptions).ToArray();
    }
</code>```

Route works fine, filtering works fine, and when I test the route in Postman I get the right response. However this is only a back-end, and I would like to invoke this route from my custom API gateway.

The issue I'm facing is getting that exact response back. Instead I am getting success status, headers, version, request message etc.

```<code>    public object TestGetAll(string ApiRoute, T json)
    {
        Task<HttpResponseMessage> response;
        var url = ApiHome + ApiRoute;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                response = client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, "application/json"));

                return response.Result;
            }
            catch (Exception e)
            {
                ...
            }
        }
    }
</code>```

How can I get exact content back?

答:
You have to return the response as an HttpResponseMessage.

Try changing your return statement to

```<code>[HttpPost("api/v1/testGetAll")]
public IHttpActionResult Test([FromBody]object filteringOptions)
{
    return Ok(myService.GetLogs(filteringOptions).ToArray());
}
</code>```

Please note: This will return the response with status code 200. In case you want to handle the response based on different response code. You can create the HttpResponseMessage like this-

```<code>Request.CreateResponse<T>(HttpStatusCode.OK, someObject); //success, code- 200
Request.CreateResponse<T>(HttpStatusCode.NotFound, someObject); //error, code- 404
</code>```

T is your object type.

And so on...

Body:
I am making a POST request to a route which is returning JSON data.

    [HttpPost("api/v1/testGetAll")]
    public object Test([FromBody]object filteringOptions)
    {
        return myService.GetLogs(filteringOptions).ToArray();
    }

Route works fine, filtering works fine, and when I test the route in Postman I get the right response. However this is only a back-end, and I would like to invoke this route from my custom API gateway.

The issue I'm facing is getting that exact response back. Instead I am getting success status, headers, version, request message etc.

    public object TestGetAll(string ApiRoute, T json)
    {
        Task<HttpResponseMessage> response;
        var url = ApiHome + ApiRoute;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                response = client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, "application/json"));

                return response.Result;
            }
            catch (Exception e)
            {
                ...
            }
        }
    }

How can I get exact content back?

Body:
You have to return the response as an HttpResponseMessage.

Try changing your return statement to

[HttpPost("api/v1/testGetAll")]
public IHttpActionResult Test([FromBody]object filteringOptions)
{
    return Ok(myService.GetLogs(filteringOptions).ToArray());
}

Please note: This will return the response with status code 200. In case you want to handle the response based on different response code. You can create the HttpResponseMessage like this-

Request.CreateResponse<T>(HttpStatusCode.OK, someObject); //success, code- 200
Request.CreateResponse<T>(HttpStatusCode.NotFound, someObject); //error, code- 404

T is your object type.

And so on...


问:
NoClassDefFoundError: scala/Product$class
I am new to scala and I am trying to create a mixed project with Scala and Java.
However I am facing some issues when I run the test code. When I run the test, I am getting an error

and my pom.xml as follows:

```<code><properties>
    <scala.version>2.12.2</scala.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-compiler</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-reflect</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.scala-tools</groupId>
            <artifactId>maven-scala-plugin</artifactId>
            <version>2.15.2</version>
            <executions>
                <execution>
                    <id>compile</id>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                    <phase>compile</phase>
                </execution>
                <execution>
                    <id>test-compile</id>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                    <phase>test-compile</phase>
                </execution>
                <execution>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.5</source>
                <target>1.5</target>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

My code as follows:

```<code>class BptConsumer {

def consumeLogevent(): Unit ={
  val conf = new SparkConf().setMaster("local[2]").setAppName("PVStatistics");
  val ssc = new StreamingContext(conf,Seconds(5));

  val kafkaParams = Map[String, Object](
    "bootstrap.servers" -> "172.20.13.196:9092",
    "key.deserializer" -> classOf[StringDeserializer],
    "value.deserializer" -> classOf[StringDeserializer],
    "group.id" -> "1",
    "auto.offset.reset" -> "latest",
    "enable.auto.commit" -> (false: java.lang.Boolean)
  )

  val topics = Array("fd-blogs-tst")

  val stream = KafkaUtils.createDirectStream[String, String](
    ssc,
    PreferConsistent,
    Subscribe[String, String](topics, kafkaParams)
  )
  /*val rdd = stream.transform(x=>RDD[String]);*/
  val lines = stream.map(record => (record.key,record.value))

  lines.print();
  ssc.start();
  ssc.awaitTermination();
}
}
</code>```

Could someone help me out in finding the issue?

答:
You're using Scala 2.12.2 with Spark libraries that are built with Scala 2.11. Change your Scala version to a 2.11 release:</p>

```<code><properties>
    <scala.version>2.11.11</scala.version>
</properties>
</code>```

Body:
I am new to scala and I am trying to create a mixed project with Scala and Java.
However I am facing some issues when I run the test code. When I run the test, I am getting an error

and my pom.xml as follows:

<properties>
    <scala.version>2.12.2</scala.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-compiler</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-reflect</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.scala-tools</groupId>
            <artifactId>maven-scala-plugin</artifactId>
            <version>2.15.2</version>
            <executions>
                <execution>
                    <id>compile</id>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                    <phase>compile</phase>
                </execution>
                <execution>
                    <id>test-compile</id>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                    <phase>test-compile</phase>
                </execution>
                <execution>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.5</source>
                <target>1.5</target>
            </configuration>
        </plugin>
    </plugins>
</build>

My code as follows:

class BptConsumer {

def consumeLogevent(): Unit ={
  val conf = new SparkConf().setMaster("local[2]").setAppName("PVStatistics");
  val ssc = new StreamingContext(conf,Seconds(5));

  val kafkaParams = Map[String, Object](
    "bootstrap.servers" -> "172.20.13.196:9092",
    "key.deserializer" -> classOf[StringDeserializer],
    "value.deserializer" -> classOf[StringDeserializer],
    "group.id" -> "1",
    "auto.offset.reset" -> "latest",
    "enable.auto.commit" -> (false: java.lang.Boolean)
  )

  val topics = Array("fd-blogs-tst")

  val stream = KafkaUtils.createDirectStream[String, String](
    ssc,
    PreferConsistent,
    Subscribe[String, String](topics, kafkaParams)
  )
  /*val rdd = stream.transform(x=>RDD[String]);*/
  val lines = stream.map(record => (record.key,record.value))

  lines.print();
  ssc.start();
  ssc.awaitTermination();
}
}

Could someone help me out in finding the issue?

Body:
You're using Scala 2.12.2 with Spark libraries that are built with Scala 2.11. Change your Scala version to a 2.11 release:

<properties>
    <scala.version>2.11.11</scala.version>
</properties>


问:
Unable to find typings.d.ts and declare modules in angular 2 typescript app
I am new to Typescript and Angular 2. I need to install an npm dependency and use it in my angular 2 app.

The dependency is https://www.npmjs.com/package/ng2-stomp-service

I have installed the necessary packages, but I need to add the following to my typings.d.ts file

```<code>declare module 'stompjs';
declare module 'sockjs-client';
</code>```

I am unable to find the typings.d.ts file in my project.

I have tried the following so far,

```<code>npm install typings --global
npm install @types/stompjs
npm isntall @types/sockjs-client
typings install dt~stompjs --save
typings install dt~sockjs-client --save
</code>```

I have typings.json file with contents,

```<code>{
  "dependencies": {
    "sockjs-client": "registry:dt/sockjs-client#1.0.3+20160727010356",
    "stompjs": "registry:dt/stompjs#2.3.0+20161111105645"
  }
}
</code>```

When I run my angular 2 app with npm start it throws error as follows

```<code>ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.
</code>```

I am not sure what is causing the issue, I am guessing it is because I have not declared the modules in typings.d.ts

Please advise. Thank you.

答: If you are not using new version of angular you can't find typings.d.ts file in your project. My suggestion is to update your project using angular CLI https://cli.angular.io/

Body:
I am new to Typescript and Angular 2. I need to install an npm dependency and use it in my angular 2 app.

The dependency is https://www.npmjs.com/package/ng2-stomp-service

I have installed the necessary packages, but I need to add the following to my typings.d.ts file

declare module 'stompjs';
declare module 'sockjs-client';

I am unable to find the typings.d.ts file in my project.

I have tried the following so far,

npm install typings --global
npm install @types/stompjs
npm isntall @types/sockjs-client
typings install dt~stompjs --save
typings install dt~sockjs-client --save

I have typings.json file with contents,

{
  "dependencies": {
    "sockjs-client": "registry:dt/sockjs-client#1.0.3+20160727010356",
    "stompjs": "registry:dt/stompjs#2.3.0+20161111105645"
  }
}

When I run my angular 2 app with npm start it throws error as follows

ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.

I am not sure what is causing the issue, I am guessing it is because I have not declared the modules in typings.d.ts

Please advise. Thank you.


问:
How to use list in list with Flask-Jinja Python
I try to make few tables with data import on web page! I'm using Flask-Jinja with Python.
For example I have this double list:

```<code>list = [[{'pricebb': 1199.99, 'model': 'model1', 'pricebh': 1199, 'pricea': 1299},  {'pricebb': 1199.99, 'model': 'model2', 'pricebh': 1199, 'pricea': 1299}, {'pricebb': 1499.99, 'model': 'model3', 'pricebh': 1499, 'pricea': 1599}], [{'pricebb': 399.99, 'model': 'model4', 'pricebh': 459, 'pricea': 499}, {'pricebb': 599.99, 'model': 'model5', 'pricebh': 669, 'pricea': 699}, {'pricebb': None, 'model': 'model6', 'pricebh': 899, 'pricea': 999}]]
</code>```

I want to separate it with loop and create 2 different tables on one page.
If I use Python with list[0] I get 1-st sublist, but when I try it on Flask:

```<code>{% for post in posts %}
   <p>{{post[0]}}</p>
       {% endfor %}
</code>```

It return to me - model1 and model4) Why its happened? How can I get 1-st sublist from list? Have you any idea !? Thank you!

```<code>run1()

list= sqlselect()# here is array from DB
a = list # its a list sample that I posted above

@FlaskApp2.route('/', methods=('Get', 'Post'))
@FlaskApp2.route('/index')
def index():
    user = {'nickname': 'parser'}  # fake user
    return render_template("index.html",
                           title='Web',
                           user=user,
                           posts=list, describe=des)
</code>```

Here is index.html:

```<code><table>
    <caption>products compare list ({{item}})</caption>

    <thead>
    <tr>

    <th>qqq.com</th>
    <th>Price</th>
    <th>qqq.com</th>
    <th>qqq.com</th>
    </tr>
    </thead>

    {% for post in posts %}
    <p>{{post[0]}}</p>
       {% endfor %}

</table>
</code>```

答:
You can access internal lists by posts[0] - first list, and posts[1] -
 second list (you never should name a variable with a reserved word in python - don't name your var list, but mylist). So to access the elements for the first list you should use:

```<code>{% for post in posts[0] %}
    {% for key, value in post.items %}
    <p>{{ key }}: {{ value }}</p>
{% endfor %}
</code>```

and for the second list:

```<code>{% for post in posts[1] %}
    {% for key, value in post.items %}
    <p>{{ key }}: {{ value }}</p>
{% endfor %}
</code>```

Body:
I try to make few tables with data import on web page! I'm using Flask-Jinja with Python.
For example I have this double list:

list = [[{'pricebb': 1199.99, 'model': 'model1', 'pricebh': 1199, 'pricea': 1299},  {'pricebb': 1199.99, 'model': 'model2', 'pricebh': 1199, 'pricea': 1299}, {'pricebb': 1499.99, 'model': 'model3', 'pricebh': 1499, 'pricea': 1599}], [{'pricebb': 399.99, 'model': 'model4', 'pricebh': 459, 'pricea': 499}, {'pricebb': 599.99, 'model': 'model5', 'pricebh': 669, 'pricea': 699}, {'pricebb': None, 'model': 'model6', 'pricebh': 899, 'pricea': 999}]]

I want to separate it with loop and create 2 different tables on one page.
If I use Python with list[0] I get 1-st sublist, but when I try it on Flask:

{% for post in posts %}

{{post[0]}}

       {% endfor %}

It return to me - model1 and model4) Why its happened? How can I get 1-st sublist from list? Have you any idea !? Thank you!

run1()

list= sqlselect()# here is array from DB
a = list # its a list sample that I posted above

@FlaskApp2.route('/', methods=('Get', 'Post'))
@FlaskApp2.route('/index')
def index():
    user = {'nickname': 'parser'}  # fake user
    return render_template("index.html",
                           title='Web',
                           user=user,
                           posts=list, describe=des)

Here is index.html:

products compare list ({{item}})

    qqq.com
    Price
    qqq.com
    qqq.com

    {% for post in posts %}

{{post[0]}}

       {% endfor %}

Body:
You can access internal lists by posts[0] - first list, and posts[1] -
 second list (you never should name a variable with a reserved word in python - don't name your var list, but mylist). So to access the elements for the first list you should use:

{% for post in posts[0] %}
    {% for key, value in post.items %}
    <p>{{ key }}: {{ value }}</p>
{% endfor %}

and for the second list:

{% for post in posts[1] %}
    {% for key, value in post.items %}
    <p>{{ key }}: {{ value }}</p>
{% endfor %}


问:
libjvm.so: to link or not to link?
All the guides to JNI I've seen (e. g. JNI runtime linking) recommend that I link my JNI libraries against libjvm.so:

```<code>$ gcc -I${JAVA_HOME}/include -c -o test.o test.c
$ gcc -shared -o libtest.so test.o -L${JAVA_HOME}/jre/lib/i386/server -Wl,-rpath,${JAVA_HOME}/jre/lib/i386/server -ljvm
</code>```

If my custom library is written in C++ and uses the C++ JNI API, I can clearly see the corresponding weak symbols in nm -C output:

```<code>00000690 W JNIEnv_::ThrowNew(_jclass*, char const*)
00000672 W JNIEnv_::FindClass(char const*)
</code>```

Still, if I don't mention -ljvm on the command line, the custom native library continues to work just fine, probably because libjvm.so gets automatically loaded by any Java process.

Can you tell me when it is absolutely necessary to explicitly link against libjvm.so?

答:
I think you need it when you want it running the other way round.

For example, you want to create JVM from C/C++ code and call JVM's methods.

For example, here, we need to link with ljvm, otherwise you will not find symbols in your C code.

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo027

Title: libjvm.so: to link or not to link?

Body:
All the guides to JNI I've seen (e. g. JNI runtime linking) recommend that I link my JNI libraries against libjvm.so:

$ gcc -I${JAVA_HOME}/include -c -o test.o test.c
$ gcc -shared -o libtest.so test.o -L${JAVA_HOME}/jre/lib/i386/server -Wl,-rpath,${JAVA_HOME}/jre/lib/i386/server -ljvm

If my custom library is written in C++ and uses the C++ JNI API, I can clearly see the corresponding weak symbols in nm -C output:

00000690 W JNIEnv_::ThrowNew(_jclass*, char const*)
00000672 W JNIEnv_::FindClass(char const*)

Still, if I don't mention -ljvm on the command line, the custom native library continues to work just fine, probably because libjvm.so gets automatically loaded by any Java process.

Can you tell me when it is absolutely necessary to explicitly link against libjvm.so?


问:
space auto add in input php
I have made a form to modify the data with the framework laravel 5.1, everything is ok, but when I submit the form, there are two input are added a space automatically

like this screenshot

there is my form

```<code><form method="post">
 <input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="hidden" name="id_article" value="{!!$opusdef->id_article !!}">
<div class="td w10">
<input type="text" name="code_article" value="{!!$opusdef->code_article  !!}"  required/></div>
<div class="td w5">
<input type="text" name="num_activité" value="{!!$opusdef->num_activité !!}" required/>  </div>
<div class="td w15">
<input type="text" name="libellé_activité" value="{!! $opusdef->libellé_activité !!}" required/> </div>
<div class="td w5">
<input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/></div>
<div class="td w10">
<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/></div>
</code>```

my controller

```<code> protected function  postAllOpusDef(Request $request){
   $data=$request->except('_token');

    $opusDefs=OpusDefs::where('id_article',$data['id_article']);
    if($opusDefs->update($data)){
        return redirect()->back()->with('status','donnée modifiée');
    };
}
</code>```

答:
here in the html only you put two space in the input value

```<code><input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/></div>
<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/></div>
</code>```

remove this as

```<code><input type="text" name="domaine" value="{{$opusdef->domaine}}" required/></div>
<input type="text" name="s_domaine" value="{!!$opusdef->s_domaine!!}" required/></div>
</code>```

Title: space auto add in input php

Body:
I have made a form to modify the data with the framework laravel 5.1, everything is ok, but when I submit the form, there are two input are added a space automatically

like this screenshot

there is my form

<form method="post">
 <input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="hidden" name="id_article" value="{!!$opusdef->id_article !!}">

<input type="text" name="code_article" value="{!!$opusdef->code_article  !!}"  required/>

<input type="text" name="num_activité" value="{!!$opusdef->num_activité !!}" required/>

<input type="text" name="libellé_activité" value="{!! $opusdef->libellé_activité !!}" required/>

<input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/>

<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/>

my controller

 protected function  postAllOpusDef(Request $request){
   $data=$request->except('_token');

    $opusDefs=OpusDefs::where('id_article',$data['id_article']);
    if($opusDefs->update($data)){
        return redirect()->back()->with('status','donnée modifiée');
    };
}

Body:
here in the html only you put two space in the input value

<input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/></div>
<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/></div>

remove this as

<input type="text" name="domaine" value="{{$opusdef->domaine}}" required/></div>
<input type="text" name="s_domaine" value="{!!$opusdef->s_domaine!!}" required/></div>


问:
Regex Contains in the XML element
How can I use "contains" in the regex ("Contains" or "%like%")?

I have a regex to match the XML node with exact text:

```<code><([\w]+)[^>]*>sample<\/\1>
</code>```

It yields the exact Node name, but I want to apply the regex like in C# and SQL (%LIKE%).

Text:

```<code>    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>
</code>```

Expected regex result should return all the above nodes, but currently it returns only the last node.

I created a sample here to test.

答:
You are looking for exact match of the "sample" string inside any tag not the string containing "sample" as substring. You can fix your expression as following to get all the lines:</p>

```<code><([\w]+)[^>]*>[a-zA-Z ]*sample[a-zA-Z ]*<\/\1>
</code>```

Title: Regex Contains in the XML element

Body:
How can I use "contains" in the regex ("Contains" or "%like%")?

I have a regex to match the XML node with exact text:

<([\w]+)[^>]*>sample<\/\1>

It yields the exact Node name, but I want to apply the regex like in C# and SQL (%LIKE%).

Text:

    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>

Expected regex result should return all the above nodes, but currently it returns only the last node.

I created a sample here to test.

Body:
You are looking for exact match of the "sample" string inside any tag not the string containing "sample" as substring. You can fix your expression as following to get all the lines:

<([\w]+)[^>]*>[a-zA-Z ]*sample[a-zA-Z ]*<\/\1>


问:
How to access property of $data?
I do
```</code></p>

<p>and i get 2 arrays with some data. </p>

<p><code><pre data-bind='text: ko.toJSON($data.ResourceDetails)'>```

does return me the properties of the specific array but if i do $data.ResourceDetails.Name it doesnt return anything.

Sample data from ResourceDetails

```<code>"Name": "298ff799-a4a6-4e2e-82d9-e8eb99e8e2d2",
"BranchID": 0,
"GroupUID": "37c0a2fc-caef-4bf3-adf0-9d187d9cf441",
"Capacity": 11,
"Duration": 60,
"ScheduleUID": "d62be6f8-b6ae-4806-9aef-832e073ee82c",
"Description": "Test",
"Active": 1,
"SortOrder": 0,
"CreatedBy": "System",
"CreatedOn": "2017-05-17T14:12:57.317",
"LastEditBy": "System",
"LastEditOn": "2017-05-17T14:12:57.317",
</code>```

Whats wrong? Why i cannot success Name ?

```

doesnt work aswell.

答:
if ResourceDetails is an observable array, you need to access to one position in this array:

```<code>   ResourceDetails()[0]
</code>```

More information: Observable arrays

Title: How to access property of $data?

Body:
I do

and i get 2 arrays with some data.

does return me the properties of the specific array but if i do $data.ResourceDetails.Name it doesnt return anything.

Sample data from ResourceDetails

"Name": "298ff799-a4a6-4e2e-82d9-e8eb99e8e2d2",
"BranchID": 0,
"GroupUID": "37c0a2fc-caef-4bf3-adf0-9d187d9cf441",
"Capacity": 11,
"Duration": 60,
"ScheduleUID": "d62be6f8-b6ae-4806-9aef-832e073ee82c",
"Description": "Test",
"Active": 1,
"SortOrder": 0,
"CreatedBy": "System",
"CreatedOn": "2017-05-17T14:12:57.317",
"LastEditBy": "System",
"LastEditOn": "2017-05-17T14:12:57.317",

Whats wrong? Why i cannot success Name ?

doesnt work aswell.

Body:
if ResourceDetails is an observable array, you need to access to one position in this array:

   ResourceDetails()[0]

More information: Observable arrays


问:
Linq select self reference during creation in C#
Basically what I want is the same that is answered here but in C#:
Self-references in object literal declarations

What I have is this code:

```<code>private List<myObject> myFunction()
{
    return myList.Select(l => new myObject
    {
        propA = 6,
        propB = 3,
        propC = propA + propB
    }
    ).ToList();
}
</code>```

Of course it does not work, because I cannot reference propA and propB this way. What it the right way to do it?

Thank you

答:
You can use body in lambda expression:

```<code>private List<myObject> myFunction()
{
    return myList.Select(l =>
    {
        var myObject = new myObject
        {
            propA = 6,
            propB = 3
        };

        myObject.propC = myObject.propA + myObject.propB;

        return myObject;

    }).ToList();
}
</code>```

Or you can return sum in getter of propC:

```<code>public int propC
{
    get
    {
        return propA + propB;
    }
}
</code>```

And you don't need to set propC.

Body:
Basically what I want is the same that is answered here but in C#:
Self-references in object literal declarations

What I have is this code:

private List<myObject> myFunction()
{
    return myList.Select(l => new myObject
    {
        propA = 6,
        propB = 3,
        propC = propA + propB
    }
    ).ToList();
}

Of course it does not work, because I cannot reference propA and propB this way. What it the right way to do it?

Thank you

Body:
You can use body in lambda expression:

private List<myObject> myFunction()
{
    return myList.Select(l =>
    {
        var myObject = new myObject
        {
            propA = 6,
            propB = 3
        };

        myObject.propC = myObject.propA + myObject.propB;

        return myObject;

    }).ToList();
}

Or you can return sum in getter of propC:

public int propC
{
    get
    {
        return propA + propB;
    }
}

And you don't need to set propC.


问:
How to avoid negative time between time difference?
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

```<code>@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}
</code>```

答:
check if the startTime is after endTime and swap the opernads if required:

```<code>    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);
    String calculatedTimeMorning;

    if (startTime.isAfter(endTime)) {
        calculatedTimeMorning = (ChronoUnit.HOURS.between(endTime, startTime) % 24) + ":"
                + (ChronoUnit.MINUTES.between(endTime, startTime) % 60);
    } else {
        calculatedTimeMorning = (ChronoUnit.HOURS.between(startTime, endTime) % 24) + ":"
                + (ChronoUnit.MINUTES.between(startTime, endTime) % 60);
    }
</code>```

Body:
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}

Body:
check if the startTime is after endTime and swap the opernads if required:

    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);
    String calculatedTimeMorning;

    if (startTime.isAfter(endTime)) {
        calculatedTimeMorning = (ChronoUnit.HOURS.between(endTime, startTime) % 24) + ":"
                + (ChronoUnit.MINUTES.between(endTime, startTime) % 60);
    } else {
        calculatedTimeMorning = (ChronoUnit.HOURS.between(startTime, endTime) % 24) + ":"
                + (ChronoUnit.MINUTES.between(startTime, endTime) % 60);
    }


问:
Delphi 2009 gives access violation error when integrated debugging is enabled
I'm pretty much at my wits end at the moment.

I am using Delphi 2009 (Update 3) on Vista (service pack 2) and without fail, if integrated debugging is enabled and I try to run a project, it will give an access violation and the project will crash out.

This happens even if I haven't even added any code to the default project template.

The only way I get around this is by disabling the integrated debugger, (then I may as well just be using a text editor and a command line compiler...)

Does anyone have any advice for this? I've been googling without much success.

Thanks in advance.

答: Go to Project > Options, Compiler tab.  Uncheck Optimization, check stack frames.  This seems to be the usual advice in the faqs on Delphi debugging.  It may only apply to the earlier versions of Delphi but is worth trying.</p>


问:
DOM Event - start download after E-Mail has been sent
I am struggeling with a DOM Code i want to use with Contact Form 7 on a Wordpresssite of mine.
Here is what i want to do:
After users have sumbitted some personal information they should get a pdf via download.
Currently i just send them to the pdf location, as you can see in the following script:

```<code>    <script>
       document.addEventListener( 'wpcf7mailsent', function( event ) {
       location = 'path_with_pdf_file';
       }, false );
    </script>
</code>```

Is there some simple codeline i am missing to start the download?
Would appreciate every answer i can get.

Kind regards

答:
I've prepared 3 solutions for you. I think second one is the easiest and does what you asked.

Solution 1

In your case window.location will never work unless you make HTTP request and setup headers telling the browser to handle the request as octet stream.

```<code>// PHP example code
header('Content-disposition: attachment; filename=FILENAME.pdf');
header('Content-type: application/pdf');
</code>```

Solution 2

Your best bet is to create anchor element, which holds all your download information and then execute .click() method.

Let's prepare our function which will handle everything for us.

```<code>function downloadFile(path) {
  var fileName = path.split('/').pop();
  // We create anchor
  var element = document.createElement('a');
  // Let's add properties to our anchor
  element.href = path;
  element.download = fileName;
  // Now we fire .click() method
  element.click();
}

document.addEventListener( 'wpcf7mailsent', function( event ) {
  downloadFile('http://domain/path/filename.pdf');
}, false );
</code>```

Solution 3

Why not send pdf via email? To do it we need to hook to wpcf7_before_send_mail action.

Here is code I used which should be working with the latest CF7.

```<code>add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");
function wpcf7_do_something_else($cf7) {

  $wpcf = WPCF7_ContactForm::get_current();
  $mail = $cf7->prop('mail');
  // Use it if you need to access form Id
  // $wpcf->id;

  // Your attachment do magic here
  $mail['attachments'] .= "\nuploads/regulations.pdf";

  $cf7->set_properties( array( 'mail' => $mail ) );

  return $wpcf;
}
</code>```

Body:
I am struggeling with a DOM Code i want to use with Contact Form 7 on a Wordpresssite of mine.
Here is what i want to do:
After users have sumbitted some personal information they should get a pdf via download.
Currently i just send them to the pdf location, as you can see in the following script:

Is there some simple codeline i am missing to start the download?
Would appreciate every answer i can get.

Kind regards

Body:
I've prepared 3 solutions for you. I think second one is the easiest and does what you asked.

Solution 1

In your case window.location will never work unless you make HTTP request and setup headers telling the browser to handle the request as octet stream.

// PHP example code
header('Content-disposition: attachment; filename=FILENAME.pdf');
header('Content-type: application/pdf');

Solution 2

Your best bet is to create anchor element, which holds all your download information and then execute .click() method.

Let's prepare our function which will handle everything for us.

function downloadFile(path) {
  var fileName = path.split('/').pop();
  // We create anchor
  var element = document.createElement('a');
  // Let's add properties to our anchor
  element.href = path;
  element.download = fileName;
  // Now we fire .click() method
  element.click();
}

document.addEventListener( 'wpcf7mailsent', function( event ) {
  downloadFile('http://domain/path/filename.pdf');
}, false );

Solution 3

Why not send pdf via email? To do it we need to hook to wpcf7_before_send_mail action.

Here is code I used which should be working with the latest CF7.

add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");
function wpcf7_do_something_else($cf7) {

  $wpcf = WPCF7_ContactForm::get_current();
  $mail = $cf7->prop('mail');
  // Use it if you need to access form Id
  // $wpcf->id;

  // Your attachment do magic here
  $mail['attachments'] .= "\nuploads/regulations.pdf";

  $cf7->set_properties( array( 'mail' => $mail ) );

  return $wpcf;
}


问:
Server fails to upload large files with gunicorn
I made a small server with flask to upload files (and then do stuff with them). The upload is through and HTML form that sends a file:

```<code><form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
</code>```

On the server side I do the following:

```<code>@app.route('/upload', methods=['POST'])
def upload():
    if 'file' in request.files:
        f = request.files['file']
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], werkzeug.secure_filename(f.filename))
        f.save(file_path)

    return 'File is being uploaded'
</code>```

It works fine for small files but on large files, it fails. The problem is that if I run the script manually not through gunicorn python main.py I can upload files that I couldn't before. I thought I needed to change the max size in gunicorn but couldn't find how to do it.

I also thought to use a stream and then write chunks but again, I couldn't find how to access the stream with flask.

Thanks for your help

答:
It might be due to timeout problem. By default, gunicorn will hang if a process takes more than 30 seconds. The time to upload a large file can easily exceed this amount. You might want to specify a custom timeout value when you start gunicorn. For example if you want to set timeout to 300 seconds: exec gunicorn [app]:[app] --timeout 300

Source: gunicorn timeout setting

Body:
I made a small server with flask to upload files (and then do stuff with them). The upload is through and HTML form that sends a file:

<form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>

On the server side I do the following:

@app.route('/upload', methods=['POST'])
def upload():
    if 'file' in request.files:
        f = request.files['file']
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], werkzeug.secure_filename(f.filename))
        f.save(file_path)

    return 'File is being uploaded'

It works fine for small files but on large files, it fails. The problem is that if I run the script manually not through gunicorn python main.py I can upload files that I couldn't before. I thought I needed to change the max size in gunicorn but couldn't find how to do it.

I also thought to use a stream and then write chunks but again, I couldn't find how to access the stream with flask.

Thanks for your help


问:
PySpark Overwrite added sc.addPyFile
I have these 2 files saved under this path:

C:\code\sample1\main.py

```<code>def method():
    return "this is sample method 1"
</code>```

C:\code\sample2\main.py

```<code>def method():
    return "this is sample method 2"
</code>```

and then i run this:

```<code>from pyspark import SparkContext
from pyspark.sql import SparkSession

sc = SparkContext()
spark = SparkSession(sc)

sc.addPyFile("~/code/sample1/main.py")
main1 = __import__("main")
print(main1.method()) # this is sample method 1

sc.addPyFile("~/code/sample2/main.py") # Error
</code>```

The error is

Py4JJavaError: An error occurred while calling o21.addFile.
: org.apache.spark.SparkException: File C:\Users\hans.yulian\AppData\Local\Temp\spark-5da165cf-410f-4576-8124-0ab23aba6aa3\userFiles-25a7ca23-84fb-42b7-95d9-206867fb9dfd\main.py exists and does not match contents of /C:/Users/hans.yulian/Documents/spark-test/main2/main.py

Which means that it already have "main.py" file in their temporary folder and the content is different. I wonder if there are any workaround for this case, but for me i have these limitation:

The file name still have to be "main.py", only folder can be
different

It's okay to somehow purge the temporary folder to add aga

in another file The only solution i have is by appending random
string in front of main.py, for example abcdemain.py and
fghijmain.py, then i will import main =  __import__("abcdemain"),
but this one is not really preferable

答:
While it is technically possible, by setting spark.files.overwrite  to "true":

```<code>from pyspark import SparkConf, SparkContext

sc = SparkContext(conf=SparkConf().set("spark.files.overwrite", "true"))
</code>```

and in simple cases will give correct results

```<code>def f(*_):
    from main import method
    return [method()]

sc.addFile("/path/to/sample1/main.py")
sc.parallelize([], 3).mapPartitions(f).collect()
</code>```

['this is sample method 1',
'this is sample method 1',
'this is sample method 1']
```

<pre class="lang-py prettyprint-override"><code>sc.addFile("/path/to/sample2/main.py")

sc.parallelize([], 3).mapPartitions(f).collect()
</code>```

['this is sample method 2',
 'this is sample method 2',
 'this is sample method 2']
```

it won't be reliable in practice, even if you reload modules on each access and will make your application hard to reason about. Since Spark may implicitly cache certain objects, or transparently restart Python workers you can easily end up in a situation, where different nodes see different state of the source.

Title: PySpark Overwrite added sc.addPyFile

Body:
I have these 2 files saved under this path:

C:\code\sample1\main.py

def method():
    return "this is sample method 1"

C:\code\sample2\main.py

def method():
    return "this is sample method 2"

and then i run this:

from pyspark import SparkContext
from pyspark.sql import SparkSession

sc = SparkContext()
spark = SparkSession(sc)

sc.addPyFile("~/code/sample1/main.py")
main1 = __import__("main")
print(main1.method()) # this is sample method 1

sc.addPyFile("~/code/sample2/main.py") # Error

The error is

Py4JJavaError: An error occurred while calling o21.addFile.
: org.apache.spark.SparkException: File C:\Users\hans.yulian\AppData\Local\Temp\spark-5da165cf-410f-4576-8124-0ab23aba6aa3\userFiles-25a7ca23-84fb-42b7-95d9-206867fb9dfd\main.py exists and does not match contents of /C:/Users/hans.yulian/Documents/spark-test/main2/main.py

Which means that it already have "main.py" file in their temporary folder and the content is different. I wonder if there are any workaround for this case, but for me i have these limitation:

The file name still have to be "main.py", only folder can be
different

It's okay to somehow purge the temporary folder to add aga

in another file The only solution i have is by appending random
string in front of main.py, for example abcdemain.py and
fghijmain.py, then i will import main =  __import__("abcdemain"),
but this one is not really preferable

Body:
While it is technically possible, by setting spark.files.overwrite  to "true":

from pyspark import SparkConf, SparkContext

sc = SparkContext(conf=SparkConf().set("spark.files.overwrite", "true"))

and in simple cases will give correct results

def f(*_):
    from main import method
    return [method()]

sc.addFile("/path/to/sample1/main.py")
sc.parallelize([], 3).mapPartitions(f).collect()

['this is sample method 1',
'this is sample method 1',
'this is sample method 1']

sc.addFile("/path/to/sample2/main.py")

sc.parallelize([], 3).mapPartitions(f).collect()

['this is sample method 2',
 'this is sample method 2',
 'this is sample method 2']

it won't be reliable in practice, even if you reload modules on each access and will make your application hard to reason about. Since Spark may implicitly cache certain objects, or transparently restart Python workers you can easily end up in a situation, where different nodes see different state of the source.