问:
Tensorflow- I'm getting those labels, is that expected?
I have the following convolutional neural network (CNN), but wasn't trained on many  images. In this CNN, I'm entering an image and trying to see what label would the model return. The model returned two labels for the two images added. The labels were [1 1], while I was expecting them to be [0 0]. But, since I didn't train a lot of images, is that expected?

```<code>import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import tensorflow as tf

learning_rate = 0.001

data = cifar_tools.read_data()

x = tf.placeholder(tf.float32, [None, 150 * 150])
y = tf.placeholder(tf.float32, [None, 2])

w1 = tf.Variable(tf.random_normal([5, 5, 1, 64]))
b1 = tf.Variable(tf.random_normal([64]))

w2 = tf.Variable(tf.random_normal([5, 5, 64, 64]))
b2 = tf.Variable(tf.random_normal([64]))

w3 = tf.Variable(tf.random_normal([38*38*64, 1024]))
b3 = tf.Variable(tf.random_normal([1024]))

w_out = tf.Variable(tf.random_normal([1024, 2]))
b_out = tf.Variable(tf.random_normal([2]))

def conv_layer(x,w,b):
    conv = tf.nn.conv2d(x,w,strides=[1,1,1,1], padding = 'SAME')
    conv_with_b = tf.nn.bias_add(conv,b)
    conv_out = tf.nn.relu(conv_with_b)
    return conv_out

def maxpool_layer(conv,k=2):
    return tf.nn.max_pool(conv, ksize=[1,k,k,1], strides=[1,k,k,1], padding='SAME')

def model():
    x_reshaped = tf.reshape(x, shape=[-1, 150, 150, 1])

    conv_out1 = conv_layer(x_reshaped, w1, b1)
    maxpool_out1 = maxpool_layer(conv_out1)
    norm1 = tf.nn.lrn(maxpool_out1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
    conv_out2 = conv_layer(norm1, w2, b2)
    norm2 = tf.nn.lrn(conv_out2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
    maxpool_out2 = maxpool_layer(norm2)

    maxpool_reshaped = tf.reshape(maxpool_out2, [-1, w3.get_shape().as_list()[0]])
    local = tf.add(tf.matmul(maxpool_reshaped, w3), b3)
    local_out = tf.nn.relu(local)

    out = tf.add(tf.matmul(local_out, w_out), b_out)
    return out

model_op = model()

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model_op, y))
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

res_model=tf.argmax(model_op, 1) # testing
correct_pred = tf.equal(tf.argmax(model_op, 1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    batch_size = len(data)
    # Save model
    saver = tf.train.Saver()
    # Restore model
    saver = tf.train.import_meta_graph('C:\\Users\\abc\\Desktop\\\Testing\\mymodel.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    tf.add_to_collection("vars", w1)
    tf.add_to_collection("vars", b1)
    all_vars = tf.get_collection('vars')
    for v in all_vars:
        v_ = sess.run(v)

    print('model restored')

    # Test on unlabeled data
    for i in range(0, len(data), batch_size):
        new_data = data[i:i+batch_size, :] #testing
        res_new = sess.run(res_model, feed_dict={x: new_data})
        print('LABEL IS')
        print(res_new)
</code>```

Thanks.

答:
Even if you train your network on a lot of data, having two misclassified images in your test set is not unexpected. So in general, I don't think that you can infer much when you consider only two test cases. You should definitely increase the amount of your test images to be able to assess the performance of your network.

Keep in mind that even before you start training, you could get by random correct classification for some images. Recall that your weight matrices are initialized randomly. So if you have 2 classes and you apply your untrained network, probably around 50% of your images will be classified correctly by random (and 50% will not).

In addition, depending on the type of images that you use and other factors, you may need more data to be able to train the network well enough. You can read here some discussion about how to determine if you have enough training data.

Body:
I have the following convolutional neural network (CNN), but wasn't trained on many  images. In this CNN, I'm entering an image and trying to see what label would the model return. The model returned two labels for the two images added. The labels were [1 1], while I was expecting them to be [0 0]. But, since I didn't train a lot of images, is that expected?

import numpy as np
import matplotlib.pyplot as plt
import cifar_tools
import tensorflow as tf

learning_rate = 0.001

data = cifar_tools.read_data()

x = tf.placeholder(tf.float32, [None, 150 * 150])
y = tf.placeholder(tf.float32, [None, 2])

w1 = tf.Variable(tf.random_normal([5, 5, 1, 64]))
b1 = tf.Variable(tf.random_normal([64]))

w2 = tf.Variable(tf.random_normal([5, 5, 64, 64]))
b2 = tf.Variable(tf.random_normal([64]))

w3 = tf.Variable(tf.random_normal([38*38*64, 1024]))
b3 = tf.Variable(tf.random_normal([1024]))

w_out = tf.Variable(tf.random_normal([1024, 2]))
b_out = tf.Variable(tf.random_normal([2]))

def conv_layer(x,w,b):
    conv = tf.nn.conv2d(x,w,strides=[1,1,1,1], padding = 'SAME')
    conv_with_b = tf.nn.bias_add(conv,b)
    conv_out = tf.nn.relu(conv_with_b)
    return conv_out

def maxpool_layer(conv,k=2):
    return tf.nn.max_pool(conv, ksize=[1,k,k,1], strides=[1,k,k,1], padding='SAME')

def model():
    x_reshaped = tf.reshape(x, shape=[-1, 150, 150, 1])

    conv_out1 = conv_layer(x_reshaped, w1, b1)
    maxpool_out1 = maxpool_layer(conv_out1)
    norm1 = tf.nn.lrn(maxpool_out1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
    conv_out2 = conv_layer(norm1, w2, b2)
    norm2 = tf.nn.lrn(conv_out2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
    maxpool_out2 = maxpool_layer(norm2)

    maxpool_reshaped = tf.reshape(maxpool_out2, [-1, w3.get_shape().as_list()[0]])
    local = tf.add(tf.matmul(maxpool_reshaped, w3), b3)
    local_out = tf.nn.relu(local)

    out = tf.add(tf.matmul(local_out, w_out), b_out)
    return out

model_op = model()

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model_op, y))
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

