问:
FeathersJS and MongoDB different results querying a field from HTTP GET and service.find in hooks
I'm getting different response when querying a service from a specific field, depending on if I'm using CURL or running app.service().find() on the server. I'm using MongoDB, here's an example of my results.

```<code>// Here's a list of all data in the service
curl 'http://192.168.99.100:3030/players/'
[
    {"_id":"5a04bd4eee3648000fbad08f","userId":"59f8e18c14b066000ff63cbb","gameId":"5a04bd4eee3648000fbad08e","isHost":true,"handle":"dude"},
    {"_id":"5a0b41bbacd285000ffb310c","userId":"59f8e18c14b066000ff63cbb","gameId":"5a0b41bbacd285000ffb310b","isHost":true,"handle":"dude"},
    {"_id":"5a0b440aacd285000ffb310d","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b44f7acd285000ffb310e","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b498dc31cea000fef17dd","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"},
    {"_id":"5a0b4a76c31cea000fef17de","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"}
]}

// If I query on the gameId 5a0b41bbacd285000ffb310b from curl, it only returns
// 4 of 5 rows skipping the first player
curl 'http://192.168.99.100:3030/players/?gameId=5a0b41bbacd285000ffb310b'
[
    {"_id":"5a0b440aacd285000ffb310d","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b44f7acd285000ffb310e","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b498dc31cea000fef17dd","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"},
    {"_id":"5a0b4a76c31cea000fef17de","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"}
]}

// When I run this query server side passing gameID = 5a0b41bbacd285000ffb310b
// I only get the first created player in the list.
var gameID = hook.result._id;
app.service('players').find({
    query:{
      gameId: gameID,
    }
}).then(players => {
    console.log(players);
});
[
    {"_id":"5a0b41bbacd285000ffb310c","userId":"59f8e18c14b066000ff63cbb","gameId":"5a0b41bbacd285000ffb310b","isHost":true,"handle":"dude"}
]
</code>```

My filters are blank, and the hooks don't remove data they just get the "handle" from the userId.

It seems like the query might not work because there may be a difference in datatype. As in the fieldname gameId or the data stored.

The first ID in Players 5a0b41bbacd285000ffb310c was given the gameId from the server side after the game object was created using a hook. Like this:

```<code>// This hook is run after a new game is created
return function joinNewGame (hook) {
    var userid = hook.params.user._id;
    var gameid = hook.result._id;

    return hook.app.service('players').create({
            userId: userid,
            gameId: gameid,
            isHost: true,
        }).then(player => {

            return hook;
        });
};
</code>```

The other players were written in a post request where gameId was passed as a string.

```<code>curl 'http://192.168.99.100:3030/players/' -H 'Content-Type: application/json' --data-binary '{ "gameId":"5a0b41bbacd285000ffb310b"}'
</code>```

Thanks for your help!

答:
After some additional testing I find that it's a typing error. The typeof gameId for the server side created entry was "Object" while the client side was "String".

So my current fix is to cast the id's to strings before storing / querying from the server. Is this the best way to do Many to One relationships in the ORM? The Docs doesn't go into detail.

Update: Here's a different fix, I created a new hook that converts string to a MongoDB Object ID when storing the data, pass the fields that need to be updated in an array.

```<code>var ObjectID = require('mongodb').ObjectID;

module.exports = function (fields, options = {}) { // eslint-disable-line no-unused-vars
  return function stringToObjectId (hook) {
    // For each passed field
    for(var i = 0; fields.length > i; i++){
      // Test if there's queries on the field, then convert
      if(hook.params.query && typeof hook.params.query[fields[i]] != "Object"){
        hook.params.query[fields[i]] = ObjectID(hook.params.query[fields[i]]);
      }
      // Test if there's data on the field, then convert
      if(hook.data && typeof hook.data[fields[i]] != "Object"){
        hook.data[fields[i]] = ObjectID(hook.data[fields[i]]);
      }
    }
    return Promise.resolve(hook);
  };
};
</code>```

Body:
I'm getting different response when querying a service from a specific field, depending on if I'm using CURL or running app.service().find() on the server. I'm using MongoDB, here's an example of my results.

// Here's a list of all data in the service
curl 'http://192.168.99.100:3030/players/'
[
    {"_id":"5a04bd4eee3648000fbad08f","userId":"59f8e18c14b066000ff63cbb","gameId":"5a04bd4eee3648000fbad08e","isHost":true,"handle":"dude"},
    {"_id":"5a0b41bbacd285000ffb310c","userId":"59f8e18c14b066000ff63cbb","gameId":"5a0b41bbacd285000ffb310b","isHost":true,"handle":"dude"},
    {"_id":"5a0b440aacd285000ffb310d","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b44f7acd285000ffb310e","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b498dc31cea000fef17dd","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"},
    {"_id":"5a0b4a76c31cea000fef17de","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"}
]}

// If I query on the gameId 5a0b41bbacd285000ffb310b from curl, it only returns
// 4 of 5 rows skipping the first player
curl 'http://192.168.99.100:3030/players/?gameId=5a0b41bbacd285000ffb310b'
[
    {"_id":"5a0b440aacd285000ffb310d","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b44f7acd285000ffb310e","gameId":"5a0b41bbacd285000ffb310b"},
    {"_id":"5a0b498dc31cea000fef17dd","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"},
    {"_id":"5a0b4a76c31cea000fef17de","gameId":"5a0b41bbacd285000ffb310b","userId":"5a0b4117acd285000ffb310a","handle":"dog"}
]}

// When I run this query server side passing gameID = 5a0b41bbacd285000ffb310b
// I only get the first created player in the list.
var gameID = hook.result._id;
app.service('players').find({
    query:{
      gameId: gameID,
    }
}).then(players => {
    console.log(players);
});
[
    {"_id":"5a0b41bbacd285000ffb310c","userId":"59f8e18c14b066000ff63cbb","gameId":"5a0b41bbacd285000ffb310b","isHost":true,"handle":"dude"}
]

My filters are blank, and the hooks don't remove data they just get the "handle" from the userId.

It seems like the query might not work because there may be a difference in datatype. As in the fieldname gameId or the data stored.

The first ID in Players 5a0b41bbacd285000ffb310c was given the gameId from the server side after the game object was created using a hook. Like this:

// This hook is run after a new game is created
return function joinNewGame (hook) {
    var userid = hook.params.user._id;
    var gameid = hook.result._id;

    return hook.app.service('players').create({
            userId: userid,
            gameId: gameid,
            isHost: true,
        }).then(player => {

            return hook;
        });
};

The other players were written in a post request where gameId was passed as a string.

curl 'http://192.168.99.100:3030/players/' -H 'Content-Type: application/json' --data-binary '{ "gameId":"5a0b41bbacd285000ffb310b"}'

Thanks for your help!

Body:
After some additional testing I find that it's a typing error. The typeof gameId for the server side created entry was "Object" while the client side was "String".

So my current fix is to cast the id's to strings before storing / querying from the server. Is this the best way to do Many to One relationships in the ORM? The Docs doesn't go into detail.

Update: Here's a different fix, I created a new hook that converts string to a MongoDB Object ID when storing the data, pass the fields that need to be updated in an array.

var ObjectID = require('mongodb').ObjectID;

module.exports = function (fields, options = {}) { // eslint-disable-line no-unused-vars
  return function stringToObjectId (hook) {
    // For each passed field
    for(var i = 0; fields.length > i; i++){
      // Test if there's queries on the field, then convert
      if(hook.params.query && typeof hook.params.query[fields[i]] != "Object"){
        hook.params.query[fields[i]] = ObjectID(hook.params.query[fields[i]]);
      }
      // Test if there's data on the field, then convert
      if(hook.data && typeof hook.data[fields[i]] != "Object"){
        hook.data[fields[i]] = ObjectID(hook.data[fields[i]]);
      }
    }
    return Promise.resolve(hook);
  };
};


来源: stackexchange

问:
CFML - query row to structure
I would like to handle a row from a query by a function, where I pass the row as a structure.

ideally...

```<code><cfloop query="myquery">
 #myfunction(#row#)#
</cfloop>
</code>```

I could set it up like this too...

```<code><cfloop query="myquery">
 #myfunction(#col1#,#col2#,#col3#,#col4#)#
</cfloop>
</code>```

but I don't want to. I haven't been able to finda simple way of extracting a row, But I thought I'd ask.

答:
Another solution would be:</p>

