问:
TensorFlow example but with middle layer
I am trying to get this code to work. It may not look like it, but it comes mostly from the TensorFlow mnist example. I am trying to get three layers, though, and I've changed the input and output size. The input size is 12, the mid size is 6, and the output size is 2. This is what happens when I run this. It does not throw an error, but when I run the test option I always get 50%. When I go back to training it runs and I am sure the weights are changing. There is code for saving the model and weights, so I'm pretty confident it's not wiping out my weights every time I re-start it. The idea behind self.d_y_out is to have something that will allow me to run the model and get output for just one image. I think the problem is near the comment that says "PROBLEM??".

```<code>        self.d_keep = tf.placeholder(tf.float32)
        self.d_W_2 = tf.Variable(tf.random_normal([mid_num, output_num], stddev=0.0001))
        self.d_b_2 = tf.Variable(tf.random_normal([output_num], stddev=0.5))

        self.d_x = tf.placeholder(tf.float32, [None, input_num])
        self.d_W_1 = tf.Variable(tf.random_normal([input_num, mid_num], stddev=0.0001))  # 0.0004
        self.d_b_1 = tf.Variable(tf.zeros([mid_num]))

        self.d_y_ = tf.placeholder(tf.float32, [None, output_num])

        self.d_x_drop = tf.nn.dropout(self.d_x, self.d_keep)

        self.d_y_logits_1 = tf.matmul(self.d_x_drop, self.d_W_1) + self.d_b_1
        self.d_y_mid = tf.nn.relu(self.d_y_logits_1)
        self.d_y_mid_drop = tf.nn.dropout(self.d_y_mid, self.d_keep)

        self.d_y_logits_2 = tf.matmul(self.d_y_mid_drop, self.d_W_2) + self.d_b_2

        self.d_y_softmax = tf.nn.softmax_cross_entropy_with_logits(logits=self.d_y_logits_2, labels=self.d_y_)

        self.d_cross_entropy = tf.reduce_mean(self.d_y_softmax) ## PROBLEM??

        self.d_train_step = tf.train.GradientDescentOptimizer(0.001).minimize(self.d_cross_entropy)  # 0.0001

        # train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #0.5

        #self.d_y_out = tf.argmax(self.d_y, 1)  ## for prediction
        self.d_y_out = tf.argmax(self.d_y_logits_2, 1, name="d_y_out")

    if self.train :

        for i in range(self.start_train,self.cursor_tot): #1000
            batch_xs, batch_ys = self.get_nn_next_train(self.batchsize)
            self.sess.run(self.d_train_step, feed_dict={self.d_x: batch_xs, self.d_y_: batch_ys, self.d_keep: 0.5})
            if True: #mid_num > 0:
                cost = self.sess.run([self.d_cross_entropy, self.d_train_step],
                    feed_dict={self.d_x: batch_xs, self.d_y_: batch_ys, self.d_keep: 0.5})
                print cost[0], "cost"

    if self.test :
        d_correct_prediction = tf.equal(self.d_y_out, tf.argmax(self.d_y_,1))
        #d_correct_prediction = tf.equal(tf.argmax(self.d_y , 1), tf.argmax(self.d_y_, 1))

        d_accuracy = tf.reduce_mean(tf.cast(d_correct_prediction, tf.float32))

        if self.use_loader : self.get_nn_next_test(self.batchsize)
        print(self.sess.run([d_accuracy, self.d_cross_entropy],
            feed_dict={self.d_x: self.mnist_test.images, self.d_y_: self.mnist_test.labels, self.d_keep: 1.0}))

    if self.predict_dot :
        for i in range(start, stop ) :
            batch_0, batch_1 = self.get_nn_next_predict(self.batchsize)
            if len(batch_0) > 0 :
                out.extend( self.sess.run([self.d_y_out, self.d_cross_entropy],
                    feed_dict={self.d_x : batch_0, self.d_y_: batch_1, self.d_keep: 1.0})[0])
                print "out" , len(out) , i, self.cursor_tot, out[:10],"..."
</code>```

EDIT I've edited the code in this question significantly. Much thanks to vijay m for getting me this far. Any help would be appreciated. Thanks.

答:
The problem in this code is you calling dropout on the inputs. Yours is a single layer network and you don't need dropout. And use a momentum optimizer like Adam for training faster. The changes i made:

```<code>d_y_logits_1 = tf.matmul(d_x, d_W_1) + d_b_1
d_y_mid = tf.nn.relu(d_y_logits_1)

d_y_logits_2 = tf.matmul(d_y_mid, d_W_2) + d_b_2

d_y_softmax = tf.nn.softmax_cross_entropy_with_logits(logits=d_y_logits_2, labels=d_y_)

d_cross_entropy = tf.reduce_mean(d_y_softmax)

d_train_step = tf.train.AdamOptimizer(0.01).minimize(d_cross_entropy)
</code>```

Body:
I am trying to get this code to work. It may not look like it, but it comes mostly from the TensorFlow mnist example. I am trying to get three layers, though, and I've changed the input and output size. The input size is 12, the mid size is 6, and the output size is 2. This is what happens when I run this. It does not throw an error, but when I run the test option I always get 50%. When I go back to training it runs and I am sure the weights are changing. There is code for saving the model and weights, so I'm pretty confident it's not wiping out my weights every time I re-start it. The idea behind self.d_y_out is to have something that will allow me to run the model and get output for just one image. I think the problem is near the comment that says "PROBLEM??".

        self.d_keep = tf.placeholder(tf.float32)
        self.d_W_2 = tf.Variable(tf.random_normal([mid_num, output_num], stddev=0.0001))
        self.d_b_2 = tf.Variable(tf.random_normal([output_num], stddev=0.5))

        self.d_x = tf.placeholder(tf.float32, [None, input_num])
        self.d_W_1 = tf.Variable(tf.random_normal([input_num, mid_num], stddev=0.0001))  # 0.0004
        self.d_b_1 = tf.Variable(tf.zeros([mid_num]))

        self.d_y_ = tf.placeholder(tf.float32, [None, output_num])

        self.d_x_drop = tf.nn.dropout(self.d_x, self.d_keep)

        self.d_y_logits_1 = tf.matmul(self.d_x_drop, self.d_W_1) + self.d_b_1
        self.d_y_mid = tf.nn.relu(self.d_y_logits_1)
        self.d_y_mid_drop = tf.nn.dropout(self.d_y_mid, self.d_keep)

        self.d_y_logits_2 = tf.matmul(self.d_y_mid_drop, self.d_W_2) + self.d_b_2

        self.d_y_softmax = tf.nn.softmax_cross_entropy_with_logits(logits=self.d_y_logits_2, labels=self.d_y_)

        self.d_cross_entropy = tf.reduce_mean(self.d_y_softmax) ## PROBLEM??

        self.d_train_step = tf.train.GradientDescentOptimizer(0.001).minimize(self.d_cross_entropy)  # 0.0001

        # train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #0.5

        #self.d_y_out = tf.argmax(self.d_y, 1)  ## for prediction
        self.d_y_out = tf.argmax(self.d_y_logits_2, 1, name="d_y_out")

    if self.train :

        for i in range(self.start_train,self.cursor_tot): #1000
            batch_xs, batch_ys = self.get_nn_next_train(self.batchsize)
            self.sess.run(self.d_train_step, feed_dict={self.d_x: batch_xs, self.d_y_: batch_ys, self.d_keep: 0.5})
            if True: #mid_num > 0:
                cost = self.sess.run([self.d_cross_entropy, self.d_train_step],
                    feed_dict={self.d_x: batch_xs, self.d_y_: batch_ys, self.d_keep: 0.5})
                print cost[0], "cost"

    if self.test :
        d_correct_prediction = tf.equal(self.d_y_out, tf.argmax(self.d_y_,1))
        #d_correct_prediction = tf.equal(tf.argmax(self.d_y , 1), tf.argmax(self.d_y_, 1))

        d_accuracy = tf.reduce_mean(tf.cast(d_correct_prediction, tf.float32))

        if self.use_loader : self.get_nn_next_test(self.batchsize)
        print(self.sess.run([d_accuracy, self.d_cross_entropy],
            feed_dict={self.d_x: self.mnist_test.images, self.d_y_: self.mnist_test.labels, self.d_keep: 1.0}))

    if self.predict_dot :
        for i in range(start, stop ) :
            batch_0, batch_1 = self.get_nn_next_predict(self.batchsize)
            if len(batch_0) > 0 :
                out.extend( self.sess.run([self.d_y_out, self.d_cross_entropy],
                    feed_dict={self.d_x : batch_0, self.d_y_: batch_1, self.d_keep: 1.0})[0])
                print "out" , len(out) , i, self.cursor_tot, out[:10],"..."

EDIT I've edited the code in this question significantly. Much thanks to vijay m for getting me this far. Any help would be appreciated. Thanks.

Body:
The problem in this code is you calling dropout on the inputs. Yours is a single layer network and you don't need dropout. And use a momentum optimizer like Adam for training faster. The changes i made:

d_y_logits_1 = tf.matmul(d_x, d_W_1) + d_b_1
d_y_mid = tf.nn.relu(d_y_logits_1)

d_y_logits_2 = tf.matmul(d_y_mid, d_W_2) + d_b_2

d_y_softmax = tf.nn.softmax_cross_entropy_with_logits(logits=d_y_logits_2, labels=d_y_)