res_model=tf.argmax(model_op, 1) # testing
correct_pred = tf.equal(tf.argmax(model_op, 1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    batch_size = len(data)
    # Save model
    saver = tf.train.Saver()
    # Restore model
    saver = tf.train.import_meta_graph('C:\\Users\\abc\\Desktop\\\Testing\\mymodel.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    tf.add_to_collection("vars", w1)
    tf.add_to_collection("vars", b1)
    all_vars = tf.get_collection('vars')
    for v in all_vars:
        v_ = sess.run(v)

    print('model restored')

    # Test on unlabeled data
    for i in range(0, len(data), batch_size):
        new_data = data[i:i+batch_size, :] #testing
        res_new = sess.run(res_model, feed_dict={x: new_data})
        print('LABEL IS')
        print(res_new)

Thanks.


来源: stackexchange

问:
Can you import a library from one repo into a web app in another repo using Webpack?
So I have a library with Vue.js components, and I have a Vue web app, that imports those components. Both run on Webpack and both are in separate repositories.

Before using webpack, I used browserify-hmr and could use npm link to import the library from my dev env into the web pack. Essentially, it did the same as import '../../../library/index.js'

With Webpack, I get an error like this:

```<code>ERROR  Failed to compile with 1 errors
1:16:18 PM

This dependency was not found:

* !!vue-style-loader!css-loader!../../../web-app/node_modules/vue-loader/lib/style-rewriter
?id=data-v-6afebbcb!sass-loader!../../../web-app/node_modules/vue-loader/lib/selector
?type=styles&index=0!./Component.vue in ../TheLibrary/src/Component.vue

To install it, you can run: npm install --save !!vue-style-loader!css-loader
!../../../web-app/node_modules/vue-loader/lib/style-rewriter?id=data-v-6afebbcb
!sass-loader!../../../web-app/node_modules/vue-loader/lib/selector?type=styles
&index=0!./Component.vue
</code>```

I'm trying to make changes to the library locally, and import it in my web app locally, too, without having to push up the library changes and pull the module updates from the web app. Is there anyway to do with with Webpack?

Also, the webpack project was built using this https://github.com/vuejs-templates/webpack

Update

The error is happening because the library has a dependency, https://www.npmjs.com/package/susy, which is not installed on the web app. As soon as I install that dependency on the web app, the error goes away.

Any ideas?

答: I think the best way in your case is to move your common functionality to npm package and use it into dependencies of both webpack projects. This is the right way!  </p>

ContentLicense: CC BY-SA 3.0

Body:
So I have a library with Vue.js components, and I have a Vue web app, that imports those components. Both run on Webpack and both are in separate repositories.

Before using webpack, I used browserify-hmr and could use npm link to import the library from my dev env into the web pack. Essentially, it did the same as import '../../../library/index.js'

With Webpack, I get an error like this:

ERROR  Failed to compile with 1 errors
1:16:18 PM

This dependency was not found:

* !!vue-style-loader!css-loader!../../../web-app/node_modules/vue-loader/lib/style-rewriter
?id=data-v-6afebbcb!sass-loader!../../../web-app/node_modules/vue-loader/lib/selector
?type=styles&index=0!./Component.vue in ../TheLibrary/src/Component.vue

To install it, you can run: npm install --save !!vue-style-loader!css-loader
!../../../web-app/node_modules/vue-loader/lib/style-rewriter?id=data-v-6afebbcb
!sass-loader!../../../web-app/node_modules/vue-loader/lib/selector?type=styles
&index=0!./Component.vue

I'm trying to make changes to the library locally, and import it in my web app locally, too, without having to push up the library changes and pull the module updates from the web app. Is there anyway to do with with Webpack?

Also, the webpack project was built using this https://github.com/vuejs-templates/webpack

Update

The error is happening because the library has a dependency, https://www.npmjs.com/package/susy, which is not installed on the web app. As soon as I install that dependency on the web app, the error goes away.

Any ideas?


问:
Cassandra python error no viable alternative at input 'SOURCE' ([SOURCE]...)">
When I try to run the following command from python (I am using the Cassandra Datastax Python Driver with Python 2.7.6)

```<code>cluster = Cluster([CASSANDRA_HOST], port=CASSANDRA_PORT, cql_version=CASSANDRA_CQL_VERSION, protocol_version=3)
session = cluster.connect(CASSANDRA_KEYSPACE)

NEW_ID = "9999999999"
CQL_FILE_NAME = "FNAME-"+NEW_ID+".cql"
cql_cmd = "SOURCE '~/dev/cql_files/"+ CQL_FILE_NAME + "'"
session.execute(cql_cmd)
</code>```

I get the error below:

```<code> File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 2012, in execute
    return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 3801, in result
    raise self._final_exception
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:0 no viable alternative at input 'SOURCE' ([SOURCE]...)">
</code>```

But when I run the same string from cqlsh it runs fine. Any ideas on what I should change? Thanks!

The string looks like this:

```<code>"SOURCE '~/dev/cql_files/FNAME-9999999999.cql'"
</code>```

答:
SOURCE is a command unique to cqlsh, it is not actually part of the CQL specification so you cannot use it using a client driver:

Important: The CQL shell commands described in this section work only within the cqlsh shell and are not accessible from drivers. CQL shell uses native protocol and the Datastax python driver to execute CQL commands on the connected Cassandra host. For configuration information, see the Cassandra 3.0 cassandra.yaml file.

Body:
When I try to run the following command from python (I am using the Cassandra Datastax Python Driver with Python 2.7.6)

cluster = Cluster([CASSANDRA_HOST], port=CASSANDRA_PORT, cql_version=CASSANDRA_CQL_VERSION, protocol_version=3)
session = cluster.connect(CASSANDRA_KEYSPACE)

NEW_ID = "9999999999"
CQL_FILE_NAME = "FNAME-"+NEW_ID+".cql"
cql_cmd = "SOURCE '~/dev/cql_files/"+ CQL_FILE_NAME + "'"
session.execute(cql_cmd)

I get the error below:

 File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 2012, in execute
    return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 3801, in result
    raise self._final_exception
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:0 no viable alternative at input 'SOURCE' ([SOURCE]...)">

But when I run the same string from cqlsh it runs fine. Any ideas on what I should change? Thanks!

The string looks like this:

"SOURCE '~/dev/cql_files/FNAME-9999999999.cql'"


问:
ProxyPassMatch regex does not match
Using Apache 2.2.15, I'm trying to set a ProxyPassMatch rule that matches the following request only when the "year" parameter is equal to 2015:

```<code>/my-servlet/DownloadPdf?param1=40978659700000&year=2015&param3=testrv%2540rv.com
</code>```

I know that the following configuration matches my request and works:

```<code>ProxyPassMatch /my-servlet/(.*)$ balancer://mycluster
</code>```

But I want something like this, and it doesn't work:

```<code>ProxyPassMatch /my-servlet/(.*year=2015.*)$ balancer://mycluster
</code>```

I have also tried other regex that match the request, unsucessfully:

```<code>ProxyPassMatch /my-servlet/.*year=2015.* balancer://mycluster
ProxyPassMatch /my-servlet/.*year=2015.*$ balancer://mycluster
</code>```

I don't understand what's wrong with my configuration?

答:
Excerpt from mod_proxy docs

```<code>The path is the name of a local virtual path; url is a partial URL for the remote server and cannot include a query string.
</code>```

Didn't test it, but a possible workaround:

```<code>RewriteEnginge On
RewriteCond %{QUERY_STRING} year=2015
RewriteRule (.*) balancer://mycluster [P]
</code>```

Let us know, if it did the job and even more so, if it didn't ;)

Title: ProxyPassMatch regex does not match

Body:
Using Apache 2.2.15, I'm trying to set a ProxyPassMatch rule that matches the following request only when the "year" parameter is equal to 2015:

/my-servlet/DownloadPdf?param1=40978659700000&year=2015&param3=testrv%2540rv.com

I know that the following configuration matches my request and works:

ProxyPassMatch /my-servlet/(.*)$ balancer://mycluster

But I want something like this, and it doesn't work:

ProxyPassMatch /my-servlet/(.*year=2015.*)$ balancer://mycluster

I have also tried other regex that match the request, unsucessfully:

ProxyPassMatch /my-servlet/.*year=2015.* balancer://mycluster
ProxyPassMatch /my-servlet/.*year=2015.*$ balancer://mycluster

I don't understand what's wrong with my configuration?

Body:
Excerpt from mod_proxy docs

The path is the name of a local virtual path; url is a partial URL for the remote server and cannot include a query string.

Didn't test it, but a possible workaround:

RewriteEnginge On
RewriteCond %{QUERY_STRING} year=2015
RewriteRule (.*) balancer://mycluster [P]

Let us know, if it did the job and even more so, if it didn't ;)


问:
best CMS for a custom and new employees?
we're moving to use an OPENSOURCE CMS system, for years we been using our own CMS, and it's time to move to OPENSOURCE. so which of Drupal, Joomla, WordPress is the best choice if

the team needs to learn it ...

supporting multi languages and RTL directions

easy to use ( for end users )

customization and templating

or if there are any other CMS that would make the process faster.

thanks all

答:
I give my vote to Joomla!  Joomla! has one of the most active support forums.  Ask a question it will be answered over 90% of the time.  There are numerous professional template sites that charge very little for single template usage.

Joomla! grows bigger and bigger by the day.  Just go to www.joomla.org and see for yourself.

Good luck.

ContentLicense: CC BY-SA 2.5


问:
How can I use python to iterate through multiple csv files and if a value is the same, update another value?
I'm trying to iterate through a few .csv files, and if a value is the same, add up the related entries. If a value is not the same, add that as a new row.

My current code is:

```<code>import pandas
s1011 = pandas.read_csv('goals/1011.csv', sep=',', usecols=(1,3,5))
s1011.dropna(how="all", inplace=True)
print s1011

s1112 = pandas.read_csv('goals/1112.csv', sep=',', usecols=(1,3,5))
s1112.dropna(how="all", inplace=True)
print s1112

s1213 = pandas.read_csv('goals/1213.csv', sep=',', usecols=(1,3,5))
s1213.dropna(how="all", inplace=True)
print s1213
</code>```

Currently this doesn't do much I know. It prints out 3 headings, Team, For & Against. It the prints out 20 football teams, how many goals they've scored, and how many conceded. I've tried using merge in python but it isn't suitable as it just makes one big table.

What I'm trying to do is open the multiple csv files, iterate through the list, if the Team is the same, add together goals for and goals against from each file. If Team has not been entered before, add a new row with new entries.

Is this possible using python?

Edit:

It currently prints

Team
  For
  Against

Man Utd
  86
  43

Man City
  83
  45

Chelsea
  89
  39

etc for 20 teams. So I want to update the For and Against entries by adding up the number of goals for each team over a number of seasons. Since it won't be the same 20 teams each season, I want to add a new row of entries if a team hasn't been in the league before.

答:
Assume you have the following csv's:

df1

Team For Against

Man Utd 86 43

Man City 83 45

Chelsea 89 39

df2

Team For Against

Man Utd 88 45

Man City 85 47

ICantNameATeam 91 41

You can first stack them using pandas.concat:

```<code>df_concat = pandas.concat([df1, df2], axis=0)
</code>```

which would give you:

df_concat

Team For Against

Man Utd 86 43

Man City 83 45

Chelsea 89 39

Man Utd 88 45

Man City 85 47

ICantNameATeam 91 41

Then you can use dataframe.groupby to take the sum:

```<code>df_sum = df_concat.groupby('Team').sum().reset_index()
</code>```

This will group the dataframe according to unique team names and take the sum of each column.

Body:
I'm trying to iterate through a few .csv files, and if a value is the same, add up the related entries. If a value is not the same, add that as a new row.

My current code is:

import pandas
s1011 = pandas.read_csv('goals/1011.csv', sep=',', usecols=(1,3,5))
s1011.dropna(how="all", inplace=True)
print s1011

s1112 = pandas.read_csv('goals/1112.csv', sep=',', usecols=(1,3,5))
s1112.dropna(how="all", inplace=True)
print s1112

s1213 = pandas.read_csv('goals/1213.csv', sep=',', usecols=(1,3,5))
s1213.dropna(how="all", inplace=True)
print s1213

Currently this doesn't do much I know. It prints out 3 headings, Team, For & Against. It the prints out 20 football teams, how many goals they've scored, and how many conceded. I've tried using merge in python but it isn't suitable as it just makes one big table.

What I'm trying to do is open the multiple csv files, iterate through the list, if the Team is the same, add together goals for and goals against from each file. If Team has not been entered before, add a new row with new entries.

Is this possible using python?

Edit:

It currently prints

Team
  For
  Against

Man Utd
  86
  43

Man City
  83
  45

Chelsea
  89
  39

etc for 20 teams. So I want to update the For and Against entries by adding up the number of goals for each team over a number of seasons. Since it won't be the same 20 teams each season, I want to add a new row of entries if a team hasn't been in the league before.

Body:
Assume you have the following csv's:

df1

Team For Against

Man Utd 86 43

Man City 83 45

Chelsea 89 39

df2

Team For Against

Man Utd 88 45

Man City 85 47

ICantNameATeam 91 41

You can first stack them using pandas.concat:

df_concat = pandas.concat([df1, df2], axis=0)

which would give you:

df_concat

Team For Against

Man Utd 86 43

Man City 83 45

Chelsea 89 39

Man Utd 88 45

Man City 85 47

ICantNameATeam 91 41

Then you can use dataframe.groupby to take the sum:

df_sum = df_concat.groupby('Team').sum().reset_index()

This will group the dataframe according to unique team names and take the sum of each column.


问:
VB.net Webform Gridview with checkbox DataControlRowType
VB.net webform pulling data from Sql database to gridview.

I have two Bit Columns Rush and Normal - In the code behind if Rush is Checked then the row cells turn Red and Normal turns blue.

The problem I have is the bit is True or False not having much luck converting them to Integer or Int32.

Here is a code I am working with, this code turn all rows blue , if cell 7 not equal to 1.

If I go to Rush cell(10) error input string not in correct format.

Question is how to convert bit from True/false to 1/0 or correct format.

```<code>Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim sh As String = Convert.ToInt32(e.Row.Cells(7).Text)

        For Each cell As TableCell In e.Row.Cells
            If sh = 1 Then
                cell.BackColor = Drawing.Color.Red
            Else
                cell.BackColor = Drawing.Color.Blue

            End If

        Next

    End If

End Sub
</code>```

答:
I think I have it here , instead of fighting the Boolean , I decided to
change the cells to Integer. Please check over and let me know your thoughts.
It works, Rush orders are red and normal are blue ..</p>

```<code>Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim Chkb As Integer = (e.Row.DataItem(10))

        For Each cell As TableCell In e.Row.Cells
            If Chkb = -1 Then
                cell.BackColor = Drawing.Color.Red
            Else
                cell.BackColor = Drawing.Color.Blue

            End If

        Next

    End If

End Sub
</code>```

Body:
VB.net webform pulling data from Sql database to gridview.

I have two Bit Columns Rush and Normal - In the code behind if Rush is Checked then the row cells turn Red and Normal turns blue.

The problem I have is the bit is True or False not having much luck converting them to Integer or Int32.

Here is a code I am working with, this code turn all rows blue , if cell 7 not equal to 1.

If I go to Rush cell(10) error input string not in correct format.

Question is how to convert bit from True/false to 1/0 or correct format.

Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim sh As String = Convert.ToInt32(e.Row.Cells(7).Text)

        For Each cell As TableCell In e.Row.Cells
            If sh = 1 Then
                cell.BackColor = Drawing.Color.Red
            Else
                cell.BackColor = Drawing.Color.Blue

            End If

        Next

    End If

End Sub

Body:
I think I have it here , instead of fighting the Boolean , I decided to
change the cells to Integer. Please check over and let me know your thoughts.
It works, Rush orders are red and normal are blue ..

Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim Chkb As Integer = (e.Row.DataItem(10))

        For Each cell As TableCell In e.Row.Cells
            If Chkb = -1 Then
                cell.BackColor = Drawing.Color.Red
            Else
                cell.BackColor = Drawing.Color.Blue

            End If

        Next

    End If

End Sub


问:
Outputting JS variable into my PHP file
I'm trying to output a JS variable into my PHP-file. And then let the PHP send the variable value into my database.
But somehow it doesn't work..

Here I have a form that triggers the JS function:   (This file is called index.php)

```<code><form method="post" action="index.php" onsubmit="return phpFunction()" >
      <input type="hidden" name="submitted" value="true">
      <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
      <input type="submit" id="submitted" value="Submit your highscore">
      </form>
</code>```

Here we have the JS function:    ( This file is called main.js)

```<code>function phpFunction () {

var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;

};
</code>```

In the end we got the PHP file that sends the value to my localserver:  (This file is inside index.php)

```<code><?php

if (isset($_POST['submitted'])) {

// connect  to the database
include('connect.php');

$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;

if (!mysqli_query($conn, $sqlinsert)) {
    die('error inserting new record') ;
    } // end of my nested if statement

    $newrecord = "record added" ;

}
?>
</code>```

When I press the submit button I get a error message like this:

error 404

答:
You need to pass the query string properly you are missing an = character which is resulting in a URL like: index.php?score1234 which is invalid most likely, ie. "index.php?score" + php;.

In your phpFunction() make it look like this:

```<code>function phpFunction () {
    var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
    window.location.href = "index.php?score=" + php;
};
</code>```

Title: Outputting JS variable into my PHP file

Body:
I'm trying to output a JS variable into my PHP-file. And then let the PHP send the variable value into my database.
But somehow it doesn't work..

Here I have a form that triggers the JS function:   (This file is called index.php)

<form method="post" action="index.php" onsubmit="return phpFunction()" >
      <input type="hidden" name="submitted" value="true">
      <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
      <input type="submit" id="submitted" value="Submit your highscore">
      </form>

Here we have the JS function:    ( This file is called main.js)

function phpFunction () {

var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;

};

In the end we got the PHP file that sends the value to my localserver:  (This file is inside index.php)

<?php

if (isset($_POST['submitted'])) {

// connect  to the database
include('connect.php');

$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;

if (!mysqli_query($conn, $sqlinsert)) {
    die('error inserting new record') ;
    } // end of my nested if statement

    $newrecord = "record added" ;

}
?>

When I press the submit button I get a error message like this:

error 404

Body:
You need to pass the query string properly you are missing an = character which is resulting in a URL like: index.php?score1234 which is invalid most likely, ie. "index.php?score" + php;.

In your phpFunction() make it look like this:

function phpFunction () {
    var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
    window.location.href = "index.php?score=" + php;
};


问:
Angular 2 - Interpolation for NGX-Charts Results within ngFor
I'm trying to show charts based on some json. I made a pipe to access the various parts of the json object but don't know how to use the data, which  looks like this:

```<code>[ { "name": "Completed", "value": 50 }, { "name": "Remaining", "value": 50 } ]
</code>```

within the ngFor.

So normally I would do something like this:

```<code>  <ngx-charts-advanced-pie-chart
    mdTooltip="Click to change unit"
    [tooltipDisabled] = "true"
    [scheme]="colorScheme"
    [results]="results"     <----this is where the results normally go
    [gradient]="gradient"
    [view]="view"
    (select)="onChartClick()"
    >
  </ngx-charts-advanced-pie-chart>
</code>```

And I want to try something like this:

```<code> <div *ngFor="let chair of targetChairs | chairDimensions">
  <ngx-charts-advanced-pie-chart
    mdTooltip="Click to change unit"
    [tooltipDisabled] = "true"
    [scheme]="colorScheme"
    [results]="{{ chair.value.data.height | json }}"
    [gradient]="gradient"
    [view]="view"
    (select)="onChartClick()"
    >
  </ngx-charts-advanced-pie-chart>
</div>
</code>```

This doesn't work but is there a way to achieve this?

答:
So I found a similar issue on a git page here which solved my problem, so here is what I used in case someone else has this problem:</p>

```<code> <div *ngFor="let chair of targetChairs | chairDimensions">
  <ngx-charts-advanced-pie-chart
    mdTooltip="Click to change unit"
    [tooltipDisabled] = "true"
    [scheme]="colorScheme"
    [results]="chair.value.data.feet"
    [gradient]="gradient"
    [view]="view"
    (select)="onChartClick()"
    >
  </ngx-charts-advanced-pie-chart>
</div>
</code>```

Body:
I'm trying to show charts based on some json. I made a pipe to access the various parts of the json object but don't know how to use the data, which  looks like this:

[ { "name": "Completed", "value": 50 }, { "name": "Remaining", "value": 50 } ]

within the ngFor.

So normally I would do something like this:

  <ngx-charts-advanced-pie-chart
    mdTooltip="Click to change unit"
    [tooltipDisabled] = "true"
    [scheme]="colorScheme"
    [results]="results"     <----this is where the results normally go
    [gradient]="gradient"
    [view]="view"
    (select)="onChartClick()"
    >
  </ngx-charts-advanced-pie-chart>

And I want to try something like this:

  <ngx-charts-advanced-pie-chart
    mdTooltip="Click to change unit"
    [tooltipDisabled] = "true"
    [scheme]="colorScheme"
    [results]="{{ chair.value.data.height | json }}"
    [gradient]="gradient"
    [view]="view"
    (select)="onChartClick()"
    >
  </ngx-charts-advanced-pie-chart>

This doesn't work but is there a way to achieve this?

Body:
So I found a similar issue on a git page here which solved my problem, so here is what I used in case someone else has this problem:

 <div *ngFor="let chair of targetChairs | chairDimensions">
  <ngx-charts-advanced-pie-chart
    mdTooltip="Click to change unit"
    [tooltipDisabled] = "true"
    [scheme]="colorScheme"
    [results]="chair.value.data.feet"
    [gradient]="gradient"
    [view]="view"
    (select)="onChartClick()"
    >
  </ngx-charts-advanced-pie-chart>
</div>


问:
Whats the easiest way to know if a class is an ActiveRecord class?
So I know that I can do

```<code> Class.new.is_a?(ActiveRecord::Base)
</code>```

Is there a way to know what kind of class it is without instantiating it?  Are there any downsides to instantiating it just to find out the type of class it is?

答:
You can use Module#<:

```<code>SomeKlass < ActiveRecord::Base
=> true
</code>```

Also, if you want to include ActiveRecord::Base itself to results, you can use Module#<=:

```<code>ActiveRecord::Base <= ActiveRecord::Base
=> true
</code>```

Body:
So I know that I can do

 Class.new.is_a?(ActiveRecord::Base)

Is there a way to know what kind of class it is without instantiating it?  Are there any downsides to instantiating it just to find out the type of class it is?

Body:
You can use Module#<:

SomeKlass < ActiveRecord::Base
=> true

Also, if you want to include ActiveRecord::Base itself to results, you can use Module#<=:

ActiveRecord::Base <= ActiveRecord::Base
=> true


问:
Exit application after click on android Notification
I've implemented a method that when my app is running in background a notification will be displayed on notification bar ..
Now I want to close app when I click on that notification :

```<code>Intent intent = new Intent(this, Main.class);
PendingIntent pIntent = PendingIntent.getActivity(this,
                            (int) System.currentTimeMillis(), intent, 0);
if (Build.VERSION.SDK_INT < 16) {
    Notification n  = new Notification.Builder(this)
            .setContentTitle("Flashlight")
            .setContentText("turn off")
            .setSmallIcon(R.mipmap.light_on)
            .setContentIntent(pIntent)
            .setAutoCancel(true).getNotification();
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, n);
} else {
    Notification n  = new Notification.Builder(this)
            .setContentTitle("Flashlight")
            .setContentText("turn off")
            .setSmallIcon(R.mipmap.light_on)
            .setContentIntent(pIntent)
            .setAutoCancel(true).build();
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, n);
}
</code>```

How can I do this !?

答:
If you need to exit your app you can set an action for your intent , then create a Broadcast Receiver and finish your application inside onReceive method , then with IntentFilter receive your action , And register your receiver with action filter. Here is an example :

```<code>Intent intent = new Intent("close_app");
PendingIntent pIntent = PendingIntent.getBroadcast(this, (int)
                System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
.
.
.// build your notification
</code>```

Then in your onCreate :

```<code>    private BroadcastReceiver mReceiver;

    mReceiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
         Log.d("TAG" ,"onReceive ");
         finish();
       }
     };
</code>```

Then receive your action and register in your onCreate or onResume:

```<code>      IntentFilter filter = new IntentFilter();
      filter.addAction("close_app");
      registerReceiver(mReceiver, filter);
</code>```

And don't forget to unregister your receiver

Body:
I've implemented a method that when my app is running in background a notification will be displayed on notification bar ..
Now I want to close app when I click on that notification :

Intent intent = new Intent(this, Main.class);
PendingIntent pIntent = PendingIntent.getActivity(this,
                            (int) System.currentTimeMillis(), intent, 0);
if (Build.VERSION.SDK_INT < 16) {
    Notification n  = new Notification.Builder(this)
            .setContentTitle("Flashlight")
            .setContentText("turn off")
            .setSmallIcon(R.mipmap.light_on)
            .setContentIntent(pIntent)
            .setAutoCancel(true).getNotification();
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, n);
} else {
    Notification n  = new Notification.Builder(this)
            .setContentTitle("Flashlight")
            .setContentText("turn off")
            .setSmallIcon(R.mipmap.light_on)
            .setContentIntent(pIntent)
            .setAutoCancel(true).build();
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, n);
}

How can I do this !?

Body:
If you need to exit your app you can set an action for your intent , then create a Broadcast Receiver and finish your application inside onReceive method , then with IntentFilter receive your action , And register your receiver with action filter. Here is an example :

Intent intent = new Intent("close_app");
PendingIntent pIntent = PendingIntent.getBroadcast(this, (int)
                System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
.
.
.// build your notification

Then in your onCreate :

    private BroadcastReceiver mReceiver;

    mReceiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
         Log.d("TAG" ,"onReceive ");
         finish();
       }
     };

