问:
Picture box is not displaying image coming from the TCP socket
I am developing a TCP client - server program that the client will capture its screenshot and send it to the server via TCP socket continuously. The server will display the image in a picture box. As of now the image transfer between client and server is working fine but the image is not displaying in the picture box.

Server side code:

```<code>   private void startListening()
    {

        //label1.Text = "Server is starting...";
        Console.WriteLine("Server is starting...");
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

        Socket newsock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        newsock.Bind(ipep);
        newsock.Listen(10);
        //label1.Text="Waiting for a client...";

        Socket client = newsock.Accept();
        IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
        //label1.Text = "Connected to client.";

        while (true)
        {
            data = ReceiveVarData(client);
            MemoryStream ms = new MemoryStream(data);
            try
            {
                lock (this)
                {
                    Image img = Image.FromStream(ms);
                    pictureBox1.Image = img;
                    pictureBox1.Invoke((MethodInvoker)delegate
                    {
                        pictureBox1.Refresh();
                    });
                }
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("something broke");
            }

            if (data.Length == 0)
                newsock.Listen(10);
        }
        //Console.WriteLine("Disconnected from {0}", newclient.Address);
        client.Close();
        newsock.Close();
        /////////////////////////////////////////////

    }

    private byte[] ReceiveVarData(Socket client)
    {
        int total = 0;
        int recv;
        byte[] datasize = new byte[4];

        recv = client.Receive(datasize, 0, 4, 0);
        int size = BitConverter.ToInt32(datasize, 0);
        int dataleft = size;
        byte[] data = new byte[size];

        while (total < size)
        {
            recv = client.Receive(data, total, dataleft, 0);
            if (recv == 0)
            {
                break;
            }
            total += recv;
            dataleft -= recv;
        }
        return data;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var t = new Thread(startListening);
        t.IsBackground = true;
        t.Start();
    }
</code>```

Client side code:

```<code>    static void Main(string[] args)
    {
        byte[] data = new byte[1024];
        int sent;
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);

        Socket server = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        try
        {
            server.Connect(ipep);
        }
        catch (SocketException e)
        {
            Console.WriteLine("Unable to connect to server.");
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
        while (true)
        {

            Bitmap bmp = captureImage();

            MemoryStream ms = new MemoryStream();
            // Save to memory using the Jpeg format
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            // read to end
            byte[] bmpBytes = ms.ToArray();
            bmp.Dispose();
            ms.Close();

            sent = SendVarData(server, bmpBytes);

            //Console.WriteLine("Disconnecting from server...");
        }

    }

    private static Bitmap captureImage()
    {
        Bitmap bmpScreenshot = null;
        try
        {
            //Create a new bitmap.
            bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                           Screen.PrimaryScreen.Bounds.Height,
                                           PixelFormat.Format32bppArgb);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Image covertion exception: " + ex);
        }
        return bmpScreenshot;
    }

    private static int SendVarData(Socket s, byte[] data)
    {
        int total = 0;
        int size = data.Length;
        int dataleft = size;
        int sent;

        byte[] datasize = new byte[4];
        datasize = BitConverter.GetBytes(size);
        sent = s.Send(datasize);

        while (total < size)
        {
            sent = s.Send(data, total, dataleft, SocketFlags.None);
            total += sent;
            dataleft -= sent;
        }
        return total;
    }
}
</code>```

答:
I think your issue may be that you try to manipulate the GUI component from the network thread which this code:

```<code>lock (this)
{
   Image img = Image.FromStream(ms);
   pictureBox1.Image = img; // Access from network thread to GUI component
   pictureBox1.Invoke((MethodInvoker)delegate
   {
       pictureBox1.Refresh();
   });
}
</code>```

You should do the following:

```<code>// No lock here - it's not needed
// The image data is created on the network thread, it get's captured
// by the closure and will only get applied on the UI thread
// If this also doesn't work you might try to capturing the MemoryStream
// and transfer that to the GUI thread
Image img = Image.FromStream(ms);
pictureBox1.Invoke((MethodInvoker)delegate
{
   pictureBox1.Image = img;
   pictureBox1.Refresh();
});
</code>```

Some minor issues that I also found:

You don't handle endOfStream (recv == 0) completely. In that case you would try to pass an uncompletely received image to the GUI instead of stopping reception.

You are not capturing exceptions from the stream and cleanup in case it happens. This means your receive thread could crash. Consider using try/catch/finally. And/or a using which manages the lifetime of your socket.

You are not checking whether all bytes were received and have been sent on sending/receiving the 4 header bytes.

Body:
I am developing a TCP client - server program that the client will capture its screenshot and send it to the server via TCP socket continuously. The server will display the image in a picture box. As of now the image transfer between client and server is working fine but the image is not displaying in the picture box.

Server side code:

   private void startListening()
    {

        //label1.Text = "Server is starting...";
        Console.WriteLine("Server is starting...");
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

        Socket newsock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        newsock.Bind(ipep);
        newsock.Listen(10);
        //label1.Text="Waiting for a client...";

        Socket client = newsock.Accept();
        IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
        //label1.Text = "Connected to client.";

        while (true)
        {
            data = ReceiveVarData(client);
            MemoryStream ms = new MemoryStream(data);
            try
            {
                lock (this)
                {
                    Image img = Image.FromStream(ms);
                    pictureBox1.Image = img;
                    pictureBox1.Invoke((MethodInvoker)delegate
                    {
                        pictureBox1.Refresh();
                    });
                }
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("something broke");
            }

            if (data.Length == 0)
                newsock.Listen(10);
        }
        //Console.WriteLine("Disconnected from {0}", newclient.Address);
        client.Close();
        newsock.Close();
        /////////////////////////////////////////////

    }

    private byte[] ReceiveVarData(Socket client)
    {
        int total = 0;
        int recv;
        byte[] datasize = new byte[4];

        recv = client.Receive(datasize, 0, 4, 0);
        int size = BitConverter.ToInt32(datasize, 0);
        int dataleft = size;
        byte[] data = new byte[size];

        while (total < size)
        {
            recv = client.Receive(data, total, dataleft, 0);
            if (recv == 0)
            {
                break;
            }
            total += recv;
            dataleft -= recv;
        }
        return data;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var t = new Thread(startListening);
        t.IsBackground = true;
        t.Start();
    }

Client side code:

    static void Main(string[] args)
    {
        byte[] data = new byte[1024];
        int sent;
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);

        Socket server = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        try
        {
            server.Connect(ipep);
        }
        catch (SocketException e)
        {
            Console.WriteLine("Unable to connect to server.");
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
        while (true)
        {

            Bitmap bmp = captureImage();

            MemoryStream ms = new MemoryStream();
            // Save to memory using the Jpeg format
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            // read to end
            byte[] bmpBytes = ms.ToArray();
            bmp.Dispose();
            ms.Close();

            sent = SendVarData(server, bmpBytes);

            //Console.WriteLine("Disconnecting from server...");
        }

    }

    private static Bitmap captureImage()
    {
        Bitmap bmpScreenshot = null;
        try
        {
            //Create a new bitmap.
            bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                           Screen.PrimaryScreen.Bounds.Height,
                                           PixelFormat.Format32bppArgb);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Image covertion exception: " + ex);
        }
        return bmpScreenshot;
    }

    private static int SendVarData(Socket s, byte[] data)
    {
        int total = 0;
        int size = data.Length;
        int dataleft = size;
        int sent;

        byte[] datasize = new byte[4];
        datasize = BitConverter.GetBytes(size);
        sent = s.Send(datasize);

        while (total < size)
        {
            sent = s.Send(data, total, dataleft, SocketFlags.None);
            total += sent;
            dataleft -= sent;
        }
        return total;
    }
}

Body:
I think your issue may be that you try to manipulate the GUI component from the network thread which this code:

lock (this)
{
   Image img = Image.FromStream(ms);
   pictureBox1.Image = img; // Access from network thread to GUI component
   pictureBox1.Invoke((MethodInvoker)delegate
   {
       pictureBox1.Refresh();
   });
}

You should do the following:

// No lock here - it's not needed
// The image data is created on the network thread, it get's captured
// by the closure and will only get applied on the UI thread
// If this also doesn't work you might try to capturing the MemoryStream
// and transfer that to the GUI thread
Image img = Image.FromStream(ms);
pictureBox1.Invoke((MethodInvoker)delegate
{
   pictureBox1.Image = img;
   pictureBox1.Refresh();
});

Some minor issues that I also found:

You don't handle endOfStream (recv == 0) completely. In that case you would try to pass an uncompletely received image to the GUI instead of stopping reception.

You are not capturing exceptions from the stream and cleanup in case it happens. This means your receive thread could crash. Consider using try/catch/finally. And/or a using which manages the lifetime of your socket.

You are not checking whether all bytes were received and have been sent on sending/receiving the 4 header bytes.


来源: stackexchange

答:
Hey could it be that you defined the vocab_size wrong?
https://github.com/tensorflow/tensorflow/issues/2734

Seems perhaps like a problem like that.

To say more it is perhaps helpful to see how you execute the model with the parameters.

ContentLicense: CC BY-SA 3.0

Body:
I used tensorflow to implement a language model.  Training data is just a lot of sentences in a feed_dict like this:

feed_dict = {
    model.inputs: x,
    model.seqlen:seqlen
}

x looks like:

[[127713, 68665, 211766, 2698, 138657, 36122, 138963, 198149, 4975, 104939, 205505], [81512, 161790, 4191, 131922, 38206, 123973, 102593, 147631, 117256, 153046, 190414], [213013, 159996, 9461, 131922, 175230, 191825, 102593, 201242, 6535, 160687, 15960], [39155, 160687, 2236, 117259, 200449, 120265, 214117, 102593, 117198, 138657, 159996], [9959, 136465, 121296, 96619, 184509, 10843, 117256, 102593, 187463, 213648, 102593], [11370, 189417, 127691, 43487, 109775, 19315, 102593, 130793, 36122, 160023, 138657], [221903, 102593, 76854, 215208, 146459, 172190, 99562, 54144, 141328, 134798, 176905], [102593, 29004, 189417, 77559, 11370, 102593, 201121, 436, 127713, 85797, 71369], [67515, 90422, 141328, 102593, 222023, 107914, 155883, 102593, 148221, 169199, 36122], [205336, 11191, 127713, 115425, 147700, 152270, 80276, 143317, 4190, 2373, 24519], [61049, 144035, 219863, 54144, 111851, 104926, 117256, 182871, 10033, 188890, 102593], [97804, 95468, 72416, 178512, 56040, 190225, 169304, 214785, 127713, 106900, 32960], [220409, 11370, 117249, 213607, 89611, 34385, 117256, 198815, 49674, 94546, 37171], [179753, 176347, 160687, 32912, 72416, 189281, 203515, 44526, 190225, 160687, 189417], [49035, 165055, 100531, 102593, 187465, 6535, 174629, 175940, 208552, 124145, 42418], [136713, 67575, 193443, 24519, 0, 67515, 71905, 36122, 78050, 36122, 117492], [67575, 201558, 169304, 25531, 102593, 152308, 124145, 129101, 75544, 117256, 102593], [127713, 58045, 7814, 90422, 36130, 26354, 11370, 169304, 71048, 196602, 133966], [223954, 127713, 135835, 111851, 36122, 102593, 16398, 24622, 11370, 102593, 90879], [34539, 46136, 72416, 79125, 214125, 31507, 117256, 127713, 21687, 150290, 102593], [172081, 117256, 127713, 148704, 193249, 189417, 57754, 204591, 117256, 127713, 217441], [156885, 213648, 102593, 137549, 24519, 102593, 81722, 159996, 92404, 102593, 158063], [117256, 102593, 1481, 36122, 102593, 188983, 117249, 189417, 2698, 4190, 198149], [146627, 188890, 102593, 220327, 36122, 26266, 11370, 32603, 67575, 136465, 102593], [117249, 189417, 179882, 190414, 115744, 138657, 117249, 189417, 190225, 215006, 51726], [70710, 152185, 129802, 137980, 95640, 119899, 102593, 203527, 4191, 131922, 57303], [138657, 189417, 75401, 117256, 102593, 39587, 131922, 110117, 138657, 138963, 42664], [35145, 15678, 65575, 11370, 131922, 202552, 190414, 102593, 195413, 209716, 61049], [213218, 158064, 190414, 72416, 99562, 145256, 68055, 190414, 112808, 102593, 94655], [36117, 45024, 170008, 158664, 201179, 162247, 36117, 72039, 436, 63876, 210529], [121778, 11370, 169304, 51713, 72416, 160980, 100531, 102593, 187465, 127691, 160687], [196602, 190414, 115744, 152185, 117249, 211349, 190414, 198056, 152386, 219761, 212195], [106606, 127713, 34109, 154924, 119235, 36122, 127713, 133841, 114413, 102593, 195413], [161791, 163058, 49084, 99562, 98981, 160687, 11191, 127713, 116409, 117256, 102593], [49674, 144174, 189417, 127689, 222397, 36122, 161717, 436, 107573, 11370, 186602], [102593, 76854, 14223, 180403, 150708, 196787, 36117, 186602, 8374, 102593, 148453], [189417, 53675, 58648, 11370, 102593, 130984, 141328, 157511, 190414, 102593, 137453], [190786, 213013, 99562, 54144, 25531, 101525, 127222, 11370, 144108, 11370, 149922], [76179, 107914, 43486, 174088, 161609, 38367, 166913, 160687, 4188, 40566, 190414], [111186, 176905, 188890, 182871, 100952, 11370, 221875, 182871, 199204, 36117, 127713], [216479, 11370, 196787, 123973, 58648, 138657, 164316, 117256, 102593, 214093, 118878], [127689, 190225, 141334, 67575, 89207, 189281, 36166, 36122, 35179, 102593, 173841], [73827, 45780, 140996, 61049, 35145, 134798, 190414, 102593, 210662, 36122, 102593], [220833, 181338, 138657, 102593, 131688, 36122, 22599, 11370, 102593, 203636, 28886], [77513, 189417, 190414, 72416, 189281, 146384, 190414, 83835, 102593, 141940, 36122], [159996, 43486, 72416, 190414, 177756, 159391, 213648, 102593, 123641, 36122, 82016], [145098, 117249, 117247, 87334, 11370, 126458, 37923, 140495, 102593, 113303, 11370], [102593, 69762, 70104, 67575, 180545, 214125, 53255, 190414, 102593, 198785, 117249], [116408, 138657, 138963, 36122, 102593, 20362, 76179, 35145, 136290, 214125, 102593], [35406, 160687, 121032, 136465, 102593, 181712, 169923, 58974, 36117, 92968, 102593]]

My model code:

import numpy as np
import tensorflow as tf
from tensorflow.python.ops import array_ops