d_cross_entropy = tf.reduce_mean(d_y_softmax)

d_train_step = tf.train.AdamOptimizer(0.01).minimize(d_cross_entropy)


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: Computing the column value based on previous rows

Body:
I would like to add a new column Y to each row which will tell me percentage number of times the X column val was greater > 1 for last 10 previous records

stock price history

   ticker       date    adj_open   ad_close       X(%)
0    ABC     2017-10-06   12.10      13.11        8.0
1    ABC     2017-12-05   11.11      11.87        5.0
2    ABC     2017-12-04   12.08      11.40       -7.0
3    ABC     2017-12-03   12.01      13.03       10.1
4    ABC     2017-07-04   9.01        9.59        8.0
5    ABC     2017-07-03   7.89        8.19        4.0

Resultant transformed data set

    ticker       date    adj_open ad_close    X(%)     Y(%)
0    ABC     2017-10-06   12.10    13.11      8.0        80
1    ABC     2017-12-05   11.11    11.87      5.0        75
2    ABC     2017-12-04   12.08    11.40     -7.0       100
3    ABC     2017-12-03   12.01    13.03     10.1       100
4    ABC     2017-07-04   9.01     9.59       8.0       100
5    ABC     2017-07-03   7.89     8.19       4.0        0

Body:
You have:

df
    ticker  date        adj_open    ad_close    X(%)
0   ABC     2017-10-06  12.10       13.11       8.0
1   ABC     2017-12-05  11.11       11.87       5.0
2   ABC     2017-12-04  12.08       11.40      -7.0
3   ABC     2017-12-03  12.01       13.03       10.1
4   ABC     2017-07-04  9.01        9.59        8.0
5   ABC     2017-07-03  7.89        8.19        4.0

Let's define window and a function that will calculate wanted quantity:

w = 2
def count_pcnt(x, window = w):
    return (np.sum(x>1)/window)*100.0

Finally, let's apply the function:

df["Y(%)"] = df["X(%)"].rolling(window=w).apply(count_pcnt)
df

    ticker  date        adj_open    ad_close    X(%)    Y(%)
0   ABC     2017-10-06  12.10       13.11       8.0     NaN
1   ABC     2017-12-05  11.11       11.87       5.0     100.0
2   ABC     2017-12-04  12.08       11.40      -7.0     50.0
3   ABC     2017-12-03  12.01       13.03      10.1     50.0
4   ABC     2017-07-04  9.01         9.59       8.0     100.0
5   ABC     2017-07-03  7.89         8.19       4.0     100.0

You may change w to 10, as you have more data.

EDIT

If you wish:

w=4
df["Y(%)"] = df["X(%)"].rolling(window=w).apply(lambda x: count_pcnt(x, window = w))

df
    ticker  date        adj_open    ad_close    X(%)    Y(%)
0   ABC     2017-10-06  12.10       13.11       8.0     NaN
1   ABC     2017-12-05  11.11       11.87       5.0     NaN
2   ABC     2017-12-04  12.08       11.40      -7.0     NaN
3   ABC     2017-12-03  12.01       13.03      10.1     75.0
4   ABC     2017-07-04  9.01        9.59        8.0     75.0
5   ABC     2017-07-03  7.89        8.19        4.0     75.0

EDIT 2

w=4 # specify the desired window
df["Y(%)"] = df["X(%)"].rolling(window=w).apply(lambda x: (np.sum(x>1)/x.shape[0])* 100.0)

EDIT 3

w=4
df["Y(%)"] = df["X(%)"].rolling(window=w
                                ,min_periods = 0).apply(lambda x: (np.sum(x>1)/x.shape[0])* 100.0)
df

ticker  date    adj_open    ad_close    X(%)    Y(%)
0   ABC 2017-10-06  12.10   13.11   8.0     100.000000
1   ABC 2017-12-05  11.11   11.87   5.0     100.000000
2   ABC 2017-12-04  12.08   11.40   -7.0    66.666667
3   ABC 2017-12-03  12.01   13.03   10.1    75.000000
4   ABC 2017-07-04  9.01    9.59    8.0     75.000000
5   ABC 2017-07-03  7.89    8.19    4.0     75.000000


问:
Why do we need a Scanner Object for taking input in java
To print output we simply use System.out stream while to take input, we have to pass System.in in Constructor of a Scanner object and then use that object only. </p>

<p>Why is it so ? Why is there no direct method like System.in.nextInt() or something alike? </p>

答:
System.in is simply an InputStream. A pretty generic interface designed many years ago. Changing this aspect would break a lot of existing code. So changing the type of System.in is a no go.

Adding the scanner methods to the stream would bloat the existing class on the other hand. Think of concepts such as single responsibility principle or segregation of concerns.

You see - good object oriented design is about having small classes that have one responsibility. Not two, not 5 or 10.

But I think you have a certain point - and if Java would be rewritten today, that input stream might end up being more convenient.

Body:
To print output we simply use System.out stream while to take input, we have to pass System.in in Constructor of a Scanner object and then use that object only.

Why is it so ? Why is there no direct method like System.in.nextInt() or something alike?


问:
How to create gridview list item like that
How i can create this black container with some text like it is on this  picture?

答:
Try this :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="150dp"
            android:layout_height="150dp">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:background="#aaee00"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:background="#55000000"
    android:gravity="center"
    android:text="Dummy text"
    android:textColor="#eeffffff"/>

</RelativeLayout>
</code>```

Hope this helps.

Body:
Try this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="150dp"
            android:layout_height="150dp">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:background="#aaee00"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:background="#55000000"
    android:gravity="center"
    android:text="Dummy text"
    android:textColor="#eeffffff"/>

</RelativeLayout>

Hope this helps.


问:
Kafka data types of messages
I was wondering about what types of data we could have in Kafka topics.
As I know in application level this is a key-value pairs and this could be the data of type which is supported by the language.
For example we send some messages to the topic, could it be some json, parquet files, serialized data or we operate with the messages only like with the plain text format?

Thanks for you help.

答:
There are various message formats depending on if you are talking about the APIs, the wire protocol, or the on disk storage.

Some of these Kafka Message formats are described in the docs here

https://kafka.apache.org/documentation/#messageformat

Kafka has the concept of a Serializer/Deserializer or SerDes (pronounced Sir-Deez).

https://en.m.wikipedia.org/wiki/SerDes

A Serializer is a function that can take any message and converts it into the byte array that is actually sent on the wire using the Kafka Protocol.

A Deserializer does the opposite, it reads the raw message bytes portion of the Kafka wire protocol and re-creates a message as you want the receiving application to see it.

There are built-in SerDes libraries for Strings, Long, ByteArrays, ByteBuffers and a wealth of community SerDes libraries for JSON, ProtoBuf, Avro, as well as application specific message formats.

You can build your own SerDes libraries as well see the following

How to create Custom serializer in kafka?

Title: Kafka data types of messages


问:
getting user input without using input element
Is there a way to get the user text input without having him type in a text box, or somehow concealing the text box.
i would want to build something like a table cell with text in it and when the user clicks on the cell he can edit the text there.</p>

答:
You can use contenteditable:

document.getElementById('foo').addEventListener('keyup', e => {
 console.log(e.target.innerText)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td id="foo" contenteditable="true">Foo</td>
    </tr>
  </tbody>
</table></code>```

Body:
You can use contenteditable:

document.getElementById('foo').addEventListener('keyup', e => {
 console.log(e.target.innerText)
})

<table>
  <tbody>
    <tr>
      <td id="foo" contenteditable="true">Foo</td>
    </tr>
  </tbody>
</table>


问:
Celery event args capturing
I want to capture task arguments using the task events provided by celery.
I'm using redis as the backend and broker (Pickle as the serializer). According to the documentation, it's possible to get this info by listening to task-received handler, where args will be populated.

The problem I'm facing is, for small data input this works as expected. When I use a large input (binary file - ~16MB), args received by events is much smaller and truncated.

Does anybody know the reason for this? Thanks for the help!

答:
Celery has a limit on the size of the data pushed to an event.

It is configurable using repr_maxsize.

I'm guessing, but this probably has significant performance penalties and should be avoided.

Title: Celery event args capturing


问:
Vertically Scrolling a

I have a few nested  and I want to allow my deepest  to scroll vertically.

in CSS I have tried adding:

```<code>overflow-x: hidden; /* horizontal */
overflow-y: auto;  /* vertical */
</code>```

to the class I am assigning to the  but that does not seem to do it. Changing overflow-y: yes; does not work either.

How does one accomplish this. I want this  to scroll because it gets populated with MySQL data where the other div's just present selectable criteria to create the query and run it.

thoughts are appreciated.

Example:

```<code><div id="content">
    <div id="slidingDivKeynotePresentations">
        <!-- content here -->
    </div>
</div>
</code>```

My CSS:

```<code>#content {
    position: absolute;
    top: 0;
    left: 21%;
    margin: 26% 31% 1% 21%; /* Cater for Mac IE5 */
    /*\*/ margin: 0; /* Put back for all the rest */
    /*\*/ overflow: auto; /* no need for Mac IE5 to see this */
    overflow-x: hidden; /* horizontal */
    overflow-y: yes;  /* vertical */
}

#slidingDivKeynotePresentations {
    display: none;
    height: 600px;
    width: 600px;
    background-image: url('images/transwhite.png');
    border: 1px solid #3F4933;
    position: fixed;
    top: 100px;
    left: 290px; /*Set left value to WidthOfFrameDiv*/
    padding: 12px;
    overflow-x: hidden; /* horizontal */
    overflow-y: auto;  /* vertical */
 }
</code>```