Then receive your action and register in your onCreate or onResume:

      IntentFilter filter = new IntentFilter();
      filter.addAction("close_app");
      registerReceiver(mReceiver, filter);

And don't forget to unregister your receiver


问:
Pygame Scrolling
I am currently taking an A level computer science course in which I have to create a game for a project. I know this code is probably not efficient but I am trying to keep it to my own work and would like a hand with one bit that I am confused on.

I am trying to scroll the screen right and left which i know is done by moving every object on the screen in the relevant direction. I have created boundaries for which the screen should start to move when the robot is within them. But for the code i have written the platforms move without them being updated on the screen and the speed of the robot changes when it is within these boundaries

Any ideas or help would be appreciated.

```<code>import pygame as pg
import time
import random

pg.init()#initiates pygame

display_height = 690#Creates width and height of screen
display_width = 1024
#Colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
sky = (73,71,65) # grey

Robot_height = 99#Height of robot
Robot_width = 112#Width of robot
lives = 3 #Robot Lives
Bullet_Fired = False
PowerUp_Active = False
Robot_acc = 0.3 #Robot Acceleration
vec = pg.math.Vector2

gameDisplay = pg.display.set_mode((display_width,display_height)) #Sets display properties of window
pg.display.set_caption ("Game") #Title on window
clock = pg.time.Clock()
robotImg = pg.image.load("robot1.png") #Loads robots image

#Class for platforms
class Platform(pg.sprite.Sprite):
    def __init__(self, x,y,w,h):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((w,h))
        self.image.fill(blue)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

#List of platforms
PLATFORM_LIST = [(0,display_height - 40,display_width,40),
                 (display_width /2 - 50,display_height * 3/4,100,20)]
#Platform group
platforms = pg.sprite.Group()

#class for robot
class RobotClass(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((Robot_width,Robot_height))
        self.rect = self.image.get_rect()
        self.rect.center = (display_width / 2, display_height / 2)
        self.RobotPos = vec(display_width / 2, display_height / 2)
        self.bottom = (0,0)
        self.vel = vec(0, 0)
        self.acc = vec(0, 0.3)

#Creates Robot
Robot = RobotClass()
for plat in PLATFORM_LIST:
    p = Platform(*plat)
    platforms.add(p)
def draw():
    for plat in PLATFORM_LIST:
            p = Platform(*plat)
            pg.draw.rect(gameDisplay, blue, (p))

#Jump function
def jump():
    #Checks pixel below robot to see if there is a collision
    Robot.rect.x = Robot.rect.x +1
    hits = pg.sprite.spritecollide(Robot , platforms, False)
    Robot.rect.x = Robot.rect.x -1
    if hits:
        #Gives robot velocity of 5 upwards
        Robot.vel.y = -10

#game loop
def game_loop():
    pg.draw.rect(gameDisplay, red, Robot.rect, 2)
    Robot_friction = -0.3 #Friction value
    vec = pg.math.Vector2 #Setting vec as vector quantity
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit
                quit()
            #Starts acceleration when key is pressed
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_LEFT:
                    Robot.acc.x = -Robot_acc
                elif event.key == pg.K_RIGHT:
                    Robot.acc.x = Robot_acc
                elif event.key == pg.K_UP:
                    jump()
            #Adds friction to accleration to slow robot down when key is not being pressed
            if event.type == pg.KEYUP:
                if event.key == pg.K_LEFT or event.key == pg.K_RIGHT:
                    Robot.acc.x = Robot.acc.x * Robot_friction

        #Adjusts velocity of robot by adding the acceleration on each cycle
        Robot.vel = Robot.vel+ Robot.acc
        #Fills background
        gameDisplay.fill(sky)
        #Draws the platforms to the screen and adds them to platform group
        draw()
        #Changes Robot position according to its velocity,acceleration and the friction
        Robot.RobotPos = Robot.RobotPos + Robot.vel + 0.5 * Robot.acc
        #Loads robot onto screen
        gameDisplay.blit(robotImg,(Robot.rect))
        pg.draw.rect(gameDisplay, red, Robot.rect, 2)
        #Updates display
        pg.display.update()
        clock.tick(60)

        #Sets bottom of robot to its position
        Robot.rect.midbottom =  Robot.RobotPos

        #Collision detection
        if Robot.vel.y > 0:
            hits = pg.sprite.spritecollide(Robot , platforms, False)
            if hits:
                #Puts Robot on top of platform
                Robot.RobotPos.y = hits[0].rect.top + 1
                Robot.vel.y = 0

        #Scrolling

        if Robot.rect.left < display_width/4:
            print("left")
            Robot.RobotPos.x = Robot.RobotPos.x - abs(Robot.vel.x)
            print(Robot.vel)
            for plat in platforms:
                plat.rect.x = plat.rect.x + abs(Robot.vel.x)
                pg.draw.rect(gameDisplay, blue, (PLATFORM_LIST[0]))
        if Robot.rect.right > (display_width-display_width/4):
            print("right")
            Robot.RobotPos.x = Robot.RobotPos.x + abs(Robot.vel.x)
            print(Robot.vel)
            for plat in platforms:
                plat.rect.x = plat.rect.x - abs(Robot.vel.x)

        #Sets top velocity of robot
        if Robot.vel.x > 6:
            Robot.vel.x = 6
        if Robot.vel.x < -6:
            Robot.vel.x = -6
        #Makes robot velocity = 0 when it is close to 0
        if Robot.vel.x < 0.05 and Robot.vel.x > -0.05:
            Robot.acc.x = 0
            Robot.vel.x = 0

game_loop()
pg.quit()
quit()
</code>```