```<code>function QueryToStruct(query){
    var cols    = ListToArray(query.columnList);
    var salida  = query.map(function(v=0,i,a){
                       return {'#cols[1]#':v};
                  });
    return ValueArray(salida,'#cols[1]#');
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: CFML - query row to structure

Body:
I would like to handle a row from a query by a function, where I pass the row as a structure.

ideally...

<cfloop query="myquery">
 #myfunction(#row#)#
</cfloop>

I could set it up like this too...

<cfloop query="myquery">
 #myfunction(#col1#,#col2#,#col3#,#col4#)#
</cfloop>

but I don't want to. I haven't been able to finda simple way of extracting a row, But I thought I'd ask.

Body:
Another solution would be:

function QueryToStruct(query){
    var cols    = ListToArray(query.columnList);
    var salida  = query.map(function(v=0,i,a){
                       return {'#cols[1]#':v};
                  });
    return ValueArray(salida,'#cols[1]#');
}


问:
Azure / U-SQL - ROUND a number
I am trying to ROUND the SUM() of a float column in U-SQL but keep getting errors.

1) Is there a function that does this?

2) What kind of data can I pass it (ie int, float, etc)?

答: You can use any of the C# scalar expressions. Thus Math.Round (https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx) would be the appropriate operation.

Title: Azure / U-SQL - ROUND a number


问:
Queued model restarts with large error, despite being trained
I have a model which started as a simple feed_dict model and has been converted to one using queues. The feed_dict model works as expected, but for some reason the queued model won't resume with the same error like the feed_dict version. I can't explain why the error is so large on the first few runs? (It's implementing a 4-dimension output classifier, and diff is the difference from the training data, so the who will inversely correlate)

The only thing that I can think of is it has something to do with the Queue capacity?

```<code>def multithreaded_train_rows_layered(initial_weights, weights_filename, rows):
    keys = sorted(rows[0].keys())
    num_keys_range = range(len(keys))
    (features, outputs) = features_outputs(keys)

    x_true = np.array([ [ [float(row[feature]) for feature in features] for row in rows] ])
    y_true = np.array([ [float(row[output]) for output in outputs] for row in rows ] )

    #queue
    q = tf.FIFOQueue(capacity=40, dtypes=[tf.float32 for x in x_true])
    enq_op = q.enqueue_many(x_true)
    qr = tf.train.QueueRunner(q, [enq_op] * 1)
    tf.train.add_queue_runner(qr)

    input = q.dequeue()

    if initial_weights is None:
        print 'Creating weights', len(features), len(features), len(outputs)
        w1 = tf.Variable(tf.random_normal((len(features), len(features))), name="w1")
        b1 = tf.Variable(tf.constant(0.1, shape=[len(features)]), name="b1")
        w2 = tf.Variable(tf.random_normal((len(features), len(outputs))), name="w2")
        b2 = tf.Variable(tf.constant(0.1, shape=[len(outputs)]), name="b2")
    else:
        print 'Using supplied weights', len(weights['w1']), len(weights['w2']),  len(weights['w2'][0])
        w1 = tf.Variable(weights['w1'], name="w1")
        b1 = tf.Variable(weights['b1'], name="b1")
        w2 = tf.Variable(weights['w2'], name="w2")
        b2 = tf.Variable(weights['b2'], name="b2")

    y = tf.matmul(tf.nn.relu(tf.matmul(input, w1) + b1), w2) + b2

    loss_op = tf.reduce_mean(tf.square(y - y_true), name="loss")
    #train_op = tf.train.GradientDescentOptimizer(0.3).minimize(loss_op)
    train_op = tf.train.AdamOptimizer(0.01).minimize(loss_op)

    print 'Starting session'
    with tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=2, inter_op_parallelism_threads=2)) as sess:
        sess.run(tf.global_variables_initializer())
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        last_error = 1.7976931348623157e+308
        this_error = 1.7976931348623157e+307
        diff = 1
        iteration = initial_weights['iteration'] if initial_weights is not None and 'iteration' in initial_weights else 0

        while diff > 0:
            iteration += 1
            last_error = this_error
            for step in range(10):
                _, results, error, w1_computed, b1_computed, w2_computed, b2_computed = sess.run([train_op, y, loss_op, w1, b1, w2, b2])

            this_error = float(error)

            (diff, locs) = compare(y_true, results)
            if locs < 50:
                print "iteration:", iteration, "error:",this_error, "diff:", diff, "locs:", locs
            else:
                print "iteration:", iteration,"error:",this_error, "diff:", diff
            if this_error < last_error:
                with open(weights_filename, "w") as weights_file:
                    try:
                        json.dump({"iteration": iteration,
                        "w1": w1_computed.tolist(), "b1": b1_computed.tolist(),
                        "w2": w2_computed.tolist(), "b2": b2_computed.tolist(),
                        "error": this_error, "inputs": features}, weights_file, indent=True)
                    except Exception as e:
                        print {"iteration": iteration,
                            "w1": w1_computed.tolist(), "b1": b1_computed.tolist(),
                            "w2": w2_computed.tolist(), "b2": b2_computed.tolist(),
                        "error": this_error, "inputs": features}
                        print e
        coord.request_stop()
        coord.join(threads)
    return rows
