问:
Tensorflow: Recurrent Neural Network Batch Training
I am trying to implement RNN in Tensorflow. I am writing my own functions instead of using RNN cells to practice.

The problem is sequence tagging, input size is [32, 48, 900] where 32 is batch size, 48 is time steps and 900 is vocab size which is one-hot encoded vector. Output is [32, 48, 145] where first two dimensions are same as input, but the last dimension is output vocabulary size (one-hot). Basically this is a NLP tagging problem.

I am getting following error:

InvalidArgumentError (see above for traceback): logits and labels must
  be same size: logits_size=[48,145] labels_size=[1536,145]

The actual labels_size is [32, 48, 145] but it merges first two dimensions without my control. FYI 32*48 = 1536

If I run my RNN with batch size 1, it works fine as expected. I could not figure out how to solve the issue. I am getting the problem in the last line of the code.

I pasted the related part of the code:

```<code>    inputs = tf.placeholder(shape=[None, self.seq_length, self.vocab_size], dtype=tf.float32, name="inputs")
    targets = tf.placeholder(shape=[None, self.seq_length, self.output_vocab_size], dtype=tf.float32, name="targets")
    init_state = tf.placeholder(shape=[1, self.hidden_size], dtype=tf.float32, name="state")

    initializer = tf.random_normal_initializer(stddev=0.1)

    with tf.variable_scope("RNN") as scope:
        hs_t = init_state
        ys = []
        for t, xs_t in enumerate(tf.split(inputs[0], self.seq_length, axis=0)):
            if t > 0: scope.reuse_variables()
            Wxh = tf.get_variable("Wxh", [self.vocab_size, self.hidden_size], initializer=initializer)
            Whh = tf.get_variable("Whh", [self.hidden_size, self.hidden_size], initializer=initializer)
            Why = tf.get_variable("Why", [self.hidden_size, self.output_vocab_size], initializer=initializer)
            bh = tf.get_variable("bh", [self.hidden_size], initializer=initializer)
            by = tf.get_variable("by", [self.output_vocab_size], initializer=initializer)

            hs_t = tf.tanh(tf.matmul(xs_t, Wxh) + tf.matmul(hs_t, Whh) + bh)
            ys_t = tf.matmul(hs_t, Why) + by
            ys.append(ys_t)

    hprev = hs_t
    output_softmax = tf.nn.softmax(ys)  # Get softmax for sampling

    #outputs = tf.concat(ys, axis=0)
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=ys))
</code>```

答:
The problem may fall in the size of the ys, ys should have the size of  [32, 48, 145], but the output ys only have the size of [48,145], so if the batchsize is 1, the taget size is [1, 48, 145], which just have the same size of [48,145] after dimensionality reduction.

To solve the problem you can add a loop to deal with the batchsize ( inputs[0] ) :

such as :

```<code>for i in range(inputs.getshape(0)):
   for t, xs_t in enumerate(tf.split(inputs[i], self.seq_length, axis=0)):
</code>```

Body:
I am trying to implement RNN in Tensorflow. I am writing my own functions instead of using RNN cells to practice.

The problem is sequence tagging, input size is [32, 48, 900] where 32 is batch size, 48 is time steps and 900 is vocab size which is one-hot encoded vector. Output is [32, 48, 145] where first two dimensions are same as input, but the last dimension is output vocabulary size (one-hot). Basically this is a NLP tagging problem.

I am getting following error:

InvalidArgumentError (see above for traceback): logits and labels must
  be same size: logits_size=[48,145] labels_size=[1536,145]

The actual labels_size is [32, 48, 145] but it merges first two dimensions without my control. FYI 32*48 = 1536

If I run my RNN with batch size 1, it works fine as expected. I could not figure out how to solve the issue. I am getting the problem in the last line of the code.

I pasted the related part of the code:

    inputs = tf.placeholder(shape=[None, self.seq_length, self.vocab_size], dtype=tf.float32, name="inputs")
    targets = tf.placeholder(shape=[None, self.seq_length, self.output_vocab_size], dtype=tf.float32, name="targets")
    init_state = tf.placeholder(shape=[1, self.hidden_size], dtype=tf.float32, name="state")

    initializer = tf.random_normal_initializer(stddev=0.1)

    with tf.variable_scope("RNN") as scope:
        hs_t = init_state
        ys = []
        for t, xs_t in enumerate(tf.split(inputs[0], self.seq_length, axis=0)):
            if t > 0: scope.reuse_variables()
            Wxh = tf.get_variable("Wxh", [self.vocab_size, self.hidden_size], initializer=initializer)
            Whh = tf.get_variable("Whh", [self.hidden_size, self.hidden_size], initializer=initializer)
            Why = tf.get_variable("Why", [self.hidden_size, self.output_vocab_size], initializer=initializer)
            bh = tf.get_variable("bh", [self.hidden_size], initializer=initializer)
            by = tf.get_variable("by", [self.output_vocab_size], initializer=initializer)

            hs_t = tf.tanh(tf.matmul(xs_t, Wxh) + tf.matmul(hs_t, Whh) + bh)
            ys_t = tf.matmul(hs_t, Why) + by
            ys.append(ys_t)

    hprev = hs_t
    output_softmax = tf.nn.softmax(ys)  # Get softmax for sampling

    #outputs = tf.concat(ys, axis=0)
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=ys))

Body:
The problem may fall in the size of the ys, ys should have the size of  [32, 48, 145], but the output ys only have the size of [48,145], so if the batchsize is 1, the taget size is [1, 48, 145], which just have the same size of [48,145] after dimensionality reduction.

To solve the problem you can add a loop to deal with the batchsize ( inputs[0] ) :

such as :

for i in range(inputs.getshape(0)):
   for t, xs_t in enumerate(tf.split(inputs[i], self.seq_length, axis=0)):


来源: stackexchange

问:
shoud root start the gsoap stand alone server
I have created a Gsoap stand-alone server. I am looking to have 3 versions of the GSoap server on one host machine (one version is to be used for development, another for testing and a final for production). Of course, each will reside on a different port.

I also saw this link:
How to deploy a gSOAP Web Service in Ubuntu?

I am wondering which user should start the server - should it be root or some other user?

TIA

答:
You need root for ports 80 and 443 and some other ports that are system dependent (some ports are already reserved by other processes). You do not need to run the server as root for higher ports such as 8080.

To create a production-quality service, you should consider using the Apache module or ISAPI extension for gSOAP.

You can easily create a stand-alone server with gSOAP, but if your code in the back-end part of the service (not the gSOAP code) is not 100% robust then, well ...

ContentLicense: CC BY-SA 3.0


问:
Is it possible to create a custom screen GUI in Bukkit?
I'm wondering if it's possible to add some custom screen GUI's to my Bukkit server. So I can display a lot of text on someone's screen. Or do I need to find another option to do this?

Thanks!

答: The only practical way is to use an Inventory using blocks with name and lore for users to click on as can be seen here</p>


问:
How to move Firebase child from one node to another in Android?
I am working on a project where user request for our valet services and on the other end valet accepts request.

I am using using Firebase as backend and on request customer uid is save on 'request' child.

When valet accepts request, customer uid should move from 'request' node to 'on progress' node.

How can i do that?