答:
So here we go. Here you are updating the platforms if the robot reached the limit:

```<code>for plat in platforms:
    plat.rect.x = plat.rect.x - abs(Robot.vel.x)
</code>```

But when you draw the platforms you draw from the original PLATFORM_LIST list:

```<code>def draw():
    for plat in PLATFORM_LIST:
        p = Platform(*plat)
        pg.draw.rect(gameDisplay, blue, (p))
</code>```

So what ends up happening is even though you are updating the platforms properly, you are drawing from the original list, so you are not drawing the updated the list. You should draw from the platform list you are updating:

```<code>def draw():
    for plat in platforms:
        pg.draw.rect(gameDisplay, blue, plat)
</code>```

Second, I discovered once you hit the left scroll limit, the movement back to the right direction moved the robot the wrong way. replace this:

```<code>if Robot.rect.left < display_width/4:
    Robot.RobotPos.x = Robot.RobotPos.x - abs(Robot.vel.x)
</code>```

with this (the minus sign switched over to the plus sign):

```<code>if Robot.rect.left < display_width/4:
    Robot.RobotPos.x = Robot.RobotPos.x + abs(Robot.vel.x)
</code>```

Just a couple things I found while playing around with the game.

Update

There is also an issue with rounding. Pygame rectangles take integers. Your calculation of velocity yields a float and you are trying to add that to the x of the rectangle here:

```<code>for plat in platforms:
    plat.rect.x = plat.rect.x - abs(Robot.vel.x)
</code>```

This causes issues with rounding that show up in the display (platforms) moving in peculiar ways. You can make them ints:

```<code>for plat in platforms:
    plat.rect.x = plat.rect.x - int(abs(Robot.vel.x))
</code>```

Otherwise you will have to make the platforms like you do the Robot and deal in vec()

Title: Pygame Scrolling

Body:
I am currently taking an A level computer science course in which I have to create a game for a project. I know this code is probably not efficient but I am trying to keep it to my own work and would like a hand with one bit that I am confused on.

I am trying to scroll the screen right and left which i know is done by moving every object on the screen in the relevant direction. I have created boundaries for which the screen should start to move when the robot is within them. But for the code i have written the platforms move without them being updated on the screen and the speed of the robot changes when it is within these boundaries

Any ideas or help would be appreciated.

import pygame as pg
import time
import random

pg.init()#initiates pygame

display_height = 690#Creates width and height of screen
display_width = 1024
#Colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
sky = (73,71,65) # grey

Robot_height = 99#Height of robot
Robot_width = 112#Width of robot
lives = 3 #Robot Lives
Bullet_Fired = False
PowerUp_Active = False
Robot_acc = 0.3 #Robot Acceleration
vec = pg.math.Vector2

gameDisplay = pg.display.set_mode((display_width,display_height)) #Sets display properties of window
pg.display.set_caption ("Game") #Title on window
clock = pg.time.Clock()
robotImg = pg.image.load("robot1.png") #Loads robots image

#Class for platforms
class Platform(pg.sprite.Sprite):
    def __init__(self, x,y,w,h):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((w,h))
        self.image.fill(blue)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

#List of platforms
PLATFORM_LIST = [(0,display_height - 40,display_width,40),
                 (display_width /2 - 50,display_height * 3/4,100,20)]
#Platform group
platforms = pg.sprite.Group()