</code>```

Console log:

```<code>iteration: 155 error: 429.936584473 diff: 10258
iteration: 156 error: 1.47592782974 diff: 7480
iteration: 157 error: 46.404006958 diff: 20614
iteration: 158 error: 21.8979129791 diff: 20465
iteration: 159 error: 3.92602086067 diff: 18277
iteration: 160 error: 0.696662843227 diff: 12208
iteration: 161 error: 0.289250463247 diff: 11400
iteration: 162 error: 0.227930724621 diff: 10794
iteration: 163 error: 0.181772902608 diff: 11081
iteration: 164 error: 0.105023987591 diff: 10537
iteration: 165 error: 0.0506426692009 diff: 7624
iteration: 166 error: 0.0422255061567 diff: 4108
iteration: 167 error: 0.0387616828084 diff: 3845
iteration: 168 error: 0.0329982601106 diff: 3310
iteration: 169 error: 0.0305742416531 diff: 3913
iteration: 170 error: 0.0279670264572 diff: 2877
iteration: 171 error: 0.0260633360595 diff: 2617
iteration: 172 error: 0.0243702083826 diff: 2550
iteration: 173 error: 0.0229212064296 diff: 2355
iteration: 174 error: 0.021658487618 diff: 2191
iteration: 175 error: 0.0205383263528 diff: 2093
iteration: 176 error: 0.0195389948785 diff: 1950
iteration: 177 error: 0.0186410453171 diff: 1853
iteration: 178 error: 0.0178280193359 diff: 1740
iteration: 179 error: 0.0170874521136 diff: 1650
iteration: 180 error: 0.0164082739502 diff: 1550
iteration: 181 error: 0.015782084316 diff: 1471
iteration: 182 error: 0.0152017641813 diff: 1413
iteration: 183 error: 0.0146614015102 diff: 1359
</code>```

[restart]

```<code>Using supplied weights 1182 1182 4
Starting session
iteration: 184 error: 277.624237061 diff: 25028
iteration: 185 error: 93.7772903442 diff: 24692
iteration: 186 error: 32.6932220459 diff: 24810
iteration: 187 error: 13.0545969009 diff: 22863
iteration: 188 error: 4.19472408295 diff: 22383
iteration: 189 error: 0.274255514145 diff: 10213
iteration: 190 error: 0.441053062677 diff: 5573
iteration: 191 error: 0.188079148531 diff: 5710
iteration: 192 error: 0.103881075978 diff: 10231
iteration: 193 error: 0.0453641563654 diff: 4084
iteration: 194 error: 0.0464548133314 diff: 4007
iteration: 195 error: 0.0357639603317 diff: 4082
iteration: 196 error: 0.0287289172411 diff: 2713
iteration: 197 error: 0.0246742982417 diff: 2695
iteration: 198 error: 0.0216691829264 diff: 2425
iteration: 199 error: 0.0191784724593 diff: 2305
iteration: 200 error: 0.0170567110181 diff: 2099
iteration: 201 error: 0.0152298733592 diff: 1997
iteration: 202 error: 0.0136485118419 diff: 1869
iteration: 203 error: 0.012274238281 diff: 1761
iteration: 204 error: 0.0110755767673 diff: 1659
iteration: 205 error: 0.0100243529305 diff: 1537
iteration: 206 error: 0.00909862946719 diff: 1452
iteration: 207 error: 0.00828060507774 diff: 1371
iteration: 208 error: 0.0075555741787 diff: 1286
iteration: 209 error: 0.00691094947979 diff: 1230
iteration: 210 error: 0.00633637560531 diff: 1164
iteration: 211 error: 0.00582302454859 diff: 1103
iteration: 212 error: 0.00536326272413 diff: 1031
iteration: 213 error: 0.00495055690408 diff: 983
iteration: 214 error: 0.00457921577618 diff: 936
iteration: 215 error: 0.00424438575283 diff: 886
iteration: 216 error: 0.00394174130633 diff: 832
iteration: 217 error: 0.00366767356172 diff: 791
iteration: 218 error: 0.00341899320483 diff: 751
iteration: 219 error: 0.00319294095971 diff: 704
iteration: 220 error: 0.00298711610958 diff: 660
iteration: 221 error: 0.00279938825406 diff: 632
iteration: 222 error: 0.00262793083675 diff: 596
iteration: 223 error: 0.00247104465961 diff: 566
iteration: 224 error: 0.00232721073553 diff: 540
iteration: 225 error: 0.00219512404874 diff: 514
iteration: 226 error: 0.00207365490496 diff: 487
</code>```

[restart]

```<code>Using supplied weights 1182 1182 4
Starting session
iteration: 227 error: 163.869613647 diff: 18455
iteration: 228 error: 21.2328510284 diff: 18491
iteration: 229 error: 0.492245942354 diff: 4858
iteration: 230 error: 6.67014503479 diff: 8085
iteration: 231 error: 0.820626139641 diff: 3161
iteration: 232 error: 1.1164072752 diff: 17916
iteration: 233 error: 0.173011898994 diff: 1788
iteration: 234 error: 0.0890910178423 diff: 2969
iteration: 235 error: 0.0811333060265 diff: 10824
iteration: 236 error: 0.0661801099777 diff: 2528
iteration: 237 error: 0.0558460131288 diff: 3008
</code>```

答:
So this is a result of the AdamOptimizer. Switching to GDO makes the behavior disappear. </p>

<p>Also the assignment from sess.run() must be a tuple in order to work as intended.  </p>

```<code>(_, results, error, w1_computed, b1_computed, w2_computed, b2_computed) = sess.run([train_op, y, loss_op, w1, b1, w2, b2])
</code>```

Body:
I have a model which started as a simple feed_dict model and has been converted to one using queues. The feed_dict model works as expected, but for some reason the queued model won't resume with the same error like the feed_dict version. I can't explain why the error is so large on the first few runs? (It's implementing a 4-dimension output classifier, and diff is the difference from the training data, so the who will inversely correlate)

The only thing that I can think of is it has something to do with the Queue capacity?

def multithreaded_train_rows_layered(initial_weights, weights_filename, rows):
    keys = sorted(rows[0].keys())
    num_keys_range = range(len(keys))
    (features, outputs) = features_outputs(keys)

    x_true = np.array([ [ [float(row[feature]) for feature in features] for row in rows] ])
    y_true = np.array([ [float(row[output]) for output in outputs] for row in rows ] )

    #queue
    q = tf.FIFOQueue(capacity=40, dtypes=[tf.float32 for x in x_true])
    enq_op = q.enqueue_many(x_true)
    qr = tf.train.QueueRunner(q, [enq_op] * 1)
    tf.train.add_queue_runner(qr)

    input = q.dequeue()

    if initial_weights is None:
        print 'Creating weights', len(features), len(features), len(outputs)
        w1 = tf.Variable(tf.random_normal((len(features), len(features))), name="w1")
        b1 = tf.Variable(tf.constant(0.1, shape=[len(features)]), name="b1")
        w2 = tf.Variable(tf.random_normal((len(features), len(outputs))), name="w2")
        b2 = tf.Variable(tf.constant(0.1, shape=[len(outputs)]), name="b2")
    else:
        print 'Using supplied weights', len(weights['w1']), len(weights['w2']),  len(weights['w2'][0])
        w1 = tf.Variable(weights['w1'], name="w1")
        b1 = tf.Variable(weights['b1'], name="b1")
        w2 = tf.Variable(weights['w2'], name="w2")
        b2 = tf.Variable(weights['b2'], name="b2")

    y = tf.matmul(tf.nn.relu(tf.matmul(input, w1) + b1), w2) + b2

    loss_op = tf.reduce_mean(tf.square(y - y_true), name="loss")
    #train_op = tf.train.GradientDescentOptimizer(0.3).minimize(loss_op)
    train_op = tf.train.AdamOptimizer(0.01).minimize(loss_op)

    print 'Starting session'
    with tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=2, inter_op_parallelism_threads=2)) as sess:
        sess.run(tf.global_variables_initializer())
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        last_error = 1.7976931348623157e+308
        this_error = 1.7976931348623157e+307
        diff = 1
        iteration = initial_weights['iteration'] if initial_weights is not None and 'iteration' in initial_weights else 0

        while diff > 0:
            iteration += 1
            last_error = this_error
            for step in range(10):
                _, results, error, w1_computed, b1_computed, w2_computed, b2_computed = sess.run([train_op, y, loss_op, w1, b1, w2, b2])

            this_error = float(error)

            (diff, locs) = compare(y_true, results)
            if locs < 50:
                print "iteration:", iteration, "error:",this_error, "diff:", diff, "locs:", locs
            else:
                print "iteration:", iteration,"error:",this_error, "diff:", diff
            if this_error < last_error:
                with open(weights_filename, "w") as weights_file:
                    try:
                        json.dump({"iteration": iteration,
                        "w1": w1_computed.tolist(), "b1": b1_computed.tolist(),
                        "w2": w2_computed.tolist(), "b2": b2_computed.tolist(),
                        "error": this_error, "inputs": features}, weights_file, indent=True)
                    except Exception as e:
                        print {"iteration": iteration,
                            "w1": w1_computed.tolist(), "b1": b1_computed.tolist(),
                            "w2": w2_computed.tolist(), "b2": b2_computed.tolist(),
                        "error": this_error, "inputs": features}
                        print e
        coord.request_stop()
        coord.join(threads)
    return rows

Console log:

iteration: 155 error: 429.936584473 diff: 10258
iteration: 156 error: 1.47592782974 diff: 7480
iteration: 157 error: 46.404006958 diff: 20614
iteration: 158 error: 21.8979129791 diff: 20465
iteration: 159 error: 3.92602086067 diff: 18277
iteration: 160 error: 0.696662843227 diff: 12208
iteration: 161 error: 0.289250463247 diff: 11400
iteration: 162 error: 0.227930724621 diff: 10794
iteration: 163 error: 0.181772902608 diff: 11081
iteration: 164 error: 0.105023987591 diff: 10537
iteration: 165 error: 0.0506426692009 diff: 7624
iteration: 166 error: 0.0422255061567 diff: 4108
iteration: 167 error: 0.0387616828084 diff: 3845
iteration: 168 error: 0.0329982601106 diff: 3310
iteration: 169 error: 0.0305742416531 diff: 3913
iteration: 170 error: 0.0279670264572 diff: 2877
iteration: 171 error: 0.0260633360595 diff: 2617
iteration: 172 error: 0.0243702083826 diff: 2550
iteration: 173 error: 0.0229212064296 diff: 2355
iteration: 174 error: 0.021658487618 diff: 2191
iteration: 175 error: 0.0205383263528 diff: 2093
iteration: 176 error: 0.0195389948785 diff: 1950
iteration: 177 error: 0.0186410453171 diff: 1853
iteration: 178 error: 0.0178280193359 diff: 1740
iteration: 179 error: 0.0170874521136 diff: 1650
iteration: 180 error: 0.0164082739502 diff: 1550
iteration: 181 error: 0.015782084316 diff: 1471
iteration: 182 error: 0.0152017641813 diff: 1413
iteration: 183 error: 0.0146614015102 diff: 1359

[restart]

Using supplied weights 1182 1182 4
Starting session
iteration: 184 error: 277.624237061 diff: 25028
iteration: 185 error: 93.7772903442 diff: 24692
iteration: 186 error: 32.6932220459 diff: 24810
iteration: 187 error: 13.0545969009 diff: 22863
iteration: 188 error: 4.19472408295 diff: 22383
iteration: 189 error: 0.274255514145 diff: 10213
iteration: 190 error: 0.441053062677 diff: 5573
iteration: 191 error: 0.188079148531 diff: 5710
iteration: 192 error: 0.103881075978 diff: 10231
iteration: 193 error: 0.0453641563654 diff: 4084
iteration: 194 error: 0.0464548133314 diff: 4007
iteration: 195 error: 0.0357639603317 diff: 4082
iteration: 196 error: 0.0287289172411 diff: 2713
iteration: 197 error: 0.0246742982417 diff: 2695
iteration: 198 error: 0.0216691829264 diff: 2425
iteration: 199 error: 0.0191784724593 diff: 2305
iteration: 200 error: 0.0170567110181 diff: 2099
iteration: 201 error: 0.0152298733592 diff: 1997
iteration: 202 error: 0.0136485118419 diff: 1869
iteration: 203 error: 0.012274238281 diff: 1761
iteration: 204 error: 0.0110755767673 diff: 1659
iteration: 205 error: 0.0100243529305 diff: 1537
iteration: 206 error: 0.00909862946719 diff: 1452
iteration: 207 error: 0.00828060507774 diff: 1371
iteration: 208 error: 0.0075555741787 diff: 1286
iteration: 209 error: 0.00691094947979 diff: 1230
iteration: 210 error: 0.00633637560531 diff: 1164
iteration: 211 error: 0.00582302454859 diff: 1103
iteration: 212 error: 0.00536326272413 diff: 1031
iteration: 213 error: 0.00495055690408 diff: 983
iteration: 214 error: 0.00457921577618 diff: 936
iteration: 215 error: 0.00424438575283 diff: 886
iteration: 216 error: 0.00394174130633 diff: 832
iteration: 217 error: 0.00366767356172 diff: 791
iteration: 218 error: 0.00341899320483 diff: 751
iteration: 219 error: 0.00319294095971 diff: 704
iteration: 220 error: 0.00298711610958 diff: 660
iteration: 221 error: 0.00279938825406 diff: 632
iteration: 222 error: 0.00262793083675 diff: 596
iteration: 223 error: 0.00247104465961 diff: 566
iteration: 224 error: 0.00232721073553 diff: 540
iteration: 225 error: 0.00219512404874 diff: 514
iteration: 226 error: 0.00207365490496 diff: 487

[restart]

Using supplied weights 1182 1182 4
Starting session
iteration: 227 error: 163.869613647 diff: 18455
iteration: 228 error: 21.2328510284 diff: 18491
iteration: 229 error: 0.492245942354 diff: 4858
iteration: 230 error: 6.67014503479 diff: 8085
iteration: 231 error: 0.820626139641 diff: 3161
iteration: 232 error: 1.1164072752 diff: 17916
iteration: 233 error: 0.173011898994 diff: 1788
iteration: 234 error: 0.0890910178423 diff: 2969
iteration: 235 error: 0.0811333060265 diff: 10824
iteration: 236 error: 0.0661801099777 diff: 2528
iteration: 237 error: 0.0558460131288 diff: 3008

Body:
So this is a result of the AdamOptimizer. Switching to GDO makes the behavior disappear.

Also the assignment from sess.run() must be a tuple in order to work as intended.

(_, results, error, w1_computed, b1_computed, w2_computed, b2_computed) = sess.run([train_op, y, loss_op, w1, b1, w2, b2])


问:
Where to put Rule Sets for MSBuild 15 (Build Tools for Visual Studio 2017)
When enabling Static Code Analysis on my builds, I get the following error thrown by MSBuild:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Microsoft.CSharp.CurrentVersion.targets(134,9): warning MSB3884: Could not find rule set file "AllRules.ruleset". [C:\Program Files\VSTS Agent_work\PATH_TO_MY.csproj]

To get Static Code Analysis working on build agents (only MSBuild, no Visual Studio), for older versions of the build tools one would:

Copy C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\Rule Sets\ to the build server

Add a registry entry pointing to that folder

(see also this bug report)

However, these instructions doesn't work with "Build Tools for Visual Studio 2017". I'd like to know how I resolve this, without needing to copy the rulesets into my own repository or changing anything in my csproj?

Update:

I've tried setting the following registry key, to no avail:

```<code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\15.0\Setup\EDev]
"StanDir"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\Team Tools\\Static Analysis Tools"
</code>```

Digging through the registry, I've found that the following registry keys. On my machine I've installed both VS2017 Build Tools and Test Agent, and it seems like this points to the latter, which I have installed after installed Build Tools:

```<code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7]
"15.0"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\TestAgent\\"
"14.0"="C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\"
</code>```

Update 2:

Both answers mention the file Microsoft.CodeAnalysis.Targets. However this file is not present on my build server. I've tried copying this folder over from my VS2017 installation:

```<code>from: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
to: C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
</code>```

However besides the rulesets not being found, it now also throws errors about being unable to find Microsoft.WebApplication.targets:

XXX.csproj(296,11): error MSB4226: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuil
  d\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" was not found. Also, tried to find "WebApplications\Microsoft.WebApplication.targets" in the fallback search path(s) for $(VSToo
  lsPath) - "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0" . These search paths are defined in "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe.Config".
   Confirm that the path in the  declaration is correct, and that the file exists on disk in one of the search paths.

答:
Officially you'd need to install Visual Studio onto the build server, as the Code Analysis these rules come from are part of Visual Studio, not of MsBuild.

You can still copy the Static Analysis directory to your build server and supply the following parameter to MsBuild in the Additional Arguments option:

```<code>/p:CodeAnalysisStaticAnalysisDirectory=c:\analysisdirectory
</code>```

Or copy just the rule files and specify this MsBuild argument, that's probably easiest when you put the rules files in source control:

```<code>/p:CodeAnalysisRuleDirectories=c:\analysisdirectory\rules
</code>```

Optionally you could edit the project file and set the property in a property group.

Body:
When enabling Static Code Analysis on my builds, I get the following error thrown by MSBuild:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Microsoft.CSharp.CurrentVersion.targets(134,9): warning MSB3884: Could not find rule set file "AllRules.ruleset". [C:\Program Files\VSTS Agent_work\PATH_TO_MY.csproj]

To get Static Code Analysis working on build agents (only MSBuild, no Visual Studio), for older versions of the build tools one would:

Copy C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\Rule Sets\ to the build server

Add a registry entry pointing to that folder

(see also this bug report)

However, these instructions doesn't work with "Build Tools for Visual Studio 2017". I'd like to know how I resolve this, without needing to copy the rulesets into my own repository or changing anything in my csproj?

Update:

I've tried setting the following registry key, to no avail:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\15.0\Setup\EDev]
"StanDir"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\Team Tools\\Static Analysis Tools"

Digging through the registry, I've found that the following registry keys. On my machine I've installed both VS2017 Build Tools and Test Agent, and it seems like this points to the latter, which I have installed after installed Build Tools:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7]
"15.0"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\TestAgent\\"
"14.0"="C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\"

Update 2:

Both answers mention the file Microsoft.CodeAnalysis.Targets. However this file is not present on my build server. I've tried copying this folder over from my VS2017 installation:

from: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
to: C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis

However besides the rulesets not being found, it now also throws errors about being unable to find Microsoft.WebApplication.targets:

XXX.csproj(296,11): error MSB4226: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuil
  d\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" was not found. Also, tried to find "WebApplications\Microsoft.WebApplication.targets" in the fallback search path(s) for $(VSToo
  lsPath) - "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0" . These search paths are defined in "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe.Config".
   Confirm that the path in the  declaration is correct, and that the file exists on disk in one of the search paths.

Body:
Officially you'd need to install Visual Studio onto the build server, as the Code Analysis these rules come from are part of Visual Studio, not of MsBuild.

You can still copy the Static Analysis directory to your build server and supply the following parameter to MsBuild in the Additional Arguments option:

/p:CodeAnalysisStaticAnalysisDirectory=c:\analysisdirectory

Or copy just the rule files and specify this MsBuild argument, that's probably easiest when you put the rules files in source control:

/p:CodeAnalysisRuleDirectories=c:\analysisdirectory\rules

Optionally you could edit the project file and set the property in a property group.


问:
Creating zend form element array with same name (ZF3)?
Since i've to position checkboxes in design I'm not using MultiCheckbox and using Checkbox instead in zend. I've seen some zf1 solutions but didnt found any zf2 or zf3 solutions.

My Php Code

```<code>$languages = new \Zend\Form\Element\Checkbox('languages[]');
$languages->setLabel('English');
$languages->setValue('1');
</code>```

This produce the following output

```<code><?php
    echo $this->formRow($form->get('languages[]'));
    //It produce the following
