问:
How do I convert the string "NULL" in a flat file to DATETIME or DATETIME2?
tl;dr:  How to I convert "NULL" in a flat file to a NULL in SSDT/SSIS?

In SSMS run this code:

```<code>/* Run once
SET NOCOUNT ON
CREATE TABLE #source (DT DATETIME, DT2 DATETIME2)
CREATE TABLE #target (DT DATETIME, DT2 DATETIME2)
INSERT INTO #source
VALUES (GETDATE(),GETDATE()),(NULL,NULL),(GETDATE(),'9999-12-31 23:59:59')
*/
-- Cntl-Shift-F, results to CSV with headers
SELECT * FROM #source

-- Cntl-D, results to grid
INSERT INTO #target
SELECT * FROM #source
SELECT * FROM #target

-- Prep for next run
TRUNCATE TABLE #target
</code>```

Configure SSMS to create results to file as CSV with headers:  Tools --> Options --> Query Results --> SQL Server --> Results to Text:  Comma delimited pulldown, check Include column headers in the results set.

Your output will be similar to:

```<code>DT,DT2
2017-11-16 10:09:31.997,2017-11-16 10:09:31.9970000
NULL,NULL
2017-11-16 10:09:31.997,9999-12-31 23:59:59.0000000
</code>```

In SSDT, configure a flat file connection, Advanced "tab", set the column types to DT_DBTIMESTAMP for DT, DT_DBTIMESTAMP2 for DT2.

(Side question: any idea why SSDT invariably gets this wrong, and sets both columns to DT_DATE?  Clearly the columns have a time component.)

In the flat file source, configure RetainNulls = True (although I think this is irrelevant since I don't have true nulls, i.e. blank column containing no data.

How do I get SSDT to create the same results in #target that I get in SSMS?  IOW, I need to convert the text "NULL" to a "proper" NULL in the target.

My preferences:

configuration trickery within the flat file connection and/or flat file source,

derived column (I need help with the derivation),

script component.

答:
You'll need to pull the columns into your Flat File Source as strings (e.g., [DT_STR]) and then convert them using a Derived Column transformation with the following expressions:

Expression for DT:

```<code>DT == "NULL" ? NULL(DT_DBTIMESTAMP) : (DT_DBTIMESTAMP) DT
</code>```

Expression for DT2:

```<code>DT2 == "NULL" ? NULL(DT_DBTIMESTAMP2, 7) : (DT_DBTIMESTAMP2, 7) DT2
</code>```

Body:
tl;dr:  How to I convert "NULL" in a flat file to a NULL in SSDT/SSIS?

In SSMS run this code:

/* Run once
SET NOCOUNT ON
CREATE TABLE #source (DT DATETIME, DT2 DATETIME2)
CREATE TABLE #target (DT DATETIME, DT2 DATETIME2)
INSERT INTO #source
VALUES (GETDATE(),GETDATE()),(NULL,NULL),(GETDATE(),'9999-12-31 23:59:59')
*/
-- Cntl-Shift-F, results to CSV with headers
SELECT * FROM #source

-- Cntl-D, results to grid
INSERT INTO #target
SELECT * FROM #source
SELECT * FROM #target

-- Prep for next run
TRUNCATE TABLE #target

Configure SSMS to create results to file as CSV with headers:  Tools --> Options --> Query Results --> SQL Server --> Results to Text:  Comma delimited pulldown, check Include column headers in the results set.

Your output will be similar to:

DT,DT2
2017-11-16 10:09:31.997,2017-11-16 10:09:31.9970000
NULL,NULL
2017-11-16 10:09:31.997,9999-12-31 23:59:59.0000000

In SSDT, configure a flat file connection, Advanced "tab", set the column types to DT_DBTIMESTAMP for DT, DT_DBTIMESTAMP2 for DT2.

(Side question: any idea why SSDT invariably gets this wrong, and sets both columns to DT_DATE?  Clearly the columns have a time component.)

In the flat file source, configure RetainNulls = True (although I think this is irrelevant since I don't have true nulls, i.e. blank column containing no data.

How do I get SSDT to create the same results in #target that I get in SSMS?  IOW, I need to convert the text "NULL" to a "proper" NULL in the target.

My preferences:

configuration trickery within the flat file connection and/or flat file source,

derived column (I need help with the derivation),

script component.

Body:
You'll need to pull the columns into your Flat File Source as strings (e.g., [DT_STR]) and then convert them using a Derived Column transformation with the following expressions:

Expression for DT:

DT == "NULL" ? NULL(DT_DBTIMESTAMP) : (DT_DBTIMESTAMP) DT

Expression for DT2:

DT2 == "NULL" ? NULL(DT_DBTIMESTAMP2, 7) : (DT_DBTIMESTAMP2, 7) DT2


来源: stackexchange

问:
docker container increase listen queue size beyond 128
How can I increase the listen queue size beyond 128 on a docker image with a read only file system?

When I run my container I get the following error:

uWSGI: - Listen queue size is greater than the system max net.core.somaxconn (128).

I have a Dockerfile with base image python:2.7.  I am trying to increase system level limit on Unix socket and TCP connection listen queue so that uwsgi can set a listen queue limit of 1024, as described at uwsgi: your server socket listen backlog is limited to 100 connections.

I tried adding these RUN commands to the Dockerfile:

echo 4096 > /proc/sys/net/core/somaxconn

sysctl -w net.core.somaxconn=4096

But these both fail with the following errors respectively:

/bin/sh: 1: cannot create /proc/sys/net/core/somaxconn: Read-only file system

sysctl: setting key "net.core.somaxconn": Read-only file system

I also tried mounting a file to overwrite the /proc/sys/net/core/somaxconn and that failed with the error cannot be mounted because it is located inside "/proc"

I also tried running sudo sysctl -w net.core.somaxconn=4096
net.core.somaxconn = 4096 on the host before running, but it isn't reflected in the docker container; uwsgi still fails with the error uWSGI: - Listen queue size is greater than the system max net.core.somaxconn (128) and running cat /proc/sys/net/core/somaxconn shows 128 in the container while showing 4096 on the host.

答:
If you prefer using docker-compose. Here's the configuration that you want to adjust:

```<code>sysctls:
  net.core.somaxconn: 1024
</code>```

Or

```<code>sysctls:
  - net.core.somaxconn=1024
</code>```

Reference: https://github.com/compose-spec/compose-spec/blob/master/spec.md#sysctls

ContentLicense: CC BY-SA 3.0

Body:
If you prefer using docker-compose. Here's the configuration that you want to adjust:

sysctls:
  net.core.somaxconn: 1024

Or

sysctls:
  - net.core.somaxconn=1024

Reference: https://github.com/compose-spec/compose-spec/blob/master/spec.md#sysctls

ContentLicense: CC BY-SA 4.0


问:
Armstrong numbers in ruby
I'm having problems with this practice question.

Write a Ruby script to display the number of Armstrong numbers in an array of numbers.

An Armstrong number is a number in which the sum of [the] cubes of the digits of the number is [the] same as the number. For instance, 153, 370 and 371 are Armstrong numbers. Example:

```<code>153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
</code>```

Sample input

```<code>numbers = [123, 124, 153, 370, 234, 23, 45]
</code>```

Then the output will be

```<code>There are 2 Armstrong numbers in the list.
</code>```

My code is the following:

```<code>def get
  number = [123, 124, 153, 370, 234, 23, 45]
  s = number.count{}
  new_num = number
  sum = 0

  while new_num > 0
    sum = sum + (new_num % 10) * (new_num % 10) * (new_num % 10)
    new_num = new_num / 10
    number.count(new_num)
  end

  if sum == number
    puts "There are #{s} Armstrong"
  end
end
</code>```

It gives no output, and I'm not sure why.

答:
As already suggested you can utilise digits. Used with reduce you can write something like this:

```<code>number.select { |n| n.digits.reduce(0) { |m, n| m + n**3 } == n }
 #=> [153, 370]
</code>```

Title: Armstrong numbers in ruby

Body:
I'm having problems with this practice question.

Write a Ruby script to display the number of Armstrong numbers in an array of numbers.

An Armstrong number is a number in which the sum of [the] cubes of the digits of the number is [the] same as the number. For instance, 153, 370 and 371 are Armstrong numbers. Example:

153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Sample input

numbers = [123, 124, 153, 370, 234, 23, 45]

Then the output will be

There are 2 Armstrong numbers in the list.

My code is the following:

def get
  number = [123, 124, 153, 370, 234, 23, 45]
  s = number.count{}
  new_num = number
  sum = 0

  while new_num > 0
    sum = sum + (new_num % 10) * (new_num % 10) * (new_num % 10)
    new_num = new_num / 10
    number.count(new_num)
  end

  if sum == number
    puts "There are #{s} Armstrong"
  end
end

It gives no output, and I'm not sure why.

Body:
As already suggested you can utilise digits. Used with reduce you can write something like this:

number.select { |n| n.digits.reduce(0) { |m, n| m + n**3 } == n }
 #=> [153, 370]


问:
Customize Return Key text in JSQMessagesViewController
I'd like to make the keyboard Return key say "Send" when the user is typing in a JSQMessageViewController. I know I can do this in a normal Text Field as follows: myTextField.returnKeyType = UIReturnKeyType.send

But how do I get access to JSQMessagesViewController's text field so I can change the return key type?

答: Should be able to just  inputToolbar.contentView!.textView.returnKeyType = UIReturnKeyType.send


问:
Swift 4 URLsession with Authentication API Key
I am trying to make a POST Request for the Shippo REST API in Swift, but since it needs an API Authentication key I cannot figure out how to implement the key in the URLSession in Swift 4. As the Apple documentation puts it I cannot use urlsession.shared method.
The cURL command is:

```<code>curl https://api.goshippo.com/addresses/ \
 -H "Authorization: ShippoToken shippo_test_Token_Here" \
 -d name="Shawn Ippotle" \ -d company="Shippo" \
 -d street1="215 Clayton St." \
 -d street2="" \
 -d city="San Francisco" \
 -d state="CA" \
 -d zip=94117 \
 -d country="US" \
 -d phone="+1 555 341 9393" \
 -d email="shippotle@goshippo.com"\
 -d is_residential=True\
 -d metadata="Customer ID 123456"
</code>```

答:
what about something like:</p>

```<code>// preparing http request
let yourUrl = URL(string: "https://api.goshippo.com/addresses/")! // whatever is your url
let yourAuthorizationToken = "ShippoToken shippo_test_Token_Here" // whatever is your token
let yourPayload = Data() // whatever is your payload

var request = URLRequest(url:yourUrl)
request.httpMethod = "POST"
request.setValue(yourAuthorizationToken, forHTTPHeaderField: "Authorization")
request.httpBody = yourPayload

// executing the call
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
    // your stuff here
})
task.resume()
</code>```

Body:
I am trying to make a POST Request for the Shippo REST API in Swift, but since it needs an API Authentication key I cannot figure out how to implement the key in the URLSession in Swift 4. As the Apple documentation puts it I cannot use urlsession.shared method.
The cURL command is:

curl https://api.goshippo.com/addresses/ \
 -H "Authorization: ShippoToken shippo_test_Token_Here" \
 -d name="Shawn Ippotle" \ -d company="Shippo" \
 -d street1="215 Clayton St." \
 -d street2="" \
 -d city="San Francisco" \
 -d state="CA" \
 -d zip=94117 \
 -d country="US" \
 -d phone="+1 555 341 9393" \
 -d email="shippotle@goshippo.com"\
 -d is_residential=True\
 -d metadata="Customer ID 123456"

Body:
what about something like:

// preparing http request
let yourUrl = URL(string: "https://api.goshippo.com/addresses/")! // whatever is your url
let yourAuthorizationToken = "ShippoToken shippo_test_Token_Here" // whatever is your token
let yourPayload = Data() // whatever is your payload

var request = URLRequest(url:yourUrl)
request.httpMethod = "POST"
request.setValue(yourAuthorizationToken, forHTTPHeaderField: "Authorization")
request.httpBody = yourPayload

// executing the call
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
    // your stuff here
})
task.resume()