#class for robot
class RobotClass(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((Robot_width,Robot_height))
        self.rect = self.image.get_rect()
        self.rect.center = (display_width / 2, display_height / 2)
        self.RobotPos = vec(display_width / 2, display_height / 2)
        self.bottom = (0,0)
        self.vel = vec(0, 0)
        self.acc = vec(0, 0.3)

#Creates Robot
Robot = RobotClass()
for plat in PLATFORM_LIST:
    p = Platform(*plat)
    platforms.add(p)
def draw():
    for plat in PLATFORM_LIST:
            p = Platform(*plat)
            pg.draw.rect(gameDisplay, blue, (p))

#Jump function
def jump():
    #Checks pixel below robot to see if there is a collision
    Robot.rect.x = Robot.rect.x +1
    hits = pg.sprite.spritecollide(Robot , platforms, False)
    Robot.rect.x = Robot.rect.x -1
    if hits:
        #Gives robot velocity of 5 upwards
        Robot.vel.y = -10

#game loop
def game_loop():
    pg.draw.rect(gameDisplay, red, Robot.rect, 2)
    Robot_friction = -0.3 #Friction value
    vec = pg.math.Vector2 #Setting vec as vector quantity
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit
                quit()
            #Starts acceleration when key is pressed
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_LEFT:
                    Robot.acc.x = -Robot_acc
                elif event.key == pg.K_RIGHT:
                    Robot.acc.x = Robot_acc
                elif event.key == pg.K_UP:
                    jump()
            #Adds friction to accleration to slow robot down when key is not being pressed
            if event.type == pg.KEYUP:
                if event.key == pg.K_LEFT or event.key == pg.K_RIGHT:
                    Robot.acc.x = Robot.acc.x * Robot_friction

        #Adjusts velocity of robot by adding the acceleration on each cycle
        Robot.vel = Robot.vel+ Robot.acc
        #Fills background
        gameDisplay.fill(sky)
        #Draws the platforms to the screen and adds them to platform group
        draw()
        #Changes Robot position according to its velocity,acceleration and the friction
        Robot.RobotPos = Robot.RobotPos + Robot.vel + 0.5 * Robot.acc
        #Loads robot onto screen
        gameDisplay.blit(robotImg,(Robot.rect))
        pg.draw.rect(gameDisplay, red, Robot.rect, 2)
        #Updates display
        pg.display.update()
        clock.tick(60)

        #Sets bottom of robot to its position
        Robot.rect.midbottom =  Robot.RobotPos

        #Collision detection
        if Robot.vel.y > 0:
            hits = pg.sprite.spritecollide(Robot , platforms, False)
            if hits:
                #Puts Robot on top of platform
                Robot.RobotPos.y = hits[0].rect.top + 1
                Robot.vel.y = 0

        #Scrolling

        if Robot.rect.left < display_width/4:
            print("left")
            Robot.RobotPos.x = Robot.RobotPos.x - abs(Robot.vel.x)
            print(Robot.vel)
            for plat in platforms:
                plat.rect.x = plat.rect.x + abs(Robot.vel.x)
                pg.draw.rect(gameDisplay, blue, (PLATFORM_LIST[0]))
        if Robot.rect.right > (display_width-display_width/4):
            print("right")
            Robot.RobotPos.x = Robot.RobotPos.x + abs(Robot.vel.x)
            print(Robot.vel)
            for plat in platforms:
                plat.rect.x = plat.rect.x - abs(Robot.vel.x)

        #Sets top velocity of robot
        if Robot.vel.x > 6:
            Robot.vel.x = 6
        if Robot.vel.x < -6:
            Robot.vel.x = -6
        #Makes robot velocity = 0 when it is close to 0
        if Robot.vel.x < 0.05 and Robot.vel.x > -0.05:
            Robot.acc.x = 0
            Robot.vel.x = 0

game_loop()
pg.quit()
quit()

Body:
So here we go. Here you are updating the platforms if the robot reached the limit:

for plat in platforms:
    plat.rect.x = plat.rect.x - abs(Robot.vel.x)

But when you draw the platforms you draw from the original PLATFORM_LIST list:

def draw():
    for plat in PLATFORM_LIST:
        p = Platform(*plat)
        pg.draw.rect(gameDisplay, blue, (p))

So what ends up happening is even though you are updating the platforms properly, you are drawing from the original list, so you are not drawing the updated the list. You should draw from the platform list you are updating:

def draw():
    for plat in platforms:
        pg.draw.rect(gameDisplay, blue, plat)

Second, I discovered once you hit the left scroll limit, the movement back to the right direction moved the robot the wrong way. replace this:

if Robot.rect.left < display_width/4:
    Robot.RobotPos.x = Robot.RobotPos.x - abs(Robot.vel.x)

with this (the minus sign switched over to the plus sign):

if Robot.rect.left < display_width/4:
    Robot.RobotPos.x = Robot.RobotPos.x + abs(Robot.vel.x)

Just a couple things I found while playing around with the game.

Update

There is also an issue with rounding. Pygame rectangles take integers. Your calculation of velocity yields a float and you are trying to add that to the x of the rectangle here:

for plat in platforms:
    plat.rect.x = plat.rect.x - abs(Robot.vel.x)

This causes issues with rounding that show up in the display (platforms) moving in peculiar ways. You can make them ints:

for plat in platforms:
    plat.rect.x = plat.rect.x - int(abs(Robot.vel.x))

Otherwise you will have to make the platforms like you do the Robot and deal in vec()


问:
MvcSiteMapProvider Sitemap.xml endpoint breaks with custom route
I have a custom route to simplify the url and only use the home controller implicitly, but by doing so I can no longer access my sitemap.xml form the default endpoint, how could I fix this?</p>

```<code>'routes.MapRoute(
'    name:="OmitController",
'    url:="{action}/{id}",
'    defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
')
</code>```

答:
Nevermidn I looked at the source code and saw that the default route for the sitemap.xml is calling the XmlSiteMap and the Index action so I added this

```<code>    routes.MapRoute(
            "sitemap",
            "sitemap.xml",
            New With {.controller = "XmlSiteMap", .action = "Index"}
        )
</code>```

and it works now

Body:
I have a custom route to simplify the url and only use the home controller implicitly, but by doing so I can no longer access my sitemap.xml form the default endpoint, how could I fix this?

'routes.MapRoute(
'    name:="OmitController",
'    url:="{action}/{id}",
'    defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
')

Body:
Nevermidn I looked at the source code and saw that the default route for the sitemap.xml is calling the XmlSiteMap and the Index action so I added this

    routes.MapRoute(
            "sitemap",
            "sitemap.xml",
            New With {.controller = "XmlSiteMap", .action = "Index"}
        )

and it works now


问:
How to Create JavaFX 16 bit Greyscale Images
I have an application that generates 16 bit grey scale images. Currently these images are generated as an awt BufferedImage with data type DataBuffer.TYPE_USHORT.

In my app, I extract the 16 bit data from the BufferedImage, normalise to 8 bit, then render it into an FX Canvas with canvas.getGraphicsContext2D().getPixelWriter().setPixels(...)

It works but looks messy I am wondering if it is possible to implement a JavaFX Image or WritableImage, lets call it a UShortImage that is backed by my 16 bit data. The UShortImage could have FX properties for the normalisation levels, but otherwise could be used exactly as any JavaFX Image.

Any help or pointers on how to achieve this with good run time efficiency would be appreciated!

答:
I don't know if this is exactly what you are looking for as perhaps I don't understand your question.  But you can convert a color image to a gray image by desaturating the color using a ColorAdjust effect.

```<code>ColorAdjust monochrome = new ColorAdjust();
monochrome.setSaturation(-1);
ImageView gray = new ImageView(new Image(IMAGE_LOC));
gray.setEffect(monochrome);
</code>```

I am not sure why poor grandma and grandpa must be faded to black and white, but it must be so.

```<code>import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.*;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class GrayScale extends Application {

    @Override
    public void start(Stage stage) {
        ColorAdjust monochrome = new ColorAdjust();
        monochrome.setSaturation(-1);
        Image image = new Image(IMAGE_LOC);
        ImageView color = new ImageView(image);
        ImageView gray = new ImageView(image);
        gray.setEffect(monochrome);

        HBox layout = new HBox(10, color, gray);
        layout.setPadding(new Insets(10));

        Scene scene = new Scene(layout);
        scene.setFill(Color.BLACK);
        stage.setScene(scene);

        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    // source: http://www.photoshopessentials.com/photo-editing/black-and-white-tutorials/desaturate/
    private static final String IMAGE_LOC =
            "http://pe-images.s3.amazonaws.com/photo-effects/black-and-white/grandparents.jpg";
}
</code>```

If ColorAdjust doesn't work for you, then you could just do manipulation on a pixel-by-pixel bases using PixelReaders and PixelWriters on a WritableImage.  (I don't see a reason for a canvas to be involved as you mention in your question).  For an related implementation using a WritableImage see:

Reduce number of colors and get color of a single pixel

Perhaps you are also looking to extend PixelFormat with a new type and extend PixelReader to read your data buffer, which may be possible, though I guess that wouldn't be necessary to accomplish what you want:

```<code>PixelReader reader = new GrayScalePixelReader();
reader.getPixels(0, 0, W, H,
    GrayScalePixelFormat.instance(), grayScaleByteBuffer, 0, scanlineStride);
Image img = new WritableImage(reader, W, H);
</code>```

where GrayScalePixelReader and GrayScalePixelFormat are new classes you create via extension.

FX supports pixel types define by PixelFormat such as BYTE_BGRA and BYTE_BGRA_PRE; I am looking to add support for a new pixel type which has a single sample per pixel which is a 16 unsigned data value.

```<code>pixelFormat = PixelFormat.createByteIndexedInstance(LUT);
getPixelWriter().setPixels(0, 0, w, h, pixelFormat, normalisedImageData, 0, w);
</code>```

Yeah, you can almost do it, but it is a little tricky.  I agree that existing PixelFormat in Java 8 is not really very readily user extensible, for reasons such as you mention:

Some methods e.g getPixelWriter() of the WritabelImage class are final so you can't even override them. The Image infrastructure looks like it is not designed to be extended in this way.

Usually, when it comes to JavaFX, this lack of extensibility is built in on purpose.  Some reasons are:

Security, to make it more difficult for people to subvert the platform into doing something malicious by overriding core functionality to also perform malicious side effects.

Present a simplified interface to the application developer to make it easier to understand and use the API.

Deliberately make some parts of the platform opaque, so that it is easier for the library developers to maintain the core library implementation and change it at will without impacting user programs.

Of course the tradeoff (as in this case) can be a lack of flexibility in trying to accomplish what you wish.

If you look into the Image implementation in JavaFX, it kind of has four different components:

The javafx.scene.image APIs.

The platform implementation (prism) backing the image APIs (see source).

The image io libraries for reading common image formats (png, jpg, etc).

Interfaces to graphics hardware accelerator APIs or software rendering APIs, for example es2, which ultimately, usually treats the image as a texture input to a hardware graphics API such as OpenGL or Direct3D.

The interesting thing about grayscale pixel formats is that they are not directly exposed in (1) the javafx.scene.image APIs.  However, the prism platform implementation, the image io libraries and hardware accelerators (2, 3 and 4), do have some level of inbuilt grayscale support.  For instance, a PNG file could have a grayscale format and the imageIO will recognize the format and pass the grayscale buffer directly to the prism Image class to be interpereted.

Grayscale buffers are also supported by the hardware acceleration layer, as can be seen in the ES2Texture implementation.  So this gives an ideal situation of the grayscale pixel format encoded buffer for the image being able to be directly rendered to a hardware accelerated texture.  Note however, that the current pixel format for the grayscale byte buffer supported by the Prism/ES2 rendering system, is for an 8 bit encoding, not a 16 bit encoding you ideally ask for (though comments on the prism pixel format do not that a 16-bit type might be needed in the future ;-):

```<code>// L8, A8 types:
// NOTE : we might need L8A8 16-bit type
BYTE_GRAY    (DataType.BYTE,  1, true,  true),
</code>```

So this means that much of the infrastructure that you are looking for that allows direct interpretation of the grayscale encoded image buffer by the JavaFX runtime is already there, however it is placed inside com.sun classes and private API and not directly exposed to the user in the public javafx.scene.image APIs.

A feature request could be created to enable a public API for grayscale pixel formats or you could ask about it on the openjfx-dev mailing list.  Shortest timeframe to get such features implemented would be Java 10.  It looks like such a request may already exist, so you could comment on it or bring it up on the openjfx-dev mailing list to help move it forward:

High bit-depth Grayscale WritableImage support.

Support Writable Gray Image.