?>
<input type="checkbox" name="languages[]" value="1" checked="checked">
</code>```

How can I add more items with name "languages[]" without writing direct HTML code ?

答:
You can use a Form collection for this:

1) In your form:

```<code>use Zend\Form\Element\Collection;

...

$languages = new \Zend\Form\Element\Checkbox();
$languages->setLabel('English');
$languages->setValue('1');
$languages->setName('language');

$collection = new Collection();
$collection->setName('languages');
$collection->setLabel('Language Collection');
$collection->setCount(2);
$collection->setTargetElement($languages);
$collection->populateValues(array(
        1, 0
));

$this->add($collection);
</code>```

2) Do not forget to prepare your form in your controller action:

```<code>$form->prepare();
</code>```

3) Finally, in your view, get all elements of the collection and render them separately:

```<code><?php $elements = $form->get('languages')->getElements(); ?>
<?php //echo $this->formCollection($form->get('languages')); ?>
<?php echo $this->formRow($elements[0]); ?>
<?php echo $this->formRow($elements[1]); ?>
</code>```

Body:
Since i've to position checkboxes in design I'm not using MultiCheckbox and using Checkbox instead in zend. I've seen some zf1 solutions but didnt found any zf2 or zf3 solutions.

My Php Code

$languages = new \Zend\Form\Element\Checkbox('languages[]');
$languages->setLabel('English');
$languages->setValue('1');

This produce the following output

<?php
    echo $this->formRow($form->get('languages[]'));
    //It produce the following
?>
<input type="checkbox" name="languages[]" value="1" checked="checked">

How can I add more items with name "languages[]" without writing direct HTML code ?

Body:
You can use a Form collection for this:

1) In your form:

use Zend\Form\Element\Collection;

...

$languages = new \Zend\Form\Element\Checkbox();
$languages->setLabel('English');
$languages->setValue('1');
$languages->setName('language');

$collection = new Collection();
$collection->setName('languages');
$collection->setLabel('Language Collection');
$collection->setCount(2);
$collection->setTargetElement($languages);
$collection->populateValues(array(
        1, 0
));

$this->add($collection);

2) Do not forget to prepare your form in your controller action:

$form->prepare();

3) Finally, in your view, get all elements of the collection and render them separately:

<?php $elements = $form->get('languages')->getElements(); ?>
<?php //echo $this->formCollection($form->get('languages')); ?>
<?php echo $this->formRow($elements[0]); ?>
<?php echo $this->formRow($elements[1]); ?>


问:
Why is '[f x[1]]' ungrammatical while '[1 + x[1]]' is?
For an Array x, the following are grammatical expressions:

puts x[1]

[puts(x[1])]

[1 + x[1]]

but this:

[puts x[1]]

fails to parse with:

```<code>syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
</code>```

Why can't the parser figure out this syntax?

答:
I believe this parsing behavior is intentional--not a bug. It's an unfortunate side-effect of Ruby allowing omitted parentheses. This code is, of course, fine:

```<code>def f x, y=0
  x + y
end