答:
Here is a fiddle with it working: Just replace position: fixed with position: relative; in the inner div.  I took away all of the overflow-x and -y, and simply put overflow: auto on the containing div. And I also moved the border to the outer div so it wouldn't get cut off at the bottom. But I think all you need to do is switch the fixed with relative.

To take away the horizontal scrollbar, simply make the width of the inner div the same or smaller then the width of the outer div.  Especially since CSS3 overflow-x and -y is not widely available yet.

ContentLicense: CC BY-SA 2.5

Title: Vertically Scrolling a <DIV>

Body:
I have a few nested  and I want to allow my deepest  to scroll vertically.

in CSS I have tried adding:

overflow-x: hidden; /* horizontal */
overflow-y: auto;  /* vertical */

to the class I am assigning to the  but that does not seem to do it. Changing overflow-y: yes; does not work either.

How does one accomplish this. I want this  to scroll because it gets populated with MySQL data where the other div's just present selectable criteria to create the query and run it.

thoughts are appreciated.

Example:

My CSS:

#content {
    position: absolute;
    top: 0;
    left: 21%;
    margin: 26% 31% 1% 21%; /* Cater for Mac IE5 */
    /*\*/ margin: 0; /* Put back for all the rest */
    /*\*/ overflow: auto; /* no need for Mac IE5 to see this */
    overflow-x: hidden; /* horizontal */
    overflow-y: yes;  /* vertical */
}

#slidingDivKeynotePresentations {
    display: none;
    height: 600px;
    width: 600px;
    background-image: url('images/transwhite.png');
    border: 1px solid #3F4933;
    position: fixed;
    top: 100px;
    left: 290px; /*Set left value to WidthOfFrameDiv*/
    padding: 12px;
    overflow-x: hidden; /* horizontal */
    overflow-y: auto;  /* vertical */
 }


问:
jquery datepicker and asp.net c# empty value
I'm getting really pissed off by this code :D I'm using jQuery datepicker in input field that's set to readonly and the datepicker should appear twice in the same page and it depends on the value of a dropdownlist.

The language i'm using is ASP.NET c#:

the following input textboxes are on my aspx page:

```<code><asp:TextBox ID="txt_check_chequeDate" runat="server" BorderStyle="Solid"
BorderWidth="2px" Font-Names="Calibri" Style="margin-left: 0px" ClientIDMode="Static" ReadOnly="true"></asp:TextBox>

<tr ID="tr_wire_TransactionDate" runat="server">
    <td>
        <asp:Label ID="lbl_wire_TransactionDate" runat="server" Font-Names="Calibri"
            Text="Transaction Date"></asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txt_wire_chequeDate" runat="server" BorderStyle="Solid"
            BorderWidth="2px" ClientIDMode="Static" Font-Names="Calibri"
            Style="margin-left: 0px" ReadOnly="true"></asp:TextBox>
    </td>
</tr>
</code>```

and my jQuery script is as follows with references:

```<code><script type="text/javascript" src="../Scripts/jquery-1.4.1.min.js"></script>
<script src='../Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'></script>
<script src='../Scripts/jquery.ui.core.js' type='text/javascript'></script>
<script src='../Scripts/jquery.ui.widget.js' type='text/javascript'></script>

<link href='../Styles/jquery.ui.all.css' rel='stylesheet' type='text/css'/>

<link href='../Styles/jquery.ui.datepicker.css' rel='Stylesheet'
type='text/css' />
<script src='../Scripts/jquery.ui.datepicker.js' type='text/javascript'></script>
<script type='text/javascript'>
    $(function () {
        $('#txt_check_chequeDate').datepicker({ changeYear: true });

    });
    $(function () {
       $('#txt_wire_chequeDate').datepicker({ changeYear: true });
    });
</code>```

and when I click the submit button, I get empty value by executing the following:

```<code>Debug.WriteLine("on page click value is wire  =  " + this.txt_wire_chequeDate.Text.Trim());
        Debug.WriteLine("on page click value is cheque  =  " + this.txt_check_chequeDate.Text.Trim());
</code>```

Any idea why I'm getting empty date through datepicker, when i tried eariler i was getting the value correctly for one case only :(

答:
Remove the readonly attribute on the webform controls and set the readonly attribute through javascript.</p>

```<code><script type='text/javascript'>
        $(function () {
            $("#txt_check_chequeDate").attr("readonly", true);
            $("#txt_wire_chequeDate").attr("readonly", true);
        })
</script>
</code>```

Body:
I'm getting really pissed off by this code :D I'm using jQuery datepicker in input field that's set to readonly and the datepicker should appear twice in the same page and it depends on the value of a dropdownlist.

The language i'm using is ASP.NET c#:

the following input textboxes are on my aspx page:

<asp:TextBox ID="txt_check_chequeDate" runat="server" BorderStyle="Solid"
BorderWidth="2px" Font-Names="Calibri" Style="margin-left: 0px" ClientIDMode="Static" ReadOnly="true"></asp:TextBox>

        <asp:Label ID="lbl_wire_TransactionDate" runat="server" Font-Names="Calibri"
            Text="Transaction Date"></asp:Label>

        <asp:TextBox ID="txt_wire_chequeDate" runat="server" BorderStyle="Solid"
            BorderWidth="2px" ClientIDMode="Static" Font-Names="Calibri"
            Style="margin-left: 0px" ReadOnly="true"></asp:TextBox>

and my jQuery script is as follows with references:

<link href='../Styles/jquery.ui.all.css' rel='stylesheet' type='text/css'/>

<link href='../Styles/jquery.ui.datepicker.css' rel='Stylesheet'
type='text/css' />

Body:
Remove the readonly attribute on the webform controls and set the readonly attribute through javascript.

<script type='text/javascript'>
        $(function () {
            $("#txt_check_chequeDate").attr("readonly", true);
            $("#txt_wire_chequeDate").attr("readonly", true);
        })
</script>


问:
How to save the content of an EditText(Plain text) into a Txt File on internal storage
Im developing an app who have an EditText for users input and an ImageView that im using like a button to save the content of the EditText when the user press it.

So, my problem is that i dont know how i can save the content of the EditText in the txt file who will be save inside the internal storage. Also i need to load the content of this txt file inside the EditText every time that the user opens the app.

Does any one can put me in the right way to do this ? thanks.

答:
```<code>using System.IO;

// build path
string path = Path.Combine((string)Android.OS.Environment.ExternalStorageDirectory, "My Folder Name", "My File Name");

// write to file
File.WriteAllText(path, MyEditControl.Text);

// read from file
string text = File.ReadAllText(path);
MyEditControl.Text = text;
</code>```


问:
Listener Binding; Cannot Find the Setter
I am trying to implement listener bindings, but when I run my code I get the following error:

```<code>Caused by: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'android:onClick' with parameter type lambda on android.widget.Button. file:~/GithubBrowser/app/src/main/res/layout/loading_state.xml loc:30:31 - 30:52 ****\ data binding error ****
</code>```

This is the layout file in question:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="com.example.app.data.model.Resource"/>
        <import type="com.example.app.data.model.Status"/>
        <variable name="resource" type="Resource"/>
        <variable name="callback" type="com.example.app.ui.common.RetryCallback"/>
    </data>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="@dimen/default_margin">

        <Button android:id="@+id/retry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/retry"
            android:onClick="@{() -> callback.retry()}"/>

    </LinearLayout>

</layout>
</code>```

And this is the RetryCallback interface referenced in the layout:

```<code>package com.example.app.ui.common

interface RetryCallback {