Does the above info help you in anyway with your current problem -> probably not :-)  But hopefully it helps understanding of the platform and its capabilities, limitations and potential mechanisms for future extension to support your requirements for fully.

Body:
I don't know if this is exactly what you are looking for as perhaps I don't understand your question.  But you can convert a color image to a gray image by desaturating the color using a ColorAdjust effect.

ColorAdjust monochrome = new ColorAdjust();
monochrome.setSaturation(-1);
ImageView gray = new ImageView(new Image(IMAGE_LOC));
gray.setEffect(monochrome);

I am not sure why poor grandma and grandpa must be faded to black and white, but it must be so.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.*;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class GrayScale extends Application {

    @Override
    public void start(Stage stage) {
        ColorAdjust monochrome = new ColorAdjust();
        monochrome.setSaturation(-1);
        Image image = new Image(IMAGE_LOC);
        ImageView color = new ImageView(image);
        ImageView gray = new ImageView(image);
        gray.setEffect(monochrome);

        HBox layout = new HBox(10, color, gray);
        layout.setPadding(new Insets(10));

        Scene scene = new Scene(layout);
        scene.setFill(Color.BLACK);
        stage.setScene(scene);

        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    // source: http://www.photoshopessentials.com/photo-editing/black-and-white-tutorials/desaturate/
    private static final String IMAGE_LOC =
            "http://pe-images.s3.amazonaws.com/photo-effects/black-and-white/grandparents.jpg";
}

If ColorAdjust doesn't work for you, then you could just do manipulation on a pixel-by-pixel bases using PixelReaders and PixelWriters on a WritableImage.  (I don't see a reason for a canvas to be involved as you mention in your question).  For an related implementation using a WritableImage see:

Reduce number of colors and get color of a single pixel

Perhaps you are also looking to extend PixelFormat with a new type and extend PixelReader to read your data buffer, which may be possible, though I guess that wouldn't be necessary to accomplish what you want:

PixelReader reader = new GrayScalePixelReader();
reader.getPixels(0, 0, W, H,
    GrayScalePixelFormat.instance(), grayScaleByteBuffer, 0, scanlineStride);
Image img = new WritableImage(reader, W, H);

where GrayScalePixelReader and GrayScalePixelFormat are new classes you create via extension.

FX supports pixel types define by PixelFormat such as BYTE_BGRA and BYTE_BGRA_PRE; I am looking to add support for a new pixel type which has a single sample per pixel which is a 16 unsigned data value.

pixelFormat = PixelFormat.createByteIndexedInstance(LUT);
getPixelWriter().setPixels(0, 0, w, h, pixelFormat, normalisedImageData, 0, w);

Yeah, you can almost do it, but it is a little tricky.  I agree that existing PixelFormat in Java 8 is not really very readily user extensible, for reasons such as you mention:

Some methods e.g getPixelWriter() of the WritabelImage class are final so you can't even override them. The Image infrastructure looks like it is not designed to be extended in this way.

Usually, when it comes to JavaFX, this lack of extensibility is built in on purpose.  Some reasons are:

Security, to make it more difficult for people to subvert the platform into doing something malicious by overriding core functionality to also perform malicious side effects.

Present a simplified interface to the application developer to make it easier to understand and use the API.

Deliberately make some parts of the platform opaque, so that it is easier for the library developers to maintain the core library implementation and change it at will without impacting user programs.

Of course the tradeoff (as in this case) can be a lack of flexibility in trying to accomplish what you wish.

If you look into the Image implementation in JavaFX, it kind of has four different components:

The javafx.scene.image APIs.

The platform implementation (prism) backing the image APIs (see source).

The image io libraries for reading common image formats (png, jpg, etc).

Interfaces to graphics hardware accelerator APIs or software rendering APIs, for example es2, which ultimately, usually treats the image as a texture input to a hardware graphics API such as OpenGL or Direct3D.

The interesting thing about grayscale pixel formats is that they are not directly exposed in (1) the javafx.scene.image APIs.  However, the prism platform implementation, the image io libraries and hardware accelerators (2, 3 and 4), do have some level of inbuilt grayscale support.  For instance, a PNG file could have a grayscale format and the imageIO will recognize the format and pass the grayscale buffer directly to the prism Image class to be interpereted.

Grayscale buffers are also supported by the hardware acceleration layer, as can be seen in the ES2Texture implementation.  So this gives an ideal situation of the grayscale pixel format encoded buffer for the image being able to be directly rendered to a hardware accelerated texture.  Note however, that the current pixel format for the grayscale byte buffer supported by the Prism/ES2 rendering system, is for an 8 bit encoding, not a 16 bit encoding you ideally ask for (though comments on the prism pixel format do not that a 16-bit type might be needed in the future ;-):

// L8, A8 types:
// NOTE : we might need L8A8 16-bit type
BYTE_GRAY    (DataType.BYTE,  1, true,  true),

So this means that much of the infrastructure that you are looking for that allows direct interpretation of the grayscale encoded image buffer by the JavaFX runtime is already there, however it is placed inside com.sun classes and private API and not directly exposed to the user in the public javafx.scene.image APIs.

A feature request could be created to enable a public API for grayscale pixel formats or you could ask about it on the openjfx-dev mailing list.  Shortest timeframe to get such features implemented would be Java 10.  It looks like such a request may already exist, so you could comment on it or bring it up on the openjfx-dev mailing list to help move it forward:

High bit-depth Grayscale WritableImage support.

Support Writable Gray Image.

Does the above info help you in anyway with your current problem -> probably not :-)  But hopefully it helps understanding of the platform and its capabilities, limitations and potential mechanisms for future extension to support your requirements for fully.


问:
Learning SQL: Need help Using HAVING to get the MIN result from an aggregate
was hoping to get some help. New to SQL and trying to keep my head on straight.

I've been given this assignment:

"Using HAVING, determine whose Direct Reports have the lowest Avg Salary."

My logic was to make a join on a derived table that would calculate the AVG salary of the crew for each Manager that had direct reports. This result would then get filtered to the MIN value by a HAVING clause.

```<code>SELECT Flash.firstname, Flash.lastname, Wally.AVGSalary,
       Wally.[Direct Reports] FROM CrewMembers Flash
    JOIN
    (
        SELECT Barry.crewMemberId, AVG(Zoom.salary) AS 'AVGSalary', COUNT(Zoom.firstname) AS 'Direct Reports'
                    FROM CrewMembers Barry
            JOIN CrewMembers Zoom
                           ON Zoom.managerId = Barry.crewMemberId
        GROUP BY Barry.crewMemberId
    )
    AS Wally ON Wally.crewMemberId = Flash.crewMemberId

GROUP BY Flash.firstname, Flash.lastname, Wally.AVGSalary, Wally.[Direct Reports]

HAVING MIN(Wally.AVGSalary) in (Wally.AVGSalary)

ORDER BY Wally.AVGSalary asc
</code>```

I'm getting this result:

```<code>firstname   lastname    AVGSalary   Direct Reports
Mike        Patton      33666.500000    2
Kurt        Corgan      37300.000000    2
Amber       Bruckner    45851.666666    3
Doug        Adams       86250.000000    2
Montgomery  Scott       92500.000000    2
James       Kirk        132666.750000   3
</code>```

I'm stumped. I need it to give me JUST the row with the minimum value and it's giving me every value. I've stared at this and can't figure out what I'm doing wrong.

I know, from looking at threads online, that using TOP is a way to filter items, but that hasn't been introduced yet and I'd like to stay within the parameters that have been established in the course so far.

Any critique of what I've written or any help would be awesome. Like I said, I'm new and just trying to keep up.

Thanks,

J

答:
try this:

```<code>Select crewMemberId, avgSalary
From (Select s.crewMemberId,
         AVG(d.salary) avgSalary
      From CrewMembers d join CrewMembers s
         on s.crewMemberId = d.managerId
      group by s.crewMemberId) x
Where avgSalary =
   (Select Min(avgSalary)
    from (Select s.crewMemberId,
             AVG(d.salary) avgSalary
          From CrewMembers d join CrewMembers s
              on s.crewMemberId = d.managerId
          group by s.crewMemberId)x)
</code>```

-- Using sample data in a temp table variable:

```<code>declare @e table(crewmemberId int primary key not null,
              managerId int null, salary decimal)
Insert @e(crewmemberId, managerId, salary)
values (1, null, 23),
       (2,1,45), (3,1,33), (4,1,80),
       (5,2,14), (6,2,8), (7,2,12),
       (8,3,11), (9,3,5), (10,3,2),
       (11,4,51), (12,4,38), (13,4,17)

Select crewMemberId, avgSalary
From (Select s.crewMemberId,
         AVG(d.salary) avgSalary
      From @e d join @e s
         on s.crewMemberId = d.managerId
      group by s.crewMemberId) x
Where avgSalary =
   (Select Min(avgSalary)
    From (Select s.crewMemberId,
            AVG(d.salary) avgSalary
          From @e d join @e s
             on s.crewMemberId = d.managerId
          group by s.crewMemberId)x)
</code>```

this gives crewmemberId = 3, Avg Salary = 6.0000;

It has the advantage of producing multiple results if direct hires of two or more Managers have the same avg salaries.

Body:
was hoping to get some help. New to SQL and trying to keep my head on straight.

I've been given this assignment:

"Using HAVING, determine whose Direct Reports have the lowest Avg Salary."

My logic was to make a join on a derived table that would calculate the AVG salary of the crew for each Manager that had direct reports. This result would then get filtered to the MIN value by a HAVING clause.

SELECT Flash.firstname, Flash.lastname, Wally.AVGSalary,
       Wally.[Direct Reports] FROM CrewMembers Flash
    JOIN
    (
        SELECT Barry.crewMemberId, AVG(Zoom.salary) AS 'AVGSalary', COUNT(Zoom.firstname) AS 'Direct Reports'
                    FROM CrewMembers Barry
            JOIN CrewMembers Zoom
                           ON Zoom.managerId = Barry.crewMemberId
        GROUP BY Barry.crewMemberId
    )
    AS Wally ON Wally.crewMemberId = Flash.crewMemberId

GROUP BY Flash.firstname, Flash.lastname, Wally.AVGSalary, Wally.[Direct Reports]

HAVING MIN(Wally.AVGSalary) in (Wally.AVGSalary)

ORDER BY Wally.AVGSalary asc

I'm getting this result:

firstname   lastname    AVGSalary   Direct Reports
Mike        Patton      33666.500000    2
Kurt        Corgan      37300.000000    2
Amber       Bruckner    45851.666666    3
Doug        Adams       86250.000000    2
Montgomery  Scott       92500.000000    2
James       Kirk        132666.750000   3

I'm stumped. I need it to give me JUST the row with the minimum value and it's giving me every value. I've stared at this and can't figure out what I'm doing wrong.