f 2    # 2
f 2, 3 # 5
</code>```

But what is the result of this code?

```<code>[f 2, 3]
</code>```

[2,3] or [5]? In order for the syntactical analyzer to handle this code, it would need to understand the arity of the method. But because Ruby is dynamic that cannot be determined until the method call is actually performed.

Rather than allow the ambiguous case, which would surely result in surprising situations during runtime, the designers opted for the (still surprising, but) easily fixable error during parsing.

Note: you could still argue that in the case where it is the last element there is no ambiguity

```<code>[3, f 2]
# should be [3, 2]
</code>```

but I can imagine pulling my hair out if Ruby let's me write that and then slaps me with a syntax error when I add one more element to the end of the array. I can understand the decision to simply not allow omitted parentheses inside arrays.

Body:
For an Array x, the following are grammatical expressions:

puts x[1]

[puts(x[1])]

[1 + x[1]]

but this:

[puts x[1]]

fails to parse with:

syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('

Why can't the parser figure out this syntax?

Body:
I believe this parsing behavior is intentional--not a bug. It's an unfortunate side-effect of Ruby allowing omitted parentheses. This code is, of course, fine:

def f x, y=0
  x + y
end

f 2    # 2
f 2, 3 # 5

But what is the result of this code?

[f 2, 3]

[2,3] or [5]? In order for the syntactical analyzer to handle this code, it would need to understand the arity of the method. But because Ruby is dynamic that cannot be determined until the method call is actually performed.

Rather than allow the ambiguous case, which would surely result in surprising situations during runtime, the designers opted for the (still surprising, but) easily fixable error during parsing.

Note: you could still argue that in the case where it is the last element there is no ambiguity

[3, f 2]
# should be [3, 2]

but I can imagine pulling my hair out if Ruby let's me write that and then slaps me with a syntax error when I add one more element to the end of the array. I can understand the decision to simply not allow omitted parentheses inside arrays.


问:
Converting NAs to 0 and non-NA's to 1s in R
I am having trouble converting a table of NAs and different values to 0 for NAs and 1s for the all the values.

Table looks like this:

```<code>x    y    z
NA   8    NA
2    NA   NA
9    9    8
...
</code>```

I was able to convert the NAs to 0 using:

```<code>data[is.na(data)] <- 0
</code>```

But I couldn't manage to convert the other values for all the columns at once.

答:
Following the same approach as you mentioned in your example:

```<code># example data
df = data.frame(x = c(5,4,NA),
                y = c(NA,3,9))

df

#    x  y
# 1  5 NA
# 2  4  3
# 3 NA  9

df[!is.na(df)] = 1
df[is.na(df)] = 0

#   x y
# 1 1 0
# 2 1 1
# 3 0 1
</code>```

First replace all non NA values with 1 and then (the remaining) NAs with 0.
If you replace NAs first, then all your values will be non NA and you'll end up with a dataframe full of 1s.

Body:
I am having trouble converting a table of NAs and different values to 0 for NAs and 1s for the all the values.

Table looks like this:

x    y    z
NA   8    NA
2    NA   NA
9    9    8
...

I was able to convert the NAs to 0 using:

data[is.na(data)] <- 0

But I couldn't manage to convert the other values for all the columns at once.

Body:
Following the same approach as you mentioned in your example:

# example data
df = data.frame(x = c(5,4,NA),
                y = c(NA,3,9))

df

#    x  y
# 1  5 NA
# 2  4  3
# 3 NA  9

df[!is.na(df)] = 1
df[is.na(df)] = 0

#   x y
# 1 1 0
# 2 1 1
# 3 0 1

First replace all non NA values with 1 and then (the remaining) NAs with 0.
If you replace NAs first, then all your values will be non NA and you'll end up with a dataframe full of 1s.


问:
Symfony Admin Generator Doctrine executeCreate
Thanks for any help with this, I'm very new to the Symfony framework so just trying to get my head around it.

I want to be able to intercept a submitted form from the admin area and modify the data.

Here's what I've got so far (in basic form)..

/apps/backend/modules/proposition/actions/action.class.php

```<code>class propositionActions extends autoPropositionActions {

  public function executeCreate(sfWebRequest $request) {
    // modify the name
    $name = $request->getParameter('name');
    $name = $name . ' is an idiot';
    $request->setParameter('name', $name);

    return parent::executeCreate($request);
  }

}</code>```

My form does contain a name field:

/apps/backend/modules/proposition/config/generator.yml

```<code>generator:
  class: sfDoctrineGenerator
  param:
    model_class:           Proposition
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          proposition
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~
      form:
        display: [name, icon, overview, published]
</code>```

I'm not sure if that's the file you need to see of not, but it's definitely in the HTML:

```<code><input type="text" id="proposition_name" name="proposition[name]"></code>```

When I submit the form it just saves my name. I want it to save my name appending ' is an idiot'.

Many thanks

答:
Why do want to do it in your action? I think most suitable place is form itself.

You can modify value of any column by adding update*Column method:

```<code>class PropositionForm extends BasePropositionForm
{
  public function updateNameColumn($name)
  {
    return $name . ' is an idiot';
  }
}
</code>```

Note: If you don't want the " is an idiot" string appended in other places your form is used you can subclass the original form and add your method there (i.e. in AdminPropositionForm).

You can change the form used with admin generated module by overloading getFormClass() method in your module's configuration class (propositionGeneratorConfiguration). It should return the name of form class you want to use.

Note 2: You have to accessed form values differently:

```<code>$proposition = $request->getParameter('proposition', array());
$name = $proposition['name'];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Thanks for any help with this, I'm very new to the Symfony framework so just trying to get my head around it.

I want to be able to intercept a submitted form from the admin area and modify the data.

Here's what I've got so far (in basic form)..

/apps/backend/modules/proposition/actions/action.class.php

class propositionActions extends autoPropositionActions {

  public function executeCreate(sfWebRequest $request) {
    // modify the name
    $name = $request->getParameter('name');
    $name = $name . ' is an idiot';
    $request->setParameter('name', $name);

    return parent::executeCreate($request);
  }

}

My form does contain a name field:

/apps/backend/modules/proposition/config/generator.yml

generator:
  class: sfDoctrineGenerator
  param:
    model_class:           Proposition
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          proposition
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~
      form:
        display: [name, icon, overview, published]

I'm not sure if that's the file you need to see of not, but it's definitely in the HTML:

<input type="text" id="proposition_name" name="proposition[name]">

When I submit the form it just saves my name. I want it to save my name appending ' is an idiot'.

Many thanks

Body:
Why do want to do it in your action? I think most suitable place is form itself.

You can modify value of any column by adding update*Column method:

class PropositionForm extends BasePropositionForm
{
  public function updateNameColumn($name)
  {
    return $name . ' is an idiot';
  }
}

Note: If you don't want the " is an idiot" string appended in other places your form is used you can subclass the original form and add your method there (i.e. in AdminPropositionForm).

You can change the form used with admin generated module by overloading getFormClass() method in your module's configuration class (propositionGeneratorConfiguration). It should return the name of form class you want to use.

Note 2: You have to accessed form values differently:

$proposition = $request->getParameter('proposition', array());
$name = $proposition['name'];


问:
Error using glm::vec< 3 , double >
I am using glm on Windows and OS X.

glm::vec< 3 , double > works fine on both. But when i try to compile this on
Linux it gives me the following message:

error: 'vec' is not a member of 'glm'

Same includes like on Windows and OS X but i can't get this compiling.
Any ideas?

答:
Yes! It works now. I think it was in fact a version thing. I deleted the old 'glm' directory in /usr/include and downloaded the newest version.

@Quentin  @Jeka - Thank you :)

Title: Error using glm::vec< 3 , double >


问:
Change the text in a field with a VBA function
I'm currently working on a database in Access which has a table (Pro_Cons) who compares the pros and cons of different product-types. This table has 3 columns; Type (Product_type), Pros (Pro) and Cons.
For each of product-type I created a form which includes the pro- and the cons-field of the according type out of this table.
For adding new text to this fields I'm creating a VBA-function which is triggered by a button-click.

Because nothing worked as supposed to, I created the following function, which should only replace the Pro -field of the product type1 to change1.

Access doesnt throw an error, but nothing changes in the table.

Has someone an idea whats happening here?

```<code>Sub Change_Pos_Inf()

Dim db As DAO.Database
Dim rst As DAO.Recordset

Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String

Set db = CurrentDb()

strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst

   If .RecordCount > 0 Then

    .MoveFirst

    .Edit

    !Pro.Value = strNew

    .Update

   End If
End With
End Sub
</code>```

答:
Please try the following code. It corrects your WHERE clause:</p>

```<code>Sub Change_Pos_Inf()

Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String

Set db = CurrentDb()

strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type= '" & strProduct_type & "';"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst

   If Not rst.EOF Then

    .Edit
        !Pro.Value = strNew
    .Update
   Else
       MsgBox "No Record found!!"
   End If
End With
rst.Close
Set rst = Nothing
End Sub
</code>```

Body:
I'm currently working on a database in Access which has a table (Pro_Cons) who compares the pros and cons of different product-types. This table has 3 columns; Type (Product_type), Pros (Pro) and Cons.
For each of product-type I created a form which includes the pro- and the cons-field of the according type out of this table.
For adding new text to this fields I'm creating a VBA-function which is triggered by a button-click.

Because nothing worked as supposed to, I created the following function, which should only replace the Pro -field of the product type1 to change1.

Access doesnt throw an error, but nothing changes in the table.

Has someone an idea whats happening here?

Sub Change_Pos_Inf()

Dim db As DAO.Database
Dim rst As DAO.Recordset

Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String

Set db = CurrentDb()

strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst

   If .RecordCount > 0 Then

    .MoveFirst

    .Edit

    !Pro.Value = strNew

    .Update

   End If
End With
End Sub

Body:
Please try the following code. It corrects your WHERE clause:

Sub Change_Pos_Inf()

Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String

Set db = CurrentDb()

strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type= '" & strProduct_type & "';"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst

   If Not rst.EOF Then

    .Edit
        !Pro.Value = strNew
    .Update
   Else
       MsgBox "No Record found!!"
   End If
End With
rst.Close
Set rst = Nothing
End Sub