class Model(object):
    def __init__(
        self,
        batch_size,
        vocab_size,
        hidden_size,
        learning_rate):

    self.inputs = tf.placeholder(tf.int32, [batch_size, None])

    self.seqlen = tf.placeholder(tf.float32)

    with tf.device('/cpu:0'),  tf.name_scope("embedding"):
        # embed = tf.get_variable(name="Embedding", shape=[vocab_size, hidden_size])
        embed = tf.Variable(
            tf.random_uniform([vocab_size, hidden_size], -1.0, 1.0))
        self.embedded_chars = tf.nn.embedding_lookup(embed, self.inputs)
        self.rev_input = tf.reverse(self.inputs, [False,True])
        self.embedded_chars_rev = tf.nn.embedding_lookup(embed, self.rev_input)

    with tf.variable_scope('forward'):
        forward_lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
        forward_outputs, _ = tf.nn.dynamic_rnn(forward_lstm_cell, self.embedded_chars,
                                               sequence_length=self.seqlen,
                                               dtype=tf.float32)

    with tf.variable_scope('backward'):
        backward_lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
        backward_outputs, _ = tf.nn.dynamic_rnn(backward_lstm_cell,
                                                self.embedded_chars_rev,
                                                sequence_length=self.seqlen,
                                                dtype=tf.float32)
    lstm_outputs = tf.add(forward_outputs, backward_outputs, name="lstm_outputs")
    self.outputs = tf.nn.relu(lstm_outputs)
    # W = tf.Variable(tf.truncated_normal([hidden_size,vocab_size, 1], -0.1, 0.1))
    W =  tf.get_variable('Weights', shape=[hidden_size, 1])
    b = tf.get_variable('Bias', shape=[1])
    outputs = self.outputs[:,1,:]
    y_pred = tf.squeeze(tf.matmul(outputs, W)) + b
    inputs_0 = tf.cast(self.inputs[:,0], tf.float32)
    self.loss = tf.nn.sigmoid_cross_entropy_with_logits(y_pred, inputs_0)

    self.train_op = tf.train.AdamOptimizer(0.0002).minimize(self.loss)

when i feed data and run, error occurd:

     Traceback (most recent call last):
  File "h1_mscc/train_model.py", line 156, in <module>
    tf.app.run()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 30, in run
    sys.exit(main(sys.argv))
  File "h1_mscc/train_model.py", line 153, in main
    train()
  File "h1_mscc/train_model.py", line 143, in train
    train_step(batch,seqlen)
  File "h1_mscc/train_model.py", line 134, in train_step
    feed_dict)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 372, in run
    run_metadata_ptr)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 636, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 708, in _do_run
    target_list, options, run_metadata)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 728, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: indices[0,0] = 205505 is not in [0, 50000)
     [[Node: embedding/embedding_lookup_1 = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, _class=["loc:@embedding/Variable"], validate_indices=true, _device="/job:localhost/replica:0/task:0/cpu:0"](embedding/Variable/read, embedding/Reverse)]]
Caused by op u'embedding/embedding_lookup_1', defined at:
  File "h1_mscc/train_model.py", line 156, in <module>
    tf.app.run()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 30, in run
    sys.exit(main(sys.argv))
  File "h1_mscc/train_model.py", line 153, in main
    train()
  File "h1_mscc/train_model.py", line 81, in train
    model = create_model(sess)
  File "h1_mscc/train_model.py", line 59, in create_model
    learning_rate=FLAGS.learning_rate)
  File "/home/liac/code/Project3-preprocess-master/h1_mscc/model1.py", line 24, in __init__
    self.embedded_chars_rev = tf.nn.embedding_lookup(embed, self.rev_input)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/embedding_ops.py", line 86, in embedding_lookup
    validate_indices=validate_indices)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 780, in gather
    validate_indices=validate_indices, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 704, in apply_op
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2260, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1230, in __init__
    self._traceback = _extract_stack()

that confused me a lot, hope can get some respone!
the input


问:
How to define number of bits to generate using independent_bits_engine?
independent_bits_engine is the template class

```<code>template<
    class Engine,
    std::size_t W,
    class UIntType
> class independent_bits_engine;
</code>```

The second parametr define, how much bits need to be generated. I don't know its. I would to ask this question to user in runtime. How do it?

答:
You cannot. Template arguments have to be defined at compile-time.

To work around this, you can look at this post and answer: Specify template parameters at runtime

The idea is to use if statements to check the runtime value:

```<code>template<class Engine, class UIntType>
independent_bits_engine CreateEngine(std::size_t w) {
    if (w == 0) {
        return independent_bits_engine<Engine, 0, UIntType>();
    } else if (w == 1) {
        return independent_bits_engine<Engine, 1, UIntType>();
    }
    Etc;
}
</code>```

If W can be a big value, you may want to use boost::preprocessor to generate the ifs (example given in the link).

Note that, the more the maximum value of W is big, the more independent_bits_engine classes will be instantiated, and the more the compilation will be slow, so you may want to switch to a full runtime solution instead.

Body:
independent_bits_engine is the template class

template<
    class Engine,
    std::size_t W,
    class UIntType
> class independent_bits_engine;

The second parametr define, how much bits need to be generated. I don't know its. I would to ask this question to user in runtime. How do it?

Body:
You cannot. Template arguments have to be defined at compile-time.

To work around this, you can look at this post and answer: Specify template parameters at runtime

The idea is to use if statements to check the runtime value:

template<class Engine, class UIntType>
independent_bits_engine CreateEngine(std::size_t w) {
    if (w == 0) {
        return independent_bits_engine<Engine, 0, UIntType>();
    } else if (w == 1) {
        return independent_bits_engine<Engine, 1, UIntType>();
    }
    Etc;
}

If W can be a big value, you may want to use boost::preprocessor to generate the ifs (example given in the link).

Note that, the more the maximum value of W is big, the more independent_bits_engine classes will be instantiated, and the more the compilation will be slow, so you may want to switch to a full runtime solution instead.


问:
Select * from this week
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

```<code>$week = Date('W');
</code>```

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

```<code>$sql = 'SELECT * FROM my_table WHERE week = $week';
</code>```

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

答:
Why not simply do

```<code> $sql = "SELECT * FROM my_table WHERE week = WEEK(NOW())";
</code>```

Just a note: SELECT * is not good and very bad practice. Select only what you need.

Title: Select * from this week

Body:
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

$week = Date('W');

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

$sql = 'SELECT * FROM my_table WHERE week = $week';

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

Body:
Why not simply do

 $sql = "SELECT * FROM my_table WHERE week = WEEK(NOW())";

Just a note: SELECT * is not good and very bad practice. Select only what you need.


问:
GSM not responding to AT commands
I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:

```<code>/*

 This example tests to see if the modem of the
 GSM shield is working correctly. You do not need
 a SIM card for this example.

 Circuit:
 * GSM shield attached

 Created 12 Jun 2012
 by David del Peral
 modified 21 Nov 2012
 by Tom Igoe

 http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

 This sample code is part of the public domain

 */

// libraries
#include <GSM.h>

// modem verification object
GSMModem modem;

// IMEI variable
String IMEI = "";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start modem test (reset and check response)
  Serial.print("Starting modem test...");
  if (modem.begin()) {
    Serial.println("modem.begin() succeeded");
  } else {
    Serial.println("ERROR, no modem answer.");
  }
}

void loop() {
  // get modem IMEI
  Serial.print("Checking IMEI...");
  IMEI = modem.getIMEI();

  // check IMEI response
  if (IMEI != NULL) {
    // show IMEI in serial monitor
    Serial.println("Modem's IMEI: " + IMEI);
    // reset modem to check booting:
    Serial.print("Resetting modem...");
    modem.begin();
    // get and check IMEI one more time
    if (modem.getIMEI() != NULL) {
      Serial.println("Modem is functoning properly");
    } else {
      Serial.println("Error: getIMEI() failed after modem.begin()");
    }
  } else {
    Serial.println("Error: Could not get IMEI");
  }
  // do nothing:
  while (true);
}
</code>```

I am getting this output on Serial Monitor for 9600 baud rate:

Starting modem test...ERROR, no modem answer. Checking IMEI...Modem's IMEI: 0 Resetting modem...Modem is functioning properly

答: I think it has to do with your supply, try using an adapter, that outputs a current of 500mA to 1A.</p>