    fun retry()

}
</code>```

Edit

The top-level build.gradle:

```<code>buildscript {
    ext.android_tools_version = '3.0.0-alpha3'
    ext.kotlin_version = '1.1.2-5'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$android_tools_version"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

ext {
    architecture_version = '1.0.0-alpha2'
    constraint_version = '1.0.2'
    dagger_version = '2.11'
    espresso_version = '2.2.2'
    glide_version = '3.7.0'
    junit_version = '4.12'
    mockito_version = '2.7.19'
    mock_server_version = '3.6.0'
    moshi_version = '1.5.0'
    retrofit_version = '2.2.0'
    support_version = '25.4.0'
    timber_version = '4.5.1'
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

And the app module build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            testCoverageEnabled !project.hasProperty('android.injected.invoked.from.ide')
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

kapt {
    generateStubs = true
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile "com.android.support:appcompat-v7:$support_version"
    compile "com.android.support:cardview-v7:$support_version"
    compile "com.android.support:design:$support_version"
    compile "com.android.support:recyclerview-v7:$support_version"
    compile "com.android.support.constraint:constraint-layout:$constraint_version"

    compile "android.arch.lifecycle:extensions:$architecture_version"
    compile "android.arch.lifecycle:runtime:$architecture_version"
    compile "android.arch.persistence.room:runtime:$architecture_version"

    compile "com.google.dagger:dagger:$dagger_version"
    compile "com.google.dagger:dagger-android:$dagger_version"
    compile "com.google.dagger:dagger-android-support:$dagger_version"

    compile "com.squareup.moshi:moshi:$moshi_version"
    compile "com.squareup.retrofit2:retrofit:$retrofit_version"
    compile "com.squareup.retrofit2:converter-moshi:$retrofit_version"

    compile "com.github.bumptech.glide:glide:$glide_version"

    compile "com.jakewharton.timber:timber:$timber_version"

    kapt "com.android.databinding:compiler:$android_tools_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
    kapt "android.arch.persistence.room:compiler:$architecture_version"
    kapt "android.arch.lifecycle:compiler:$architecture_version"

    testCompile "junit:junit:$junit_version"
    testCompile "com.squareup.okhttp3:mockwebserver:$mock_server_version"
    testCompile ("android.arch.core:core-testing:$architecture_version", {
        exclude group: 'com.android.support', module: 'support-compat'
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-ccore-utils'
    })

    androidTestCompile "com.android.support:appcompat-v7:$support_version"
    androidTestCompile "com.android.support:cardview-v7:$support_version"
    androidTestCompile "com.android.support:design:$support_version"
    androidTestCompile "com.android.support:recyclerview-v7:$support_version"

    androidTestCompile ("com.android.support.test.espresso:espresso-core:$espresso_version", {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs', module: 'jsr305'
    })

    androidTestCompile ("com.android.support.test.espresso:espresso-contrib:$espresso_version", {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs', module: 'jsr305'
    })

    androidTestCompile "org.mockito:mockito-android:$mockito_version"
}
</code>```

答:
I just had that issue and I have managed to solve it by deleting .idea, .gradle and gradle folders and let Android Studio recreate whole project from scratch from gradle files.

2022 UPDATE: Do not delete gradle folder, only .gradle and .idea.

Body:
I am trying to implement listener bindings, but when I run my code I get the following error:

Caused by: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'android:onClick' with parameter type lambda on android.widget.Button. file:~/GithubBrowser/app/src/main/res/layout/loading_state.xml loc:30:31 - 30:52 ****\ data binding error ****

This is the layout file in question:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="com.example.app.data.model.Resource"/>
        <import type="com.example.app.data.model.Status"/>
        <variable name="resource" type="Resource"/>
        <variable name="callback" type="com.example.app.ui.common.RetryCallback"/>
    </data>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="@dimen/default_margin">

        <Button android:id="@+id/retry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/retry"
            android:onClick="@{() -> callback.retry()}"/>

    </LinearLayout>

</layout>

And this is the RetryCallback interface referenced in the layout:

package com.example.app.ui.common

interface RetryCallback {

    fun retry()

}

Edit

The top-level build.gradle:

buildscript {
    ext.android_tools_version = '3.0.0-alpha3'
    ext.kotlin_version = '1.1.2-5'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$android_tools_version"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

ext {
    architecture_version = '1.0.0-alpha2'
    constraint_version = '1.0.2'
    dagger_version = '2.11'
    espresso_version = '2.2.2'
    glide_version = '3.7.0'
    junit_version = '4.12'
    mockito_version = '2.7.19'
    mock_server_version = '3.6.0'
    moshi_version = '1.5.0'
    retrofit_version = '2.2.0'
    support_version = '25.4.0'
    timber_version = '4.5.1'
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And the app module build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            testCoverageEnabled !project.hasProperty('android.injected.invoked.from.ide')
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

kapt {
    generateStubs = true
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile "com.android.support:appcompat-v7:$support_version"
    compile "com.android.support:cardview-v7:$support_version"
    compile "com.android.support:design:$support_version"
    compile "com.android.support:recyclerview-v7:$support_version"
    compile "com.android.support.constraint:constraint-layout:$constraint_version"

    compile "android.arch.lifecycle:extensions:$architecture_version"
    compile "android.arch.lifecycle:runtime:$architecture_version"
    compile "android.arch.persistence.room:runtime:$architecture_version"

    compile "com.google.dagger:dagger:$dagger_version"
    compile "com.google.dagger:dagger-android:$dagger_version"
    compile "com.google.dagger:dagger-android-support:$dagger_version"

    compile "com.squareup.moshi:moshi:$moshi_version"
    compile "com.squareup.retrofit2:retrofit:$retrofit_version"
    compile "com.squareup.retrofit2:converter-moshi:$retrofit_version"

    compile "com.github.bumptech.glide:glide:$glide_version"

    compile "com.jakewharton.timber:timber:$timber_version"

    kapt "com.android.databinding:compiler:$android_tools_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
    kapt "android.arch.persistence.room:compiler:$architecture_version"
    kapt "android.arch.lifecycle:compiler:$architecture_version"

    testCompile "junit:junit:$junit_version"
    testCompile "com.squareup.okhttp3:mockwebserver:$mock_server_version"
    testCompile ("android.arch.core:core-testing:$architecture_version", {
        exclude group: 'com.android.support', module: 'support-compat'
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-ccore-utils'
    })

    androidTestCompile "com.android.support:appcompat-v7:$support_version"
    androidTestCompile "com.android.support:cardview-v7:$support_version"
    androidTestCompile "com.android.support:design:$support_version"
    androidTestCompile "com.android.support:recyclerview-v7:$support_version"

    androidTestCompile ("com.android.support.test.espresso:espresso-core:$espresso_version", {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs', module: 'jsr305'
    })

    androidTestCompile ("com.android.support.test.espresso:espresso-contrib:$espresso_version", {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs', module: 'jsr305'
    })

    androidTestCompile "org.mockito:mockito-android:$mockito_version"
}

ContentLicense: CC BY-SA 4.0


问:
ClassCastException in onLongClick of ViewHolder
I'm following this tutorial to implement multi select in my RecyclerView but I have been getting the following runtime exception when I perform a long click:

```<code>java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to android.support.v7.app.AppCompatActivity
                                                                       at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                       at android.view.View.performLongClick(View.java:5308)
                                                                       at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                       at android.os.Looper.loop(Looper.java:207)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
</code>```

Activity code:

```<code>public class IMListActivity extends AppCompatActivity implements Sertivity{

private RecyclerView recyclerView;
private IMListAdapter imListAdapter;
private List<Chat> chatList = new ArrayList<>();
List<String> stringList;
ActiveChatsDB activeChatsDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imlist);
    Toolbar toolbar = (Toolbar)findViewById(R.id.imlist_toolbar);
    setSupportActionBar(toolbar);
    setBackButtonOnToolbar();

    recyclerView = (RecyclerView)findViewById(R.id.rv_im_list);
    imListAdapter = new IMListAdapter(chatList, getApplicationContext());
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    recyclerView.setAdapter(imListAdapter);
    prepareChatListData();
}

private void prepareChatListData() {
    String friend;
    String latestMessage;
    activeChatsDB = new ActiveChatsDB(IMListActivity.this);
    stringList = activeChatsDB.getChatList();
    activeChatsDB.close();
    for (int i=0; i<stringList.size(); i++) {
        friend = stringList.get(i);
        DBAct dbAct = new  DBAct(IMListActivity.this,friend);
        latestMessage = dbAct.getLatestMessage();
        dbAct.close();
        Chat chat = new Chat(friend, latestMessage);
        chatList.add(chat);
    }
    imListAdapter.notifyDataSetChanged();
}

private void setBackButtonOnToolbar(){
    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

public RecyclerView getRecyclerView() {
    return recyclerView;
}
</code>```

}

Adapter code:

```<code>public class IMListAdapter extends RecyclerView.Adapter <com.abdralabs.talksee.IMListAdapter.IMListViewHolder> {

private List<Chat> chatList = new ArrayList<Chat>() ;
private Context ctx;
private MultiSelector multiSelector = new MultiSelector();
private ModalMultiSelectorCallback modalMultiSelectorCallback =
        new ModalMultiSelectorCallback(multiSelector) {
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                if (item.getItemId() == R.id.item_delete) {
                    mode.finish();

                    for (int i = chatList.size(); i >= 0; i--) {
                        if (multiSelector.isSelected(i, 0)) { // (1)
                            // remove item from list
                            ((IMListActivity)ctx).getRecyclerView().getAdapter().notifyItemRemoved(i);
                        }
                    }

                    multiSelector.clearSelections(); // (2)
                    return true;

                }
                return false;
            }

            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                super.onCreateActionMode(actionMode, menu);
                ((AppCompatActivity)ctx).getMenuInflater().inflate(R.menu.contextual_menu_friends, menu);
                return true;
            }
        };

public IMListAdapter(List<Chat> chatList, Context ctx){
    this.chatList = chatList;
    this.ctx = ctx;
}

@Override
public com.abdralabs.talksee.IMListAdapter.IMListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_list_row,parent,false);
    return new com.abdralabs.talksee.IMListAdapter.IMListViewHolder(itemView, chatList, ctx);    }

@Override
public void onBindViewHolder(com.abdralabs.talksee.IMListAdapter.IMListViewHolder holder, int position) {
    Chat chat = chatList.get(position);
    holder.name.setText(chat.getName());
    holder.recentMsg.setText(chat.getRecentMessage());
}

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

public class IMListViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener{
    public TextView name;
    public TextView recentMsg;
    List<Chat> chatList = new ArrayList<Chat>();
    Context ctx;

    public IMListViewHolder(View itemView, List<Chat> chatList, Context ctx) {
        super(itemView, multiSelector);
        this.chatList = chatList;
        this.ctx = ctx;
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
        itemView.setLongClickable(true);
        name = (TextView) itemView.findViewById(R.id.name_chat);
        recentMsg = (TextView)itemView.findViewById(R.id.tv_recent_msg_im_list);
    }