问:
How do I check which version of Python is running my script?
How do I check which version of the Python interpreter is running my script?</p>

答:
Several answers already suggest how to query the current python version. To check programmatically the version requirements, I'd make use of one of the following two methods:

```<code># Method 1: (see krawyoti's answer)
import sys
assert(sys.version_info >= (2,6))

# Method 2:
import platform
from distutils.version import StrictVersion
assert(StrictVersion(platform.python_version()) >= "2.6")
</code>```

Body:
Several answers already suggest how to query the current python version. To check programmatically the version requirements, I'd make use of one of the following two methods:

# Method 1: (see krawyoti's answer)
import sys
assert(sys.version_info >= (2,6))

# Method 2:
import platform
from distutils.version import StrictVersion
assert(StrictVersion(platform.python_version()) >= "2.6")


问:
Getting incorrect output from HTML form using $_POST method
I was having trouble with getting my login form to redirect to user home page since last night, after one successful attempt. After filling the form, I would press submit but I remained on the same page, except the form would be cleared.
So i decided to echo my inputs using the $_POST method, and after resubmitting the form, I saw that the page displayed 1 for both the entries. What is wrong in my code?

```<code><!DOCTYPE html>

<?php require_once("../Includes/Session.php"); ?>
<?php require_once("../Includes/DB_Connection.php"); ?>
<?php require_once("../Includes/Functions.php"); ?>
<?php require_once("../Includes/Validation_Functions.php"); ?>

<head>

<title> eTransport: Login</title>

<link rel="stylesheet" type="text/css" href="Login_Style.css">
</head>

<html>
<body>
<div class="div1">
    <h1 class="title"> Online eTransport Service (Fiji) </h1>

    <div>
    <form action="Login.php" method="POST">
        eTransport_ID: <input type="text" name="eTransport_ID"><br>
        Password: <input type="password" name="Password"><br>
        <input type="submit" name="Submit" value="submit"><br>
        <?php echo isset($_POST['eTransport_ID']); ?><br>
        <?php echo isset($_POST['Password']); ?>
    </form>
    </div>
</div>
</body>
</html>

<?php

$id = isset($_POST['eTransport_ID']);
$password = isset($_POST['Password']);

$checked_id= mysql_prep($id);

$query = "SELECT eTransport_ID ,Password FROM etrans_id_details";

$login_set = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($login_set)){
    if ($checked_id == $row["eTransport_ID"] AND $password == $row["Password"]){
        redirect_to("Home.php");
    }
}

?>
</code>```

The Output for my Code with $_POST:

答:
Here's the long answer.
Replace

$id = isset($_POST['eTransport_ID']);
$password = isset($_POST['Password']);

with

$id = $_POST['eTransport_ID'];
$password = $_POST['Password'];

and add code to test if it is set.

Body:
I was having trouble with getting my login form to redirect to user home page since last night, after one successful attempt. After filling the form, I would press submit but I remained on the same page, except the form would be cleared.
So i decided to echo my inputs using the $_POST method, and after resubmitting the form, I saw that the page displayed 1 for both the entries. What is wrong in my code?

<!DOCTYPE html>

<?php require_once("../Includes/Session.php"); ?>
<?php require_once("../Includes/DB_Connection.php"); ?>
<?php require_once("../Includes/Functions.php"); ?>
<?php require_once("../Includes/Validation_Functions.php"); ?>

<title> eTransport: Login</title>

<link rel="stylesheet" type="text/css" href="Login_Style.css">

 Online eTransport Service (Fiji)

    <form action="Login.php" method="POST">
        eTransport_ID: <input type="text" name="eTransport_ID">

        Password: <input type="password" name="Password">

        <input type="submit" name="Submit" value="submit">

        <?php echo isset($_POST['eTransport_ID']); ?>

        <?php echo isset($_POST['Password']); ?>
    </form>

<?php

$id = isset($_POST['eTransport_ID']);
$password = isset($_POST['Password']);

$checked_id= mysql_prep($id);

$query = "SELECT eTransport_ID ,Password FROM etrans_id_details";

$login_set = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($login_set)){
    if ($checked_id == $row["eTransport_ID"] AND $password == $row["Password"]){
        redirect_to("Home.php");
    }
}

?>

The Output for my Code with $_POST:


问:
Setting default value in html form date input
In a google-apps-script, I have an html form with two date inputs. I want to set the default values to be the prior week of the current day.

I cannot get the following scripts to work. Can anyone point out what I am doing wrong?

I am getting a "Object does not allow properties to be added or changed" error.

Code.gs:

```<code>function pickDates() {
  var d = new Date();
  var e = new Date();
  d.setDate((d.getDate() - d.getDay() % 7) - 7);
  e.setDate(e.getDate() - (e.getDay() + 1) % 7);
  d = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  e = e.getFullYear() + '-' + (e.getMonth() + 1) + '-' + e.getDate();
  var htmlB = HtmlService.createHtmlOutputFromFile('Pick Dates').setWidth(200).setHeight(200);
  htmlB.d = d;
  htmlB.e = e;
  SpreadsheetApp.getUi().showModalDialog(htmlB, 'Select Dates');
}
</code>```

Pick Dates.html:

```<code><!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<body>
  <form>
    Start Date<br>
    <input id="start" type="date" name="startDay">
    <br><br> End Date<br>
    <input id="end" type="date" name="endDay">
    <br><br>
    <input type="button" value="Submit" onclick="google.script.run
            .withSuccessHandler(google.script.host.close)
            .sendEmails(this.parentNode)" />
  </form>
  <script>
    document.getElementById('start').value = d;
    document.getElementById('end').value = e;
  </script>
</body>

</html>
</code>```

答:
To evaluate() the dates in the template, you will need to use createTemplateFromFile(). The error is because the HtmlOutput object returned from createHtmlOutputFromFile() can not have properties added like htmlB.d = d;. You can use a html template with scriptlets instead

```<code>function pickDates() {
  var d = new Date();
  var e = new Date();
  d.setDate((d.getDate() - d.getDay() % 7) - 7);
  e.setDate(e.getDate() - (e.getDay() + 1) % 7);
  d = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  e = e.getFullYear() + '-' + (e.getMonth() + 1) + '-' + e.getDate();

  // create a template
  var htmlB = HtmlService.createTemplateFromFile('Pick Dates');
  htmlB.d = d;
  htmlB.e = e;

  // evaluate() returns HtmlOuput object
  var modal_html = htmlB.evaluate().setWidth(200).setHeight(200);

  SpreadsheetApp.getUi().showModalDialog(modal_html, 'Select Dates');
}
</code>```

Pick Dates.html - add the printing scriptlets

```<code>...

  <script>
    document.getElementById('start').value = <?= d ?>;
    document.getElementById('end').value = <?= e ?>;
  </script>
</body>
</code>```

Body:
In a google-apps-script, I have an html form with two date inputs. I want to set the default values to be the prior week of the current day.

I cannot get the following scripts to work. Can anyone point out what I am doing wrong?

I am getting a "Object does not allow properties to be added or changed" error.