Title: GSM not responding to AT commands

Body:
I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:

/*

 This example tests to see if the modem of the
 GSM shield is working correctly. You do not need
 a SIM card for this example.

 Circuit:
 * GSM shield attached

 Created 12 Jun 2012
 by David del Peral
 modified 21 Nov 2012
 by Tom Igoe

 http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

 This sample code is part of the public domain

 */

// libraries
#include <GSM.h>

// modem verification object
GSMModem modem;

// IMEI variable
String IMEI = "";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start modem test (reset and check response)
  Serial.print("Starting modem test...");
  if (modem.begin()) {
    Serial.println("modem.begin() succeeded");
  } else {
    Serial.println("ERROR, no modem answer.");
  }
}

void loop() {
  // get modem IMEI
  Serial.print("Checking IMEI...");
  IMEI = modem.getIMEI();

  // check IMEI response
  if (IMEI != NULL) {
    // show IMEI in serial monitor
    Serial.println("Modem's IMEI: " + IMEI);
    // reset modem to check booting:
    Serial.print("Resetting modem...");
    modem.begin();
    // get and check IMEI one more time
    if (modem.getIMEI() != NULL) {
      Serial.println("Modem is functoning properly");
    } else {
      Serial.println("Error: getIMEI() failed after modem.begin()");
    }
  } else {
    Serial.println("Error: Could not get IMEI");
  }
  // do nothing:
  while (true);
}

I am getting this output on Serial Monitor for 9600 baud rate:

Starting modem test...ERROR, no modem answer. Checking IMEI...Modem's IMEI: 0 Resetting modem...Modem is functioning properly


问:
Why -1 >> 1 is -1 ? And 1 >> 1 is 0!
I have next code:

```<code>std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;
</code>```

The result is:

```<code>-5
-5
-4
-4
-3
-3
-2
-2
-1
-1
</code>```

But why?

-1 is 1111 1111 (for 1 byte), -1 >> 1 must be : 1011 1111 and it is not -1 or 0! (sign-bit is not shifted, I know)

Can someone explain to me how this works?

答:
In general, right-shifts are defined as being implemented as either "arithmetic" or "logical" The difference is that with a logical right shift, the left-most bit is always set to zero. With an arithmetic right shift, the left-most bit is a copy of the previous value.

For example, let's pretend the value is just 8 bits to make things easier to keep track of. Then:

Logical:

```<code>0111 1111 >> 1 = 0011 1111
1111 1111 >> 1 = 0111 1111
1111 1110 >> 1 = 0111 1111
</code>```

Arithmetic:

```<code>0111 1111 >> 1 = 0011 1111
1111 1111 >> 1 = 1111 1111
1111 1110 >> 1 = 1111 1111
</code>```

An arithmetic right-shift is equivalent to dividing by 2 and rounding toward negative infinity.

In C++, whether the right-shift operator is logical or arithmetic is implementation-specific. i.e. each compiler writer may decide for himself, probably based on what is easier to do giving the architecture of the computer he's working on.

Your statement that the sign bit is not shifted is incorrect. The sign bit is shifted just like all the other bits. The only question is what replaces it.

Java has two different right-shift operators: >> is arithmetic and >>> is logical.

Title: Why -1 >> 1 is -1 ? And 1 >> 1 is 0!

Body:
I have next code:

std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;

The result is:

-5
-5
-4
-4
-3
-3
-2
-2
-1
-1

But why?

-1 is 1111 1111 (for 1 byte), -1 >> 1 must be : 1011 1111 and it is not -1 or 0! (sign-bit is not shifted, I know)

Can someone explain to me how this works?

Body:
In general, right-shifts are defined as being implemented as either "arithmetic" or "logical" The difference is that with a logical right shift, the left-most bit is always set to zero. With an arithmetic right shift, the left-most bit is a copy of the previous value.

For example, let's pretend the value is just 8 bits to make things easier to keep track of. Then:

Logical:

0111 1111 >> 1 = 0011 1111
1111 1111 >> 1 = 0111 1111
1111 1110 >> 1 = 0111 1111

Arithmetic:

0111 1111 >> 1 = 0011 1111
1111 1111 >> 1 = 1111 1111
1111 1110 >> 1 = 1111 1111

An arithmetic right-shift is equivalent to dividing by 2 and rounding toward negative infinity.

In C++, whether the right-shift operator is logical or arithmetic is implementation-specific. i.e. each compiler writer may decide for himself, probably based on what is easier to do giving the architecture of the computer he's working on.

Your statement that the sign bit is not shifted is incorrect. The sign bit is shifted just like all the other bits. The only question is what replaces it.

Java has two different right-shift operators: >> is arithmetic and >>> is logical.

ContentLicense: CC BY-SA 2.5


问:
How to make a regular expression 'greedy but optional'
I'm trying to write a parser for a string which represents a file path, optionally following by a colon (:) and a string representing access flags (e.g. r+ or w). The file name can itself contain colons, e.g., foo:bar.txt, so the colon separating the access flags should be the last colon in the string.

Here is my implementation so far:

```<code>import re

def parse(string):
    SCHEME = r"file://"                             # File prefix
    PATH_PATTERN = r"(?P<path>.+)"                  # One or more of any character
    FLAGS_PATTERN = r"(?P<flags>.+)"        # The letters r, w, a, b, a '+' symbol, or any digit

    # FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + r":" + FLAGS_PATTERN + r"$"               # This makes the first test pass, but the second one fail
    FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + optional(r":" + FLAGS_PATTERN) + r"$"   # This makes the second test pass, but the first one fail

    tokens = re.match(FILE_RESOURCE_PATTERN, string).groupdict()

    return tokens['path'], tokens['flags']

def optional(re):
    '''Encloses the given regular expression in a group which matches 0 or 1 repetitions.'''
    return '({})?'.format(re)
</code>```

I've tried the following tests:

```<code>import pytest

def test_parse_file_with_colon_in_file_name():
    assert parse("file://foo:bar.txt:r+") == ("foo:bar.txt", "r+")

def test_parse_file_without_acesss_flags():
    assert parse("file://foobar.txt") == ("foobar.txt", None)

if __name__ == "__main__":
    pytest.main([__file__])
</code>```

The problem is that by either using or not using optional, I can make one or the other test pass, but not both. If I make r":" + FLAGS_PATTERN optional, then preceding regular expression consumes the entire string.

How can I adapt the parse method to make both tests pass?

答:
You should build the regex like

```<code>^file://(?P<path>.+?)(:(?P<flags>[^:]+))?$
</code>```

See the regex demo.

In your code, ^ anchor is not necessary as you are using re.match anchoring the match at the start of the string. The path group matches any 1+ chars lazily (thus, all the text that can be matched with Group 2 will land in the second capture), up to the first occurrence of : followed with 1+ chars other than : (if present) and then end of string position is tested. Thanks to $ anchor, the first group will match the whole string if the second optional group is not matched.

Use the following fix:

```<code>PATH_PATTERN = r"(?P<path>.+?)"                  # One or more of any character
FLAGS_PATTERN = r"(?P<flags>[^:]+)"        # The letters r, w, a, b, a '+' symbol, or any digit
</code>```

See the online Python demo.

Body:
I'm trying to write a parser for a string which represents a file path, optionally following by a colon (:) and a string representing access flags (e.g. r+ or w). The file name can itself contain colons, e.g., foo:bar.txt, so the colon separating the access flags should be the last colon in the string.

Here is my implementation so far:

import re