    @Override
    public void onClick(View v) {
        int position = getAdapterPosition();
        Chat chat = this.chatList.get(position);
        Intent intent = new Intent(this.ctx, IMActivity.class);
        intent.putExtra("otherUserName",chat.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.ctx.startActivity(intent);

    }

    @Override
    public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(com.abdralabs.talksee.IMListAdapter.IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }
}
</code>```

}

I don't know how I'm supposed to peform the right type casting. Please help.

EDIT 1:

I tried replacing the onLongClick code to

```<code>public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }
</code>```

as Sachin Bahukhandi suggested, but I'm getting the same error

```<code>java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to com.abdralabs.talksee.IMListActivity
                                                                     at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                     at android.view.View.performLongClick(View.java:5308)
                                                                     at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                     at android.os.Handler.handleCallback(Handler.java:815)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                     at android.os.Looper.loop(Looper.java:207)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
</code>```

In the tutorial that I'm following the code is as such:

```<code>@Override
public boolean onLongClick(View view) {
    if (!mMultiSelector.isSelectable()) {
        ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback); // (2)
        mMultiSelector.setSelectable(true);
        mMultiSelector.setSelected(MyViewHolder.this, true);
        return true;
    }
    return false;
}
</code>```

In the above code getActivity is called somehow from the Viewholder and type casted to AppCompatActivity. I don't know how to call getActivity directly from the ViewHolder since I'm getting and error so I tried to type cast a context object (which was passed from my Activity through the adapter constructor) to AppCompatActivity. So I don't exactly know what I'm doing wrong here.

答:
So I solved this by passing the activity reference to the constructor of the adapter and calling

```<code>imListActivity.startSupportActionMode(modalMultiSelectorCallback);
</code>```

instead of doing this

```<code>((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
</code>```

Body:
I'm following this tutorial to implement multi select in my RecyclerView but I have been getting the following runtime exception when I perform a long click:

java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to android.support.v7.app.AppCompatActivity
                                                                       at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                       at android.view.View.performLongClick(View.java:5308)
                                                                       at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                       at android.os.Looper.loop(Looper.java:207)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)

Activity code:

public class IMListActivity extends AppCompatActivity implements Sertivity{

private RecyclerView recyclerView;
private IMListAdapter imListAdapter;
private List<Chat> chatList = new ArrayList<>();
List<String> stringList;
ActiveChatsDB activeChatsDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imlist);
    Toolbar toolbar = (Toolbar)findViewById(R.id.imlist_toolbar);
    setSupportActionBar(toolbar);
    setBackButtonOnToolbar();

    recyclerView = (RecyclerView)findViewById(R.id.rv_im_list);
    imListAdapter = new IMListAdapter(chatList, getApplicationContext());
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    recyclerView.setAdapter(imListAdapter);
    prepareChatListData();
}

private void prepareChatListData() {
    String friend;
    String latestMessage;
    activeChatsDB = new ActiveChatsDB(IMListActivity.this);
    stringList = activeChatsDB.getChatList();
    activeChatsDB.close();
    for (int i=0; i<stringList.size(); i++) {
        friend = stringList.get(i);
        DBAct dbAct = new  DBAct(IMListActivity.this,friend);
        latestMessage = dbAct.getLatestMessage();
        dbAct.close();
        Chat chat = new Chat(friend, latestMessage);
        chatList.add(chat);
    }
    imListAdapter.notifyDataSetChanged();
}

private void setBackButtonOnToolbar(){
    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

public RecyclerView getRecyclerView() {
    return recyclerView;
}

}

Adapter code:

public class IMListAdapter extends RecyclerView.Adapter <com.abdralabs.talksee.IMListAdapter.IMListViewHolder> {

private List<Chat> chatList = new ArrayList<Chat>() ;
private Context ctx;
private MultiSelector multiSelector = new MultiSelector();
private ModalMultiSelectorCallback modalMultiSelectorCallback =
        new ModalMultiSelectorCallback(multiSelector) {
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                if (item.getItemId() == R.id.item_delete) {
                    mode.finish();

                    for (int i = chatList.size(); i >= 0; i--) {
                        if (multiSelector.isSelected(i, 0)) { // (1)
                            // remove item from list
                            ((IMListActivity)ctx).getRecyclerView().getAdapter().notifyItemRemoved(i);
                        }
                    }

                    multiSelector.clearSelections(); // (2)
                    return true;

                }
                return false;
            }

            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                super.onCreateActionMode(actionMode, menu);
                ((AppCompatActivity)ctx).getMenuInflater().inflate(R.menu.contextual_menu_friends, menu);
                return true;
            }
        };

public IMListAdapter(List<Chat> chatList, Context ctx){
    this.chatList = chatList;
    this.ctx = ctx;
}

@Override
public com.abdralabs.talksee.IMListAdapter.IMListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_list_row,parent,false);
    return new com.abdralabs.talksee.IMListAdapter.IMListViewHolder(itemView, chatList, ctx);    }

@Override
public void onBindViewHolder(com.abdralabs.talksee.IMListAdapter.IMListViewHolder holder, int position) {
    Chat chat = chatList.get(position);
    holder.name.setText(chat.getName());
    holder.recentMsg.setText(chat.getRecentMessage());
}

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

public class IMListViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener{
    public TextView name;
    public TextView recentMsg;
    List<Chat> chatList = new ArrayList<Chat>();
    Context ctx;

    public IMListViewHolder(View itemView, List<Chat> chatList, Context ctx) {
        super(itemView, multiSelector);
        this.chatList = chatList;
        this.ctx = ctx;
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
        itemView.setLongClickable(true);
        name = (TextView) itemView.findViewById(R.id.name_chat);
        recentMsg = (TextView)itemView.findViewById(R.id.tv_recent_msg_im_list);
    }

    @Override
    public void onClick(View v) {
        int position = getAdapterPosition();
        Chat chat = this.chatList.get(position);
        Intent intent = new Intent(this.ctx, IMActivity.class);
        intent.putExtra("otherUserName",chat.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.ctx.startActivity(intent);

    }

    @Override
    public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((AppCompatActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(com.abdralabs.talksee.IMListAdapter.IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }
}

}

I don't know how I'm supposed to peform the right type casting. Please help.

EDIT 1:

I tried replacing the onLongClick code to

public boolean onLongClick(View v) {
        if (!multiSelector.isSelectable()) { // (3)
            ((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);
            multiSelector.setSelectable(true); // (4)
            multiSelector.setSelected(IMListViewHolder.this, true); // (5)
            return true;
        }
        return false;
    }

as Sachin Bahukhandi suggested, but I'm getting the same error

java.lang.ClassCastException: com.abdralabs.talksee.MyApplication cannot be cast to com.abdralabs.talksee.IMListActivity
                                                                     at com.abdralabs.talksee.IMListAdapter$IMListViewHolder.onLongClick(IMListAdapter.java:116)
                                                                     at android.view.View.performLongClick(View.java:5308)
                                                                     at android.view.View$CheckForLongPress.run(View.java:21522)
                                                                     at android.os.Handler.handleCallback(Handler.java:815)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                     at android.os.Looper.loop(Looper.java:207)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5740)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)

In the tutorial that I'm following the code is as such:

@Override
public boolean onLongClick(View view) {
    if (!mMultiSelector.isSelectable()) {
        ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback); // (2)
        mMultiSelector.setSelectable(true);
        mMultiSelector.setSelected(MyViewHolder.this, true);
        return true;
    }
    return false;
}

In the above code getActivity is called somehow from the Viewholder and type casted to AppCompatActivity. I don't know how to call getActivity directly from the ViewHolder since I'm getting and error so I tried to type cast a context object (which was passed from my Activity through the adapter constructor) to AppCompatActivity. So I don't exactly know what I'm doing wrong here.

Body:
So I solved this by passing the activity reference to the constructor of the adapter and calling

imListActivity.startSupportActionMode(modalMultiSelectorCallback);

instead of doing this

((IMListActivity)ctx).startSupportActionMode(modalMultiSelectorCallback);


问:
Web Exception with Web Service
I have developed a client application to consume a web service,

there are no error's in my code however when I debug I get the following exception,

'WebException was unhandled - the underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'

I think this is to do with the fact that it is a secure web service I am trying to consume,
so my question is would this error occur due to the security certificate not being installed correctly? And if so is there a way to manually instal the certificate into the application?

Thanks for your time.

答: I agree with @Klaus Byskov Hoffmann but would like to add on this his answer. This may also happen if the server domain name being used to access the service is not exactly the same as the certificate assigned to it. It creates an invalidity to the certificate even if both names apply to the machine.</p>

Title: Web Exception with Web Service


问:
Display text with icon in Xamarin forms
How to display text with icon in button? I am using font awesome icons and displaying them using their uni code. Like this:

Now if i add unicode with text the icon doesnt show although text still shows.

This only shows text and Cross instead of icon.

答: Forms9Patch has an ImageButton and MaterialButton that does a great job of making this easy.</p>

Title: Display text with icon in Xamarin forms


问:
How to delay changing background color of a square in a grid if that square's color has just been changed?
I'm doing an exercise with vanilla javascript that changes a random square in a grid to a random color every 400ms, but the square cannot change color for at least another 3s once once it has changed color. This delay logic is what I'm hung up on.

What's the best way to check to see if the current square has just changed color, and to prevent that square from changing colors for 3 seconds?

As you can see, I've experimented with adding a new class once a square's color has been changed. I've also tried placing the set timeout within the colorChange function.

codepen

HTML:

```<code><div id="content">
  <div class = "box" id="square1"></div>
  <div class = "box" id="square2"></div>
  <div class = "box" id="square3"></div>
  <div class = "box" id="square4"></div> <br>
  <div class = "box" id="square5"></div>
  <div class = "box" id="square6"></div>
  <div class = "box" id="square7"></div>
  <div class = "box" id="square8"></div> <br>
  <div class = "box" id="square9"></div>
  <div class = "box" id="square10"></div>
  <div class = "box" id="square11"></div>
  <div class = "box" id="square12"></div> <br>
  <div class = "box" id="square13"></div>
  <div class = "box" id="square14"></div>
  <div class = "box" id="square15"></div>
  <div class = "box" id="square16"></div>
</div>
</code>```

Javascript:

```<code>setInterval(colorChange, 400);

if (square.className = "colored") {
    square.setTimeout(setColor(), 3000);
}

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 17);
    var square = document.getElementById("square"+randomId);
    square.style.backgroundColor = specificColor;
    square.addClass = "colored";
}
</code>```

Thanks for any help.

答:
See if this works out for you:

setInterval(colorChange, 400);

var timeout = new Array(16);

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 16);
    if(new Date().getTime() - (timeout[randomId-1] || 0) >= 3000) {
      timeout[randomId-1] = new Date().getTime();
      var square = document.getElementById("square"+randomId);
      square.style.backgroundColor = specificColor;
      square.addClass = "colored";
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#content {
  width: 400px;
  height: 400px;
  margin: 0 auto;
}

.box {
  width: 98px;
  height: 98px;
  border: 1px solid black;
  float: left;
}</code>```