Code.gs:

function pickDates() {
  var d = new Date();
  var e = new Date();
  d.setDate((d.getDate() - d.getDay() % 7) - 7);
  e.setDate(e.getDate() - (e.getDay() + 1) % 7);
  d = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  e = e.getFullYear() + '-' + (e.getMonth() + 1) + '-' + e.getDate();
  var htmlB = HtmlService.createHtmlOutputFromFile('Pick Dates').setWidth(200).setHeight(200);
  htmlB.d = d;
  htmlB.e = e;
  SpreadsheetApp.getUi().showModalDialog(htmlB, 'Select Dates');
}

Pick Dates.html:

<!DOCTYPE html>

  <base target="_top">

  <form>
    Start Date

    <input id="start" type="date" name="startDay">

 End Date

    <input id="end" type="date" name="endDay">

    <input type="button" value="Submit" onclick="google.script.run
            .withSuccessHandler(google.script.host.close)
            .sendEmails(this.parentNode)" />
  </form>

Body:
To evaluate() the dates in the template, you will need to use createTemplateFromFile(). The error is because the HtmlOutput object returned from createHtmlOutputFromFile() can not have properties added like htmlB.d = d;. You can use a html template with scriptlets instead

function pickDates() {
  var d = new Date();
  var e = new Date();
  d.setDate((d.getDate() - d.getDay() % 7) - 7);
  e.setDate(e.getDate() - (e.getDay() + 1) % 7);
  d = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  e = e.getFullYear() + '-' + (e.getMonth() + 1) + '-' + e.getDate();

  // create a template
  var htmlB = HtmlService.createTemplateFromFile('Pick Dates');
  htmlB.d = d;
  htmlB.e = e;

  // evaluate() returns HtmlOuput object
  var modal_html = htmlB.evaluate().setWidth(200).setHeight(200);

  SpreadsheetApp.getUi().showModalDialog(modal_html, 'Select Dates');
}

Pick Dates.html - add the printing scriptlets

...

  <script>
    document.getElementById('start').value = <?= d ?>;
    document.getElementById('end').value = <?= e ?>;
  </script>
</body>


问:
Do an A Record redirect like Tumblr's Custom Domain feature
I am wanting to make a site where users will get a subdomain such as.. user.website.com
However I would like to offer a service like Tumblr where they can get a domain from a host, say GoDaddy, and set their A Record to my server's IP and instead of when someone goes to user.website.com it goes to whatever domain they have pointing to my IP..
Can anyone please refer me to an article that tells how to do such a thing.. or give me some advice..

Thanks!

答:
What you'll do is setup a wildcard DNS record for your domain and from your httpd virtual host, you will have to configure the servername using the input of the user for their preferred name (and you'll have to be proficient in .htaccess manipulation to do that -- sorry, I am not so familiar with it too so I cannot offer an advice regarding that aspect.).

You might want to look at this blog post for more information on how it's roughly done http://ma.tt/2003/10/wildcard-dns-and-sub-domains/

Hope this helps.
Ismael Casimpan :)

ContentLicense: CC BY-SA 2.5


问:
Tensorflow - ValueError: Shape must be rank 0 but is rank 1 for 'limit' for 'range' (op: 'Range') with input shapes: [], [10], []
I am learning how to build a simple neural network recently.

Following Mr Mo's tutorial, I write the code step by step:

```<code>from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob:1})
    return result

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    # stride [1, x_movement, y_movement, 1]
    # Must have strides[0] = strides[3] = 1
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    # stride [1, x_movement, y_movement, 1]
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1],padding='SAME')

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1,28,28,1])

## conv1 layer ##
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
## conv2 layer ##
W_conv2=weight_variable([5,5,32,64])
b_conv2=bias_variable([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_conv2)
## func1 layer ##
W_fc1=weight_variable([7*7*64,1024])
b_fc1=bias_variable([1024])
#[n_samples,7,7,64]->>[n_samples,7*7*64]
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
## func2 layer ##
W_fc2=weight_variable([1024,10])
b_fc2=bias_variable([10])
prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2),b_fc2)
# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))       # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
    if i % 50 == 0:
        print(compute_accuracy(
            mnist.test.images[:1000], mnist.test.labels[:1000]))
</code>```

However, I get an Error:

```<code>runfile('C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2/full_code.py', wdir='C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2')
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):

  File "<ipython-input-1-b66fc51270cf>", line 1, in <module>
    runfile('C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2/full_code.py', wdir='C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2/full_code.py", line 66, in <module>
prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2),b_fc2)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1531, in softmax
return _softmax(logits, gen_nn_ops._softmax, dim, name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1491, in _softmax
logits = _swap_axis(logits, dim, math_ops.subtract(input_rank, 1))

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1463, in _swap_axis
math_ops.range(dim_index), [last_index],

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py", line 1163, in range
return gen_math_ops._range(start, limit, delta, name=name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 1740, in _range
delta=delta, name=name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
op_def=op_def)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2338, in create_op
set_shapes_for_outputs(ret)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1719, in set_shapes_for_outputs
shapes = shape_func(op)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1669, in call_with_requiring
return call_cpp_shape_fn(op, require_shape_fn=True)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 610, in call_cpp_shape_fn
debug_python_shape_fn, require_shape_fn)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 676, in _call_cpp_shape_fn_impl
raise ValueError(err.message)

ValueError: Shape must be rank 0 but is rank 1
     for 'limit' for 'range' (op: 'Range') with input shapes: [], [10], [].
</code>```

I find some similar questions and their solutions. For example, "You declared the learning rate as a 1D Tesnor while it should be a scalar". Unfortunately, I don't know what it actually means or how to solve my problem.

Thank you so much in advance!

答:
On this line:

```<code>prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2), b_fc2)
</code>```

It should be:

```<code>prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)
</code>```

Body:
I am learning how to build a simple neural network recently.

Following Mr Mo's tutorial, I write the code step by step:

from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob:1})
    return result

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    # stride [1, x_movement, y_movement, 1]
    # Must have strides[0] = strides[3] = 1
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    # stride [1, x_movement, y_movement, 1]
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1],padding='SAME')

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1,28,28,1])

## conv1 layer ##
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
## conv2 layer ##
W_conv2=weight_variable([5,5,32,64])
b_conv2=bias_variable([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_conv2)
## func1 layer ##
W_fc1=weight_variable([7*7*64,1024])
b_fc1=bias_variable([1024])
#[n_samples,7,7,64]->>[n_samples,7*7*64]
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
## func2 layer ##
W_fc2=weight_variable([1024,10])
b_fc2=bias_variable([10])
prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2),b_fc2)
# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))       # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
    if i % 50 == 0:
        print(compute_accuracy(
            mnist.test.images[:1000], mnist.test.labels[:1000]))

However, I get an Error:

runfile('C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2/full_code.py', wdir='C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2')
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):

  File "<ipython-input-1-b66fc51270cf>", line 1, in <module>
    runfile('C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2/full_code.py', wdir='C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/220/tutorials-master/tensorflowTUT/tf18_CNN2/full_code.py", line 66, in <module>
prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2),b_fc2)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1531, in softmax
return _softmax(logits, gen_nn_ops._softmax, dim, name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1491, in _softmax
logits = _swap_axis(logits, dim, math_ops.subtract(input_rank, 1))

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1463, in _swap_axis
math_ops.range(dim_index), [last_index],

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py", line 1163, in range
return gen_math_ops._range(start, limit, delta, name=name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 1740, in _range
delta=delta, name=name)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
op_def=op_def)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2338, in create_op
set_shapes_for_outputs(ret)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1719, in set_shapes_for_outputs
shapes = shape_func(op)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1669, in call_with_requiring
return call_cpp_shape_fn(op, require_shape_fn=True)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 610, in call_cpp_shape_fn
debug_python_shape_fn, require_shape_fn)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 676, in _call_cpp_shape_fn_impl
raise ValueError(err.message)

ValueError: Shape must be rank 0 but is rank 1
     for 'limit' for 'range' (op: 'Range') with input shapes: [], [10], [].

I find some similar questions and their solutions. For example, "You declared the learning rate as a 1D Tesnor while it should be a scalar". Unfortunately, I don't know what it actually means or how to solve my problem.

Thank you so much in advance!

Body:
On this line:

prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2), b_fc2)

It should be:

prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)


问:
Pure JavaScript image manipulation
I have a use case where I want to created (a) a Node application that (b) performs basic image manipulations (PNG resize and crop) but (c) where I cannot have external dependencies like native libraries, GraphicsMagick, ImageMagick, PhantonJS, Inkscape, etc.

It all has to be done in pure JavaScript.

Given how simple the manipulation I want to do is (just PNG resize and crop) this doesn't seem impossible. However, I cannot find a crop/resize library that doesn't ultimately have an external or native dependency.

Does such a genuinely pure JavaScript library exist for crop/resize? How difficult would it be to implement this in pure JavaScript, if I had to do it myself? And where should I start?

Alternatively, is there a suitable C function for this that I could compile using emscripten, for example?

答:
Example of resize and crop using pure javascript image manipulation with MarvinJ:

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
var canvas3 = document.getElementById("canvas3");

image = new MarvinImage();
image.load("https://i.imgur.com/gaW8OeL.jpg", imageLoaded);