问:
Mongodb load collection by ID
Probably something very simple here.
I have 2 mongoDb collections, one (users) with an objectId and the other (listings) which has the userId.

I want to get the documents in the listing collection by searching the objectId (currentUser._id).

How would i do this?

Component for page i want to display the listings on:

```<code>export class ManageComponent implements OnInit {
    listing : Listing;
    listings: Listing[] = [];
currentUser: User;

constructor(
    private listingService: ListingService,
    private userService: UserService) {
        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
     }

ngOnInit() {
    this.loadAllListings();
}

private loadAllListings() {
    this.listingService.getAll().subscribe(listings => { this.listings = listings; });
}

private loadById(userId: string) {
    this.listingService.getById(userId).subscribe(listings => { this.listings = listings});
    }
}
</code>```

I have a listing service that is used to for the CRUD operations (some omitted)

```<code>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { Listing } from '../_models/index';

@Injectable()
export class ListingService {

constructor(private http: Http) { }

getAll() {
    return this.http.get('/listings').map((response: Response) => response.json());
}

getById(_id: string) {
    return this.http.get('/listings/' + _id).map((response: Response) => response.json());
}

getByUserId(userId: string) {
    return this.http.get('/listings/' + userId).map((response: Response) => response.json());
}

create(listing: Listing) {
    return this.http.post('/listings/add', listing);
}
</code>```

Server side listing controller which uses the server side service (see below):

```<code>function getRelevant(req, res) {
listingService.getByUserId(req.listing.sub)
    .then(function (listing) {
        if (listing) {
            res.send(listing);
        } else {
            res.sendStatus(404);
        }
    })
    .catch(function (err) {
        res.status(400).send(err);
    });
}
</code>```

Server side listing service:

```<code>function getByUserId(userId) {
var deferred = Q.defer();

db.listings.findById(userId, function (err, listing) {
    if (err) deferred.reject(err.name + ': ' + err.message);

    if (listing) {
        // return listing
        deferred.resolve(listing);
    } else {
        // listing not found
        deferred.resolve();
    }
});

return deferred.promise;
}
</code>```

答:
MongoDB's function findById() will find the current model's documents by Id on which the function is operated (db.listings.findById() will find All Listings by Listing Id).

That said, if you want to find by other criteria that is in your model (listing). You need to do find({query}).

Specifically in your case, you'll need to:

```<code>const query = {userId: userIdThatIsPassedIn};
db.listings.find(query).exec(callback);
</code>```

Title: Mongodb load collection by ID

Body:
Probably something very simple here.
I have 2 mongoDb collections, one (users) with an objectId and the other (listings) which has the userId.

I want to get the documents in the listing collection by searching the objectId (currentUser._id).

How would i do this?

Component for page i want to display the listings on:

export class ManageComponent implements OnInit {
    listing : Listing;
    listings: Listing[] = [];
currentUser: User;

constructor(
    private listingService: ListingService,
    private userService: UserService) {
        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
     }

ngOnInit() {
    this.loadAllListings();
}

private loadAllListings() {
    this.listingService.getAll().subscribe(listings => { this.listings = listings; });
}

private loadById(userId: string) {
    this.listingService.getById(userId).subscribe(listings => { this.listings = listings});
    }
}

I have a listing service that is used to for the CRUD operations (some omitted)

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { Listing } from '../_models/index';

@Injectable()
export class ListingService {

constructor(private http: Http) { }

getAll() {
    return this.http.get('/listings').map((response: Response) => response.json());
}

getById(_id: string) {
    return this.http.get('/listings/' + _id).map((response: Response) => response.json());
}

getByUserId(userId: string) {
    return this.http.get('/listings/' + userId).map((response: Response) => response.json());
}

create(listing: Listing) {
    return this.http.post('/listings/add', listing);
}

Server side listing controller which uses the server side service (see below):

function getRelevant(req, res) {
listingService.getByUserId(req.listing.sub)
    .then(function (listing) {
        if (listing) {
            res.send(listing);
        } else {
            res.sendStatus(404);
        }
    })
    .catch(function (err) {
        res.status(400).send(err);
    });
}

Server side listing service:

function getByUserId(userId) {
var deferred = Q.defer();

db.listings.findById(userId, function (err, listing) {
    if (err) deferred.reject(err.name + ': ' + err.message);

    if (listing) {
        // return listing
        deferred.resolve(listing);
    } else {
        // listing not found
        deferred.resolve();
    }
});

return deferred.promise;
}

Body:
MongoDB's function findById() will find the current model's documents by Id on which the function is operated (db.listings.findById() will find All Listings by Listing Id).

That said, if you want to find by other criteria that is in your model (listing). You need to do find({query}).

Specifically in your case, you'll need to:

const query = {userId: userIdThatIsPassedIn};
db.listings.find(query).exec(callback);


问:
EventBus comunication between activity and service
I'm working on an Android application with EventBus library. I have an activity and a service. I want to to fire an event from activity and receive it on service.

The activity is:

```<code>public class MainActivity extends AppCompatActivity {

    public static final String TAG="ACTIVITY";

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartEvent event) {
        Log.d(TAG, "Received message");
        Snackbar.make(fab, "Stop task", Snackbar.LENGTH_LONG).show();
        txtMessage.setText(event.message);
    };

    FloatingActionButton fab;

    TextView txtMessage;

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

        txtMessage=findViewById(R.id.txtMessage);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Start background process", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                txtMessage.setText("Begin");
                Log.d(TAG,Thread.currentThread().getName()+ " ");
                EventBus.getDefault().post(new StartEvent());
            }
        });
    }

    @Override
    protected void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        // registriamo un receiver per ricevere una notifica alla fine del servizio in background
        EventBus.getDefault().register(this);
        super.onResume();
    }

}
</code>```

The service is:

```<code>public class MyService extends Service {
    public static final String TAG="SERVICE";

    public MyService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY_COMPATIBILITY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(StartEvent event){
        Log.d(TAG, "BEGIN process in background su thread "+Thread.currentThread().getName());

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "END processo in background su thread "+Thread.currentThread().getName());

        MessageEvent message=new MessageEvent();
        message.message="Operazione in background terminata!";
        EventBus.getDefault().post(message);
    }

}
</code>```

The manifest is:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication6">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>
</code>```

When i press button on activity to start background task, EventBus show me the following message on logcat:

```<code>ACTIVITY: main
EventBus: No subscribers registered for event class xx.StartEvent
EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
</code>```

What is wrong?

答:
The service should be running before it can receive events.

If it is not running it is not registered, and if it is not registered you see the no subscribers message.

Body:
I'm working on an Android application with EventBus library. I have an activity and a service. I want to to fire an event from activity and receive it on service.

The activity is:

public class MainActivity extends AppCompatActivity {

    public static final String TAG="ACTIVITY";

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartEvent event) {
        Log.d(TAG, "Received message");
        Snackbar.make(fab, "Stop task", Snackbar.LENGTH_LONG).show();
        txtMessage.setText(event.message);
    };

    FloatingActionButton fab;

    TextView txtMessage;

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

        txtMessage=findViewById(R.id.txtMessage);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Start background process", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                txtMessage.setText("Begin");
                Log.d(TAG,Thread.currentThread().getName()+ " ");
                EventBus.getDefault().post(new StartEvent());
            }
        });
    }

    @Override
    protected void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        // registriamo un receiver per ricevere una notifica alla fine del servizio in background
        EventBus.getDefault().register(this);
        super.onResume();
    }

}

The service is:

public class MyService extends Service {
    public static final String TAG="SERVICE";

    public MyService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY_COMPATIBILITY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(StartEvent event){
        Log.d(TAG, "BEGIN process in background su thread "+Thread.currentThread().getName());

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "END processo in background su thread "+Thread.currentThread().getName());

        MessageEvent message=new MessageEvent();
        message.message="Operazione in background terminata!";
        EventBus.getDefault().post(message);
    }

}

The manifest is:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication6">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

When i press button on activity to start background task, EventBus show me the following message on logcat:

ACTIVITY: main
EventBus: No subscribers registered for event class xx.StartEvent
EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

What is wrong?


问:
nifi: which property should we add sql condition in querydatabasetable?
i am using QueryDatabaseTable processor in nifi-1.3 version. i have successfully connected with Mysql database.
the table i use is, User which has columns such as user_id,name,email,gender.

```<code>TableName: User
Columns To Return: User_id, Email
Maximum Value Columns: user_id
</code>```

with the above properties, i could successfully fetch the table with the columns (user_id,email) with the incremental records of user_id.

now i want to add some additional condition to the query.
suppose, simple condition "where gender='Male'".

as given in documentation https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.4.0/org.apache.nifi.processors.standard.QueryDatabaseTable/index.html , we can add additional where clause properties.

hence, i have added property in QueryDatabaseTable processor like below,

```<code>property  -   value
WHERE     -   gender='Male'
</code>```

but it does not work.

any help on this.

how to add additional conditional clause in QueryDatabaseTable and also how to debug this processor what query has run.

答: I believe you should put gender = 'Male' in the property called "Additional Where Clause", instead of adding new properties.</p>

Body:
i am using QueryDatabaseTable processor in nifi-1.3 version. i have successfully connected with Mysql database.
the table i use is, User which has columns such as user_id,name,email,gender.

TableName: User
Columns To Return: User_id, Email
Maximum Value Columns: user_id

with the above properties, i could successfully fetch the table with the columns (user_id,email) with the incremental records of user_id.

now i want to add some additional condition to the query.
suppose, simple condition "where gender='Male'".

as given in documentation https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.4.0/org.apache.nifi.processors.standard.QueryDatabaseTable/index.html , we can add additional where clause properties.

hence, i have added property in QueryDatabaseTable processor like below,

property  -   value
WHERE     -   gender='Male'

but it does not work.

any help on this.

how to add additional conditional clause in QueryDatabaseTable and also how to debug this processor what query has run.


问:
Update multiple records with one form in MYSQL
I need to update multiple records in a single form but am not sure how to proceed. The following is the code I am using to insert the fields into the database originally.

```<code>$case = date(ymdHis);

//register into database
if (!empty($p1_firstname)) mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p1_firstname','$p1_lastname ''$city’)");