def parse(string):
    SCHEME = r"file://"                             # File prefix
    PATH_PATTERN = r"(?P<path>.+)"                  # One or more of any character
    FLAGS_PATTERN = r"(?P<flags>.+)"        # The letters r, w, a, b, a '+' symbol, or any digit

    # FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + r":" + FLAGS_PATTERN + r"$"               # This makes the first test pass, but the second one fail
    FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + optional(r":" + FLAGS_PATTERN) + r"$"   # This makes the second test pass, but the first one fail

    tokens = re.match(FILE_RESOURCE_PATTERN, string).groupdict()

    return tokens['path'], tokens['flags']

def optional(re):
    '''Encloses the given regular expression in a group which matches 0 or 1 repetitions.'''
    return '({})?'.format(re)

I've tried the following tests:

import pytest

def test_parse_file_with_colon_in_file_name():
    assert parse("file://foo:bar.txt:r+") == ("foo:bar.txt", "r+")

def test_parse_file_without_acesss_flags():
    assert parse("file://foobar.txt") == ("foobar.txt", None)

if __name__ == "__main__":
    pytest.main([__file__])

The problem is that by either using or not using optional, I can make one or the other test pass, but not both. If I make r":" + FLAGS_PATTERN optional, then preceding regular expression consumes the entire string.

How can I adapt the parse method to make both tests pass?

Body:
You should build the regex like

^file://(?P<path>.+?)(:(?P<flags>[^:]+))?$

See the regex demo.

In your code, ^ anchor is not necessary as you are using re.match anchoring the match at the start of the string. The path group matches any 1+ chars lazily (thus, all the text that can be matched with Group 2 will land in the second capture), up to the first occurrence of : followed with 1+ chars other than : (if present) and then end of string position is tested. Thanks to $ anchor, the first group will match the whole string if the second optional group is not matched.

Use the following fix:

PATH_PATTERN = r"(?P<path>.+?)"                  # One or more of any character
FLAGS_PATTERN = r"(?P<flags>[^:]+)"        # The letters r, w, a, b, a '+' symbol, or any digit

See the online Python demo.


问:
How does synchronizing an object works in java
I'm making a basic android game, I have a fragment that displays the game world. When I open that fragment I create a new thread that just waits until my NetworkThread gets the world from the server. Also my GetWorldThread is a static Thread that I only initialize inside the fragment.

This is how my GetWorldThread looks like:

```<code>synchronized (this)
{
    try
    {
        Log.d("getWorldThread", "waiting()");
        wait();
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
}
</code>```

and my NetworkThread looks like this

```<code>if (buffer instanceof World)
{
    synchronized (WorldFragment.getWorldThread)
    {
        World.setWorld(((World) buffer));
        Log.d("NetworkThread", "notifying World");

        WorldFragment.getWorldThread.notify();
    }

}
</code>```

My code works, but I want to know if there is a way to do this more elegant?.

答:
As mentioned in documentation you always should use wait() in while loop. So your code may not work correctly.

More elegant way is to use more high-level abstracnions. For example Future  and standart FutureTask. This way allows you don't write low-level stuff like loops and therefore to avoid mistakes.

Update: Also note that there are Conditions/Locks intended for wait/synchronyzed substitution as described here. In fact, using wait() is obsolete in 2017

Body:
I'm making a basic android game, I have a fragment that displays the game world. When I open that fragment I create a new thread that just waits until my NetworkThread gets the world from the server. Also my GetWorldThread is a static Thread that I only initialize inside the fragment.

This is how my GetWorldThread looks like:

synchronized (this)
{
    try
    {
        Log.d("getWorldThread", "waiting()");
        wait();
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
}

and my NetworkThread looks like this

if (buffer instanceof World)
{
    synchronized (WorldFragment.getWorldThread)
    {
        World.setWorld(((World) buffer));
        Log.d("NetworkThread", "notifying World");

        WorldFragment.getWorldThread.notify();
    }

}

My code works, but I want to know if there is a way to do this more elegant?.


问:
What is "Post on Changes" or "Reflection" functionality?
I am new to CC Guidewire. I didnt understand what post on change will do?

Thanks.

答:
The "postOnChange" attribute on a PCF UI element can either be true or false.

If it is true then everytime that UI field is changed by a user; it will POST back to the server.

The server will then execute the code in corresponding UI elements "onChange" attribute.

These together basically allows you to add a piece of code that will fire when that UI field is been changed on screen by the user.

The reflection items can be used to use AJAX style updates to multiple fields on the basis of others. It is a bit more complex to use and understand.

ContentLicense: CC BY-SA 4.0


问:
Calculating MaxTimeUuid and MinTimeUuid in C#
I'm trying to:

a) Generate timeuuids from a C# DateTime

b) Get the DateTime back from a given timeuuid

c) Find the MaxTimeUuid and MinTimeUuid for a given DateTime

For a) and b) I've found this link which provides me a struct with the required functionality.

For c) I've found this link which seems to have the functions, but they just return null, so it looks like it's not been implemented yet.

Is this the case?

Is there C# functionality anywhere that I can create a max and min timeuuid for a given time?

Thank you

答:
The DataStax C# driver provides those methods in the TimeUuid structure:

Use TimeUuid.GetDate() to retrieve the timestamp from a given TimeUuid.

Use TimeUuid.NewId(DateTimeOffset) static method to generate a timeuuid from a given timestamp.

About max and min timeuuid methods, those are not yet available on the C# side. You can use those from CQL: SELECT field1, field2 FROM table1 WHERE id = ? and time >= minTimeuuid(?).

https://docs.datastax.com/en/cql/3.1/cql/cql_reference/timeuuid_functions_r.html


问:
How to make side bar collapsible manu which won't affect main page?

this is the demo images from random website...

i want to make this type of side bar...
i mean after expand it wont affect the page...

so how to make left side-bar manu?

答: Try position:fixed and add some z-index to always be on top


问:
Save custom Object to Application Settings does not work
I have a object in an application that saves settings for this application. The instance of this object is saved in the settings of the application.

```<code>[global::System.Configuration.ApplicationScopedSetting()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public ReportingConfiguration ReportingConfiguration
{
    get { return ((ReportingConfiguration)(this["ReportingConfiguration"])); }
    set { this["ReportingConfiguration"] = value; }
}
</code>```

At application start up the object is read out and if its null new instantiated. After that immediately saved.

```<code>// Get existing ReportingConfiguration or create new if null
var reportingConfiguration = Properties.Settings.Default.ReportingConfiguration;
if (reportingConfiguration == null)
{
    reportingConfiguration = new ReportingConfiguration();
    Properties.Settings.Default.ReportingConfiguration = reportingConfiguration;
    Properties.Settings.Default.Save();
}
</code>```

When the settings are modified from the settings dialog and should be saved, the object is saved to the settings.

```<code>Properties.Settings.Default.ReportingConfiguration = _reportingConfiguration;
Properties.Settings.Default.Save();
</code>```

However, when I restart the application, the read out object is null again. This happens at debugging and also when I try it to start without debugging.

What am I doing wrong? Is it even possible to save a custom object to settings?

答:
Seems like you want to serialize your settings based on objects. I would recommend using Newtonsoft Json.NET.

Serialize your object into a JSON string when ever you want to save it to your settings. Deserialize the setting string to the actual object when reading out your setting.

Body:
I have a object in an application that saves settings for this application. The instance of this object is saved in the settings of the application.