function imageLoaded(){
  imageOut = image.clone()
  image.draw(canvas1)
  // Crop
  Marvin.crop(image, imageOut, 50, 50, 100, 100);
  imageOut.draw(canvas2);
  // Scale
  Marvin.scale(image, imageOut, 100);
 imageOut.draw(canvas3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas><br/>
<canvas id="canvas3" width="200" height="200"></canvas></code>```

Title: Pure JavaScript image manipulation

Body:
Example of resize and crop using pure javascript image manipulation with MarvinJ:

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
var canvas3 = document.getElementById("canvas3");

image = new MarvinImage();
image.load("https://i.imgur.com/gaW8OeL.jpg", imageLoaded);

function imageLoaded(){
  imageOut = image.clone()
  image.draw(canvas1)
  // Crop
  Marvin.crop(image, imageOut, 50, 50, 100, 100);
  imageOut.draw(canvas2);
  // Scale
  Marvin.scale(image, imageOut, 100);
 imageOut.draw(canvas3);
}

<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas><br/>
<canvas id="canvas3" width="200" height="200"></canvas>


问:
ecma6 shortest for loop with if check
what is the shortest way to achieve this for loop in ecmascript 6:

```<code>var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};
</code>```

here is my attempt to see if the key is equal to my manually set variable, then i change that key item's field, if not, i change it to something else.

```<code>var str = '0'; // could also be an integer
for (var key in data.sales) {
  key ===  str ? data.sales[key].region = 'StateChosen' : data.sales[key].region = 'stateEliminated';
}
</code>```

what is the shortest way to achieve this using ecma6, object.keys, map, filter, every, etc methods?

答:
A for of loop with destructuring assignment and .entries() would help.

```<code>for (let [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';
</code>```

var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};
var str = '0';

for (var [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';

console.log(data);```

Title: ecma6 shortest for loop with if check

Body:
what is the shortest way to achieve this for loop in ecmascript 6:

var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};

here is my attempt to see if the key is equal to my manually set variable, then i change that key item's field, if not, i change it to something else.

var str = '0'; // could also be an integer
for (var key in data.sales) {
  key ===  str ? data.sales[key].region = 'StateChosen' : data.sales[key].region = 'stateEliminated';
}

what is the shortest way to achieve this using ecma6, object.keys, map, filter, every, etc methods?

Body:
A for of loop with destructuring assignment and .entries() would help.

for (let [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';

var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};
var str = '0';

for (var [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';

console.log(data);


问:
Trying to get the minimum value from dataset using reduceByKey
I have my data like this

```<code>id,category,price,description
1,2,59.98,xyz
2,2,129.99,pqr
3,2,89.99,mno
</code>```

I would like to retrieve the minimum float value using reduceByKey as a tuple by category
My expected answer should be like this (2,59.98)
I tried It like this but it  says error

```<code>val minPricedProducts= products.map(x=>(x.split(",")(1).toInt,x.split(",")(2).toFloat)).reduceByKey((a,b)=> if(a._1 < b._1) a else b).map(rec._1)
</code>```

:33: error: value _2 is not a member of Float

答:
The short answer is, this will work:

```<code>    val minPricedProducts= products.map{ x =>
       val d = x.split(",")
       (d(1).toInt,d(2).toFloat)
    }.reduceByKey( (a,b) => if(a < b) a else b)
</code>```

a and b are not tuples since reduceByKey already extracts the value part of the tuple for you, so you don't need the _1s.

Note that I did the split once, you don't want it do do twice since it takes twice as much time and memory.

Also, using .reduceByKey( (a,b) => Math.min(a,b) ) instead of the if is probably more readable.

I am not sure how you got an error: value _2 is not a member of Float when _2
 is not in the code you posted, did you mean _1 ?

It is worth noticing that there are better way to do this, since it's a CSV file
you could just read it with read.csv() and then you could just use df.groupBy("category").agg(min("price")).

Body:
I have my data like this

id,category,price,description
1,2,59.98,xyz
2,2,129.99,pqr
3,2,89.99,mno

I would like to retrieve the minimum float value using reduceByKey as a tuple by category
My expected answer should be like this (2,59.98)
I tried It like this but it  says error

val minPricedProducts= products.map(x=>(x.split(",")(1).toInt,x.split(",")(2).toFloat)).reduceByKey((a,b)=> if(a._1 < b._1) a else b).map(rec._1)

:33: error: value _2 is not a member of Float

Body:
The short answer is, this will work:

    val minPricedProducts= products.map{ x =>
       val d = x.split(",")
       (d(1).toInt,d(2).toFloat)
    }.reduceByKey( (a,b) => if(a < b) a else b)

a and b are not tuples since reduceByKey already extracts the value part of the tuple for you, so you don't need the _1s.

Note that I did the split once, you don't want it do do twice since it takes twice as much time and memory.

Also, using .reduceByKey( (a,b) => Math.min(a,b) ) instead of the if is probably more readable.

I am not sure how you got an error: value _2 is not a member of Float when _2
 is not in the code you posted, did you mean _1 ?

It is worth noticing that there are better way to do this, since it's a CSV file
you could just read it with read.csv() and then you could just use df.groupBy("category").agg(min("price")).


问:
How to notify if a class property of a class property has changed?
Let's say I have two classes in my WPF application:

```<code>public class Radio
{
    public int Volume { get; set; }
}

public class Vehicle
{
    public Radio MusicRadio { get; set; }

    private void Explode()
    {
        if (MusicRadio.Volume == 10)
        {
           Application.Shutdown();
        }
    }
}
</code>```

...where Vehicle has a property which is an instance of the Radio class. In my code behind, I want to set the volume of that radio class when a button is clicked:

```<code>private void startButton_Click(object sender, TextChangedEventArgs e)
{
    Vehicle Xterra = new Vehicle() { MusicRadio = new Radio() };

    for (int i = 0; i < 666; i++)
    {
        Xterra.MusicRadio.Volume = i;
    }
}
</code>```

In the above code, the application should shutdown via the Explode() method once the for loop reaches 10 iterations.

I want my Vehicle class to execute its private function Explode() every time the volume the MusicRadio property changes. How can I make sure it is alerted to this change?

答:
One way to do this would be to add a VolumeChanged event to your Radio class. Then in your Vehicle class, you can subscribe to the event and call Explode from there. Note I haven't worked with wpf, I am just assuming it will work there. Happy to delete the answer if that's not the case.

First, add the event to the Radio class:

```<code>public class Radio
{
    private int volume;

    public int Volume
    {
        get { return volume; }
        set
        {
            if (value == volume) return;
            volume = value;
            OnVolumeChanged(new EventArgs());
        }
    }

    public event EventHandler VolumeChanged;

    protected virtual void OnVolumeChanged(EventArgs e)
    {
        VolumeChanged?.Invoke(this, e);
    }
}
</code>```

Then, subscribe to it in the Vehicle class, and call Explode from there (or move the Explode code into the event directly):

```<code>public class Vehicle
{
    private Radio musicRadio;

    public Radio MusicRadio
    {
        get { return musicRadio; }
        set
        {
            musicRadio = value;
            if (musicRadio != null)
            {
                // In the unlikely event that the same radio is assigned more than once,
                // we only want to subscribe to the event one time, so remove it first.
                musicRadio.VolumeChanged -= MusicRadio_VolumeChanged;
                musicRadio.VolumeChanged += MusicRadio_VolumeChanged;
            }
        }
    }

    private void MusicRadio_VolumeChanged(object sender, EventArgs e)
    {
        Explode();
    }

    private void Explode()
    {
        if (MusicRadio.Volume == 10)
        {
            Application.Shutdown();
        }
    }
}
</code>```

Body:
Let's say I have two classes in my WPF application:

public class Radio
{
    public int Volume { get; set; }
}

public class Vehicle
{
    public Radio MusicRadio { get; set; }

    private void Explode()
    {
        if (MusicRadio.Volume == 10)
        {
           Application.Shutdown();
        }
    }
}

...where Vehicle has a property which is an instance of the Radio class. In my code behind, I want to set the volume of that radio class when a button is clicked:

private void startButton_Click(object sender, TextChangedEventArgs e)
{
    Vehicle Xterra = new Vehicle() { MusicRadio = new Radio() };

    for (int i = 0; i < 666; i++)
    {
        Xterra.MusicRadio.Volume = i;
    }
}

In the above code, the application should shutdown via the Explode() method once the for loop reaches 10 iterations.

I want my Vehicle class to execute its private function Explode() every time the volume the MusicRadio property changes. How can I make sure it is alerted to this change?

Body:
One way to do this would be to add a VolumeChanged event to your Radio class. Then in your Vehicle class, you can subscribe to the event and call Explode from there. Note I haven't worked with wpf, I am just assuming it will work there. Happy to delete the answer if that's not the case.

First, add the event to the Radio class:

public class Radio
{
    private int volume;

    public int Volume
    {
        get { return volume; }
        set
        {
            if (value == volume) return;
            volume = value;
            OnVolumeChanged(new EventArgs());
        }
    }

    public event EventHandler VolumeChanged;

    protected virtual void OnVolumeChanged(EventArgs e)
    {
        VolumeChanged?.Invoke(this, e);
    }
}

Then, subscribe to it in the Vehicle class, and call Explode from there (or move the Explode code into the event directly):

public class Vehicle
{
    private Radio musicRadio;

    public Radio MusicRadio
    {
        get { return musicRadio; }
        set
        {
            musicRadio = value;
            if (musicRadio != null)
            {
                // In the unlikely event that the same radio is assigned more than once,
                // we only want to subscribe to the event one time, so remove it first.
                musicRadio.VolumeChanged -= MusicRadio_VolumeChanged;
                musicRadio.VolumeChanged += MusicRadio_VolumeChanged;
            }
        }
    }

    private void MusicRadio_VolumeChanged(object sender, EventArgs e)
    {
        Explode();
    }

    private void Explode()
    {
        if (MusicRadio.Volume == 10)
        {
            Application.Shutdown();
        }
    }
}


问:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "users" does not exist
I am trying to run an existing Rails application (cloned from Github), but when I try to do db:migrate, I get the following error. I get the same error when I run db:purge, db:schema:load, etc... </p>

<p>This is the error: </p>

```<code>rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation
"users" does not exist
LINE 8:                WHERE a.attrelid = '"users"'::regclass
                                      ^
:               SELECT a.attname, format_type(a.atttypid,
a.atttypmod),
                 pg_get_expr(d.adbin, d.adrelid), a.attnotnull,
a.atttypid, a.atttypmod,
                 c.collname, col_description(a.attrelid, a.attnum) AS
comment
            FROM pg_attribute a
            LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND
a.attnum = d.adnum
            LEFT JOIN pg_type t ON a.atttypid = t.oid
            LEFT JOIN pg_collation c ON a.attcollation = c.oid AND
a.attcollation <> t.typcollation
           WHERE a.attrelid = '"users"'::regclass
             AND a.attnum > 0 AND NOT a.attisdropped
           ORDER BY a.attnum
</code>```

答:
When cloning a Rails project and setting up the database, you don't want to run the migrations. Migrations are intended for incremental database updates, and it's quite likely that they get old and don't run anymore. You want to run rake db:schema:load, which directly loads the db/schema.rb file into the database.

If you want a shortcut to running the seeds as well, you can use rake db:setup which creates the database (db:create), loads the schema (db:schema:load), then runs the seeds (db:seed). You can also do rake db:reset which does the same thing but drops the database first.

For more info see the Rails Guides on this topic: http://guides.rubyonrails.org/active_record_migrations.html#what-are-schema-files-for-questionmark

There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.

Body:
I am trying to run an existing Rails application (cloned from Github), but when I try to do db:migrate, I get the following error. I get the same error when I run db:purge, db:schema:load, etc...

This is the error:

rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation
"users" does not exist
LINE 8:                WHERE a.attrelid = '"users"'::regclass
                                      ^
:               SELECT a.attname, format_type(a.atttypid,
a.atttypmod),
                 pg_get_expr(d.adbin, d.adrelid), a.attnotnull,
a.atttypid, a.atttypmod,
                 c.collname, col_description(a.attrelid, a.attnum) AS
comment
            FROM pg_attribute a
            LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND
a.attnum = d.adnum
            LEFT JOIN pg_type t ON a.atttypid = t.oid
            LEFT JOIN pg_collation c ON a.attcollation = c.oid AND
a.attcollation <> t.typcollation
           WHERE a.attrelid = '"users"'::regclass
             AND a.attnum > 0 AND NOT a.attisdropped
           ORDER BY a.attnum


问:
.Net WebAPI Post method is not working from Angular2 service
I am newbie in Angular 2. I am sending form data from angular 2 to webapi but it is not working.
WebAPI:

```<code>public class FetchDataController : ApiController
    {

        [HttpGet]
        public IList<Student> ListOfStudents()
        {
            AppRepository objapp = new AppRepository();
            IList<Student> objData = null;
            objData = objapp.getStudent();
            return objData;
        }

        [HttpPost]
        [Route("PostStudent")]
        public JsonResult<Boolean> PostStudent(Student value)
        {
            // Append text to an existing file named "WriteLines.txt".
            string data = "ID: " + value.Id + ", FirstName: " + value.FirstName + ",LastName: " + value.LastName + ",Salary: " + value.salary;
            using (StreamWriter outputFile = new StreamWriter(HttpContext.Current.Server.MapPath("~")+ "/TestVD/WriteLines.txt", true))
            {
                outputFile.WriteLine(data);
            }
            return Json(true);
        }

    }
</code>```

My WebAPIConfig.js is as follows. I have added CORS handling in here as well as Webconfig file:

```<code>var cors = new EnableCorsAttribute("http://localhost", "*", "*");
              config.EnableCors(cors);

            // Web API configuration and services
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
            name: "ListOfStudents",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { controller = "FetchData", action = "ListOfStudents", id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "PostStudent",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { controller = "FetchData", action = "PostStudent", id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
</code>```

Now, From Angular 2, I am able to show data using List of student webAPI method but while posting I am getting "405 (Method Not Allowed)" from my WEBAPI url.
I am gettling below response from WEBAPI post method.

```<code>ok
:
false
status
:
405
statusText
:
"Method Not Allowed"
type
:
2
url
:
"http://localhost/TestWebService/api/FetchData/"
_body
:
"{"Message":"The requested resource does not support http method 'POST'."}"
</code>```

My Angular 2 service code is as follows

```<code>@Injectable()
export class RssService {
private studentUrl = "http://localhost/TestWebService/api/FetchData/";
    constructor(private http: Http) {   }
    getStudentList() {
        return this.http.get(this.studentUrl)
            .map(res => <Student[]>res.json())
            .catch(this.handleError);
    }
    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
    postStudent(model: any): Observable<any> {
        let body = JSON.stringify(model);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        console.log('add Student start : ' + body);
        return this.http.post(this.studentUrl , body, options)
            .map((response: Response) => <any>response.json())
            .catch(this.handleError);
    }
}
</code>```

Could you please help me...

答: I have resolved it due to System.Net and System.Web namespace. This link help me a lot.</p>

Body:
I am newbie in Angular 2. I am sending form data from angular 2 to webapi but it is not working.
WebAPI:

public class FetchDataController : ApiController
    {

        [HttpGet]
        public IList<Student> ListOfStudents()
        {
            AppRepository objapp = new AppRepository();
            IList<Student> objData = null;
            objData = objapp.getStudent();
            return objData;
        }

        [HttpPost]
        [Route("PostStudent")]
        public JsonResult<Boolean> PostStudent(Student value)
        {
            // Append text to an existing file named "WriteLines.txt".
            string data = "ID: " + value.Id + ", FirstName: " + value.FirstName + ",LastName: " + value.LastName + ",Salary: " + value.salary;
            using (StreamWriter outputFile = new StreamWriter(HttpContext.Current.Server.MapPath("~")+ "/TestVD/WriteLines.txt", true))
            {
                outputFile.WriteLine(data);
            }
            return Json(true);
        }

    }

My WebAPIConfig.js is as follows. I have added CORS handling in here as well as Webconfig file:

var cors = new EnableCorsAttribute("http://localhost", "*", "*");
              config.EnableCors(cors);

            // Web API configuration and services
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
            name: "ListOfStudents",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { controller = "FetchData", action = "ListOfStudents", id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "PostStudent",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { controller = "FetchData", action = "PostStudent", id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Now, From Angular 2, I am able to show data using List of student webAPI method but while posting I am getting "405 (Method Not Allowed)" from my WEBAPI url.
I am gettling below response from WEBAPI post method.

ok
:
false
status
:
405
statusText
:
"Method Not Allowed"
type
:
2
url
:
"http://localhost/TestWebService/api/FetchData/"
_body
:
"{"Message":"The requested resource does not support http method 'POST'."}"

My Angular 2 service code is as follows

@Injectable()
export class RssService {
private studentUrl = "http://localhost/TestWebService/api/FetchData/";
    constructor(private http: Http) {   }
    getStudentList() {
        return this.http.get(this.studentUrl)
            .map(res => <Student[]>res.json())
            .catch(this.handleError);
    }
    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
    postStudent(model: any): Observable<any> {
        let body = JSON.stringify(model);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        console.log('add Student start : ' + body);
        return this.http.post(this.studentUrl , body, options)
            .map((response: Response) => <any>response.json())
            .catch(this.handleError);
    }
}

Could you please help me...


问:
MS Access - Show/hide label based on checkbox
I need to print a label on a report only if a checkbox is checked.
I've tried many different lines of code but I can't get it to work. This is what I have at the moment (on the OnFormat event of the footer of my report):

```<code>If chkSignature = True Then
  CEOsign.Visible = True
Else
  CEOsign.Visible = False
End If
</code>```

and this is a working example you can play with.

If the checkbox is ticked I want to print the label for the signature. If the checkbox is unticked I want to hide it. Can you help me? Thanks.

答: I didn't download the file, but I am guessing you are not changing the checkbox during the right event. As I recall, Detail_Format is the right event in which to place this code if you want to change visibility of items in the Detail section. MS Access is sometimes finicky, however, and I recall times when this sort of task did not go smoothly. Good luck!</p>

Body:
I need to print a label on a report only if a checkbox is checked.
I've tried many different lines of code but I can't get it to work. This is what I have at the moment (on the OnFormat event of the footer of my report):

If chkSignature = True Then
  CEOsign.Visible = True
Else
  CEOsign.Visible = False
End If

and this is a working example you can play with.

If the checkbox is ticked I want to print the label for the signature. If the checkbox is unticked I want to hide it. Can you help me? Thanks.


问:
Python end function after another function returns result
I may be approaching this all wrong but still this is where I'm at.  I have very large log files I'm trying to search, up to 30gb in some cases.  I'm writing a script to pull info and have been playing with multi process to speed it up a bit.  right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work.  I'm wondering if it's possible to stop one function one a result from the other.  Such as if the top function finds a result they both stop.  This way I can build it out as needed.</p>

```<code>from file_read_backwards import FileReadBackwards
from multiprocessing import Process
import sys

z = "log.log"

#!/usr/bin/env python
rocket = 0

def top():
    target = "test"
    with open(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

def bottom():
    target = "text"
    with FileReadBackwards(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

if __name__=='__main__':
     p1 = Process(target = top)
     p1.start()
     p2 = Process(target = bottom)
     p2.start()
</code>```

答:
Simple example using a multiprocessing.Pool and callback function.
Terminates remaining pool processes once a result has returned.

You could add an arbitrary number of processes to search from different offsets in the file using this approach.

```<code>import math
import time

from multiprocessing import Pool
from random import random

def search(pid, wait):
    """Sleep for wait seconds, return PID
    """
    time.sleep(wait)
    return pid

def done(result):
    """Do something with result and stop other processes
    """
    print("Process: %d done." % result)
    pool.terminate()
    print("Terminate Pool")

pool = Pool(2)
pool.apply_async(search, (1, math.ceil(random() * 3)), callback=done)
pool.apply_async(search, (2, math.ceil(random() * 3)), callback=done)

# do other stuff ...

# Wait for result
pool.close()
pool.join()  # block our main thread
</code>```

Body:
I may be approaching this all wrong but still this is where I'm at.  I have very large log files I'm trying to search, up to 30gb in some cases.  I'm writing a script to pull info and have been playing with multi process to speed it up a bit.  right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work.  I'm wondering if it's possible to stop one function one a result from the other.  Such as if the top function finds a result they both stop.  This way I can build it out as needed.

from file_read_backwards import FileReadBackwards
from multiprocessing import Process
import sys

z = "log.log"

#!/usr/bin/env python
rocket = 0

def top():
    target = "test"
    with open(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

def bottom():
    target = "text"
    with FileReadBackwards(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

if __name__=='__main__':
     p1 = Process(target = top)
     p1.start()
     p2 = Process(target = bottom)
     p2.start()

Body:
Simple example using a multiprocessing.Pool and callback function.
Terminates remaining pool processes once a result has returned.

You could add an arbitrary number of processes to search from different offsets in the file using this approach.

import math
import time

from multiprocessing import Pool
from random import random

def search(pid, wait):
    """Sleep for wait seconds, return PID
    """
    time.sleep(wait)
    return pid

def done(result):
    """Do something with result and stop other processes
    """
    print("Process: %d done." % result)
    pool.terminate()
    print("Terminate Pool")

pool = Pool(2)
pool.apply_async(search, (1, math.ceil(random() * 3)), callback=done)
pool.apply_async(search, (2, math.ceil(random() * 3)), callback=done)

# do other stuff ...

# Wait for result
pool.close()
pool.join()  # block our main thread


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答:
The main disadvantage of output buffering is not knowing (or paying attention to) how deep your buffer stack is. Combine this with overly aggressive error handling or subroutines that exit/die unexpectedly and you will lose whatever is in the buffer, leaving few clues as to what is going on.

For example, the Zend framework makes use of output buffering for almost everything, but when it hits a critical error it prints a message and exits immediately. Any helpful debugging information is lost.


问:
How to use substring function in oracle in date columns which is in number format
I have a Column Called FILLD_DT in a table which has number(8) data type format. I am trying to use this column and create a new column called Derived date in my own table.

Ex: Filled Date = 20170107

Below is the query I am using and I am getting

ORA-00932: inconsistent datatypes: expected CHAR got NUMBER

```<code>(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170501'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
 ELSE FILLD_DT
 END ) AS DRVD_DATE
</code>```

please help me understand

below is the full query

```<code>SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
 WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170401'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170115'
 WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170415'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170715'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171015'
ELSE FILLD_DT
END)
FROM
SOURCE
</code>```

and I modified the query to your suggestion and I am getting the below error

[Error] Execution (8: 29): ORA-01830: date format picture ends
  before converting entire input string

```<code>SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
( trunc( to_date( FILLD_DT || '01', 'yyyymmdd' ), 'Q' )
 ) AS DRVD_DATE
FROM
SOURCE
WHERE
SRC_ID = 163662
</code>```

答:
I will assume that you're using oracle 10g or gratter and the format in FILLD_DT is "YYYYMMDD".

This work in Oracle 11g:

```<code>SELECT TO_DATE(FILLD_DT,'YYYYMMDD') AS Derived_date  FROM SOURCE;
</code>```

Just in case if a single value in FILLD_DT not match with the given format it will return an error. To prevent the miss parse you can skip those records using a user defined function and a case statement.

Some data to play with:

```<code>CREATE TABLE SOME_DATA (
  NUMBER_DATE NUMBER(8)
);

INSERT INTO SOME_DATA VALUES(20170912);
INSERT INTO SOME_DATA VALUES(20030530);
INSERT INTO SOME_DATA VALUES(19901131);
INSERT INTO SOME_DATA VALUES(20170731);
INSERT INTO SOME_DATA VALUES(20170230);
COMMIT;
</code>```

Function to validate if is a valid date:

```<code>CREATE OR REPLACE FUNCTION IS_DATE(V_DATE IN VARCHAR2) RETURN NUMBER IS
    V_DATE1 DATE;
BEGIN
    SELECT TO_DATE(V_DATE,'YYYYMMDD') INTO V_DATE1 FROM DUAL;
        RETURN 1;
    EXCEPTION WHEN OTHERS THEN
        RETURN 0;
END;
</code>```

Finally the query:

```<code>SELECT
    CASE IS_DATE(NUMBER_DATE)
        WHEN 1 THEN TO_DATE(NUMBER_DATE,'YYYYMMDD')
        ELSE NULL
    END AS Derived_date,NUMBER_DATE
FROM SOME_DATA ;
</code>```

User defined function

Body:
I have a Column Called FILLD_DT in a table which has number(8) data type format. I am trying to use this column and create a new column called Derived date in my own table.

Ex: Filled Date = 20170107

Below is the query I am using and I am getting

ORA-00932: inconsistent datatypes: expected CHAR got NUMBER

(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170501'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
 ELSE FILLD_DT
 END ) AS DRVD_DATE

please help me understand

below is the full query

SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
 WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170401'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170115'
 WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170415'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170715'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171015'
ELSE FILLD_DT
END)
FROM
SOURCE

and I modified the query to your suggestion and I am getting the below error

[Error] Execution (8: 29): ORA-01830: date format picture ends
  before converting entire input string

SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
( trunc( to_date( FILLD_DT || '01', 'yyyymmdd' ), 'Q' )
 ) AS DRVD_DATE
FROM
SOURCE
WHERE
SRC_ID = 163662

Body:
I will assume that you're using oracle 10g or gratter and the format in FILLD_DT is "YYYYMMDD".

This work in Oracle 11g:

SELECT TO_DATE(FILLD_DT,'YYYYMMDD') AS Derived_date  FROM SOURCE;

Just in case if a single value in FILLD_DT not match with the given format it will return an error. To prevent the miss parse you can skip those records using a user defined function and a case statement.

Some data to play with:

CREATE TABLE SOME_DATA (
  NUMBER_DATE NUMBER(8)
);

INSERT INTO SOME_DATA VALUES(20170912);
INSERT INTO SOME_DATA VALUES(20030530);
INSERT INTO SOME_DATA VALUES(19901131);
INSERT INTO SOME_DATA VALUES(20170731);
INSERT INTO SOME_DATA VALUES(20170230);
COMMIT;

Function to validate if is a valid date:

CREATE OR REPLACE FUNCTION IS_DATE(V_DATE IN VARCHAR2) RETURN NUMBER IS
    V_DATE1 DATE;
BEGIN
    SELECT TO_DATE(V_DATE,'YYYYMMDD') INTO V_DATE1 FROM DUAL;
        RETURN 1;
    EXCEPTION WHEN OTHERS THEN
        RETURN 0;
END;

Finally the query:

SELECT
    CASE IS_DATE(NUMBER_DATE)
        WHEN 1 THEN TO_DATE(NUMBER_DATE,'YYYYMMDD')
        ELSE NULL
    END AS Derived_date,NUMBER_DATE
FROM SOME_DATA ;

User defined function


问:
How to enable "tap and slide" in a UISlider?
What I want to get is a UISlider which lets the user not only slide when he starts on its thumbRect, but also when he taps elsewhere. When the user taps on the slider but outside of the thumbRect, the slider should jump to that value and then still keeping up to the user's sliding gesture.

What I have tried so far was implementing a subclass of UIGestureRecognizer like in this suggestion. It starts right then when a touch down somewhere outside the thumbRect occurs. The problem is that the slider sets its value but then further sliding gestures are ignored because the touch down recognizer has stolen the touch.

How can I implement a slider where you can tap anywhere but still slide right away?

Edit: ali59a was so kind to add an example of what I've done now. This requires to lift the finger again, after that I can touch and drag to slide (a tap is not what I want, I need a 'touch and slide' right away).

答:
I didn't check David Williames answer, but I'll post my solution in case someone is looking for another way to do it.

Swift 4

First create a custom UISlider so that it will detect touches on the bar as well :

```<code>class CustomSlider: UISlider {
    override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        return true
    }
}
</code>```

(don't forget to set your slider to be this CustomSlider, on storyboard)

The on viewDidLoad of the view controller that is displaying the slider:

```<code>self.slider.addTarget(self, action: #selector(sliderTap), for: .touchDown)
</code>```

(this is only used to pause the player when moving the slider)

Then, on your UISlider action:

```<code>@IBAction func moveSlider(_ sender: CustomSlider, forEvent event: UIEvent) {
    if let touchEvent = event.allTouches?.first {
        switch touchEvent.phase {
            case .ended, .cancelled, .stationary:
                //here, start playing if needed
                startPlaying()
            default:
                break
        }
    }
}
</code>```

And on your "sliderTap" selector method:

```<code>@objc func sliderTap() {
    //pause the player, if you want
    audioPlayer?.pause()
}
</code>```

Suggestion: set the player "currentTime" before starting to play:

```<code>private func startPlaying() {
    audioPlayer?.currentTime = Double(slider.value)
    audioPlayer?.play()
}
</code>```

Body:
I didn't check David Williames answer, but I'll post my solution in case someone is looking for another way to do it.

Swift 4

First create a custom UISlider so that it will detect touches on the bar as well :

class CustomSlider: UISlider {
    override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        return true
    }
}

(don't forget to set your slider to be this CustomSlider, on storyboard)

The on viewDidLoad of the view controller that is displaying the slider:

self.slider.addTarget(self, action: #selector(sliderTap), for: .touchDown)

(this is only used to pause the player when moving the slider)

Then, on your UISlider action:

@IBAction func moveSlider(_ sender: CustomSlider, forEvent event: UIEvent) {
    if let touchEvent = event.allTouches?.first {
        switch touchEvent.phase {
            case .ended, .cancelled, .stationary:
                //here, start playing if needed
                startPlaying()
            default:
                break
        }
    }
}

And on your "sliderTap" selector method:

@objc func sliderTap() {
    //pause the player, if you want
    audioPlayer?.pause()
}

Suggestion: set the player "currentTime" before starting to play:

private func startPlaying() {
    audioPlayer?.currentTime = Double(slider.value)
    audioPlayer?.play()
}


问:
How to store json data when I use Android Studio 3.0?
In my Android App, I desgin the following json data construction, the json data will be read, added, updated and deleted node in the future.

I think I should store the json data, how can I persist the json data? do I have to save it as text file under the folder \assets ?

And more, is there a simple way to handle json data ? do I need use Gson library?

```<code>{
   "Setting": [

      {
        "id": "34345",
        "Bluetooth": { "Status": "ON" },
        "WiFi": { "Name": "MyConnect", "Status": "OFF"  }
      }
      ,

      {
         "id": "16454",
         "Bluetooth": { "Status": "OFF" }
      }

   ]

}
</code>```

答:
Compare to the answer https://stackoverflow.com/a/18463758/4265739

The easiest way is to use SharedPreferences and Gson.

add GSON dependency in Gradle file:

```<code>compile 'com.google.code.gson:gson:2.8.0'
</code>```

The code adjusted for Kotlin is
to store:

```<code>val prefsEditor = PreferenceManager.getDefaultSharedPreferences(this).edit()
val json = Gson().toJson(yourObject)
prefsEditor.putString("yourObject", json)
prefsEditor.commit()
</code>```

to retrieve:

```<code> val json: String = sp.getString("yourObject", "")
 val yourObject = Gson().fromJson<YourObject>(json, YourObject::class.java)
</code>```

If you have lots of data look at https://developer.android.com/guide/topics/data/data-storage.html for your options

Body:
In my Android App, I desgin the following json data construction, the json data will be read, added, updated and deleted node in the future.

I think I should store the json data, how can I persist the json data? do I have to save it as text file under the folder \assets ?

And more, is there a simple way to handle json data ? do I need use Gson library?

{
   "Setting": [

      {
        "id": "34345",
        "Bluetooth": { "Status": "ON" },
        "WiFi": { "Name": "MyConnect", "Status": "OFF"  }
      }
      ,

      {
         "id": "16454",
         "Bluetooth": { "Status": "OFF" }
      }

   ]

}

Body:
Compare to the answer https://stackoverflow.com/a/18463758/4265739

The easiest way is to use SharedPreferences and Gson.

add GSON dependency in Gradle file:

compile 'com.google.code.gson:gson:2.8.0'

The code adjusted for Kotlin is
to store:

val prefsEditor = PreferenceManager.getDefaultSharedPreferences(this).edit()
val json = Gson().toJson(yourObject)
prefsEditor.putString("yourObject", json)
prefsEditor.commit()

to retrieve:

 val json: String = sp.getString("yourObject", "")
 val yourObject = Gson().fromJson<YourObject>(json, YourObject::class.java)

If you have lots of data look at https://developer.android.com/guide/topics/data/data-storage.html for your options


问:
ConfigurationManager.AppSettings in Roslyn returns an empty string
I'm fully aware this question has been asked multiple time on here, but I have scoured the internet and have yet to find a solution.

I run the following .csx file with scriptcs (just to test and make sure the ConfigurationManager works):

```<code>#load "C:\Tickets\LoadConfig.csx"

using System;
using System.Configuration;
Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Console.WriteLine(ConfigurationManager.AppSettings.AllKeys);
</code>```

Here is the LoadConfig.csx, I found it on here SO post and multiple people said they had good results.

```<code>#r "System.Configuration"

using System;
using System.IO;
using System.Linq;

var paths = new[] { Path.Combine(Environment.CurrentDirectory, "web.config"), Path.Combine(Environment.CurrentDirectory, "app.config") };
var configPath = paths.FirstOrDefault(p => File.Exists(p));

if (configPath != null)
{
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath);

    var t = typeof(System.Configuration.ConfigurationManager);
    var f = t.GetField("s_initState", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
    f.SetValue(null, 0);

    Console.Write(configPath); // Here to make sure it found the app.config file properly
}
</code>```

Here's the app.config too:

```<code><?xml version="1.0" encoding="utf-8" ?>

<configuration>
    <appSettings>
        <add key="testKey" value="testValue" />
    </appSettings>
</configuration>
</code>```

However, when I run the first code block it tells me that the current configuration file is app.config and that the AllKeys property is System.String[]. I've made sure that all the files are in the same folder and that the app.config is written correctly too. I'm just stuck right now and not sure if there are any other solutions or if I'm completely overlooking something. If anyone has any suggestions they'd be much appreciated, thanks.

答:
This is because you are printing ConfigurationManager.AppSettings.AllKeys directly, which is not a string so it just prints the object type.

You need to iterate around the keys with something like

```<code>var keys = ConfigurationManager.AppSettings.AllKeys;
foreach (var key in keys)
{
    Console.WriteLine(key);
}
Console.ReadLine();
</code>```

or

```<code>ConfigurationManager.AppSettings.AllKeys.ToList().ForEach(k => Console.WriteLine(k));
</code>```

Output:

testKey

Body:
I'm fully aware this question has been asked multiple time on here, but I have scoured the internet and have yet to find a solution.

I run the following .csx file with scriptcs (just to test and make sure the ConfigurationManager works):

#load "C:\Tickets\LoadConfig.csx"

using System;
using System.Configuration;
Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Console.WriteLine(ConfigurationManager.AppSettings.AllKeys);

Here is the LoadConfig.csx, I found it on here SO post and multiple people said they had good results.

#r "System.Configuration"

using System;
using System.IO;
using System.Linq;

var paths = new[] { Path.Combine(Environment.CurrentDirectory, "web.config"), Path.Combine(Environment.CurrentDirectory, "app.config") };
var configPath = paths.FirstOrDefault(p => File.Exists(p));

if (configPath != null)
{
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath);

    var t = typeof(System.Configuration.ConfigurationManager);
    var f = t.GetField("s_initState", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
    f.SetValue(null, 0);

    Console.Write(configPath); // Here to make sure it found the app.config file properly
}

Here's the app.config too:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>
    <appSettings>
        <add key="testKey" value="testValue" />
    </appSettings>
</configuration>

However, when I run the first code block it tells me that the current configuration file is app.config and that the AllKeys property is System.String[]. I've made sure that all the files are in the same folder and that the app.config is written correctly too. I'm just stuck right now and not sure if there are any other solutions or if I'm completely overlooking something. If anyone has any suggestions they'd be much appreciated, thanks.

Body:
This is because you are printing ConfigurationManager.AppSettings.AllKeys directly, which is not a string so it just prints the object type.

You need to iterate around the keys with something like

var keys = ConfigurationManager.AppSettings.AllKeys;
foreach (var key in keys)
{
    Console.WriteLine(key);
}
Console.ReadLine();

or

ConfigurationManager.AppSettings.AllKeys.ToList().ForEach(k => Console.WriteLine(k));

Output:

testKey


问:
iOS Text View Not Updating
I've got a UITextView defined by

```<code>@property (nonatomic, retain) IBOutlet UITextView *quote;
</code>```

in my view controller header, and I can set the value by using

```<code>quote.text = @"some text";
</code>```

but the view doens't want to update the value, what can I do

答: Make sure you connected quote to your UITextField in your XIB. Also, make sure that you @synthesize quote; in your .m.

Title: iOS Text View Not Updating

Body:
I've got a UITextView defined by

@property (nonatomic, retain) IBOutlet UITextView *quote;

in my view controller header, and I can set the value by using

quote.text = @"some text";

but the view doens't want to update the value, what can I do


问:
SSH: Unable to authenticate with key signed by Hashicorp Vault using Go
I have signed my public key using Hashicorp's Vault, and saved the generated certificiate in ~/.ssh/id_rsa-cert.pub
It works just fine, I can do ssh -i ~/.ssh/id_rsa-cert.pub user@hostname and it lets me in.

My problems start when I try to implement this in Go.

This is my code:

```<code>package main

import (
"encoding/base64"
"fmt"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"net"
"os"
)

func main() {
pubKey := "AAAAB3NzaC1yc2EAAAADAQABA..."
signedKey := "AAAAHHNzaC1yc2EtY2VydC..."
pubKeyBytes, err := base64.StdEncoding.DecodeString(pubKey)
if err != nil {
    panic(err)
}
pk, err := ssh.ParsePublicKey(pubKeyBytes)
if err != nil {
    panic(err)
}
fmt.Printf("%T\n", pk)

signedKeyBytes, err := base64.StdEncoding.DecodeString(signedKey)
if err != nil {
    panic(err)
}
fmt.Printf("%T\n", pk)
sk, err := ssh.ParsePublicKey(signedKeyBytes)
if err != nil {
    panic(err)
}
fmt.Printf("%T\n", sk)

conn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
    panic(err)
}
sshAgent := agent.NewClient(conn)
signers, err := sshAgent.Signers()
if err != nil {
    panic(err)
}

c := &ssh.Certificate{
    Key:          pk,
    SignatureKey: sk,
}

signer, err := ssh.NewCertSigner(c, signers[0])
if err != nil {
    panic(err)
}

auths := []ssh.AuthMethod{ssh.PublicKeys(signer)}
sshClient, err := ssh.Dial("tcp", "10.0.0.150:22", &ssh.ClientConfig{
    User: "user1",
    /*The signed key is signed against user2's public key, and should allow him to log in.
    It works via command line; user2@localhost: ssh -i id_rsa-cert.pub user1@10.0.150*/
    Auth:            auths,
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
fmt.Println(sshClient, err) /*This does not work*/

sshClient2, err := ssh.Dial("tcp", "10.0.0.150:22", &ssh.ClientConfig{
    User: "user2",
    /*User2 is allowed to connect with his basic keypair
    user2@localhost: ssh user2@10.0.0.150*/
    Auth: []ssh.AuthMethod{
        ssh.PublicKeysCallback(sshAgent.Signers),
    },
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
fmt.Println(sshClient2, err) /*This works fine*/
}
</code>```

The errors I get are:

```<code>ssh: handshake failed: ssh: unable to authenticate, attempted methods [publickey none],
no supported methods remain
</code>```

And the sshd logs from the server in question:

```<code> sshd[7149]: error: Unknown certificate type 0 sshd[7149]: error:
 key_from_blob: can't parse cert data sshd[7149]: error:
 userauth_pubkey: cannot decode key: ssh-rsa-cert-v01@openssh.com
</code>```

What do I need to do here to get this to work?

答:
I spent a few hours to figure this out.

The solution is to use your private key and your cert and make a signer first, then a certsigner and combine the two. Below is the working code which works as expected.

```<code>package main

import (
    "bytes"
    "golang.org/x/crypto/ssh"
    "io/ioutil"
    "log"
)

func main() {
    authorizedKeysBytes, _ := ioutil.ReadFile("/home/wooh/.ssh/signed-cert.pub")
    pcert, _, _, _, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)

    privkeyBytes, _ := ioutil.ReadFile("/home/wooh/.ssh/id_rsa")
    upkey, err := ssh.ParseRawPrivateKey(privkeyBytes)

    if err != nil {
        log.Printf("Failed to load authorized_keys, err: %v", err)
    }

    usigner, err := ssh.NewSignerFromKey(upkey)
    if err != nil {
        log.Printf("Failed to create new signer, err: %v", err)
    }
    log.Printf("signer: %v", usigner)

    ucertSigner, err := ssh.NewCertSigner(pcert.(*ssh.Certificate), usigner)

    if err != nil {
        log.Printf("Failed to create new signer, err: %v", err)
    }

    sshConfig := &ssh.ClientConfig{
        User:            "wooh",
        Auth:            []ssh.AuthMethod{ssh.PublicKeys(ucertSigner)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }

    client, err := ssh.Dial("tcp", "127.0.0.1:22", sshConfig)

    if err != nil {
        log.Fatalf("Failed to dial, err: %v", err)
    }

    session, err := client.NewSession()
    if err != nil {
        log.Fatal("Failed to create session: ", err)
    }
    defer session.Close()

    var b bytes.Buffer
    session.Stdout = &b
    if err := session.Run("/usr/bin/whoami"); err != nil {
        log.Fatal("Failed to run: " + err.Error())
    }
    log.Println(b.String())
}
</code>```

Body:
I have signed my public key using Hashicorp's Vault, and saved the generated certificiate in ~/.ssh/id_rsa-cert.pub
It works just fine, I can do ssh -i ~/.ssh/id_rsa-cert.pub user@hostname and it lets me in.

My problems start when I try to implement this in Go.

This is my code:

package main

import (
"encoding/base64"
"fmt"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"net"
"os"
)

func main() {
pubKey := "AAAAB3NzaC1yc2EAAAADAQABA..."
signedKey := "AAAAHHNzaC1yc2EtY2VydC..."
pubKeyBytes, err := base64.StdEncoding.DecodeString(pubKey)
if err != nil {
    panic(err)
}
pk, err := ssh.ParsePublicKey(pubKeyBytes)
if err != nil {
    panic(err)
}
fmt.Printf("%T\n", pk)

signedKeyBytes, err := base64.StdEncoding.DecodeString(signedKey)
if err != nil {
    panic(err)
}
fmt.Printf("%T\n", pk)
sk, err := ssh.ParsePublicKey(signedKeyBytes)
if err != nil {
    panic(err)
}
fmt.Printf("%T\n", sk)

conn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
    panic(err)
}
sshAgent := agent.NewClient(conn)
signers, err := sshAgent.Signers()
if err != nil {
    panic(err)
}

c := &ssh.Certificate{
    Key:          pk,
    SignatureKey: sk,
}

signer, err := ssh.NewCertSigner(c, signers[0])
if err != nil {
    panic(err)
}

auths := []ssh.AuthMethod{ssh.PublicKeys(signer)}
sshClient, err := ssh.Dial("tcp", "10.0.0.150:22", &ssh.ClientConfig{
    User: "user1",
    /*The signed key is signed against user2's public key, and should allow him to log in.
    It works via command line; user2@localhost: ssh -i id_rsa-cert.pub user1@10.0.150*/
    Auth:            auths,
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
fmt.Println(sshClient, err) /*This does not work*/

sshClient2, err := ssh.Dial("tcp", "10.0.0.150:22", &ssh.ClientConfig{
    User: "user2",
    /*User2 is allowed to connect with his basic keypair
    user2@localhost: ssh user2@10.0.0.150*/
    Auth: []ssh.AuthMethod{
        ssh.PublicKeysCallback(sshAgent.Signers),
    },
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
fmt.Println(sshClient2, err) /*This works fine*/
}

The errors I get are:

ssh: handshake failed: ssh: unable to authenticate, attempted methods [publickey none],
no supported methods remain

And the sshd logs from the server in question:

 sshd[7149]: error: Unknown certificate type 0 sshd[7149]: error:
 key_from_blob: can't parse cert data sshd[7149]: error:
 userauth_pubkey: cannot decode key: ssh-rsa-cert-v01@openssh.com

What do I need to do here to get this to work?

Body:
I spent a few hours to figure this out.

The solution is to use your private key and your cert and make a signer first, then a certsigner and combine the two. Below is the working code which works as expected.

package main

import (
    "bytes"
    "golang.org/x/crypto/ssh"
    "io/ioutil"
    "log"
)

func main() {
    authorizedKeysBytes, _ := ioutil.ReadFile("/home/wooh/.ssh/signed-cert.pub")
    pcert, _, _, _, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)

    privkeyBytes, _ := ioutil.ReadFile("/home/wooh/.ssh/id_rsa")
    upkey, err := ssh.ParseRawPrivateKey(privkeyBytes)

    if err != nil {
        log.Printf("Failed to load authorized_keys, err: %v", err)
    }

    usigner, err := ssh.NewSignerFromKey(upkey)
    if err != nil {
        log.Printf("Failed to create new signer, err: %v", err)
    }
    log.Printf("signer: %v", usigner)

    ucertSigner, err := ssh.NewCertSigner(pcert.(*ssh.Certificate), usigner)

    if err != nil {
        log.Printf("Failed to create new signer, err: %v", err)
    }

    sshConfig := &ssh.ClientConfig{
        User:            "wooh",
        Auth:            []ssh.AuthMethod{ssh.PublicKeys(ucertSigner)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }

    client, err := ssh.Dial("tcp", "127.0.0.1:22", sshConfig)

    if err != nil {
        log.Fatalf("Failed to dial, err: %v", err)
    }

    session, err := client.NewSession()
    if err != nil {
        log.Fatal("Failed to create session: ", err)
    }
    defer session.Close()

    var b bytes.Buffer
    session.Stdout = &b
    if err := session.Run("/usr/bin/whoami"); err != nil {
        log.Fatal("Failed to run: " + err.Error())
    }
    log.Println(b.String())
}


问:
iPhone not connected. Xcode will continue when iPhone is connected
I have my iPhone connected to Xcode. It used to work just fine recently. I see it in the Devices and Simulators section, but when I try to compile my app, it says:

D's iPhone 6S is not connected. Xcode will continue when D's iPhone 6S is connected.

In the Devices and Simulators I see it as disconnected.

I tried restarting the phone, turning it's wifi on and off. It's connected to the same wifi network, I tried restarting Xcode, nothing. I run Xcode 9, Beta 6 at the moment. Does anyone has similar issue and hopefully know how to solve it?

答: As Sam H.'s answer, can Connect via IP Address.  This is XCode 9 or 9.1 's function.  And need your device update to iOS11 +


问:
Should I bother with cross browser compatibility if i'll be just using nwjs?
And should I also bother myself with the semantics of each html tag I use?

It somehow bothers me that i'll be shooting myself in the foot if I developed an html5/javascrippt app that doesn't conform to the web standard and can only run specifically with nwjs.

答: If you develop for the desktop app only. You shouldn't worry about the compatibility issue and can use all the new features in new Chrome.</p>