if (!empty($p2_firstname)) $register_case = mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p2_firstname','$p2_lastname','$city’)");
</code>```

I have an update form which displays data for however many records there are for each "case". How can I use UPDATE to edit information in different rows when each row has the same identifier ($case)?

答: You don't. You reorganize your database to where it actually makes sense then proceed from there.</p>

Body:
I need to update multiple records in a single form but am not sure how to proceed. The following is the code I am using to insert the fields into the database originally.

$case = date(ymdHis);

//register into database
if (!empty($p1_firstname)) mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p1_firstname','$p1_lastname ''$city’)");

if (!empty($p2_firstname)) $register_case = mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p2_firstname','$p2_lastname','$city’)");

I have an update form which displays data for however many records there are for each "case". How can I use UPDATE to edit information in different rows when each row has the same identifier ($case)?


问:
Having problems with my Guess the number game python 3
I've been working out with my python 3 and I made a simple project which is a game "Guess the number", I'm having problems here that i could't understand. The game was find until i'm adding something in the script which is to check if guess = input() is a number. And i messed up, when i run it, it always keep sending me error messages.
Can you guys check my code and if can how to check if guess = input() is a number.

Zelandini

```<code>import random

def main():
    USER = input('Hello there wht is your name?')
    print('Hello, ' + USER + '')
    question = input('Do you want to play a game? [Yes/No]')

    if question == 'n' or question == 'No' or question == 'no' or question == 'N' or question == 'NO':
        print('Bye, ' + USER + '!')

    if question == 'y' or question == 'Yes' or question == 'Y' or question == 'yes':
        print("Okay, the game is to guess my number,")

        replay()

def replay():
    tries = 1
    number = random.randint(1, 10)

    play_again = True

    print("I'm thinking a number between 1 and 10")
    Guess = input("Have a guess?")

    while play_again:

        if Guess > number:
            print("Go lower, your number is too big")

        if Guess < number:
            print("Go higher, you number is to small")

    while Guess != number:
        tries += 1
        Guess = int(input("Try again?"))

        if tries == 4:
            print('You have out of tries')

            print("\nWould you like to play again?")

            response = input("> ").lower()
            if response not in ("yes", "y"):
                play_again = False
                print("Bye!")

            replay()

        if Guess > number:
            print("Go lower, your number is too big")

        if Guess < number:
            print("Go higher, you number is to small")

    if Guess == number:
        print("Congratulations! You've got it")
        print("\nWould you like to play again?")

    response = input("> ").lower()
    if response not in ("yes", "y"):
        play_again = False
        print("Bye you Sad!")

    replay()
if __name__ == "__replay__":
    replay()

if __name__ == "__main__":
    main()
</code>```

答:
If you run this slightly adjusted code (INDENTATIONS & SCOPES) you will no longer receive non-stop error messages and can focus on getting the functionality right. I won't spoil that for you, happy debugging. :)

```<code>import random

def main():
USER = input('Hello there wht is your name?')
print('Hello, ' + USER + '')
question = input('Do you want to play a game? [Yes/No]')

if question == 'n' or question == 'No' or question == 'no' or question == 'N' or question == 'NO':
    print('Bye, ' + USER + '!')

if question == 'y' or question == 'Yes' or question == 'Y' or question == 'yes':
    print("Okay, the game is to guess my number,")

replay()

def replay():
tries = 1
number = random.randint(1, 10)

play_again = True

while play_again:

print("I'm thinking a number between 1 and 10")
guess = input("Have a guess?")

while guess != number:
    tries += 1
    guess = int(input("Try again?"))

    if tries == 4:
        print('You have out of tries')

        print("\nWould you like to play again?")

        response = input("> ").lower()
        if response not in ("yes", "y"):
            play_again = False
            print("Bye!")

        replay()

    if guess > number:
        print("Go lower, your number is too big")

    if guess < number:
        print("Go higher, you number is to small")

if guess == number:
print("Congratulations! You've got it")
print("\nWould you like to play again?")

response = input("> ").lower()
if response not in ("yes", "y"):
    play_again = False
    print("Bye you Sad!")

replay()

if name == "main": main()
</code>```

Body:
I've been working out with my python 3 and I made a simple project which is a game "Guess the number", I'm having problems here that i could't understand. The game was find until i'm adding something in the script which is to check if guess = input() is a number. And i messed up, when i run it, it always keep sending me error messages.
Can you guys check my code and if can how to check if guess = input() is a number.

Zelandini

import random

def main():
    USER = input('Hello there wht is your name?')
    print('Hello, ' + USER + '')
    question = input('Do you want to play a game? [Yes/No]')

    if question == 'n' or question == 'No' or question == 'no' or question == 'N' or question == 'NO':
        print('Bye, ' + USER + '!')

    if question == 'y' or question == 'Yes' or question == 'Y' or question == 'yes':
        print("Okay, the game is to guess my number,")

        replay()

def replay():
    tries = 1
    number = random.randint(1, 10)

    play_again = True

    print("I'm thinking a number between 1 and 10")
    Guess = input("Have a guess?")

    while play_again:

        if Guess > number:
            print("Go lower, your number is too big")

        if Guess < number:
            print("Go higher, you number is to small")

    while Guess != number:
        tries += 1
        Guess = int(input("Try again?"))

        if tries == 4:
            print('You have out of tries')

            print("\nWould you like to play again?")

            response = input("> ").lower()
            if response not in ("yes", "y"):
                play_again = False
                print("Bye!")

            replay()

        if Guess > number:
            print("Go lower, your number is too big")

        if Guess < number:
            print("Go higher, you number is to small")

    if Guess == number:
        print("Congratulations! You've got it")
        print("\nWould you like to play again?")

    response = input("> ").lower()
    if response not in ("yes", "y"):
        play_again = False
        print("Bye you Sad!")

    replay()
if __name__ == "__replay__":
    replay()

if __name__ == "__main__":
    main()

Body:
If you run this slightly adjusted code (INDENTATIONS & SCOPES) you will no longer receive non-stop error messages and can focus on getting the functionality right. I won't spoil that for you, happy debugging. :)

import random

def main():
USER = input('Hello there wht is your name?')
print('Hello, ' + USER + '')
question = input('Do you want to play a game? [Yes/No]')

if question == 'n' or question == 'No' or question == 'no' or question == 'N' or question == 'NO':
    print('Bye, ' + USER + '!')

if question == 'y' or question == 'Yes' or question == 'Y' or question == 'yes':
    print("Okay, the game is to guess my number,")

replay()

def replay():
tries = 1
number = random.randint(1, 10)

play_again = True

while play_again:

print("I'm thinking a number between 1 and 10")
guess = input("Have a guess?")

while guess != number:
    tries += 1
    guess = int(input("Try again?"))

    if tries == 4:
        print('You have out of tries')

        print("\nWould you like to play again?")

        response = input("> ").lower()
        if response not in ("yes", "y"):
            play_again = False
            print("Bye!")

        replay()

    if guess > number:
        print("Go lower, your number is too big")

    if guess < number:
        print("Go higher, you number is to small")

if guess == number:
print("Congratulations! You've got it")
print("\nWould you like to play again?")

response = input("> ").lower()
if response not in ("yes", "y"):
    play_again = False
    print("Bye you Sad!")

replay()

if name == "main": main()


问:
composing a dateframe with an index of a datetime
I have two lists but one is a datetime. How can I combine to form a date frame with index of this datetime and the values of lista2?</p>

```<code>lista1 = [datetime.datetime(2017, 11, 11, 0, 0), datetime.datetime(2017, 11, 12, 0, 0), datetime.datetime(2017, 11, 13, 0, 0)]
lista2 = [31488, 14335, 89]
</code>```

答:
You can use the index parameter from the constructor to specify a list as indices, and use the other one as data:

```<code>pd.DataFrame(lista2,index=lista1)
</code>```

For your sample data, this gives:

```<code>>>> pd.DataFrame(lista2,index=lista1)
                0