答:
As of compile firebase-database:11.0.1, this is the same function with the new class references (https://firebase.google.com/support/guides/firebase-android July 05 2017)</p>

```<code>private void moveGameRoom(final DatabaseReference fromPath, final DatabaseReference toPath) {
        fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                toPath.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
                        if (firebaseError != null) {
                            System.out.println("Copy failed");
                        } else {
                            System.out.println("Success");

                        }
                    }
                });

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

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

Body:
As of compile firebase-database:11.0.1, this is the same function with the new class references (https://firebase.google.com/support/guides/firebase-android July 05 2017)

private void moveGameRoom(final DatabaseReference fromPath, final DatabaseReference toPath) {
        fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                toPath.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
                        if (firebaseError != null) {
                            System.out.println("Copy failed");
                        } else {
                            System.out.println("Success");

                        }
                    }
                });

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }


问:
Is there a way to "click" on a link extracted from html text using C#?
I have the text body of an email in html, and that email has a link to another webpage in it (so the url is in html). I would like to know if there's a way in C# to "click" on this link and then extract the html information from the page I would be redirected to if I clicked on the link normally. </p>

答:
You can use the System.Net.WebClient to download the html from the url.</p>

```<code> var html = new System.Net.WebClient().DownloadString(url);
</code>```

Body:
You can use the System.Net.WebClient to download the html from the url.

 var html = new System.Net.WebClient().DownloadString(url);


问:
How to post new records in sql in an existing table where my column has all NULL values?
I have added a new Column name Age in an existing table called StudentRecords. All the values are showing Null when I do Select * From StudentRecords;

How do I update so I can give a new age to a student in my table ?

Alter Table StudentRecords Add Age varchar (40);

答:
First of all, if you wanted the column to not be null, or a default value for all Age column data, this is the way to do so in SQL:

```<code>ALTER TABLE <YourTable>
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
</code>```

So in your case, the above would be (if you wanted the records to not be null):

```<code>ALTER TABLE StudentRecords
ADD Age VARCHAR(40) NOT NULL
</code>```

If you wanted to change/modify an existing record though, here's the SQL code to do that (if you wanted to only alter the record with 4 as an ID:

```<code>UPDATE StudentRecords
SET Age = "This person is old"
WHERE ID = 4;
</code>```

Body:
First of all, if you wanted the column to not be null, or a default value for all Age column data, this is the way to do so in SQL:

ALTER TABLE <YourTable>
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>

So in your case, the above would be (if you wanted the records to not be null):

ALTER TABLE StudentRecords
ADD Age VARCHAR(40) NOT NULL

If you wanted to change/modify an existing record though, here's the SQL code to do that (if you wanted to only alter the record with 4 as an ID:

UPDATE StudentRecords
SET Age = "This person is old"
WHERE ID = 4;


问:
Rank error in tf.nn.dynamic_rnn
I am trying to build a CNN + RNN model and I am getting the following error.
Any help will be appreciated.

fc2 has shape (?,4096)

```<code>cell = tf.contrib.rnn.BasicLSTMCell(self.rnn_hidden_units)
stack = tf.contrib.rnn.MultiRNNCell([cell]*self.rnn_layers)
initial_state = cell.zero_state(self.batch_size, tf.float32)
initial_state = tf.identity(initial_state, name='initial_state')
outputs, _ = tf.nn.dynamic_rnn(stack, fc2,dtype=tf.float32)
</code>```

File "rcnn.py", line 182, in model
      outputs, _ = tf.nn.dynamic_rnn(stack, [fc2],dtype=tf.float32)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 574, in dynamic_rnn
      dtype=dtype)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 637, in _dynamic_rnn_loop
      for input_ in flat_input)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 637, in
      for input_ in flat_input)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 649, in with_rank_at_least
      raise ValueError("Shape %s must have rank at least %d" % (self, rank))
  ValueError: Shape (4096, ?) must have rank at least 3

答:
Copying the answer of @jdehesa from his comment for better visibility:

The error seems fairly clear, tf.nn.dynamic_rnn expects a 3-dimensional tensor as input (i.e. rank 3), but fc2 has only two dimensions. The shape of fc2 should be something like (<batch_size>, <max_time>, <num_features>) (or (<max_time>, <batch_size>, <num_features>) if you pass time_major=True)

Title: Rank error in tf.nn.dynamic_rnn

Body:
I am trying to build a CNN + RNN model and I am getting the following error.
Any help will be appreciated.

fc2 has shape (?,4096)

cell = tf.contrib.rnn.BasicLSTMCell(self.rnn_hidden_units)
stack = tf.contrib.rnn.MultiRNNCell([cell]*self.rnn_layers)
initial_state = cell.zero_state(self.batch_size, tf.float32)
initial_state = tf.identity(initial_state, name='initial_state')
outputs, _ = tf.nn.dynamic_rnn(stack, fc2,dtype=tf.float32)

File "rcnn.py", line 182, in model
      outputs, _ = tf.nn.dynamic_rnn(stack, [fc2],dtype=tf.float32)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 574, in dynamic_rnn
      dtype=dtype)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 637, in _dynamic_rnn_loop
      for input_ in flat_input)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 637, in
      for input_ in flat_input)

    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 649, in with_rank_at_least
      raise ValueError("Shape %s must have rank at least %d" % (self, rank))
  ValueError: Shape (4096, ?) must have rank at least 3


问:
Specify alternate JSONpaths
Suppose I have one JSON log that outputs the following information:

```<code>{"timestamp":"someText","alert":"someMoreText","Level":someInt}
</code>```

And I have another JSON log that outputs the same kind of information but with different label's:

```<code>{"ts":"someText","alert":"someMoreText","Level":someInt}
</code>```

The difference being "timestamp" and "ts" have different names yet same quality information. How would I reference, with one JSON path call, either one of the alternate names, if such a technique is possible?

So for example, if I wanted it to reference the timestamp of both logs, I would want to use something like $.[timestamp|ts]

答:
Using the new record processors, you might be able to do something like...

Define a schema that has both 'timestamp' and 'ts'

Send all the records with 'ts' to an UpdateRecord processor

Set the UpdateRecord processor to make /timestamp = /ts

Define another version of the schema that doesn't have 'ts'

Use a ConvertRecord processor with a writer that uses the second schema

That last step would rewrite the records without the 'ts' field.

Alternatively, you could try defining a schema with a 'timestamp' field and an alias of 'ts' which should let any of the record processors access both fields by using 'timestamp'. It would depend what you are doing in your flow to see if it can be achieved with the record processors.

Title: Specify alternate JSONpaths

Body:
Suppose I have one JSON log that outputs the following information:

{"timestamp":"someText","alert":"someMoreText","Level":someInt}

And I have another JSON log that outputs the same kind of information but with different label's:

{"ts":"someText","alert":"someMoreText","Level":someInt}

The difference being "timestamp" and "ts" have different names yet same quality information. How would I reference, with one JSON path call, either one of the alternate names, if such a technique is possible?

So for example, if I wanted it to reference the timestamp of both logs, I would want to use something like $.[timestamp|ts]


问:
How to parse XML output into single line
I am trying to setup a PHP code to use a XML API to contact Kunaki to get shipping prices. I try to parse the response via this code but get no output.

<?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';

$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml);
echo $xml->Description[3]->Description;
//print_r($xml); Debug line to make sure xml is outputing
?>
```

<p>I am not sure what I am doing wrong, any help would be appreciated to figure out how to output this.</p>

<p>This is the output I get in XML</p>

<pre class="lang-php prettyprint-override"><code>SimpleXMLElement Object (
    [ErrorCode] => 0
    [ErrorText] => success
    [Option] => Array (
        [0] => SimpleXMLElement Object (
            [Description] => USPS First Class Mail
            [DeliveryTime] => 2-5 business days
            [Price] => 0.66
        )
        [1] => SimpleXMLElement Object (
            [Description] => UPS Ground
            [DeliveryTime] => 1-5 business days
            [Price] => 17.17
        )
        [2] => SimpleXMLElement Object (
            [Description] => UPS 2nd Day Air
            [DeliveryTime] => 2 business days
            [Price] => 30.42
        )
        [3] => SimpleXMLElement Object (
            [Description] => UPS Next Day Air Saver
            [DeliveryTime] => 1 business day
            [Price] => 50.17
        )
    )
)
</code>```

答:
You have to cast simpleXML Object to a string.
Try the code below:

```<code>foreach ($xml->Option as $opt) {
    print "<br>";
    echo $value = (string)$opt->DeliveryTime." will cost - ".(string)$opt->Price;

}
</code>```

OUTPUT -

2-5 business days will cost - 0.66

1-5 business days will cost - 17.17

2 business days will cost - 30.42

1 business day will cost - 50.17

Body:
I am trying to setup a PHP code to use a XML API to contact Kunaki to get shipping prices. I try to parse the response via this code but get no output.

<?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';

$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml);
echo $xml->Description[3]->Description;
//print_r($xml); Debug line to make sure xml is outputing
?>

I am not sure what I am doing wrong, any help would be appreciated to figure out how to output this.

This is the output I get in XML

SimpleXMLElement Object (
    [ErrorCode] => 0
    [ErrorText] => success
    [Option] => Array (
        [0] => SimpleXMLElement Object (
            [Description] => USPS First Class Mail
            [DeliveryTime] => 2-5 business days
            [Price] => 0.66
        )
        [1] => SimpleXMLElement Object (
            [Description] => UPS Ground
            [DeliveryTime] => 1-5 business days
            [Price] => 17.17
        )
        [2] => SimpleXMLElement Object (
            [Description] => UPS 2nd Day Air
            [DeliveryTime] => 2 business days
            [Price] => 30.42
        )
        [3] => SimpleXMLElement Object (
            [Description] => UPS Next Day Air Saver
            [DeliveryTime] => 1 business day
            [Price] => 50.17
        )
    )
)

Body:
You have to cast simpleXML Object to a string.
Try the code below:

foreach ($xml->Option as $opt) {
    print "<br>";
    echo $value = (string)$opt->DeliveryTime." will cost - ".(string)$opt->Price;

}

OUTPUT -

2-5 business days will cost - 0.66

1-5 business days will cost - 17.17

2 business days will cost - 30.42

1 business day will cost - 50.17


问:
Run the same line of code but incrementing the number. Swift, Php
I want to run the same line of code but incrementing the number "prodottiNome_prodotto0" and forKey: ("nome_prodotto0") always.

```<code>let prodotti = jsonData.value(forKey: "prodotti") as! NSDictionary

let prodottiNome_prodotto0 = prodotti.value(forKey: "nome_prodotto0") as! String

self.defaultValues.set(prodottiNome_prodotto0, forKey: "nome_prodotto0")
</code>```

nome_prodotto0 refers to the result of a return in php ------------>

```<code>"prodotti":{"nome_prodotto0":"farina","nome_prodotto1":"dfd"}
</code>```

答:
If I understand what you're asking, your code might look like this:</p>

```<code>let max = 50 //Or whatever limit you want to use

for i in 0...max {
  let key = "nome_prodotto" + String(i)
  //Use `if let` so you don't crash if a value is not a string
  //Don't use `value(forKey:)` on a dictionary. That's a KVO method
  if let value = prodotti[key] as? String {
    self.defaultValues.set(value, forKey: key)
  {
}
</code>```

Body:
I want to run the same line of code but incrementing the number "prodottiNome_prodotto0" and forKey: ("nome_prodotto0") always.

let prodotti = jsonData.value(forKey: "prodotti") as! NSDictionary

let prodottiNome_prodotto0 = prodotti.value(forKey: "nome_prodotto0") as! String

self.defaultValues.set(prodottiNome_prodotto0, forKey: "nome_prodotto0")

nome_prodotto0 refers to the result of a return in php ------------>

"prodotti":{"nome_prodotto0":"farina","nome_prodotto1":"dfd"}

Body:
If I understand what you're asking, your code might look like this:

let max = 50 //Or whatever limit you want to use

for i in 0...max {
  let key = "nome_prodotto" + String(i)
  //Use `if let` so you don't crash if a value is not a string
  //Don't use `value(forKey:)` on a dictionary. That's a KVO method
  if let value = prodotti[key] as? String {
    self.defaultValues.set(value, forKey: key)
  {
}


问:
How many times a digit show up
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

```<code>#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}
</code>```

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

答:
You ARE multiplying max by 10 since you are doing everything 100 times (instead of 10) because of your totally redundant for i loop.

Specifically your problem is you are incrementing the values in occurs 10 times (instead of once). Since most doesn't use the incremented values it doesn't have problem.

Title: How many times a digit show up

Body:
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.


问:
WSO2 API Manager Basic Authentication instead of OAuth
I am searching a way to use Basic Authentication on the API I expose through WSO2 API Manager.

As I could see by default it uses OAuth, and I didn't find a way to choose to use Basic Authentication instead.

Is it possible?

Thanks

答:
There is no out of the box way to secure your APIs with basic authentication in WSO2 API Manager. But you can write a new authentication handler for your requirement. </p>

<p>However please note you need to evaluate the security mechanism and how it is applied via a handler first. For example, when the current handler receives an OAuth2 access token, it knows the user, application, subscription information. That's how it knows how to throttle and publish stats accordingly. You need to be able to find these information from your new handler you introduce for the throttling and stats to work accurately. </p>

Body:
There is no out of the box way to secure your APIs with basic authentication in WSO2 API Manager. But you can write a new authentication handler for your requirement.

However please note you need to evaluate the security mechanism and how it is applied via a handler first. For example, when the current handler receives an OAuth2 access token, it knows the user, application, subscription information. That's how it knows how to throttle and publish stats accordingly. You need to be able to find these information from your new handler you introduce for the throttling and stats to work accurately.


问:
Is there an equivalent method to C's scanf in Java?
Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversion.

I was wondering if there's an input conversion method akin to C's scanf in Java?

答:
If one really wanted to they could make there own version of scanf() like so:

```<code>    import java.util.ArrayList;
    import java.util.Scanner;

public class Testies {

public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // get input
    System.out.println("Give me input:");
    scanf(strings, nums);

    System.out.println("Ints gathered:");
    // print numbers scanned in
    for(Integer num : nums){
        System.out.print(num + " ");
    }
    System.out.println("\nStrings gathered:");
    // print strings scanned in
    for(String str : strings){
        System.out.print(str + " ");
    }

    System.out.println("\nData:");
    for(int i=0; i<strings.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner getLine = new Scanner(System.in);
    Scanner input = new Scanner(getLine.nextLine());

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner input = (new Scanner(in));

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

}
</code>```

Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them.  Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

Output:

Give me input:
        apples 8 9 pears oranges 5
        Ints gathered:
        8 9 5
        Strings gathered:
        apples pears oranges
        Data:
        8 apples
        9 pears
        5 oranges

Probably not the best example; but, the point is that Scanner implements the Iterator class.  Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.

ContentLicense: CC BY-SA 4.0

Body:
If one really wanted to they could make there own version of scanf() like so:

    import java.util.ArrayList;
    import java.util.Scanner;

public class Testies {

public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // get input
    System.out.println("Give me input:");
    scanf(strings, nums);

    System.out.println("Ints gathered:");
    // print numbers scanned in
    for(Integer num : nums){
        System.out.print(num + " ");
    }
    System.out.println("\nStrings gathered:");
    // print strings scanned in
    for(String str : strings){
        System.out.print(str + " ");
    }

    System.out.println("\nData:");
    for(int i=0; i<strings.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner getLine = new Scanner(System.in);
    Scanner input = new Scanner(getLine.nextLine());

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner input = (new Scanner(in));

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

}

Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them.  Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

Output:

Give me input:
        apples 8 9 pears oranges 5
        Ints gathered:
        8 9 5
        Strings gathered:
        apples pears oranges
        Data:
        8 apples
        9 pears
        5 oranges

Probably not the best example; but, the point is that Scanner implements the Iterator class.  Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.


问:
Django Templates: Display a date only if it's in the future
How do I compare dates in a Django template? I thought of several possible avenues:

Send today's date in the context to be compared at the template

Create my own template tag

Have some logic in the view to only pass the date if it's in the future

Although the last option seems easier, I rather leave the display logic in the template than in the view. I also do not want to pass something that seems so trivial like today's date in the template context.

Perhaps someone has another option or could share their implementation of one of the options I mentioned above and why they decided to go that route.

答:
I'd go with a template filter:

```<code>from datetime import date
...
@register.filter
def future_dates_only(the_date):
   if the_date > date.today():
       return the_date
   else:
       return None
</code>```

Then in your view do something like:

```<code>{{specialdate|future_dates_only|date:"d M Y"}}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'd go with a template filter:

from datetime import date
...
@register.filter
def future_dates_only(the_date):
   if the_date > date.today():
       return the_date
   else:
       return None

Then in your view do something like:

{{specialdate|future_dates_only|date:"d M Y"}}


问:
SQL Using Like, One Variable, Multiple Columns
```<code>--where 'email@aol.com' in(o.SuOrderEmailAddress, o.SuBusEmailAddress, o.SuReturnEmail, O.SuPartsEmail) and es.ictid = 7
</code>```

I want to search one variable (email address) in the multiple columns. This is what I have now, and it works.

I think I need to use Like, because I want to use wildcards. For instance, being able to use *@aol.com would be very helpful. Right now I have to enter an exact email address.

```<code>--Where s.suname like 'rizt%'and es.ictid = 7
</code>```

It was simple enough in this above example, but once I rearrange the syntax to do multiple columns Im lost as to where I can use LIKE so that I can use Wildcards.

Thanks

答:
This is the general idea. Usually, @search would be a parameter to a stored proc. Look at the WHERE clause first.

```<code>    declare @search varchar(50) = '@aol.com'

    set @search = '%' + @search + '%'

    select case when o.SuOrderEmailAddress like @search then o.SuOrderEmailAddress
                when o.SuBusEmailAddress like @search then o.SuBusEmailAddress
                when o.SuReturnEmail like @search then o.SuReturnEmail
                when o.SuPartsEmail like @search end as matchedEmail
    from MyTable as o
    where (o.SuOrderEmailAddress like @search
           or o.SuBusEmailAddress like @search
           or o.SuReturnEmail like @search
           or o.SuPartsEmail like @search) and ...
</code>```

You could control the adding of '%'s on the front end. This seems to me to be written clearly for the reader and gives you back the email address that was the match.

Body:
--where 'email@aol.com' in(o.SuOrderEmailAddress, o.SuBusEmailAddress, o.SuReturnEmail, O.SuPartsEmail) and es.ictid = 7

I want to search one variable (email address) in the multiple columns. This is what I have now, and it works.

I think I need to use Like, because I want to use wildcards. For instance, being able to use *@aol.com would be very helpful. Right now I have to enter an exact email address.

--Where s.suname like 'rizt%'and es.ictid = 7

It was simple enough in this above example, but once I rearrange the syntax to do multiple columns Im lost as to where I can use LIKE so that I can use Wildcards.

Thanks

Body:
This is the general idea. Usually, @search would be a parameter to a stored proc. Look at the WHERE clause first.

    declare @search varchar(50) = '@aol.com'

    set @search = '%' + @search + '%'

    select case when o.SuOrderEmailAddress like @search then o.SuOrderEmailAddress
                when o.SuBusEmailAddress like @search then o.SuBusEmailAddress
                when o.SuReturnEmail like @search then o.SuReturnEmail
                when o.SuPartsEmail like @search end as matchedEmail
    from MyTable as o
    where (o.SuOrderEmailAddress like @search
           or o.SuBusEmailAddress like @search
           or o.SuReturnEmail like @search
           or o.SuPartsEmail like @search) and ...

You could control the adding of '%'s on the front end. This seems to me to be written clearly for the reader and gives you back the email address that was the match.


问:
DataTables - kill ajax requests when a new one has started
I'm using DataTables 1.10.15 in Server Side mode.

I'm passing the contents of a form to a PHP script via ajax in order for it to search a database:

```<code> var myTable = $('#myTable').DataTable( {
    "processing": false,
    "serverSide": true,
    "searching": false,
    "ajax": {
        "url" : "/getData.php",
        "data" : function ( d ) {
            // Search input data
            d.field1 = $('#field1').val(),
            d.field2 = $('#field2').val(),
            d.field3 = $('#field3').val()
        },
        "method" : "POST",
    }
 });
</code>```

I have some other js which checks for at least 3 characters entered into a field before firing the ajax request to /getData.php.

This means - after 3 characters have been entered - that an ajax request is made each time a key is pressed, so there can be a queue of ajax requests.

```<code>$('#primarySearch input[type="text"]').on({
    "keyup": function(e) {
      // Ignore tab key.
      if (e.which != 9) {
        processPrimarySearch.call(this);

      }
    }
});

/* Handle Primary Search */
function processPrimarySearch() {
    var obj = $(this),
        search_id = obj.attr('id'), // e.g. #field1
        search_value = obj.val(); // e.g. '123-456'

    /* Wait until at least 3 characters have been entered, or user has cleared the input */
    if (search_value.length >= 3 || (!search_value) ) {
        myTable.draw();
    }
}
</code>```

How can I kill off the previous ajax requests whenever a new one is made, so that they don't queue in this way? I've read How can I stop all the currently ongoing Ajax queries that DataTables instance have started? but the solution is for an older version of DataTables and the accepted answer doesn't seem to work for me.

答:
If you were using the search field that DataTable offers by default, you'd want to use the searchDelay option. By default it is set to 400ms when you use server-side processing. However, you have "searching": false, therefore you cannot use this option for your use-case.

You provide your own custom input element to perform searches. This is a perfectly valid use of DataTables. However, what you should do is not abort requests after they are created but prevent the creation of extraneous requests in the first place. What you should do is debounce your calls to myTable.draw() In the example below I'm using Lodash's debounce. You could use an implementation from another library if you want. In the following example, I've also modified the event handling to check whether the input field value has actually changed between keystrokes. You were checking for tabs but that's only the tip of the iceberg. Using arrow keys will also generate keyup events. Event just pressing and releasing the shift key will generate a keyup. The code below takes care of all those situations by checking whether the value of the field has changed since the last stroke and just ignore the event if there has been no change.

I type fast enough that if I type "I'm a little teapot" in the field presented in the example below I'm seeing "drawing" on the console only once.

// We create a new function that will debounce calls to the draw() function.
var debouncedDraw = _.debounce(function() {
  // myTable.draw();
  console.log("drawing");
}, 500);

var prev_value = undefined;

/* Handle Primary Search */
function processPrimarySearch() {
  var obj = $(this),
    search_id = obj.attr('id'), // e.g. #field1
    search_value = obj.val(); // e.g. '123-456'

  // There's been no change to the field, ignore.
  if (prev_value === search_value) {
    return;
  }
  prev_value = search_value;

  /* Wait until at least 3 characters have been entered, or user has cleared the input */
  if (search_value.length >= 3 || (!search_value)) {
    debouncedDraw();
  }
}

$('#primarySearch input[type="text"]').on("keyup", processPrimarySearch);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="primarySearch">
  <input type="text">
</div></code>```

You asked in a comment if you should keep the code you had that aborts any previous Ajax query launched by DataTables when DataTables launches a new query. I would remove it. I've never relied on such code ever in my applications. (You mentioned my question. Yes, I do use the code in the answer I gave there but that's tear down code which is part of a test suite, not application code.) In theory it would seem like it is a good thing to do. After all, a new query makes the old ones obsolete so why not ditch the old queries and save some work? Right? In practice, the gains would be modest because:

At the speed humans interact with your GUI, chances are that by the time an abort() call is issued, the Ajax request will already have been sent out on the network. (I actually ran some manual tests, and indeed, I was never fast enough to prevent the browser from sending the request out.) So it means that the server will receive it even if you abort it.

Furthermore, abort() is not meant to notify the server that the request has been cancelled. So you won't save work on the part of your server. Look at this question for the issues. (Searching for "server" on the page will bring you right where people talk about the issue of whether the server is notified, and what to do if you need to notify the server that a request has been cancelled.)

You may be saving some redrawing time but that's not something I'd worry about until it is actually a problem.

On the other hand, aborting requests like this may cause other problems. For the sake of seeing what would happen, I modified one of my applications to abort old requests, and the whole thing immediately bombed. Aborting requests did not play well with the way I've set up DataTables. I don't know what exactly is causing the problem. Maybe I'm using just the right settings to get it to go boom. Or I'm using a plugin that does not like aborted requests. At any rate, aborting requests can cause problems.

Body:
I'm using DataTables 1.10.15 in Server Side mode.

I'm passing the contents of a form to a PHP script via ajax in order for it to search a database:

 var myTable = $('#myTable').DataTable( {
    "processing": false,
    "serverSide": true,
    "searching": false,
    "ajax": {
        "url" : "/getData.php",
        "data" : function ( d ) {
            // Search input data
            d.field1 = $('#field1').val(),
            d.field2 = $('#field2').val(),
            d.field3 = $('#field3').val()
        },
        "method" : "POST",
    }
 });

I have some other js which checks for at least 3 characters entered into a field before firing the ajax request to /getData.php.

This means - after 3 characters have been entered - that an ajax request is made each time a key is pressed, so there can be a queue of ajax requests.

$('#primarySearch input[type="text"]').on({
    "keyup": function(e) {
      // Ignore tab key.
      if (e.which != 9) {
        processPrimarySearch.call(this);

      }
    }
});

/* Handle Primary Search */
function processPrimarySearch() {
    var obj = $(this),
        search_id = obj.attr('id'), // e.g. #field1
        search_value = obj.val(); // e.g. '123-456'

    /* Wait until at least 3 characters have been entered, or user has cleared the input */
    if (search_value.length >= 3 || (!search_value) ) {
        myTable.draw();
    }
}

How can I kill off the previous ajax requests whenever a new one is made, so that they don't queue in this way? I've read How can I stop all the currently ongoing Ajax queries that DataTables instance have started? but the solution is for an older version of DataTables and the accepted answer doesn't seem to work for me.

Body:
If you were using the search field that DataTable offers by default, you'd want to use the searchDelay option. By default it is set to 400ms when you use server-side processing. However, you have "searching": false, therefore you cannot use this option for your use-case.

You provide your own custom input element to perform searches. This is a perfectly valid use of DataTables. However, what you should do is not abort requests after they are created but prevent the creation of extraneous requests in the first place. What you should do is debounce your calls to myTable.draw() In the example below I'm using Lodash's debounce. You could use an implementation from another library if you want. In the following example, I've also modified the event handling to check whether the input field value has actually changed between keystrokes. You were checking for tabs but that's only the tip of the iceberg. Using arrow keys will also generate keyup events. Event just pressing and releasing the shift key will generate a keyup. The code below takes care of all those situations by checking whether the value of the field has changed since the last stroke and just ignore the event if there has been no change.

I type fast enough that if I type "I'm a little teapot" in the field presented in the example below I'm seeing "drawing" on the console only once.

// We create a new function that will debounce calls to the draw() function.
var debouncedDraw = _.debounce(function() {
  // myTable.draw();
  console.log("drawing");
}, 500);

var prev_value = undefined;

/* Handle Primary Search */
function processPrimarySearch() {
  var obj = $(this),
    search_id = obj.attr('id'), // e.g. #field1
    search_value = obj.val(); // e.g. '123-456'

  // There's been no change to the field, ignore.
  if (prev_value === search_value) {
    return;
  }
  prev_value = search_value;

  /* Wait until at least 3 characters have been entered, or user has cleared the input */
  if (search_value.length >= 3 || (!search_value)) {
    debouncedDraw();
  }
}

$('#primarySearch input[type="text"]').on("keyup", processPrimarySearch);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="primarySearch">
  <input type="text">
</div>

You asked in a comment if you should keep the code you had that aborts any previous Ajax query launched by DataTables when DataTables launches a new query. I would remove it. I've never relied on such code ever in my applications. (You mentioned my question. Yes, I do use the code in the answer I gave there but that's tear down code which is part of a test suite, not application code.) In theory it would seem like it is a good thing to do. After all, a new query makes the old ones obsolete so why not ditch the old queries and save some work? Right? In practice, the gains would be modest because:

At the speed humans interact with your GUI, chances are that by the time an abort() call is issued, the Ajax request will already have been sent out on the network. (I actually ran some manual tests, and indeed, I was never fast enough to prevent the browser from sending the request out.) So it means that the server will receive it even if you abort it.

Furthermore, abort() is not meant to notify the server that the request has been cancelled. So you won't save work on the part of your server. Look at this question for the issues. (Searching for "server" on the page will bring you right where people talk about the issue of whether the server is notified, and what to do if you need to notify the server that a request has been cancelled.)

You may be saving some redrawing time but that's not something I'd worry about until it is actually a problem.

On the other hand, aborting requests like this may cause other problems. For the sake of seeing what would happen, I modified one of my applications to abort old requests, and the whole thing immediately bombed. Aborting requests did not play well with the way I've set up DataTables. I don't know what exactly is causing the problem. Maybe I'm using just the right settings to get it to go boom. Or I'm using a plugin that does not like aborted requests. At any rate, aborting requests can cause problems.


问:
Merge objects while preserving unique attributes
I am working on a C# project that takes lists of hundreds of objects of a custom class, and merges them together into a new list.  There may be some cases where a single real-world item is represented several times in the list, but with different attributes.  I am looking for an efficient way to merge these two lists together in such a way that any time a duplicate is found on my search key property, the other properties are merged together (either by overwriting the attributes of one of the objects or by creating a new object with the merged attributes) instead of deleting the second instance.

Here is an example of what I want to do:
Objects of class Dog with elements (ID, Owner, Breed, Colour). The Dog Rover is owned by both Sharon and Paul.  I want my merged list to include the text “Sharon/Paul” as the new attribute for the “Owner” variable.

Original lists:

List A:

1.Rover (23, Sharon, Labrador, Black)

2.Spot (40, Paul, Retriever, Golden)

List B:

Rover (23, Paul, Labrador, Black)

Merged list:

Rover (23, Sharon/ Paul, Labrador, Black)

Spot (40, Paul, Retriever, Golden)

I have been able to join the lists to create:
1.  Rover (23, Sharon, Labrador, Black)
2.  Rover (23, Paul, Labrador, Black)
3.  Spot (40, Paul, Retriever, Golden)
Or run .Unique on the lists to create:
1.  Rover (23, Sharon, Labrador, Black)
2.  Spot (40, Paul, Retriever, Golden)

But neither of those give me all of the information I need in the smallest list possible.

答:
Given you have lists defined like this:

```<code>var listA = new []
{
    new Dog() { ID  = 23, Owner = "Sharon", Breed = "Labrador", Colour = "Black" },
    new Dog() { ID  = 40, Owner = "Paul", Breed = "Retriever", Colour = "Golden" },
};

var listB = new []
{
    new Dog() { ID  = 23, Owner = "Paul", Breed = "Labrador", Colour = "Black" },
};
</code>```

The interesting thing from your data is that the Dog records are not normalized - you have the same ID with different property data, i.e. the Owner can be different. I think it's then important to also make sure that the final query also ensures that multiple values in the Breed and Colour properties are also handled.

The query you need is:

```<code>var query =
    from dog in listA.Concat(listB)
    orderby dog.ID
    group dog by dog.ID into gdogs
    select new Dog()
    {
        ID = gdogs.Key,
        Owner = String.Join("/", gdogs.Select(x => x.Owner).Distinct()),
        Breed = String.Join("/", gdogs.Select(x => x.Breed).Distinct()),
        Colour = String.Join("/", gdogs.Select(x => x.Colour).Distinct()),
    };
</code>```

If you have multiple lists you just simply keep calling .Concat to join them together.

The result you get from this query is:

Body:
Given you have lists defined like this:

var listA = new []
{
    new Dog() { ID  = 23, Owner = "Sharon", Breed = "Labrador", Colour = "Black" },
    new Dog() { ID  = 40, Owner = "Paul", Breed = "Retriever", Colour = "Golden" },
};

var listB = new []
{
    new Dog() { ID  = 23, Owner = "Paul", Breed = "Labrador", Colour = "Black" },
};

The interesting thing from your data is that the Dog records are not normalized - you have the same ID with different property data, i.e. the Owner can be different. I think it's then important to also make sure that the final query also ensures that multiple values in the Breed and Colour properties are also handled.

The query you need is:

var query =
    from dog in listA.Concat(listB)
    orderby dog.ID
    group dog by dog.ID into gdogs
    select new Dog()
    {
        ID = gdogs.Key,
        Owner = String.Join("/", gdogs.Select(x => x.Owner).Distinct()),
        Breed = String.Join("/", gdogs.Select(x => x.Breed).Distinct()),
        Colour = String.Join("/", gdogs.Select(x => x.Colour).Distinct()),
    };

If you have multiple lists you just simply keep calling .Concat to join them together.

The result you get from this query is:


问:
How to integrate LUIS to a QnA bot Azure
So I was recently tinkering with Azure Bot Services and Q&A but I noticed it didn't answer everything correctly and didn't get the intent sometimes so I decided to add LUIS to it but I don't really get how to integrate it to the bot. (They give a code sample but I don't really know where to put it).

I also wanted to know if there's a way for me to change the Q&A bot's language from English to French because most of my customers are French.

答: You might want to look at this sample: https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/intelligence-LUIS</p>


问:
How do I keep Transform Control from moving your object if there is a collision, using raycasting?
So I'm using Three.js and I have some cubes inside of a box.  I'm using the Transform Control to move the cubes around inside of the box with my mouse.  I'd like to use raycasting in order to check for collisions.  The question is how to I prevent the transform controller from moving the object if there is a collision?  I'd like to stop it if it hits the wall. By the way, I'm on version r81 for Three.js.

UPDATE: I've used the size of the room to constrain the cubes from
  moving outside of the room.  This seems to work well.  Is there a way
  to use the cannon.js just for collisions?  I don't want the momentum
  or gravity or any other feature.  JUST the collision check and to stop
  it dead in its tracks when there is a collision.

答:
I know this post is from a long time ago, but hopefully a googler finds this helpful. I wasn't able to stop the user from moving my object, but I was able to move it back to its proper position immediately afterward by adding some logic to the render method.

For the original poster's problem with collisions, you could attach an event listener to the transform controls and request the object to be repositioned if it is in an illegal state.

```<code>transformControls.addEventListener('objectChange', (e) => {
  if (illegalPosition(this.obj.position)) {
    needsReset = true;
  }
  lastPosition = attachedObject.position.clone();
});
</code>```

and then in your render function

```<code>if (needsReset) {
  attachedObject.position.set(lastPosition.x, lastPosition.y, lastPosition.z);
}
</code>```

If this feels a little hacky, that's because it is. But for those of us who don't have the time or skill to read and modify TransformControls.js, I think it may prove helpful.

Body:
I know this post is from a long time ago, but hopefully a googler finds this helpful. I wasn't able to stop the user from moving my object, but I was able to move it back to its proper position immediately afterward by adding some logic to the render method.

For the original poster's problem with collisions, you could attach an event listener to the transform controls and request the object to be repositioned if it is in an illegal state.

transformControls.addEventListener('objectChange', (e) => {
  if (illegalPosition(this.obj.position)) {
    needsReset = true;
  }
  lastPosition = attachedObject.position.clone();
});

and then in your render function

if (needsReset) {
  attachedObject.position.set(lastPosition.x, lastPosition.y, lastPosition.z);
}

If this feels a little hacky, that's because it is. But for those of us who don't have the time or skill to read and modify TransformControls.js, I think it may prove helpful.


问:
python using requests with valid hostname
Trying to use requests to download a list of urls and catch the exception if it is a bad url. Here's my test code:

```<code>import requests
from requests.exceptions import ConnectionError

#goodurl
url = "http://www.google.com"

#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"

#url with bad host
#url = "http://somethingpotato.com"

print url
try:
    r = requests.get(url, allow_redirects=True)
    print "the url is good"
except ConnectionError,e:
    print e
    print "the url is bad"
</code>```

The problem is if I pass in url = "http://www.google.com" everything works as it should and as expected since it is a good url.

```<code>http://www.google.com
the url is good
</code>```

But if I pass in url = "http://www.google.com/thereisnothing.jpg"

I still get :

```<code>http://www.google.com/thereisnothing.jpg
the url is good
</code>```

So its almost like its not even looking at anything after the "/"

just to see if the error checking is working at all I passed a bad hostname: #url = "http://somethingpotato.com"

Which kicked back the error message I expected:

```<code>http://somethingpotato.com
HTTPConnectionPool(host='somethingpotato.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1b6cd15b90>: Failed to establish a new connection: [Errno -2] Name or service not known',))
the url is bad
</code>```

What am I missing to make request capture a bad url not just a bad hostname?

Thanks

答: what you want is to check r.status_code. Getting r.status_code on "http://www.google.com/thereisnothing.jpg" will give you 404. you can put a condition for only 200 code URL to be "good".

Body:
Trying to use requests to download a list of urls and catch the exception if it is a bad url. Here's my test code:

import requests
from requests.exceptions import ConnectionError

#goodurl
url = "http://www.google.com"

#badurl with good host
#url = "http://www.google.com/thereisnothing.jpg"

#url with bad host
#url = "http://somethingpotato.com"

print url
try:
    r = requests.get(url, allow_redirects=True)
    print "the url is good"
except ConnectionError,e:
    print e
    print "the url is bad"

The problem is if I pass in url = "http://www.google.com" everything works as it should and as expected since it is a good url.

http://www.google.com
the url is good

But if I pass in url = "http://www.google.com/thereisnothing.jpg"

I still get :

http://www.google.com/thereisnothing.jpg
the url is good

So its almost like its not even looking at anything after the "/"

just to see if the error checking is working at all I passed a bad hostname: #url = "http://somethingpotato.com"

Which kicked back the error message I expected:

http://somethingpotato.com
HTTPConnectionPool(host='somethingpotato.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1b6cd15b90>: Failed to establish a new connection: [Errno -2] Name or service not known',))
the url is bad

What am I missing to make request capture a bad url not just a bad hostname?

Thanks


问:
Sendgrid status 202 node.js
I receive the following error when using SendGrid. Even though i get an error the mail is still sent.

null { statusCode: 202,   body: '',   headers:    { server: 'nginx',
       date: 'Wed, 05 Jul 2017 18:50:52 GMT',
       'content-type': 'text/plain; charset=utf-8',
       'content-length': '0',
       connection: 'close',
       'x-message-id': 'EUkSULsjRku6bJTkTFsQ9w',
       'x-frame-options': 'DENY',
       'access-control-allow-origin': 'https://sendgrid.api-docs.io',
       'access-control-allow-methods': 'POST',
       'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
       'access-control-max-age': '600',
       'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' } }
  _http_outgoing.js:357
      throw new Error('Can\'t set headers after they are sent.');

Using the following code:

```<code>var helper = require('sendgrid').mail,
  sg = require('sendgrid')('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');

  var from_email = new helper.Email('my.mail');
  var to_email = new helper.Email('my.mai');
  var subject = 'Subject';
  var content = new helper.Content('text/plain', 'test');
  var mail = new helper.Mail(from_email, subject, to_email, content);

  var request = sg.emptyRequest({
      method: 'POST',
      path: '/v3/mail/send',
      body: mail.toJSON()
  });

  sg.API(request, function(err, response) {
      console.log(err, response);
      if (!err) {
          res.send({
              message: 'An email has been sent to the provided email with further instructions.'
          });
      } else {
          return res.status(400).send({
              message: 'Failure sending email'
          });
      }
  });
</code>```

How can i fix this?

答:
A 202 is a success message, not an error.  It simply means that your message was "Accepted"

http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

Your code shouldn't be detecting any errors on any 20x response.

Title: Sendgrid status 202 node.js

Body:
I receive the following error when using SendGrid. Even though i get an error the mail is still sent.

null { statusCode: 202,   body: '',   headers:    { server: 'nginx',
       date: 'Wed, 05 Jul 2017 18:50:52 GMT',
       'content-type': 'text/plain; charset=utf-8',
       'content-length': '0',
       connection: 'close',
       'x-message-id': 'EUkSULsjRku6bJTkTFsQ9w',
       'x-frame-options': 'DENY',
       'access-control-allow-origin': 'https://sendgrid.api-docs.io',
       'access-control-allow-methods': 'POST',
       'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
       'access-control-max-age': '600',
       'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' } }
  _http_outgoing.js:357
      throw new Error('Can\'t set headers after they are sent.');

Using the following code:

var helper = require('sendgrid').mail,
  sg = require('sendgrid')('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');

  var from_email = new helper.Email('my.mail');
  var to_email = new helper.Email('my.mai');
  var subject = 'Subject';
  var content = new helper.Content('text/plain', 'test');
  var mail = new helper.Mail(from_email, subject, to_email, content);

  var request = sg.emptyRequest({
      method: 'POST',
      path: '/v3/mail/send',
      body: mail.toJSON()
  });

  sg.API(request, function(err, response) {
      console.log(err, response);
      if (!err) {
          res.send({
              message: 'An email has been sent to the provided email with further instructions.'
          });
      } else {
          return res.status(400).send({
              message: 'Failure sending email'
          });
      }
  });

How can i fix this?


问:
Messaging between two angularjs services
I want to realise a communication (by sending and receiving messages) between two services in an angularjs web site. Actually, messaging would be unnecessary if we could merge two services into one service. But the reality is I don't want to merge them for some reason. As mutual dependency of two services is not possible (please correct me if i am wrong), it seems that I have to let them communicate via messaging.

Let me explain... Assume we have two services serA and serB. In serA, we have

```<code>this.startTask1 = function () {
    console.log("B, please do task 1")
    sendMsgFromAtoB("B, please do task 1")
}

this.receiveMsgFromBtoA = function (msg) {
    if (msg === "A, B has done task 1") {
        console.log("A, B has done task 1");
        console.log("task 1 is finally over!!!")
    }
}
</code>```

in serB, we have

```<code>this.receiveMsgFromAtoB = function (msg) {
    if (msg === "B, please do task 1") {
        console.log("B is doing task 1... Done!");
        sendMsgFromBtoA("A, B has done task 1")
    }
}
</code>```

As a result, if a controller runs serA.startTask1(), I expect to see in the console:

```<code>B, please do task 1
B is doing task 1... Done!
A, B has done task 1
task 1 is finally over!!!
</code>```

To this end, I need to make sendMsgFromAtoB and sendMsgFromBtoA, and complete receiveMsgFromAtoB and receiveMsgFromBtoA. However, I don't know by which mean I could implement them.

I have used $window.addEventListener("message", ...) (ie, postMessage) and $window.addEventListener("storage", ...) (ie, StorageEvent). But StorageEvent is not fully cross-platform, I am not sure postMessage is good for messaging inside 1 page.

So does anyone have a good idea?

答:
A circular dependency is always the sign of mixing of concerns, which is a really bad thing. Miško Hevery, one of the authors of AngularJS, explains a nice solution on his awesome blog. In short, you probably have a third service hidden somewhere, which is the only part of your code really needed by the two others.

Change:

```<code>+---------+      +---------+
|    A    |<-----|  B      |
|         |      |  |  +-+ |
|         |      |  +->|C| |
|         |------+---->| | |
|         |      |     +-+ |
+---------+      +---------+
</code>```

To this:

```<code>                         +---------+
+---------+              |    B    |
|    A    |<-------------|         |
|         |              |         |
|         |    +---+     |         |
|         |--->| C |<----|         |
|         |    +---+     +---------+
+---------+
</code>```

See also,

Problems with circular dependency and OOP in AngularJS

Miško Hevery, Circular Dependency in constructors and Dependency Injection

Body:
I want to realise a communication (by sending and receiving messages) between two services in an angularjs web site. Actually, messaging would be unnecessary if we could merge two services into one service. But the reality is I don't want to merge them for some reason. As mutual dependency of two services is not possible (please correct me if i am wrong), it seems that I have to let them communicate via messaging.

Let me explain... Assume we have two services serA and serB. In serA, we have

this.startTask1 = function () {
    console.log("B, please do task 1")
    sendMsgFromAtoB("B, please do task 1")
}

this.receiveMsgFromBtoA = function (msg) {
    if (msg === "A, B has done task 1") {
        console.log("A, B has done task 1");
        console.log("task 1 is finally over!!!")
    }
}

in serB, we have

this.receiveMsgFromAtoB = function (msg) {
    if (msg === "B, please do task 1") {
        console.log("B is doing task 1... Done!");
        sendMsgFromBtoA("A, B has done task 1")
    }
}

As a result, if a controller runs serA.startTask1(), I expect to see in the console:

B, please do task 1
B is doing task 1... Done!
A, B has done task 1
task 1 is finally over!!!

To this end, I need to make sendMsgFromAtoB and sendMsgFromBtoA, and complete receiveMsgFromAtoB and receiveMsgFromBtoA. However, I don't know by which mean I could implement them.

I have used $window.addEventListener("message", ...) (ie, postMessage) and $window.addEventListener("storage", ...) (ie, StorageEvent). But StorageEvent is not fully cross-platform, I am not sure postMessage is good for messaging inside 1 page.

So does anyone have a good idea?

Body:
A circular dependency is always the sign of mixing of concerns, which is a really bad thing. Miško Hevery, one of the authors of AngularJS, explains a nice solution on his awesome blog. In short, you probably have a third service hidden somewhere, which is the only part of your code really needed by the two others.

Change:

+---------+      +---------+
|    A    |<-----|  B      |
|         |      |  |  +-+ |
|         |      |  +->|C| |
|         |------+---->| | |
|         |      |     +-+ |
+---------+      +---------+

To this:

                         +---------+
+---------+              |    B    |
|    A    |<-------------|         |
|         |              |         |
|         |    +---+     |         |
|         |--->| C |<----|         |
|         |    +---+     +---------+
+---------+

See also,

Problems with circular dependency and OOP in AngularJS

Miško Hevery, Circular Dependency in constructors and Dependency Injection


问:
Installation set up of dynamoDb in PHP
I have downloaded Libraries from Aws server to install in my server.
I downloaded library from Link - href="http://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.zip". I want to know how to work this library as using PHP. I have read the document but did not get it working.
please let me know what I need do to make it working, new file need create and configuration etc. </p>

答:
The best way to start using DynamoDB would be to follow a complete step by step guide and then customize the solution as per your need.

Read this to follow a step by step guide.

If you are aware of the basics then you can start creating your own application.

Title: Installation set up of dynamoDb in PHP


答:
Your description is inside the Option elements, you need to iterate over that.

```<code>$xml = new simplexmlelement($xml);
foreach($xml->Option as $options){
     echo $options->Description . "\n";
}
</code>```

Demo: https://eval.in/828259

To get just the fourth description you can do something like:

```<code>echo $xml->Option[3]->Description->__tostring();
</code>```

Demo (v2): https://eval.in/828268

Title: How to parse XML output into single line

Body:
I am trying to setup a PHP code to use a XML API to contact Kunaki to get shipping prices. I try to parse the response via this code but get no output.

<?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';

$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml);
echo $xml->Description[3]->Description;
//print_r($xml); Debug line to make sure xml is outputing
?>

I am not sure what I am doing wrong, any help would be appreciated to figure out how to output this.

This is the output I get in XML

SimpleXMLElement Object (
    [ErrorCode] => 0
    [ErrorText] => success
    [Option] => Array (
        [0] => SimpleXMLElement Object (
            [Description] => USPS First Class Mail
            [DeliveryTime] => 2-5 business days
            [Price] => 0.66
        )
        [1] => SimpleXMLElement Object (
            [Description] => UPS Ground
            [DeliveryTime] => 1-5 business days
            [Price] => 17.17
        )
        [2] => SimpleXMLElement Object (
            [Description] => UPS 2nd Day Air
            [DeliveryTime] => 2 business days
            [Price] => 30.42
        )
        [3] => SimpleXMLElement Object (
            [Description] => UPS Next Day Air Saver
            [DeliveryTime] => 1 business day
            [Price] => 50.17
        )
    )
)

Body:
Your description is inside the Option elements, you need to iterate over that.

$xml = new simplexmlelement($xml);
foreach($xml->Option as $options){
     echo $options->Description . "\n";
}

Demo: https://eval.in/828259

To get just the fourth description you can do something like:

echo $xml->Option[3]->Description->__tostring();

Demo (v2): https://eval.in/828268


问:
How to create two triangles with overlaying?
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.
</div>

<div class="shape">
  <div class="shape--1"></div>
  <div class="shape--2"></div>
</div>

<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.
</div></code>```

答:
What I did is first create the element that holds the photo, then I created a rectangular shape in the body background color, rotated it and made it overflown. Then inside of it I placed another rectangular block that I rotated in the opposite way of the original triangle:

HTML:

```<code><div class="photo"></div>
<div class="triangle"></div>
</code>```

CSS:

```<code>body {
  background: #fff;
  overflow:hidden;
  padding: 0;
  margin: 0;
}

.photo {
  width: 100%;
  height: 200px;
  background: red;
}

.triangle {
  position: absolute;
  background: #fff;
  left: -100px;
  right: -100px;
  height: 300px;
  transform: rotate(5deg);
  transform-origin: 100% 100%;
  overflow: hidden;
}

.triangle:after {
  content: "";
  display: block;
  width: 400px;
  height: 200px;
  position: absolute;
  background: orange;
  left: 0;
  top: -180px;
  transform: rotate(-20deg)
}
</code>```

And here is a working fiddle:
https://jsfiddle.net/62o7wqom/2/

Edit: Added overflow:hidden to the body tag to avoid having a horizontal scrollbar because of the absolutely positioned element...overflowing the body.

Body:
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.

Body:
What I did is first create the element that holds the photo, then I created a rectangular shape in the body background color, rotated it and made it overflown. Then inside of it I placed another rectangular block that I rotated in the opposite way of the original triangle:

HTML:

<div class="photo"></div>
<div class="triangle"></div>

CSS:

body {
  background: #fff;
  overflow:hidden;
  padding: 0;
  margin: 0;
}

.photo {
  width: 100%;
  height: 200px;
  background: red;
}

.triangle {
  position: absolute;
  background: #fff;
  left: -100px;
  right: -100px;
  height: 300px;
  transform: rotate(5deg);
  transform-origin: 100% 100%;
  overflow: hidden;
}

.triangle:after {
  content: "";
  display: block;
  width: 400px;
  height: 200px;
  position: absolute;
  background: orange;
  left: 0;
  top: -180px;
  transform: rotate(-20deg)
}

And here is a working fiddle:
https://jsfiddle.net/62o7wqom/2/

Edit: Added overflow:hidden to the body tag to avoid having a horizontal scrollbar because of the absolutely positioned element...overflowing the body.


问:
How to prevent unauthorized spidering
I want to prevent automated html scraping from one of our sites while not affecting legitimate spidering (googlebot, etc.). Is there something that already exists to accomplish this? Am I even using the correct terminology?

EDIT: I'm mainly looking to prevent people that would be doing this maliciously. I.e. they aren't going to abide by robots.txt

EDIT2: What about preventing use by "rate of use" ... i.e. captcha to continue browsing if automation is detected and the traffic isn't from a legitimate (google, yahoo, msn, etc.) IP.

答:
This is difficult if not impossible to accomplish.  Many "rogue" spiders/crawlers do not identify themselves via the user agent string, so it is difficult to identify them.  You can try to block them via their IP address, but it is difficult to keep up with adding new IP addresses to your block list.  It is also possible to block legitimate users if IP addresses are used since proxies make many different clients appear as a single IP address.

The problem with using robots.txt in this situation is that the spider can just choose to ignore it.

EDIT: Rate limiting is a possibility, but it suffers from some of the same problems of identifying (and keeping track of) "good" and "bad" user agents/IPs.  In a system we wrote to do some internal page view/session counting, we eliminate sessions based on page view rate, but we also don't worry about eliminating "good" spiders since we don't want them counted in the data either.  We don't do anything about preventing any client from actually viewing the pages.

OwnerDisplayName: Kyle West

Title: How to prevent unauthorized spidering

LastEditorDisplayName: Kyle West

OwnerDisplayName: Sean Carpenter

LastEditorDisplayName: Sean Carpenter


问:
Remove Leading zero in date
I have to enter the dates in the (mm/dd/yyyy) form. So, I will have something like 05/13/1999 when reporting this date how do I remove the zero so from the month. I want it to still be able to read double digit months like 11/12/1999

```<code>from functionax import disp_bday
name = raw_input("Enter name: ")
s = date = raw_input("Enter dob (mm/dd/yyyy): ")
x = month = int((s[0:1])
year = s[6:10]
print disp_bday(name, month, year)
</code>```

functionax is below

```<code>from datetime import date

def display_birthday_wishes(name, month, year):
    p = current_year = date.today().year
    current_age = (int(p)-int(year))
    if month == 1:
        month = 'Carnations'
    elif month == 2:
        month = 'Primroses'
    elif month == 3:
        month = 'Daffodils'
    elif month == 4:
        month = 'Sweet peas'
    elif month == 5:
        month = 'Hawthorn flowers'
    elif month == 6:
        month = 'Roses'
    elif month == 7:
        month = 'Water lilies'
    elif month == 8:
        month = 'Poppies'
    elif month == 9:
        month = 'Asters'
    elif month == 10:
        month = 'Calendulas'
    elif month == 11:
        month = 'Chrysanthemums'
    elif month == 12:
        month = 'Holly flowers'

    return "Hi, " + name + ". You are " + str(current_age) +\
    " years old this year! Here's a bouquet of "+month+" for you!"
</code>```

答:
I haven't tried this in python2, but it works if you're using python3

```<code>from datetime import date, datetime as dt

day, month, year = "05/13/1999".split("/")
old_date = date(int(year), int(day), int(month))
new_date = dt.strftime(old_date, "{0}/{1}/{2}".format(old_date.month, \
old_date.day, old_date.year))
</code>```

Title: Remove Leading zero in date

Body:
I have to enter the dates in the (mm/dd/yyyy) form. So, I will have something like 05/13/1999 when reporting this date how do I remove the zero so from the month. I want it to still be able to read double digit months like 11/12/1999

from functionax import disp_bday
name = raw_input("Enter name: ")
s = date = raw_input("Enter dob (mm/dd/yyyy): ")
x = month = int((s[0:1])
year = s[6:10]
print disp_bday(name, month, year)

functionax is below

from datetime import date

def display_birthday_wishes(name, month, year):
    p = current_year = date.today().year
    current_age = (int(p)-int(year))
    if month == 1:
        month = 'Carnations'
    elif month == 2:
        month = 'Primroses'
    elif month == 3:
        month = 'Daffodils'
    elif month == 4:
        month = 'Sweet peas'
    elif month == 5:
        month = 'Hawthorn flowers'
    elif month == 6:
        month = 'Roses'
    elif month == 7:
        month = 'Water lilies'
    elif month == 8:
        month = 'Poppies'
    elif month == 9:
        month = 'Asters'
    elif month == 10:
        month = 'Calendulas'
    elif month == 11:
        month = 'Chrysanthemums'
    elif month == 12:
        month = 'Holly flowers'

    return "Hi, " + name + ". You are " + str(current_age) +\
    " years old this year! Here's a bouquet of "+month+" for you!"

Body:
I haven't tried this in python2, but it works if you're using python3

from datetime import date, datetime as dt

day, month, year = "05/13/1999".split("/")
old_date = date(int(year), int(day), int(month))
new_date = dt.strftime(old_date, "{0}/{1}/{2}".format(old_date.month, \
old_date.day, old_date.year))


问:
Format exception unhandled: input string was not in a correct format
when ever i try to run my program the compiler brings me an error  Input string was not in a correct format.

my code:

```<code>public int number;
public int evenOrOdd()
        {
            if(number % 2 == 0)
            {
                return int.Parse(number+" is a even number");
            }
            else
            {
                return int.Parse(number + " is a oddnumber");
            }
        }
</code>```

and

```<code>private void checkerButton_Click(object sender, EventArgs e)
        {
            pali = new Palindrome() { number = int.Parse(checkerBox.Text) };
            checkerLabel.Text = pali.evenOrOdd().ToString();
        }
</code>```

答:
There seem to be a couple of problems:

One is simply a design/usage issue: you have a method called "evenOrOdd" that returns an int. It would make more sense if instead you had a method that was called "IsEven" (or "IsOdd") that returned a bool, or maybe one called "GetEvenOrOddMessage" that returned a string.

Another is that you are trying to convert a non-numeric string to an integer (your int.Parse method will fail with a non-numeric string value).

Presumably you want a method that returns a message string if the number is even or odd, so you don't need to try to cast anything to an int, but rather to a string.

So we can create a method that returns the message we want, give some numeric input:

```<code>public string GetEvenOrOddMessage()
{
    if (number % 2 == 0)
    {
        return (number + " is an even number");
    }
    else
    {
        return (number + " is an odd number");
    }
}
</code>```

Now, to test if the string is indeed an integer, we can use int.TryParse, which returns true if the parse succeeds and sets an out parameter to the value.

```<code>private void checkerButton_Click(object sender, EventArgs e)
{
    int input;
    if (int.TryParse(checkerBox.Text, out input))
    {
        pali = new Palindrome() { number = input };
        checkerLabel.Text = pali.GetEvenOrOddMessage();
    }
    else
    {
        // Do something if the input string is not a number
    }
}
</code>```

Body:
when ever i try to run my program the compiler brings me an error  Input string was not in a correct format.

my code:

public int number;
public int evenOrOdd()
        {
            if(number % 2 == 0)
            {
                return int.Parse(number+" is a even number");
            }
            else
            {
                return int.Parse(number + " is a oddnumber");
            }
        }

and

private void checkerButton_Click(object sender, EventArgs e)
        {
            pali = new Palindrome() { number = int.Parse(checkerBox.Text) };
            checkerLabel.Text = pali.evenOrOdd().ToString();
        }

Body:
There seem to be a couple of problems:

One is simply a design/usage issue: you have a method called "evenOrOdd" that returns an int. It would make more sense if instead you had a method that was called "IsEven" (or "IsOdd") that returned a bool, or maybe one called "GetEvenOrOddMessage" that returned a string.

Another is that you are trying to convert a non-numeric string to an integer (your int.Parse method will fail with a non-numeric string value).

Presumably you want a method that returns a message string if the number is even or odd, so you don't need to try to cast anything to an int, but rather to a string.

So we can create a method that returns the message we want, give some numeric input:

public string GetEvenOrOddMessage()
{
    if (number % 2 == 0)
    {
        return (number + " is an even number");
    }
    else
    {
        return (number + " is an odd number");
    }
}

Now, to test if the string is indeed an integer, we can use int.TryParse, which returns true if the parse succeeds and sets an out parameter to the value.

private void checkerButton_Click(object sender, EventArgs e)
{
    int input;
    if (int.TryParse(checkerBox.Text, out input))
    {
        pali = new Palindrome() { number = input };
        checkerLabel.Text = pali.GetEvenOrOddMessage();
    }
    else
    {
        // Do something if the input string is not a number
    }
}


问:
project oxford text not printing correctly
I'm using project oxfords modules and I trying to print out the text in the image
when i print response it looks like this. My guess is the text is in the 'lines'. How do i print that?

```<code>client3 = new oxford.Client('api key')
client3.vision.ocr({
 path: './words.jpg',
 language: 'en',
}).then(function (response) {
 console.log(response);
}).catch(function (err) {
 console.log(err);
});
</code>```

probably a simple fix I just cant figure it out

答:
There's a sample JSON here.

Basically, lines is an array of an object consisting of a boundingBox and words.  words, in turn, is an array of object consisting of a boundingBox and text.

So for example, you could do something like this:

```<code>for (i=0; i<response.regions.length; i++) {
  region = response.regions[i];
  for (j=0; j<region.lines.length; j++) {
    line = region.lines[j];
    words = [];
    for (k=0; k<line.words.length; k++) {
      words.push(line.words[k].text);
    }
    console.log(words.join(' '));
  }
}
</code>```

Body:
I'm using project oxfords modules and I trying to print out the text in the image
when i print response it looks like this. My guess is the text is in the 'lines'. How do i print that?

client3 = new oxford.Client('api key')
client3.vision.ocr({
 path: './words.jpg',
 language: 'en',
}).then(function (response) {
 console.log(response);
}).catch(function (err) {
 console.log(err);
});

probably a simple fix I just cant figure it out

Body:
There's a sample JSON here.

Basically, lines is an array of an object consisting of a boundingBox and words.  words, in turn, is an array of object consisting of a boundingBox and text.

So for example, you could do something like this:

for (i=0; i<response.regions.length; i++) {
  region = response.regions[i];
  for (j=0; j<region.lines.length; j++) {
    line = region.lines[j];
    words = [];
    for (k=0; k<line.words.length; k++) {
      words.push(line.words[k].text);
    }
    console.log(words.join(' '));
  }
}


问:
How to manually delete a subscription in SSRS?
I am trying to delete a subscription using the SSRS Manager portal.  I get the following error when trying to delete the subscription:

There are two or more jobs named '12FC1298-3060-4CC9-B406-4A612FFDB620'. Specify @job_id instead of @job_name to uniquely identify the job.

I get the same error if I try to delete the entire report via the Report Manager portal.

How can I clean up this issue manually ?

答: I deleted the single record I found and got an error message that said there was a duplicate, etc. However when I again selected from the subscriptions table using that ID, there were no records. So apparently both were deleted. I was then able to fix the schedule in the Manage option of the report in the SSRS folder. It seems to be a glitch because it deleted SOMETHING, but my subscription was still there in SSRS, the error just went away. No idea HOW this worked, but it did.</p>


问:
Adding a method to a Rails ActiveRecord class
In plain Ruby, this works just fine:

```<code>class TestSuper
  def foo
    puts "In TestSuper.foo"
  end
end

class TestClass < TestSuper
  def foo
    super
    puts "In TestClass.bar"
  end
end

class TestClass
  def bar
    puts "In TestClass.bar, second definition"
    puts "Calling foo:"
    foo
  end
end

t = TestClass.new
t.foo
t.bar
</code>```

I can call foo() and bar() on a TestClass instance and get exactly what I expect:

```<code>In TestSuper.foo
In TestClass.bar
In TestClass.bar, second definition
Calling foo:
In TestSuper.foo
In TestClass.bar
</code>```

However, when I try something very similar in a Rails migration, I get errors:

```<code>#### my_model.rb ####
puts "In my_model.rb"
class MyModel
  has_many :foo
end

#### my_migration.rb ####
puts "In my_migration.rb"
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

class MyMigration < ActiveRecord::Migration
  def self.up
    MyModel.find(1).bar
  end

  def self.down
    # Not applicable
  end
end
</code>```

The first problem is that MyModel.find() disappears unless I explicitly have it extend ActiveRecord in my_migration.rb. Otherwise, it drops the superclass.

If I do that, I then get an error on the foo call in MyModel.bar().

If I comment out the class (re)definition in my_migration.rb, find() and bar() both work just fine.

During the course of my debugging, I added the puts statements to see when each file & class was being executed. It appears that my_model.rb doesn't even get loaded if MyModel is already defined (which I'm doing in my_migration.rb).

So: why does this happen in Rails, and how can I work around it?

答:
in your example i think you're missing

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

from your first definition.

in your migration monkey patch you also need a matching

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

the two class definitions have to match

Body:
In plain Ruby, this works just fine:

class TestSuper
  def foo
    puts "In TestSuper.foo"
  end
end

class TestClass < TestSuper
  def foo
    super
    puts "In TestClass.bar"
  end
end

class TestClass
  def bar
    puts "In TestClass.bar, second definition"
    puts "Calling foo:"
    foo
  end
end

t = TestClass.new
t.foo
t.bar

I can call foo() and bar() on a TestClass instance and get exactly what I expect:

In TestSuper.foo
In TestClass.bar
In TestClass.bar, second definition
Calling foo:
In TestSuper.foo
In TestClass.bar

However, when I try something very similar in a Rails migration, I get errors:

#### my_model.rb ####
puts "In my_model.rb"
class MyModel
  has_many :foo
end

#### my_migration.rb ####
puts "In my_migration.rb"
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

class MyMigration < ActiveRecord::Migration
  def self.up
    MyModel.find(1).bar
  end

  def self.down
    # Not applicable
  end
end

The first problem is that MyModel.find() disappears unless I explicitly have it extend ActiveRecord in my_migration.rb. Otherwise, it drops the superclass.

If I do that, I then get an error on the foo call in MyModel.bar().

If I comment out the class (re)definition in my_migration.rb, find() and bar() both work just fine.

During the course of my debugging, I added the puts statements to see when each file & class was being executed. It appears that my_model.rb doesn't even get loaded if MyModel is already defined (which I'm doing in my_migration.rb).

So: why does this happen in Rails, and how can I work around it?

Body:
in your example i think you're missing

< ActiveRecord::Base

from your first definition.

in your migration monkey patch you also need a matching

< ActiveRecord::Base

the two class definitions have to match


问:
Angular2 router-outlet outputs component into ng-component
In Angular2 app I use Bootstrap's grid.
Module's main component's template provides a grid's row:

```<code><div class="row">
    <router-outlet></router-outlet>
</div>
</code>```

And sub-components have Bootstrap's grid's columns:

```<code><div class="col-md-8">Hello, world!</div>
<div class="col-md-4"></div>
</code>```

The problem is Angular2 generates such a HTML:

```<code><div class="row">
    <router-outlet></router-outlet>
    <ng-component>
        <div class="col-md-8">Hello, world!</div>
        <div class="col-md-4"></div>
    </ng-component>
</div>
</code>```

So: it adds an ng-component tag, which breaks the structure, required by Bootstrap (the column block must be a child of a row block).

How can I prevent generation of the ng-component tag?

答:
This is happening because of .row class. It has an property of display:flex which is a container of flex items.

In this case <ng-componet> is now become a flex item and start having the default properties of flex items.

I will suggest you to change you HTML construction for now may be bootstrap team will fix this.

To get more info about default properties flex item you can click here.

Body:
In Angular2 app I use Bootstrap's grid.
Module's main component's template provides a grid's row:

    <router-outlet></router-outlet>

And sub-components have Bootstrap's grid's columns:

Hello, world!

The problem is Angular2 generates such a HTML:

    <router-outlet></router-outlet>
    <ng-component>

Hello, world!

    </ng-component>

So: it adds an ng-component tag, which breaks the structure, required by Bootstrap (the column block must be a child of a row block).

How can I prevent generation of the ng-component tag?


问:
Zephyr OS boot and flash
I tried to flash my application to Carbon 96 board (successfully).
Booting guide created bin and elf files but not image file.
How do i make a boot able file ?
What are the required files to flash ?
Is there any boot image file for zephyr?
Can I get explanation about flashing and booting Zephyr OS ? </p>

答:
The zephyr.bin file is the bootable image file; it's the only file required to flash. The zephyr.elf file contains extra debugging information you would need to run a debugger, so you would use that on the host PC side (e.g. pass it to gdb).

The method of flashing the zephyr.bin file depends on the board. It looks like for the Carbon 96 you use dfu-util. You then press the Reset button to boot with the new image.

Title: Zephyr OS boot and flash