I know, from looking at threads online, that using TOP is a way to filter items, but that hasn't been introduced yet and I'd like to stay within the parameters that have been established in the course so far.

Any critique of what I've written or any help would be awesome. Like I said, I'm new and just trying to keep up.

Thanks,

J

Body:
try this:

Select crewMemberId, avgSalary
From (Select s.crewMemberId,
         AVG(d.salary) avgSalary
      From CrewMembers d join CrewMembers s
         on s.crewMemberId = d.managerId
      group by s.crewMemberId) x
Where avgSalary =
   (Select Min(avgSalary)
    from (Select s.crewMemberId,
             AVG(d.salary) avgSalary
          From CrewMembers d join CrewMembers s
              on s.crewMemberId = d.managerId
          group by s.crewMemberId)x)

-- Using sample data in a temp table variable:

declare @e table(crewmemberId int primary key not null,
              managerId int null, salary decimal)
Insert @e(crewmemberId, managerId, salary)
values (1, null, 23),
       (2,1,45), (3,1,33), (4,1,80),
       (5,2,14), (6,2,8), (7,2,12),
       (8,3,11), (9,3,5), (10,3,2),
       (11,4,51), (12,4,38), (13,4,17)

Select crewMemberId, avgSalary
From (Select s.crewMemberId,
         AVG(d.salary) avgSalary
      From @e d join @e s
         on s.crewMemberId = d.managerId
      group by s.crewMemberId) x
Where avgSalary =
   (Select Min(avgSalary)
    From (Select s.crewMemberId,
            AVG(d.salary) avgSalary
          From @e d join @e s
             on s.crewMemberId = d.managerId
          group by s.crewMemberId)x)

this gives crewmemberId = 3, Avg Salary = 6.0000;

It has the advantage of producing multiple results if direct hires of two or more Managers have the same avg salaries.


问:
C++ cin reading string into int type returns 0
```<code>#include <iostream>
using namespace std;
int main()
{
    cout << "Please enter your name and age\n";
    string first_name;
    int age;
    cin >> first_name;
    cin >> age;
    cout << "Hello, " << first_name << " (age " << age << ")!\n";
}
</code>```

If I type in Carlos for age or any other string I get a 0. How does this work(why)?

答:
If the input cannot be converted to a int (in your case), then the failbit will be set for std::cin. This can be retrieved by calling std::cin.fail() .

```<code> std::cin >> age;
 if (std::cin.fail()) {
     std::cout << "data entered is not of int type";
 }
</code>```

You can also use !std::cin instead of std::cin.fail() .

Body:
#include <iostream>
using namespace std;
int main()
{
    cout << "Please enter your name and age\n";
    string first_name;
    int age;
    cin >> first_name;
    cin >> age;
    cout << "Hello, " << first_name << " (age " << age << ")!\n";
}

If I type in Carlos for age or any other string I get a 0. How does this work(why)?

Body:
If the input cannot be converted to a int (in your case), then the failbit will be set for std::cin. This can be retrieved by calling std::cin.fail() .

 std::cin >> age;
 if (std::cin.fail()) {
     std::cout << "data entered is not of int type";
 }

You can also use !std::cin instead of std::cin.fail() .


问:
How do I make a scanner for a char array?
Like how do I make it so that the user can input the values for a char array?

Here's my attempt at trying to make it, but got a syntax error:

```<code>    char [] bacteriaStrand = new char[9];
    String bacteria = bac.next();
    bacteriaStrand = bacteria;
</code>```

Here's my entire code so far:

```<code>import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
    public static void main(String[] args)
    {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        bacteriaStrand = bacteria;
        for (int b = 0; b < bacteriaStrand.length; b++)
        {
            System.out.print(bacteriaStrand[b]);
            if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
            {
                System.out.println("Error! You can only input capital A, C, T, and G.");
            }
        }
    }
}
</code>```

答:
If you want a char[] (primitives) you can use a method which returns a char[].

src:

```<code>public static char[] toCharArray(String input){
        StringTokenizer stringTokenizer = new StringTokenizer(input, " ");
        char[] chars = new char[stringTokenizer.countTokens()];

        for (int i = 0; i < chars.length; i++)
            chars[i] = stringTokenizer.nextToken().charAt(0);

        return chars;
    }
</code>```

implementation:

```<code>char[] bacteriaStrand = toCharArray(bacteria);
</code>```

- OR -

If your string is not delimited:

*edited*

That second example can be easily implemented by just calling String#toCharArray(), which returns a copy of the characters in the string. – Obicere

```<code>String string = "STRING";
char[] chars = string.toCharArray();
</code>```

Thanks

Body:
Like how do I make it so that the user can input the values for a char array?

Here's my attempt at trying to make it, but got a syntax error:

    char [] bacteriaStrand = new char[9];
    String bacteria = bac.next();
    bacteriaStrand = bacteria;

Here's my entire code so far:

import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
    public static void main(String[] args)
    {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        bacteriaStrand = bacteria;
        for (int b = 0; b < bacteriaStrand.length; b++)
        {
            System.out.print(bacteriaStrand[b]);
            if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
            {
                System.out.println("Error! You can only input capital A, C, T, and G.");
            }
        }
    }
}

Body:
If you want a char[] (primitives) you can use a method which returns a char[].

src:

public static char[] toCharArray(String input){
        StringTokenizer stringTokenizer = new StringTokenizer(input, " ");
        char[] chars = new char[stringTokenizer.countTokens()];

        for (int i = 0; i < chars.length; i++)
            chars[i] = stringTokenizer.nextToken().charAt(0);

        return chars;
    }

implementation:

char[] bacteriaStrand = toCharArray(bacteria);

- OR -

If your string is not delimited:

*edited*

That second example can be easily implemented by just calling String#toCharArray(), which returns a copy of the characters in the string. – Obicere

String string = "STRING";
char[] chars = string.toCharArray();

Thanks


问:
Git push changes always force for pull
We are using git in our organization.
Now whenever we try to push the code in origin/development branch from our local development branch. Git always force us to take a pull before pushing the changes.

Is it possible to push the change without git pull ?

We tried out to create new branch from development branch. lets say dev_mybranch.
and pushed the branch to origin. So it is possible to merge origin/dev_mybranch to origin/dev branch ? In this way we may avoid to take pull each time. Can anyone help me out in this.

Because each time we take a pull. It takes a lot of time to setup the workspace again.

答:
git push -f <repository> <branch>
This should force push command.

Title: Git push changes always force for pull


问:
ffmpeg - extract exact number of frames from video
I want to create a maximum of 30 images from a video (and tile them for a sprite sheet).

I've tried using the 'select' with 'mod' but if the total number of frames does not fit neatly into the desired number of images (30) then I sometimes end up with more images, sometimes less.

For example if my video is 72 frames long, my 'mod' would be 72 / 30, which is 2.4.

I'm running this from a python script so i'm doing something like the following for the filter:

```<code>select='not(mod(n\," + str(mod) + "))'
</code>```

I think the mod has to be an integer (?) so I could either round down and use 2 which gives me 36 images or round up which gives me 24 images

Whats the best way to get exactly 30? - obviously the interval wouldn't be identical but thats fine.

Maybe I could use a for loop to generate a list of the frames closest to the desired interval and then pass that in as the select filter?

e.g. to get the frames I would do something like this:

```<code>nframes = 72 # number of frames in video
outImages = 30 # number of images I want
mod = float(nframes) / outImages # 2.4

frames = []

idx = 1

while i < nframes:
    print str(idx) + ": " + str(math.floor(i+0.5))
    frames.append(int(math.floor(i+0.5)))
    idx += 1
    i += mod
</code>```

Then am I able to pass that (the frames list) into the ffmpeg command? Or can I tell ffmpeg to do something similar?

答:
If you have a list of frames, you can just run

```<code>ffmpeg -i in.mp4 -vf select='eq(n,5)+eq(n,11)+eq(n,15)..' -vsync 0 frames%d.jpg
</code>```

There is a way to do this directly with select filter if you can decompose the frequency into a rational number (and do a bit of maths).

Let's take f = 2.4 which is the same as 12/5. So that means you need 5 frames from every 12. You can decompose that as 1 out of 3 + 1 out of 12. Since, in this case, the latter will coincide with the former selection, we can pick one frame earlier i.e. the 11th of every 12th frame.

```<code>ffmpeg -i in.mp4 -vf select='not(mod(n,3))+not(mod(n+1,12))' -vsync 0 frames%d.jpg
</code>```

The idea is to represent your frequency as a sum of reciprocals, 1/f = 1/m + 1/n + 1/p. You can use the offset device n+c or n-c if one of the denominators is a multiple of the others.

A cruder way to do this is

```<code>ffmpeg -i in.mp4 -vf select='not(mod(n,12))+not(mod(n+3,12))+not(mod(n+5,12))+not(mod(n+7,12))+not(mod(n+11,12))` -vsync 0 frames%d.jpg
</code>```

where total number of select clauses is equal to the number of frames needed from each set of X frames.

In any case, you can crudely limit the total number of frames by adding -vframes 30

Body:
I want to create a maximum of 30 images from a video (and tile them for a sprite sheet).

I've tried using the 'select' with 'mod' but if the total number of frames does not fit neatly into the desired number of images (30) then I sometimes end up with more images, sometimes less.

For example if my video is 72 frames long, my 'mod' would be 72 / 30, which is 2.4.

I'm running this from a python script so i'm doing something like the following for the filter:

select='not(mod(n\," + str(mod) + "))'

I think the mod has to be an integer (?) so I could either round down and use 2 which gives me 36 images or round up which gives me 24 images

Whats the best way to get exactly 30? - obviously the interval wouldn't be identical but thats fine.

Maybe I could use a for loop to generate a list of the frames closest to the desired interval and then pass that in as the select filter?

e.g. to get the frames I would do something like this:

nframes = 72 # number of frames in video
outImages = 30 # number of images I want
mod = float(nframes) / outImages # 2.4

frames = []

idx = 1

while i < nframes:
    print str(idx) + ": " + str(math.floor(i+0.5))
    frames.append(int(math.floor(i+0.5)))
    idx += 1
    i += mod

Then am I able to pass that (the frames list) into the ffmpeg command? Or can I tell ffmpeg to do something similar?

Body:
If you have a list of frames, you can just run

ffmpeg -i in.mp4 -vf select='eq(n,5)+eq(n,11)+eq(n,15)..' -vsync 0 frames%d.jpg

There is a way to do this directly with select filter if you can decompose the frequency into a rational number (and do a bit of maths).

Let's take f = 2.4 which is the same as 12/5. So that means you need 5 frames from every 12. You can decompose that as 1 out of 3 + 1 out of 12. Since, in this case, the latter will coincide with the former selection, we can pick one frame earlier i.e. the 11th of every 12th frame.

ffmpeg -i in.mp4 -vf select='not(mod(n,3))+not(mod(n+1,12))' -vsync 0 frames%d.jpg

The idea is to represent your frequency as a sum of reciprocals, 1/f = 1/m + 1/n + 1/p. You can use the offset device n+c or n-c if one of the denominators is a multiple of the others.

A cruder way to do this is

ffmpeg -i in.mp4 -vf select='not(mod(n,12))+not(mod(n+3,12))+not(mod(n+5,12))+not(mod(n+7,12))+not(mod(n+11,12))` -vsync 0 frames%d.jpg