[global::System.Configuration.ApplicationScopedSetting()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public ReportingConfiguration ReportingConfiguration
{
    get { return ((ReportingConfiguration)(this["ReportingConfiguration"])); }
    set { this["ReportingConfiguration"] = value; }
}

At application start up the object is read out and if its null new instantiated. After that immediately saved.

// Get existing ReportingConfiguration or create new if null
var reportingConfiguration = Properties.Settings.Default.ReportingConfiguration;
if (reportingConfiguration == null)
{
    reportingConfiguration = new ReportingConfiguration();
    Properties.Settings.Default.ReportingConfiguration = reportingConfiguration;
    Properties.Settings.Default.Save();
}

When the settings are modified from the settings dialog and should be saved, the object is saved to the settings.

Properties.Settings.Default.ReportingConfiguration = _reportingConfiguration;
Properties.Settings.Default.Save();

However, when I restart the application, the read out object is null again. This happens at debugging and also when I try it to start without debugging.

What am I doing wrong? Is it even possible to save a custom object to settings?


问:
Stacked MPI derived data types in Fortran
MPI2 allows us to create derived data types and send them by writing

```<code>call mpi_type_create_indexed_block(size,1,dspl_send,rtype,DerType,ierr)
call mpi_send(data,1,DerType,jRank,20,comm,ierr)
</code>```

By doing this the position dspl_send of data(N) are sent by the MPI library.

Now, for a matrix data(M,N) we can send its position via the following code:

```<code>call mpi_type_create_indexed_block(size,M,dspl_send,rtype,DerTypeM,ierr)
call mpi_send(data,1,DerTypeM,jRank,20,comm,ierr)
</code>```

That is the entries data(i, dspl_send(j)) are sent.

My question concern the role of the 1 in the subsequent mpi_send. Does it has always to be 1? Is another size possible? MPI derived data types are explained nicely in many documents on the internet, but always the size in send/recv is 1 without mention if another size is allowed and then how it could be used.

If we want to work with matrices data(M,N) with a size M that varies between calls, do we need to always create a derived data type whenever we call it? Is it impossible to use DerType for sending a matrix data(M,N) or data(N,M)?

答:
The description about extent in https://stackoverflow.com/a/13802243/7784768 is not entirely correct, as the extent does not take into account the padding in the end of datatype. MPI datatypes are defined by typemap:

```<code>typemap = ((type_0, disp_0 ), ..., (type_n−1, disp_n−1 ))
</code>```

Extent is then defined according to

```<code>lb = min(disp_j)
ub = max(disp_j + sizeof(type_j)) + e)
extent = ub - lb,
</code>```

where e can be non-zero due alignment requirements.

This means that in the example

```<code>MPI_TYPE_VECTOR(count = 1,
                blocklength = 10,
                stride = 20,
                oldtype = MPI_INTEGER,
                newtype = newtype)
</code>```

with count=1, typemap is

```<code>((int, 0), (int, 4), ... (int, 36))
</code>```

and extent is in most systems 40 and not 80 (i.e. stride has no effect for the typemap in this case). For count=2, typemap would be

```<code>((int, 0), (int, 4), ... (int, 36), (int, 80), (int, 84), ... (int, 116))
</code>```

and extent 120 (40 bytes for the first block of 10 integers, 40 bytes for the stride, and 40 bytes for the second block of 10 integers, but the remaining stride is neglected in the extent). One can easily find out the extent with the MPI_Type_get_extent function.

Extent is quite tricky concept, and it is easy to make mistakes when trying to communicate multiple elements of derived datatype.

Body:
MPI2 allows us to create derived data types and send them by writing

call mpi_type_create_indexed_block(size,1,dspl_send,rtype,DerType,ierr)
call mpi_send(data,1,DerType,jRank,20,comm,ierr)

By doing this the position dspl_send of data(N) are sent by the MPI library.

Now, for a matrix data(M,N) we can send its position via the following code:

call mpi_type_create_indexed_block(size,M,dspl_send,rtype,DerTypeM,ierr)
call mpi_send(data,1,DerTypeM,jRank,20,comm,ierr)

That is the entries data(i, dspl_send(j)) are sent.

My question concern the role of the 1 in the subsequent mpi_send. Does it has always to be 1? Is another size possible? MPI derived data types are explained nicely in many documents on the internet, but always the size in send/recv is 1 without mention if another size is allowed and then how it could be used.

If we want to work with matrices data(M,N) with a size M that varies between calls, do we need to always create a derived data type whenever we call it? Is it impossible to use DerType for sending a matrix data(M,N) or data(N,M)?

Body:
The description about extent in https://stackoverflow.com/a/13802243/7784768 is not entirely correct, as the extent does not take into account the padding in the end of datatype. MPI datatypes are defined by typemap:

typemap = ((type_0, disp_0 ), ..., (type_n−1, disp_n−1 ))

Extent is then defined according to

lb = min(disp_j)
ub = max(disp_j + sizeof(type_j)) + e)
extent = ub - lb,

where e can be non-zero due alignment requirements.

This means that in the example

MPI_TYPE_VECTOR(count = 1,
                blocklength = 10,
                stride = 20,
                oldtype = MPI_INTEGER,
                newtype = newtype)

with count=1, typemap is

((int, 0), (int, 4), ... (int, 36))

and extent is in most systems 40 and not 80 (i.e. stride has no effect for the typemap in this case). For count=2, typemap would be

((int, 0), (int, 4), ... (int, 36), (int, 80), (int, 84), ... (int, 116))

and extent 120 (40 bytes for the first block of 10 integers, 40 bytes for the stride, and 40 bytes for the second block of 10 integers, but the remaining stride is neglected in the extent). One can easily find out the extent with the MPI_Type_get_extent function.

Extent is quite tricky concept, and it is easy to make mistakes when trying to communicate multiple elements of derived datatype.


问:
How to remove the border of an image?
I have founded many question like mine on StackOverflow example1  example2 but for a unknown reason I still have some borders displayed around my image:

```<code> .imgCadenas{
  width:  50px;
  height: 50px;
  background: url('/cadenas.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border:0;
  border-style: none;

  position: absolute;
  right: 150px;
  top: 5px;
}
</code>```

Someone has a solution ?

[EDIT] with your advices I have this CSS in the browser:

.liMachine {
    list-style-type: none;
    border-style: solid;
    margin-bottom: 5px;
    word-break: break-all;
    position: relative;

}