```

Body:
I'm doing an exercise with vanilla javascript that changes a random square in a grid to a random color every 400ms, but the square cannot change color for at least another 3s once once it has changed color. This delay logic is what I'm hung up on.

What's the best way to check to see if the current square has just changed color, and to prevent that square from changing colors for 3 seconds?

As you can see, I've experimented with adding a new class once a square's color has been changed. I've also tried placing the set timeout within the colorChange function.

codepen

HTML:

Javascript:

setInterval(colorChange, 400);

if (square.className = "colored") {
    square.setTimeout(setColor(), 3000);
}

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 17);
    var square = document.getElementById("square"+randomId);
    square.style.backgroundColor = specificColor;
    square.addClass = "colored";
}

Thanks for any help.

Body:
See if this works out for you:

setInterval(colorChange, 400);

var timeout = new Array(16);

function colorChange() {
    var colors = ["red", "blue", "yellow", "green", "orange", "purple"];
    var specificColor = colors[Math.floor(Math.random()*colors.length)];
    var randomId = Math.ceil(Math.random() * 16);
    if(new Date().getTime() - (timeout[randomId-1] || 0) >= 3000) {
      timeout[randomId-1] = new Date().getTime();
      var square = document.getElementById("square"+randomId);
      square.style.backgroundColor = specificColor;
      square.addClass = "colored";
    }
}

#content {
  width: 400px;
  height: 400px;
  margin: 0 auto;
}

.box {
  width: 98px;
  height: 98px;
  border: 1px solid black;
  float: left;
}

<div id="content">
  <div class = "box" id="square1"></div>
  <div class = "box" id="square2"></div>
  <div class = "box" id="square3"></div>
  <div class = "box" id="square4"></div> <br>
  <div class = "box" id="square5"></div>
  <div class = "box" id="square6"></div>
  <div class = "box" id="square7"></div>
  <div class = "box" id="square8"></div> <br>
  <div class = "box" id="square9"></div>
  <div class = "box" id="square10"></div>
  <div class = "box" id="square11"></div>
  <div class = "box" id="square12"></div> <br>
  <div class = "box" id="square13"></div>
  <div class = "box" id="square14"></div>
  <div class = "box" id="square15"></div>
  <div class = "box" id="square16"></div>
</div>


问:
trouble with installing rvm in ubuntu
I just installed rvm in my machine using the following command

```<code>bash < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
</code>```

and got this in my terminal

```<code>Installation of RVM to /home/rahul/.rvm/ is complete.
</code>```

When I go to /home/rahul/.rvm/, I am able to see all the necessary folders but when I give rvm command in the terminal, I get this error

```<code> rvm --version
No command 'rvm' found, but there are 19 similar ones
rvm: command not found
</code>```

How can I fix it?

EDIT

I have also added the following lines in my bashrc

```<code>if [[ -n "$PS1" ]]; then
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi
fi
</code>```

答:
Open terminal go to Edit > Profile Preferences click on Title and Command tab and check Run command as login shell.

Find out the tutorial

Title: trouble with installing rvm in ubuntu

Body:
I just installed rvm in my machine using the following command

bash < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )

and got this in my terminal

Installation of RVM to /home/rahul/.rvm/ is complete.

When I go to /home/rahul/.rvm/, I am able to see all the necessary folders but when I give rvm command in the terminal, I get this error

 rvm --version
No command 'rvm' found, but there are 19 similar ones
rvm: command not found

How can I fix it?

EDIT

I have also added the following lines in my bashrc

if [[ -n "$PS1" ]]; then
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi
fi


问:
Default MySQL user privileges after executing CREATE USER
What privileges does a newly created user have after running:</p>

```<code>CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';
</code>```

答:
creates a new row in the mysql.user table and assigns the account no privileges
  http://dev.mysql.com/doc/refman/5.1/en/create-user.html

Body:
What privileges does a newly created user have after running:

CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';


问:
Use string to refer to an array name in vba
I have Powerpoint presentation. On each slide I have 8 shapes with text space. They can contain text representing group which has sth related to content/data update and so on.
I have following arrays which contain users for those responsibility area:

```<code>GEN = Array("username_01","username_02","username_03",..."username_xx")
POL = Array("username_01","username_02","username_03",..."username_xx")
B2B = Array("username_01","username_02","username_03",..."username_xx")
RUS = Array("username_01","username_02","username_03",..."username_xx")
</code>```

And this function which is checking if user is in array

```<code>   Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
   IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
   End Function
</code>```

My problem is that when I want to use the function it works only if I will give the Array name as below:

```<code>auser = Environ("UserName")
IsInArray(auser,GEN) 'it will give me answer if the user is in array
</code>```

I want to get shape text:

```<code>res_group_txt = ActivePresentation.Slides(i).Shapes(shape_owner).TextEffect.Text
</code>```

And put it somehow in a function so it will not return an error

```<code>auser = Environ("UserName")
IsInArray(auser,res_group_txt)
</code>```

I have tried to change variables and look through all topics but I have not found answer :(

Help pls :)

BR Misza

答:
You can use a Dictionary object to map the text to the array...

```<code>Dim oDic As Object
Dim GEN As Variant
Dim POL As Variant
Dim B2B As Variant
Dim RUS As Variant

GEN = Array("username_01", "username_02", "username_03")
POL = Array("username_01", "username_02", "username_03")
B2B = Array("username_01", "username_02", "username_03")
RUS = Array("username_01", "username_02", "username_03")

Set oDic = CreateObject("Scripting.Dictionary")
oDic.comparemode = vbTextCompare

oDic("GEN") = GEN
oDic("POL") = POL
oDic("B2B") = B2B
oDic("RUS") = RUS
</code>```

Then you can call your function as follows...

```<code>IsInArray(auser, oDic(res_group_txt))
</code>```

Body:
I have Powerpoint presentation. On each slide I have 8 shapes with text space. They can contain text representing group which has sth related to content/data update and so on.
I have following arrays which contain users for those responsibility area:

GEN = Array("username_01","username_02","username_03",..."username_xx")
POL = Array("username_01","username_02","username_03",..."username_xx")
B2B = Array("username_01","username_02","username_03",..."username_xx")
RUS = Array("username_01","username_02","username_03",..."username_xx")

And this function which is checking if user is in array

   Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
   IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
   End Function

My problem is that when I want to use the function it works only if I will give the Array name as below:

auser = Environ("UserName")
IsInArray(auser,GEN) 'it will give me answer if the user is in array

I want to get shape text:

res_group_txt = ActivePresentation.Slides(i).Shapes(shape_owner).TextEffect.Text

And put it somehow in a function so it will not return an error

auser = Environ("UserName")
IsInArray(auser,res_group_txt)

I have tried to change variables and look through all topics but I have not found answer :(

Help pls :)

BR Misza

Body:
You can use a Dictionary object to map the text to the array...

Dim oDic As Object
Dim GEN As Variant
Dim POL As Variant
Dim B2B As Variant
Dim RUS As Variant

GEN = Array("username_01", "username_02", "username_03")
POL = Array("username_01", "username_02", "username_03")
B2B = Array("username_01", "username_02", "username_03")
RUS = Array("username_01", "username_02", "username_03")

Set oDic = CreateObject("Scripting.Dictionary")
oDic.comparemode = vbTextCompare

oDic("GEN") = GEN
oDic("POL") = POL
oDic("B2B") = B2B
oDic("RUS") = RUS

Then you can call your function as follows...

IsInArray(auser, oDic(res_group_txt))


答:
Scanner is a class which is defined in the standard Java Class Library, that you can use it to read from the console like this:

```<code>Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
</code>```

however there are even more options that this constructer can do, for example you can read from a file and not console like this:

```<code>Scanner sc = new Scanner(new File("myNumbers"));
  while (sc.hasNextLong()) {
      long aLong = sc.nextLong();
  }