where total number of select clauses is equal to the number of frames needed from each set of X frames.

In any case, you can crudely limit the total number of frames by adding -vframes 30


问:
trying to have selectable dice and sides
i am trying to generate being able to have a number of dice and then selecting the number of sides on the dice this is my code how would i make this work</p>

```<code>print("\n") #Creates new program
print("Welcome...")
print("You are are playing a game of dice, this is a two player game, who  ever rolls the highest number wins")
name1 = input("What is Player 1's Name?") #Inputs "player 1's" name
print("Hello", name1)
name2 = input("What is Player 2's Name?")
print("Greetings",name2)
from random import randint
Dice = input("Please select number of dice you would like to use (atleast 1)")
Sides = input("Please select number of sides on dice you would like to use")
print("You have selected", Dice," dice and", Sides,"Sides")
Roll11 = int(randint(Dice,Sides))
Roll12 = int(randint(Dice,Sides))
print ("Player 1's Roll")
print(Roll11)
print ("Player 2's Roll")
print (Roll12)
</code>```

答:
Problem, I can see, is this line:

```<code>Roll11 = int(randint(Dice,Sides))
</code>```

You are trying to pass string values as integer parameters.

try to use it like this:

```<code>Roll11 = randint(int(Dice), int(Sides))
</code>```

Body:
i am trying to generate being able to have a number of dice and then selecting the number of sides on the dice this is my code how would i make this work

print("\n") #Creates new program
print("Welcome...")
print("You are are playing a game of dice, this is a two player game, who  ever rolls the highest number wins")
name1 = input("What is Player 1's Name?") #Inputs "player 1's" name
print("Hello", name1)
name2 = input("What is Player 2's Name?")
print("Greetings",name2)
from random import randint
Dice = input("Please select number of dice you would like to use (atleast 1)")
Sides = input("Please select number of sides on dice you would like to use")
print("You have selected", Dice," dice and", Sides,"Sides")
Roll11 = int(randint(Dice,Sides))
Roll12 = int(randint(Dice,Sides))
print ("Player 1's Roll")
print(Roll11)
print ("Player 2's Roll")
print (Roll12)

Body:
Problem, I can see, is this line:

Roll11 = int(randint(Dice,Sides))

You are trying to pass string values as integer parameters.

try to use it like this:

Roll11 = randint(int(Dice), int(Sides))


问:
Copy input into another input BUT remove certain characters in the 2nd input
Please read before evaluate!
I know very well how to copy one input into another input, but I need something different, I need to remove some characters in the second input, i'm using this example:

```<code>window.onload = function() {
    var src = document.getElementById("one"),
        dst = document.getElementById("two");
    src.addEventListener('input', function() {
        dst.value = src.value;
    });
};
</code>```

And the HTML:

```<code><input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />
</code>```

What I need I think is simple, I only need to allow [a-zA-Z0-9-] in the 2nd input.

So, If I write in "one": Hello, How are you?

I want to see in "two": HelloHowareyou

My apologize for this stupid question, but I don't have too much knowledge on JS

答:
You definitely have options here, either with the use of replace() or match(). The example below simply replaces any characters that don't match (using ^ in Regex) with an empty character.

var src = document.getElementById("one"),
    dst = document.getElementById("two");

src.addEventListener('input', function() {
    dst.value = src.value.replace(/[^a-zA-Z0-9-]+/g, "");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="one" name="one" />
<input type="text" id="two" name="two" /></code>```

Body:
Please read before evaluate!
I know very well how to copy one input into another input, but I need something different, I need to remove some characters in the second input, i'm using this example:

window.onload = function() {
    var src = document.getElementById("one"),
        dst = document.getElementById("two");
    src.addEventListener('input', function() {
        dst.value = src.value;
    });
};

And the HTML:

<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />

What I need I think is simple, I only need to allow [a-zA-Z0-9-] in the 2nd input.

So, If I write in "one": Hello, How are you?

I want to see in "two": HelloHowareyou

My apologize for this stupid question, but I don't have too much knowledge on JS

Body:
You definitely have options here, either with the use of replace() or match(). The example below simply replaces any characters that don't match (using ^ in Regex) with an empty character.

var src = document.getElementById("one"),
    dst = document.getElementById("two");

src.addEventListener('input', function() {
    dst.value = src.value.replace(/[^a-zA-Z0-9-]+/g, "");
});

<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />


问:
How to get last Git tag matching regex criteria
I need Git command to get/find last tag starting with 'v' to get last versioning commit (I am using tags with v letter at the beginning to tag next application version (example: v0.9.1beta).

Is there any way to do it?

答:
While a single pattern --match "v[0-9]*" is enough here, know that Git 2.13 (Q2 2017) will improve that:

"git describe" and "git name-rev" have been taught to take more than one refname patterns to restrict the set of refs to base their naming output on, and also learned to take negative patterns to
name refs not to be used for naming via their "--exclude" option.

See commit 77d21f2, commit 43f8080, commit 96415b4, commit 290be66, commit 4a68748 (18 Jan 2017) by Jacob Keller (jacob-keller).

(Merged by Junio C Hamano -- gitster -- in commit 1b32498, 27 Feb 2017)

You now can have multiple match pattern:

```<code>--match <pattern>:
</code>```

Only consider tags matching the given glob(7) pattern,  excluding the "refs/tags/" prefix.

This can be used to avoid leaking private tags from the repository.

If given multiple times, a list of patterns will be accumulated, and tags matching any of the patterns will be considered.

Use --no-match to clear and reset the list of patterns.

And you have also an exclude pattern (or several) now!

```<code>--exclude <pattern>::
</code>```

Do not consider tags matching the given glob(7) pattern, excluding the "refs/tags/" prefix.

This can be used to narrow the tag space and  find only tags matching some meaningful criteria.

If given multiple times, a list of patterns will be accumulated and tags matching any of the patterns will be excluded.

When combined with --match a tag will be considered when it matches at least one --match pattern and does not match any of the --exclude patterns.

Use --no-exclude to clear and reset the list of patterns.

Body:
While a single pattern --match "v[0-9]*" is enough here, know that Git 2.13 (Q2 2017) will improve that:

"git describe" and "git name-rev" have been taught to take more than one refname patterns to restrict the set of refs to base their naming output on, and also learned to take negative patterns to
name refs not to be used for naming via their "--exclude" option.

See commit 77d21f2, commit 43f8080, commit 96415b4, commit 290be66, commit 4a68748 (18 Jan 2017) by Jacob Keller (jacob-keller).

(Merged by Junio C Hamano -- gitster -- in commit 1b32498, 27 Feb 2017)

You now can have multiple match pattern:

--match <pattern>:

Only consider tags matching the given glob(7) pattern,  excluding the "refs/tags/" prefix.

This can be used to avoid leaking private tags from the repository.

If given multiple times, a list of patterns will be accumulated, and tags matching any of the patterns will be considered.

Use --no-match to clear and reset the list of patterns.

And you have also an exclude pattern (or several) now!

--exclude <pattern>::

Do not consider tags matching the given glob(7) pattern, excluding the "refs/tags/" prefix.

This can be used to narrow the tag space and  find only tags matching some meaningful criteria.

If given multiple times, a list of patterns will be accumulated and tags matching any of the patterns will be excluded.

When combined with --match a tag will be considered when it matches at least one --match pattern and does not match any of the --exclude patterns.

Use --no-exclude to clear and reset the list of patterns.

ContentLicense: CC BY-SA 4.0


问:
sublime text error: 'php' is not recognized as an internal or external command, operable program or batch file
Only php path is not enough..........
Sublime Text3 error:PHP Screenshot

How can solve this problem?

答:
To add php & Sublime to the PATH:
1. Right click Computer -> Properties -> Advanced System Settings -> Environment Variable;
2. Under 'System Variables' select variable: Path and hit 'Edit';
3. At the 'Edit environment variable' hit 'New';
4. hit 'Browse';
5. find PHP folder (for me it was "H:\xampp\php") & add (hit 'Ok');
6. Go rule no.3 and no.4 add 'Sublime Text 3'(for me it was "C:\Program Files\Sublime Text 3")
4. OK, OK, OK

It's  work also for CMD.
  Blockquote
  Thanks


答:
Try this:

```<code>   print("Welcome...")
    print("You are are playing a game of dice, this is a two player game, who  ever rolls the highest number wins")
    name1 = input("What is Player 1's Name?") #Inputs "player 1's" name
    print("Hello", name1)
    name2 = input("What is Player 2's Name?")
    print("Greetings",name2)
    from random import randint
    Dice = int(input("Please select number of dice you would like to use (atleast 1)"))
    Sides = int(input("Please select number of sides on dice you would like to use"))
    print("You have selected", Dice," dice and", Sides,"Sides")
    Roll1=0
    Roll2=0
    for i in range(Dice):
        Roll1 += randint(1,Sides)
        Roll2 += randint(1,Sides)
    print ("Player 1's Roll")
    print(Roll1)
    print ("Player 2's Roll")
    print (Roll2)
</code>```

Changes: First, the first line is unnecessary in your code. Second, you were applying int to the wrong line. randint returns an int but input returns a string. Third, you were generating a random number between Dice and Sides. I modified to generate Dice random numbers between 1 and Sides

Title: trying to have selectable dice and sides

Body:
Try this:

   print("Welcome...")
    print("You are are playing a game of dice, this is a two player game, who  ever rolls the highest number wins")
    name1 = input("What is Player 1's Name?") #Inputs "player 1's" name
    print("Hello", name1)
    name2 = input("What is Player 2's Name?")
    print("Greetings",name2)
    from random import randint
    Dice = int(input("Please select number of dice you would like to use (atleast 1)"))
    Sides = int(input("Please select number of sides on dice you would like to use"))
    print("You have selected", Dice," dice and", Sides,"Sides")
    Roll1=0
    Roll2=0
    for i in range(Dice):
        Roll1 += randint(1,Sides)
        Roll2 += randint(1,Sides)
    print ("Player 1's Roll")
    print(Roll1)
    print ("Player 2's Roll")
    print (Roll2)

Changes: First, the first line is unnecessary in your code. Second, you were applying int to the wrong line. randint returns an int but input returns a string. Third, you were generating a random number between Dice and Sides. I modified to generate Dice random numbers between 1 and Sides