.imgCadenas{
  width:  50px;
  height: 50px;
  background: url('http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border: 0 !important;
  border-style: none !important;
  outline: none !important;
  display: block;

  position: absolute;
  right: 250px;
  top: 5px;
}

.whoLock{
  position: absolute;
  right: 15px;
  top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="liMachine switch">
        <div id="nameMachine">
            <h3>My machine</h3>
        </div>
        <div id="stateMachine">
            State:<span class="state">running</span>
        </div>
        <div>
            <img class="imgCadenas">
            <p class="whoLock">Locked by: StackOverflow</p>
        </div>
    </li></code>```

答:
This can change on different browsers. You can try border-style:none !important;

So for all img:

```<code>img{border-style:none !important;}
</code>```

or just for your img

```<code><img class="imgCadenas" src"">

.imgCadenas{border-style:none !important;}
</code>```

If you send your link for control. I can look for you.

Title: How to remove the border of an image?

Body:
I have founded many question like mine on StackOverflow example1  example2 but for a unknown reason I still have some borders displayed around my image:

 .imgCadenas{
  width:  50px;
  height: 50px;
  background: url('/cadenas.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border:0;
  border-style: none;

  position: absolute;
  right: 150px;
  top: 5px;
}

Someone has a solution ?

[EDIT] with your advices I have this CSS in the browser:

.liMachine {
    list-style-type: none;
    border-style: solid;
    margin-bottom: 5px;
    word-break: break-all;
    position: relative;

}

.imgCadenas{
  width:  50px;
  height: 50px;
  background: url('http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border: 0 !important;
  border-style: none !important;
  outline: none !important;
  display: block;

  position: absolute;
  right: 250px;
  top: 5px;
}

.whoLock{
  position: absolute;
  right: 15px;
  top: 10px;
}

My machine

            State:running

Locked by: StackOverflow

Body:
This can change on different browsers. You can try border-style:none !important;

So for all img:

img{border-style:none !important;}

or just for your img

<img class="imgCadenas" src"">

.imgCadenas{border-style:none !important;}

If you send your link for control. I can look for you.


问:
Difference between basic and url base64 encoding in Java 8
The Java 8 Base64 library has two variants that can be used in URI building: the "Basic" one and the "URL and Filename safe". The documentation points to RFC 4648 Table 2 as an explanation for the differences.

After reading the spec it still isn't clear to me what the practical difference is between both encodings: are both standards "widely" supported? What about browsers specifically? Is the URL and filename safe encoding recommended for data URI encoding? Are there known support limitations?

答:
The easiest way is to provide an example(IMHO):

```<code>    Base64.Encoder enc = Base64.getEncoder();
    Base64.Encoder encURL = Base64.getUrlEncoder();

    byte[] bytes = enc.encode("subjects?_d".getBytes());
    byte[] bytesURL = encURL.encode("subjects?_d".getBytes());

    System.out.println(new String(bytes)); // c3ViamVjdHM/X2Q=      notice the "/"
    System.out.println(new String(bytesURL)); // c3ViamVjdHM_X2Q=   notice the "_"

    Base64.Decoder dec = Base64.getDecoder();
    Base64.Decoder decURL = Base64.getUrlDecoder();

    byte[] decodedURL = decURL.decode(bytesURL);
    byte[] decoded = dec.decode(bytes);

    System.out.println(new String(decodedURL));
    System.out.println(new String(decoded));
</code>```

Notice how one is URL safe and the other is not.

As a matter of fact if you look at the implementation, there are two look-up tables used for encoding: toBase64 and toBase64URL. There are two characters only that differ for them:

+ and / for toBase64 versus - and _ for toBase64URL.

So it seems that your question is one URI safe and should be used there?; the answer is yes.

Body:
The easiest way is to provide an example(IMHO):

    Base64.Encoder enc = Base64.getEncoder();
    Base64.Encoder encURL = Base64.getUrlEncoder();

    byte[] bytes = enc.encode("subjects?_d".getBytes());
    byte[] bytesURL = encURL.encode("subjects?_d".getBytes());

    System.out.println(new String(bytes)); // c3ViamVjdHM/X2Q=      notice the "/"
    System.out.println(new String(bytesURL)); // c3ViamVjdHM_X2Q=   notice the "_"

    Base64.Decoder dec = Base64.getDecoder();
    Base64.Decoder decURL = Base64.getUrlDecoder();

    byte[] decodedURL = decURL.decode(bytesURL);
    byte[] decoded = dec.decode(bytes);

    System.out.println(new String(decodedURL));
    System.out.println(new String(decoded));

Notice how one is URL safe and the other is not.

As a matter of fact if you look at the implementation, there are two look-up tables used for encoding: toBase64 and toBase64URL. There are two characters only that differ for them:

+ and / for toBase64 versus - and _ for toBase64URL.

So it seems that your question is one URI safe and should be used there?; the answer is yes.


问:
how to get sum of integer value from recyclerview
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

```<code>public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}
</code>```

here is my fragment class

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}
</code>```

答:
Well I have similar answer to @Adrian-Alexandru Coman beause the method to calculate the sum is the same.
I believe your Total Amount is just a TextView with in the fragment,as that's what the image shows. So first you define a method in the Fragment to calculate the sum.
Assuming that you have an instance variable of arraylist and a Entity Class(POJO)that holds your arraylist data :

Suppose your arraylist is foodList and entity class is Foods.Then you
  have an arraylist like below:

```<code>ArrayList<Foods> foodList
</code>```

then,the method will be:

```<code>public void getSumofAllitems(){
int total_sum=0;
for(int i=0;i<foodList.size();i++){
Foods food_items=foodList.get(i);
int price=food_items.getPrice();//getPrice() is a getter method in your POJO class.
total_sum+= price;
}
totalpriceTextView.setText(total_sum+"");
}
</code>```

Then from your RecyclerView's onBindViewHolder method,check the posiion of the view that is:

```<code>@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));
if(position==data.size()-1){
((Activity)context).getSumofAllitems();
}
}
</code>```

I called the method from RecyclerView  and checked the position so that the method won't be executed util all your views are bind to RecyclerView and the RecycleView is populated. I believe this is the correct way to do this.

Body:
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}

here is my fragment class

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}

Body:
Well I have similar answer to @Adrian-Alexandru Coman beause the method to calculate the sum is the same.
I believe your Total Amount is just a TextView with in the fragment,as that's what the image shows. So first you define a method in the Fragment to calculate the sum.
Assuming that you have an instance variable of arraylist and a Entity Class(POJO)that holds your arraylist data :

Suppose your arraylist is foodList and entity class is Foods.Then you
  have an arraylist like below:

ArrayList<Foods> foodList

then,the method will be:

public void getSumofAllitems(){
int total_sum=0;
for(int i=0;i<foodList.size();i++){
Foods food_items=foodList.get(i);
int price=food_items.getPrice();//getPrice() is a getter method in your POJO class.
total_sum+= price;
}
totalpriceTextView.setText(total_sum+"");
}

Then from your RecyclerView's onBindViewHolder method,check the posiion of the view that is:

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));
if(position==data.size()-1){
((Activity)context).getSumofAllitems();
}
}

I called the method from RecyclerView  and checked the position so that the method won't be executed util all your views are bind to RecyclerView and the RecycleView is populated. I believe this is the correct way to do this.


问:
How to calculate the least square coefficient error in python
Now I need to calculate the relation between two columns of data using least square method. I can get the equation of x and y with the function scipy.optimize.leastsq, the equation can be written as y=ax+b. The error of coefficients (a and b) is needed as well, but how to calculate them in python?
Any help is appreciated!

答: I think the appropriate package to use here is scipy.stats.linregress.


问:
Java android EventBus detect if server is send to phone message
I want to use a EventBus to detect if server is send something

I register an eventBus :

```<code>App.getBus().register(this);
public static App getInstance() {
    return instance;
}

public static EventBus getBus() {
    return EventBus.getDefault();
}
</code>```

But I don't have idea how I can detect if server is send something

答:
I don't have idea how I can detect if server is send something

EventBus is use used to send events with in the app, it can not be used to send messages from server to client via internet. Sending message from server to client can be implemented by using FCM by google.

Body:
I want to use a EventBus to detect if server is send something

I register an eventBus :

App.getBus().register(this);
public static App getInstance() {
    return instance;
}

public static EventBus getBus() {
    return EventBus.getDefault();
}

But I don't have idea how I can detect if server is send something


问:
How to overwrite existing files in batch?
The following command copies and moves a file but I also need it to overwrite the file it's replacing.</p>

```<code>xcopy /s c:\mmyinbox\test.doc C:\myoutbox
</code>```

答:
If destination file is read only use /y/r

```<code>xcopy /y/r source.txt dest.txt
</code>```

Body:
The following command copies and moves a file but I also need it to overwrite the file it's replacing.

xcopy /s c:\mmyinbox\test.doc C:\myoutbox

Body:
If destination file is read only use /y/r

xcopy /y/r source.txt dest.txt


问:
Why should I practice Test Driven Development and how should I start?
Lots of people talk about writing tests for their code before they start writing their code. This practice is generally known as Test Driven Development or TDD for short. What benefits do I gain from writing software this way? How do I get started with this practice?</p>

答: In my opinion, the single greatest thing is that it clearly allows you to see if your code does what it is supposed to.  This may seem obvious, but it is super easy to run astray of your original goals, as I have found out in the past :p</p>


问:
C# numeric constants
I have the following C# code:

```<code>byte rule = 0;
...
rule = rule | 0x80;
</code>```

which produces the error:

Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

[Update: first version of the question was wrong ... I misread the compiler output]

Adding the cast doesn't fix the problem:

```<code>rule = rule | (byte) 0x80;
</code>```

I need to write it as:

```<code>rule |= 0x80;
</code>```

Which just seems weird. Why is the |= operator any different to the | operator?

Is there any other way of telling the compiler to treat the constant as a byte?

@ Giovanni Galbo : yes and no.  The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory.  I could cast it later, but this seemed more obvious.  I guess my C heritage is showing through too much!

@ Jonathon Holland : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:

The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)

答:
Apparently the expression 'rule |
  0x80' returns an int even if you
  define 0x80 as 'const byte 0x80'.

I think the rule is numbers like 0x80 defaults to int unless you include a literal suffix. So for the expression rule | 0x80, the result will be an int since 0x80 is an int and rule (which is a byte) can safely be converted to int.

OwnerDisplayName: Rob Walker

Title: C# numeric constants

Body:
I have the following C# code:

byte rule = 0;
...
rule = rule | 0x80;

which produces the error:

Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

[Update: first version of the question was wrong ... I misread the compiler output]

Adding the cast doesn't fix the problem:

rule = rule | (byte) 0x80;

I need to write it as:

rule |= 0x80;

Which just seems weird. Why is the |= operator any different to the | operator?

Is there any other way of telling the compiler to treat the constant as a byte?

@ Giovanni Galbo : yes and no.  The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory.  I could cast it later, but this seemed more obvious.  I guess my C heritage is showing through too much!

@ Jonathon Holland : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:

The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)

LastEditorDisplayName: Rob Walker

OwnerDisplayName: John


问:
AjaxControlKit in .NET 2.0 from Visual Studio 2008
I am working on a project which was developed in Visual Studio 2005 (.NET 2.0). I have Visual Studio 2008 and on opening the solution the files are converted to older framework.

But the project uses a AjaxControlKit which I guess is not available by default in ASP.NET 2.0 and hence it throws an error that a reference/library is missing on conversion and compiling it in 2008.

Any library/ reference can be added to solve this ? where can I find it?

答:
the AjaxControlToolkit is not included in the base .Net framework, you need to install it on your development machine.

You can find more information on the AjaxTookit site

OwnerDisplayName: Tom Anderson


问:
C++ Line into Vector
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.

Anyways, I have a text file:

```<code>6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10
</code>```

6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.

I have a Vector

```<code>std::vector<double> numbers;
</code>```

All i need to do, is get the Second line put into numbers.
So right now I have

```<code>ifstream myfile (filename.c_str());
</code>```

I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).

Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.

Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.

答:
something like : </p>

```<code>int count, a, b;
double tmp;
std::vector<double> numbers;
ifstream myfile (filename.c_str());
myfile >> count;
for(int i = 0; i < count; ++i) {
    myfile >> tmp; numbers.push_back(tmp);
}
myfile >> a >> b;
</code>```

Title: C++ Line into Vector

Body:
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.

Anyways, I have a text file:

6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10

6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.

I have a Vector

std::vector<double> numbers;

All i need to do, is get the Second line put into numbers.
So right now I have

ifstream myfile (filename.c_str());

I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).

Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.

Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.

Body:
something like :

int count, a, b;
double tmp;
std::vector<double> numbers;
ifstream myfile (filename.c_str());
myfile >> count;
for(int i = 0; i < count; ++i) {
    myfile >> tmp; numbers.push_back(tmp);
}
myfile >> a >> b;


问:
XML traversing to find the node name
Following is a string containing an XML file that specifies folder structure

```<code>     String xml ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                    "<folder name=\"c\">" +
                        "<folder name=\"program files\">" +
                            "<folder name=\"uninstall information\" />" +
                        "</folder>" +
                        "<folder name=\"users\" />" +
                    "</folder>";
</code>```

If user enter initial letter of the folder the method must return the folder name (following is part of it method i have tried)

```<code>DocumentBuilder builder =
    DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource src = new InputSource();
            src.setCharacterStream(new StringReader(xml));
            Document doc = builder.parse(src);
            List<String> listObj = new ArrayList<String>();
            if(doc.getElementsByTagName("folder").item(0) != null){
    System.out.println(doc.getElementsByTagName("folder").item(0).getNodeValue());}
</code>```

But in my method i always get null. How do I iterate and find out the folder name?

答:
name is an Attribute of the Folder tag, so you have to use the following code:

```<code>System.out.println(doc.getElementsByTagName("folder").item(0).getAttributes().getNamedItem("name").getNodeValue());
</code>```

Title: XML traversing to find the node name

Body:
Following is a string containing an XML file that specifies folder structure

     String xml ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                    "<folder name=\"c\">" +
                        "<folder name=\"program files\">" +
                            "<folder name=\"uninstall information\" />" +
                        "</folder>" +
                        "<folder name=\"users\" />" +
                    "</folder>";

If user enter initial letter of the folder the method must return the folder name (following is part of it method i have tried)

DocumentBuilder builder =
    DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource src = new InputSource();
            src.setCharacterStream(new StringReader(xml));
            Document doc = builder.parse(src);
            List<String> listObj = new ArrayList<String>();
            if(doc.getElementsByTagName("folder").item(0) != null){
    System.out.println(doc.getElementsByTagName("folder").item(0).getNodeValue());}

But in my method i always get null. How do I iterate and find out the folder name?

Body:
name is an Attribute of the Folder tag, so you have to use the following code:

System.out.println(doc.getElementsByTagName("folder").item(0).getAttributes().getNamedItem("name").getNodeValue());


问:
Dialog box not displaying upon clicking button
I have a site which has the button 'Currency Converter'. When clicked on it, it should open the dialog box and conversion should happen. Following is the code:

currency_converter.php

<!DOCTYPE HTML>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

    <button id="opener">Currency Converter</button>

    ```

The problem is: dialog box is not getting opened in my browser.

Can anyone please help. Thanks in advance

答:
Chnage your jquery and css url with these

https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
  https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js
  https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css

Body:
I have a site which has the button 'Currency Converter'. When clicked on it, it should open the dialog box and conversion should happen. Following is the code:

currency_converter.php

<!DOCTYPE HTML>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

    <button id="opener">Currency Converter</button>

The problem is: dialog box is not getting opened in my browser.

Can anyone please help. Thanks in advance


问:
Change img src by clicking li item CSS
I have a ul of images and a main image. Is it possible to change the src of the main image by clicking one of the ul just by CSS?</p>

答:
In my opinion, you will need to use JavaScript for that.

In case you are using jQuery (UNTESTED)

```<code>$(document).on('click', '.ul-li-element-image', function() {
    $('.mainImage').attr('src', $(this).attr('src'));
});
</code>```

Try something along these lines...

Title: Change img src by clicking li item CSS

Body:
In my opinion, you will need to use JavaScript for that.

In case you are using jQuery (UNTESTED)

$(document).on('click', '.ul-li-element-image', function() {
    $('.mainImage').attr('src', $(this).attr('src'));
});

Try something along these lines...


答:
Try to modify like this:

```<code>.imgCadenas{
  width:  50px;
  height: 50px;
  background: url('/cadenas.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border: 0 !important;
  border-style: none !important;
  outline: none !important;

  position: absolute;
  right: 150px;
  top: 5px;
}
</code>```

EDITED

Your img element missing src attribute,
Try to change img element to div element.

See also:
https://stackoverflow.com/a/22097004/4964262

Title: How to remove the border of an image?

Body:
Try to modify like this:

.imgCadenas{
  width:  50px;
  height: 50px;
  background: url('/cadenas.png');
  background-repeat: no-repeat;
  background-position: right;
  background-size: 100%;

  border: 0 !important;
  border-style: none !important;
  outline: none !important;

  position: absolute;
  right: 150px;
  top: 5px;
}

EDITED

Your img element missing src attribute,
Try to change img element to div element.

See also:
https://stackoverflow.com/a/22097004/4964262