</code>```

so basically depending on the constructer you can choose where you want to read your input from.

Additionally, there are multiple ways to represent integers in a stream. Scanner.nextInt() reads them as a text string. DataInputStream.readInt() reads them as binary data.

If you mix them up, a human would enter 1234 and get 825373492, or a computer would enter 825373492 and get 1234. Both would be confused. By having to specify Scanner or DataInputStream, there are no such surprises or bugs, because you state up front what "read an integer" means.

Read this:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Title: Why do we need a Scanner Object for taking input in java

Body:
Scanner is a class which is defined in the standard Java Class Library, that you can use it to read from the console like this:

Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();

however there are even more options that this constructer can do, for example you can read from a file and not console like this:

Scanner sc = new Scanner(new File("myNumbers"));
  while (sc.hasNextLong()) {
      long aLong = sc.nextLong();
  }

so basically depending on the constructer you can choose where you want to read your input from.

Additionally, there are multiple ways to represent integers in a stream. Scanner.nextInt() reads them as a text string. DataInputStream.readInt() reads them as binary data.

If you mix them up, a human would enter 1234 and get 825373492, or a computer would enter 825373492 and get 1234. Both would be confused. By having to specify Scanner or DataInputStream, there are no such surprises or bugs, because you state up front what "read an integer" means.

Read this:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html


问:
Check if Model is empty
I am doing below query to fetch data to view however if AccountMediaServerKey table is empty. Model is throwing null exception error in view. Any idea how to check if model is null when NO data fetched from database

```<code>var MediaKey = (from p in db.AccountMediaServerKey
                where p.Tagger == USID && p.TagTo == USID
                select new MediaServerHomeModel
                {
                    Stream=p.Stream,
                    Event = p.Event,
                    Status = p.Status

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

答:
You would simply do

```<code>If(MediaKey==null)
{
   //do something
}
</code>```

Or if you want to instatiate a new object when null then you would do

```<code>var obj  = MediaKey ?? new MediaServerHomeModel();
</code>```

The return obj to view

Title: Check if Model is empty

Body:
I am doing below query to fetch data to view however if AccountMediaServerKey table is empty. Model is throwing null exception error in view. Any idea how to check if model is null when NO data fetched from database

var MediaKey = (from p in db.AccountMediaServerKey
                where p.Tagger == USID && p.TagTo == USID
                select new MediaServerHomeModel
                {
                    Stream=p.Stream,
                    Event = p.Event,
                    Status = p.Status

                }).FirstOrDefault();

Body:
You would simply do

If(MediaKey==null)
{
   //do something
}

Or if you want to instatiate a new object when null then you would do

var obj  = MediaKey ?? new MediaServerHomeModel();

The return obj to view


问:
Got error on using mysqli_real_escape_string in WHERE IN clause
I'm working on existing project and there is an abstraction layer on database (previous developers made it and I should not change it).
I extracted functions from abstraction and it looks like this:

```<code>$sql = "SELECT id FROM user WHERE username IN ({users})";
$users = "alex,john";
$users = str_replace(',', "','", $users);
$users = mysqli_real_escape_string($dbh, $users);
//Here is a replace placeholder function for sql query
...
$query = mysqli_query($dbh, $sql);
</code>```

And I got an error:

You have an error in your SQL syntax; check the manual that corresponds to your ?MySQL server version for the right syntax to use near '\\'alex\',\\'john\\')' ?at line 1"

How to correct use mysqli_real_escape_string in WHERE IN clause?

答:
Try this:

```<code>$users = "alex,john";
$users = "'" . str_replace(',', "','", $users) . "'";
$users = mysqli_real_escape_string($dbh, $users);

$sql = "SELECT id FROM user WHERE username IN ({$users})";

$query = mysqli_query($dbh, $sql);
</code>```

Recommended way is to use prepared statements instead and not worry about escaping special characters or SQL injection.

```<code>$users = "alex,john";
$users = "'" . str_replace(',', "','", $users) . "'";
$sql = "SELECT id FROM user WHERE username IN ({$users})";

$stmt = $dbh->prepare($sql);
$stmt->bind_param('s', $users);

$stmt->execute();
$results = $stmt->fetch();
</code>```

Body:
I'm working on existing project and there is an abstraction layer on database (previous developers made it and I should not change it).
I extracted functions from abstraction and it looks like this:

$sql = "SELECT id FROM user WHERE username IN ({users})";
$users = "alex,john";
$users = str_replace(',', "','", $users);
$users = mysqli_real_escape_string($dbh, $users);
//Here is a replace placeholder function for sql query
...
$query = mysqli_query($dbh, $sql);

And I got an error:

You have an error in your SQL syntax; check the manual that corresponds to your ?MySQL server version for the right syntax to use near '\\'alex\',\\'john\\')' ?at line 1"

How to correct use mysqli_real_escape_string in WHERE IN clause?

Body:
Try this:

$users = "alex,john";
$users = "'" . str_replace(',', "','", $users) . "'";
$users = mysqli_real_escape_string($dbh, $users);

$sql = "SELECT id FROM user WHERE username IN ({$users})";

$query = mysqli_query($dbh, $sql);

Recommended way is to use prepared statements instead and not worry about escaping special characters or SQL injection.

$users = "alex,john";
$users = "'" . str_replace(',', "','", $users) . "'";
$sql = "SELECT id FROM user WHERE username IN ({$users})";

$stmt = $dbh->prepare($sql);
$stmt->bind_param('s', $users);

$stmt->execute();
$results = $stmt->fetch();


问:
Uncaught TypeError: Cannot read property foo of undefined
My JavaScript:

```<code>todo.completed = !todo.completed;
</code>```

ERROR:

```<code>Uncaught TypeError: Cannot read property 'completed' of undefined
    at Object.toggleCompleted (script.js:34)
    at Object.toggleCompleted (script.js:89)
    at HTMLButtonElement.onclick ((index):33)
toggleCompleted @ script.js:34
toggleCompleted @ script.js:89
onclick @ (index):33
</code>```

Am I missing something here?

答:
What's so confusing about it is that the code will work in Plunkr, glitch or codepen, but not a text editor and browser, because of the way those sites's routing is set up. In your index.html file you need to replace
 with

Body:
My JavaScript:

todo.completed = !todo.completed;

ERROR:

Uncaught TypeError: Cannot read property 'completed' of undefined
    at Object.toggleCompleted (script.js:34)
    at Object.toggleCompleted (script.js:89)
    at HTMLButtonElement.onclick ((index):33)
toggleCompleted @ script.js:34
toggleCompleted @ script.js:89
onclick @ (index):33

Am I missing something here?

Body:
What's so confusing about it is that the code will work in Plunkr, glitch or codepen, but not a text editor and browser, because of the way those sites's routing is set up. In your index.html file you need to replace      <script src = "filename.js></script>
 with
 <script src="entire path to filename.js"></script>


问:
open another view controllers view from right side of the screen
I want to open a viewcontroller from right side of the screen.

That is on doing

[self presentModalViewController:pvc animated:YES];

I want the another viewcontroller's view to appear as if its sliding from the right of the screen instead of appearing as if it is coming from the bottom of the screen :)

How can I achieve that. Please help :)

答:
Look into UINavigationController - Class Reference. This lets you organize a hierarchy that will slide in from the side. Or you can play with the UIView animation blocks. Figure out whats best for your app. If you have several things you will be pushing from the side, like categories, use UINavigationController. If you just have a simple view you want to come in from the side and leave, you'll want to use the UIView animation or other animation methods. The UIView animation will look like this:</p>

```<code>[UIView beginAnimations:nil context:nil];
//code to move view on to screen
[UIView setAnimationDuration:0.5];
[UIView commitAnimations];
</code>```

Body:
Look into UINavigationController - Class Reference. This lets you organize a hierarchy that will slide in from the side. Or you can play with the UIView animation blocks. Figure out whats best for your app. If you have several things you will be pushing from the side, like categories, use UINavigationController. If you just have a simple view you want to come in from the side and leave, you'll want to use the UIView animation or other animation methods. The UIView animation will look like this:

[UIView beginAnimations:nil context:nil];
//code to move view on to screen
[UIView setAnimationDuration:0.5];
[UIView commitAnimations];


问:
Python: querying a list of results while processes are finishing
I am using the twitter API to capture the number of times a user has tweeted. I would like to get access to the list of results before all of the process have completed

```<code>def get_status_count(twitter_handle, output):

while True:
    try:
        auth = tweepy.OAuthHandler(consumer_keys, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        client = tweepy.API(auth)
        twitter_handle = twitter_handle
        user = client.get_user(screen_name = twitter_handle)
        timeline = user.timeline()

        status = timeline[0]
        json_str = json.dumps(status._json)
        json_dict = json.loads(json_str)

        json_user_dict =  json_dict['user']
        total_tweets = json_user_dict['statuses_count']

        output.put(total_tweets)

        break

    except tweepy.error.TweepError as e:
        print "In the except method"
        print e
        time.sleep(5)
</code>```

I want to check twitter multiple times to see if the status count has changed. I've implemented this code.

```<code>processes = [mp.Process(target=get_status_count, args=('gregcharte',
output)) for x in range(10)]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

results = [output.get() for p in processes]
print results
</code>```

which gives me a list [80, 80, 80, 80, 80, 80, 80, 80, 80, 80]. How can I instead get the list after each process finishes. For instance

[80]
[80, 80]
[80, 80, 80]

Any help would be greatly appreciated. I'm new to multiprocessing.

答:
I don't see why you need multiple processes to manage the data, you can call a function from within try block that will have all the business logic on what you want and what you don't want.

A example of what that would look like is below:

```<code># Access Tokens etc would be constants or preferably env variables...
# .....

TWEET_DATA = []

def init_tweepy():
     auth = tweepy.OAuthHandler(consumer_keys, consumer_secret)
     auth.set_access_token(access_token, access_token_secret)
     return tweepy.API(auth)

def add_new_tweet_data(data):
    # Do your checks in here...
    TWEET_DATA.append(data)

def listen_to_stream(twitter_handle):

    # Tweepy setup.
    client = init_tweepy()
    user = client.get_user(screen_name = twitter_handle)

    while True:
        try:
            # Grab user's timeline data.
            timeline = user.timeline()

        except Exception as e:
           print(e)
           time.sleep(5)

        else:

          # Data marshalling
            status = timeline[0]
            json_str = json.dumps(status._json)
            json_dict = json.loads(json_str)

            # Accessing necessary keys.
            json_user_dict =  json_dict['user']
            total_tweets = json_user_dict['statuses_count']

            # Append new data.
            add_new_tweet_data(total_tweets)
</code>```

Body:
I am using the twitter API to capture the number of times a user has tweeted. I would like to get access to the list of results before all of the process have completed

def get_status_count(twitter_handle, output):

while True:
    try:
        auth = tweepy.OAuthHandler(consumer_keys, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        client = tweepy.API(auth)
        twitter_handle = twitter_handle
        user = client.get_user(screen_name = twitter_handle)
        timeline = user.timeline()

        status = timeline[0]
        json_str = json.dumps(status._json)
        json_dict = json.loads(json_str)

        json_user_dict =  json_dict['user']
        total_tweets = json_user_dict['statuses_count']

        output.put(total_tweets)

        break

    except tweepy.error.TweepError as e:
        print "In the except method"
        print e
        time.sleep(5)

I want to check twitter multiple times to see if the status count has changed. I've implemented this code.

processes = [mp.Process(target=get_status_count, args=('gregcharte',
output)) for x in range(10)]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

results = [output.get() for p in processes]
print results

which gives me a list [80, 80, 80, 80, 80, 80, 80, 80, 80, 80]. How can I instead get the list after each process finishes. For instance

[80]
[80, 80]
[80, 80, 80]

Any help would be greatly appreciated. I'm new to multiprocessing.

Body:
I don't see why you need multiple processes to manage the data, you can call a function from within try block that will have all the business logic on what you want and what you don't want.

A example of what that would look like is below:

# Access Tokens etc would be constants or preferably env variables...
# .....

TWEET_DATA = []

def init_tweepy():
     auth = tweepy.OAuthHandler(consumer_keys, consumer_secret)
     auth.set_access_token(access_token, access_token_secret)
     return tweepy.API(auth)

def add_new_tweet_data(data):
    # Do your checks in here...
    TWEET_DATA.append(data)

def listen_to_stream(twitter_handle):

    # Tweepy setup.
    client = init_tweepy()
    user = client.get_user(screen_name = twitter_handle)

    while True:
        try:
            # Grab user's timeline data.
            timeline = user.timeline()

        except Exception as e:
           print(e)
           time.sleep(5)

        else:

          # Data marshalling
            status = timeline[0]
            json_str = json.dumps(status._json)
            json_dict = json.loads(json_str)

            # Accessing necessary keys.
            json_user_dict =  json_dict['user']
            total_tweets = json_user_dict['statuses_count']

            # Append new data.
            add_new_tweet_data(total_tweets)


问:
Microsoft rxNeuralNet acceleration
In Microsoft's R NeuralNet package, there is an option for acceleration, where you can specify "GPU" or "SSE". I know what GPU is, does anyone know what SSE acceleration is?

Thanks!

答:
I cannot comment yet, so therefore I am posting an "answer".

From what I gather SSE is nowadays "default" unless you have the ability to do GPU. A wikipedia article: https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions

Niels

Title: Microsoft rxNeuralNet acceleration


问:
Spring Profiles org.springframework.beans.factory.NoSuchBeanDefinitionException
My sample project is Maven based structure, all my application proeprties files under src/main/resources folder. Below is the complete sample code. I am not understanding why my code not able to find profiles properly unless I use @PropertySource annotation.

My actual doubt is:  I've configured spring properties pretty well in application.properties file, but yet why it cannot find profile and their respective property files? Unless I am using @PropertySource annotation, iam not getting value for env.getProperty("mysql.url"). I mean Environment class not able to pick up values from profiles property files. WHY?

Iam getting error as below:

```<code>Jul 08, 2017 7:54:26 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@300ffa5d: startup date [Sat Jul 08 19:54:26 IST 2017]; root of context hierarchy
helloBean
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'datasource' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1084)
    at com.oreilly.datasource.Main2.main(Main2.java:15)
</code>```

DatasourceConfig.java

```<code>package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

@Configuration
/*@PropertySource("classpath:/application.properties")
@PropertySource("classpath:/dev/application-dev.properties")
@PropertySource("classpath:/prod/application-prod.properties")*/
public class DatasourceConfig {

    @Autowired
    private Environment env;

    @Bean(name="helloBean")
    public String helloWorld() {
        System.out.println("helloBean");
        return "helloWorld....";
    }

    @Bean(name="datasource")
    @Profile("dev")
    public DataSource datasourceForDev(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }

    @Bean(name="datasource")
    @Profile("prod")
    public DataSource datasourceForProd(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }
}
</code>```

Main2.java

```<code>package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main2 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DatasourceConfig.class);

        DataSource dataSource = context.getBean("datasource", DataSource.class);
        String helloBean = context.getBean("helloBean", String.class);

    }

}
</code>```

application.properties

```<code>spring.profiles.active=prod
spring.config.name=application
spring.config.location=classpath:/application.properties,classpath:/dev/application-dev.properties,classpath:/prod/application-dev.properties
</code>```

Below is the project folder structure:

Please tell me what went wrong?

答:
I have resolved my issue just by modifying as below:

```<code>@PropertySource("classpath:/${spring.profiles.active}/application-${spring.profiles.active}.properties")
</code>```

Now I am able to pickup application-dev.properties (or) application-prod.properties dynamically.

Note: Environment class requires @PropertySource annotation, otherwise we get null for env.get('someproperty').

Body:
My sample project is Maven based structure, all my application proeprties files under src/main/resources folder. Below is the complete sample code. I am not understanding why my code not able to find profiles properly unless I use @PropertySource annotation.

My actual doubt is:  I've configured spring properties pretty well in application.properties file, but yet why it cannot find profile and their respective property files? Unless I am using @PropertySource annotation, iam not getting value for env.getProperty("mysql.url"). I mean Environment class not able to pick up values from profiles property files. WHY?

Iam getting error as below:

Jul 08, 2017 7:54:26 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@300ffa5d: startup date [Sat Jul 08 19:54:26 IST 2017]; root of context hierarchy
helloBean
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'datasource' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1084)
    at com.oreilly.datasource.Main2.main(Main2.java:15)

DatasourceConfig.java

package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

@Configuration
/*@PropertySource("classpath:/application.properties")
@PropertySource("classpath:/dev/application-dev.properties")
@PropertySource("classpath:/prod/application-prod.properties")*/
public class DatasourceConfig {

    @Autowired
    private Environment env;

    @Bean(name="helloBean")
    public String helloWorld() {
        System.out.println("helloBean");
        return "helloWorld....";
    }

    @Bean(name="datasource")
    @Profile("dev")
    public DataSource datasourceForDev(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }

    @Bean(name="datasource")
    @Profile("prod")
    public DataSource datasourceForProd(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }
}

Main2.java

package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main2 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DatasourceConfig.class);

        DataSource dataSource = context.getBean("datasource", DataSource.class);
        String helloBean = context.getBean("helloBean", String.class);

    }

}

application.properties

spring.profiles.active=prod
spring.config.name=application
spring.config.location=classpath:/application.properties,classpath:/dev/application-dev.properties,classpath:/prod/application-dev.properties

Below is the project folder structure:

Please tell me what went wrong?

Body:
I have resolved my issue just by modifying as below:

@PropertySource("classpath:/${spring.profiles.active}/application-${spring.profiles.active}.properties")

Now I am able to pickup application-dev.properties (or) application-prod.properties dynamically.

Note: Environment class requires @PropertySource annotation, otherwise we get null for env.get('someproperty').


问:
getting user input without using input element
Is there a way to get the user text input without having him type in a text box, or somehow concealing the text box.
i would want to build something like a table cell with text in it and when the user clicks on the cell he can edit the text there.</p>

答:
you can use editable tables like html5 editable table, click
   (https://codepen.io/ashblue/pen/mCtuA) for example!</p>

```<code>enter code here
</code>```

Body:
you can use editable tables like html5 editable table, click
   (https://codepen.io/ashblue/pen/mCtuA) for example!

enter code here