2017-11-11  31488
2017-11-12  14335
2017-11-13     89
</code>```

Body:
I have two lists but one is a datetime. How can I combine to form a date frame with index of this datetime and the values of lista2?

lista1 = [datetime.datetime(2017, 11, 11, 0, 0), datetime.datetime(2017, 11, 12, 0, 0), datetime.datetime(2017, 11, 13, 0, 0)]
lista2 = [31488, 14335, 89]

Body:
You can use the index parameter from the constructor to specify a list as indices, and use the other one as data:

pd.DataFrame(lista2,index=lista1)

For your sample data, this gives:

>>> pd.DataFrame(lista2,index=lista1)
                0
2017-11-11  31488
2017-11-12  14335
2017-11-13     89


Title: Converting NAs to 0 and non-NA's to 1s in R

Body:
data <- matrix(data = c(1:9),nrow = 3, ncol = 3)
data[3,3] <- NA

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6   NA

data[data > 0] <- 1
data[is.na(data)] <- 0

      [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    0


问:
Getting data from online MySQL DB in "onCreate" method of Activity
I am working on application that needs to get data from online MySQL database and show it as list in activity layout.

Problem is that my application gets error " Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"

In onCreate method I am calling asyncTask class to get the data from server and than below that line of code I set that data through adapter to listview which is my layout.
When starting that activity, I get the error.

Should I get the data from server before starting Activity? Or the problem is something else?
My php file is working okay when I check it in browser.

Here is onCreate Method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    final ListView listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();

    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    ArrayAdapter<Invoice> adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1, invoices);
    listView1.setAdapter(adapter);
}
</code>```

EDIT:

I fixed it as You all suggested, now there is no error, activity opens, but it still doesn't show any data from online database..
Here is edited onCreate() method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1);
    listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();
    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    adapter.notifyDataSetChanged();
}
</code>```

and here is AsyncTask class:

```<code>public class InvoiceDownloader extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        try {
            response += getHttpContent(params[0]);
        } catch (IOException e) {
            Log.e("error", e.toString());
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        adapter.addAll(invoices);
        listView1.setAdapter(adapter);

        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    public String getHttpContent(String urlStr) throws IOException {

        String response = "";

        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String json;
            while ((json = bufferedReader.readLine()) != null) {
                sb.append(json + "\n");
            }

            JSONArray jsonArray = new JSONArray(sb.toString().trim());

            for (int i = 0; i < jsonArray.length(); i++) {
                Invoice invoice = new Invoice();
                JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");

                System.out.println("Company Name 1: " + companyNameOne + " Company Name 2: " + companyNameTwo + " address: " + address + " postalCode: " + postalCode + " city: " + city + " oib: " + oib + " email: " + email + " completed: " + completed + " work order num: " + workOrderNumber + " price: " + price);

                invoice.setCompanyNameOne(companyNameOne);
                invoice.setCompanyNameTwo(companyNameTwo);
                invoice.setAddress(address);
                invoice.setPostalCode(postalCode);
                invoice.setCity(city);
                invoice.setOib(oib);
                invoice.setEmail(email);
                invoice.setCompleted(completed);
                invoice.setWorkOrderNumber(workOrderNumber);
                invoice.setPrice(price);

                invoices.add(invoice);
            }
            return response;
        } catch (Exception e) {
            return null;
        }
    }
}
</code>```

2nd EDIT:

I got it. Sorry, this issue not showing data after fixing error was my mistake. In this part:

```<code>JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");
</code>```

those strings in (" ") ALL had to be small letters, because I wrote them that way in my PHP.

Thank You all for Your help.

答:
You are passing non initialized collection (null) into adapter. Thats why you are getting NullPointerException when adapter trying to get size of the collection.
You need to do this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    ...
    invoices = new ArrayList<>();
    ArrayAdapter<Invoice> adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1, invoices);
    listView1.setAdapter(adapter);
}
</code>```

and then populate collection with new items in onPostExecute of AsyncTask and call adapter.notifyDataSetChanged

Body:
I am working on application that needs to get data from online MySQL database and show it as list in activity layout.

Problem is that my application gets error " Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"

In onCreate method I am calling asyncTask class to get the data from server and than below that line of code I set that data through adapter to listview which is my layout.
When starting that activity, I get the error.

Should I get the data from server before starting Activity? Or the problem is something else?
My php file is working okay when I check it in browser.

Here is onCreate Method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    final ListView listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();

    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    ArrayAdapter<Invoice> adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1, invoices);
    listView1.setAdapter(adapter);
}

EDIT:

I fixed it as You all suggested, now there is no error, activity opens, but it still doesn't show any data from online database..
Here is edited onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1);
    listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();
    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    adapter.notifyDataSetChanged();
}

and here is AsyncTask class:

public class InvoiceDownloader extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        try {
            response += getHttpContent(params[0]);
        } catch (IOException e) {
            Log.e("error", e.toString());
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        adapter.addAll(invoices);
        listView1.setAdapter(adapter);

        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    public String getHttpContent(String urlStr) throws IOException {

        String response = "";

        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String json;
            while ((json = bufferedReader.readLine()) != null) {
                sb.append(json + "\n");
            }

            JSONArray jsonArray = new JSONArray(sb.toString().trim());

            for (int i = 0; i < jsonArray.length(); i++) {
                Invoice invoice = new Invoice();
                JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");

                System.out.println("Company Name 1: " + companyNameOne + " Company Name 2: " + companyNameTwo + " address: " + address + " postalCode: " + postalCode + " city: " + city + " oib: " + oib + " email: " + email + " completed: " + completed + " work order num: " + workOrderNumber + " price: " + price);

                invoice.setCompanyNameOne(companyNameOne);
                invoice.setCompanyNameTwo(companyNameTwo);
                invoice.setAddress(address);
                invoice.setPostalCode(postalCode);
                invoice.setCity(city);
                invoice.setOib(oib);
                invoice.setEmail(email);
                invoice.setCompleted(completed);
                invoice.setWorkOrderNumber(workOrderNumber);
                invoice.setPrice(price);

                invoices.add(invoice);
            }
            return response;
        } catch (Exception e) {
            return null;
        }
    }
}

2nd EDIT:

I got it. Sorry, this issue not showing data after fixing error was my mistake. In this part:

JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");

those strings in (" ") ALL had to be small letters, because I wrote them that way in my PHP.

Thank You all for Your help.

Body:
You are passing non initialized collection (null) into adapter. Thats why you are getting NullPointerException when adapter trying to get size of the collection.
You need to do this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    ...
    invoices = new ArrayList<>();
    ArrayAdapter<Invoice> adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1, invoices);
    listView1.setAdapter(adapter);
}

and then populate collection with new items in onPostExecute of AsyncTask and call adapter.notifyDataSetChanged


问:
TASK_RUNNING process state
I am reading "Linux Kernel Development". It has definition about "TASK_RUNNING"

"TASK_RUNNING—The process is runnable; it is either currently running or on a runqueue waiting to run". My question is why don't we have two separate state for "currently running" and "on a runqueue waiting to run". Like TASK__RUNNING and TASK_READYTORUN.

1) because when I first look at word "TASK_RUNNING", I thought it just refers to a running process state
2)  more exact definition would avoid many troubles

So do we have strong reasons not to do this ??

答:
The process is runnable.

Futher state separation has no sence from the view of users of this field.

Because users of that state are not interact with a scheduler, knowing whether a process is scheduled or not is useless: immediately after you obtain that knowledge, the scheduler may change that property, so your knowledge becomes invalid.

As for name TASK_RUNNING, only Linux developers knows why it is choosen. It could be historic reason, or intentionally: "Think of the process as if it is running."

Title: TASK_RUNNING process state


问:
jQuery: How to select only one radio with same classes?
I have groups of radio buttons at different levels with same class in each level:

```<code><div> <!-- radio group one -->
  <input type="radio" name="rdo1" class="some1 text4 radio_group_1" />
  <input type="radio" name="rdo2" class="some2 text5 radio_group_1" />
  <input type="radio" name="rdo3" class="some3 text6 radio_group_1" />
</div>
<div> <!-- radio group two -->
  <input type="radio" name="rdo4" class="some1 text4 radio_group_2 other1" />
  <input type="radio" name="rdo5" class="some2 text5 radio_group_2 other2" />
  <input type="radio" name="rdo6" class="some3 text6 radio_group_2 other3" />
</div>
... <!-- radio group three (and so on) -->
</code>```

I can't change the radio names (due to server limitations). So the only thing that I have is the classes that starts with 'radio_group_'. I use this solution and this without success because the class names are in the middle of other class names.

How can I select radios with same class name and make them act like group radios?

答:
```<code>$("input[type=radio]").click(function () {
    var thisClass = $(this).attr("class");
    console.log(thisClass);

    $('.'+thisClass).each(function () {
        $(this).prop("checked", false);
    });
    $(this).prop("checked", true);
});
</code>```

<p>You have multiple classes so select class you want to pass to each and it will work fine </p>

Body:
I have groups of radio buttons at different levels with same class in each level:

  <input type="radio" name="rdo1" class="some1 text4 radio_group_1" />
  <input type="radio" name="rdo2" class="some2 text5 radio_group_1" />
  <input type="radio" name="rdo3" class="some3 text6 radio_group_1" />

  <input type="radio" name="rdo4" class="some1 text4 radio_group_2 other1" />
  <input type="radio" name="rdo5" class="some2 text5 radio_group_2 other2" />
  <input type="radio" name="rdo6" class="some3 text6 radio_group_2 other3" />

...

I can't change the radio names (due to server limitations). So the only thing that I have is the classes that starts with 'radio_group_'. I use this solution and this without success because the class names are in the middle of other class names.

How can I select radios with same class name and make them act like group radios?

Body:
$("input[type=radio]").click(function () {
    var thisClass = $(this).attr("class");
    console.log(thisClass);

    $('.'+thisClass).each(function () {
        $(this).prop("checked", false);
    });
    $(this).prop("checked", true);
});

You have multiple classes so select class you want to pass to each and it will work fine