问:
Trying to reach values of one column in table
I am jQuery/JS newbie, trying substract discount value (user input) from prices of one column and put the result to another column of the table.

HTML

```<code><div>
 <table id='table_one' border='1'>
  <thead>
   <tr>
    <th>Name</th>
    <th>No</th>
    <th>Qty</th>
    <th>Price A</th>
    <th>Price B</th>
   </tr>
  </thead>
   <tr>
   </tr>
 </table>
</div><br>

<form id="discount_form">Discount:
 <input type="text" id="discount">
 <input id="submit" type="button" value="Count">
</form>
</code>```

JS

```<code>var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

data = $.parseJSON(data);

$(function() {
 $.each(data, function(i, item) {
  $('<tr>').append(
  $('<td>').text(item.Name),
  $('<td>').text(item.No),
  $('<td>').text(item.Qty),
  $('<td>').text(item.Price_A),
  $('<td>').text(item.Price_B)).appendTo('#table_one');
 });
});

$(document).ready(function() {
 $('#submit').click(function() {
  var discount = parseFloat($('#discount').val() , 10);
  update_amounts();
 });
});

function update_amounts() {
 $('#table_one tr').each(function() {
  var pricea = parseFloat($(this).find(item.Price_A).val(), 10);
  var priceb = (pricea - discount);
  $(this).find(item.Price_B).text(''+priceb);
  alert($(this).text(priceb));
 });
}
</code>```

I think this I am doing wrong, getting values from column Price_A:

```<code>var pricea = parseFloat($(this).find(item.Price_A).val(), 10);
</code>```

Also this, it suppose to put result data to column Price_B

```<code>$(this).find(item.Price_B).text(''+priceb);
</code>```

Help will be much appreciated.

https://jsfiddle.net/w42zk7uy/

答:
You can use the code,

HTML:

```<code><div>
 <table id='table_one' border='1'>
  <thead>
   <tr>
    <th>Name</th>
    <th>No</th>
    <th>Qty</th>
    <th>Price A</th>
    <th>Price B</th>
   </tr>
  </thead>
 </table>
</div><br>

<form id="discount_form">Discount:
 <input type="text" id="discount">
 <input id="submit" type="button" value="Count">
</form>
</code>```

JS:

```<code>var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

data = $.parseJSON(data);

$(function() {
 $.each(data, function(i, item) {
  $('<tr>').append(
  $('<td>').text(item.Name),
  $('<td>').text(item.No),
  $('<td>').text(item.Qty),
  $('<td>').text(item.Price_A),
  $('<td>').text(item.Price_B)).appendTo('#table_one');
 });
});

$(document).ready(function() {
 $('#submit').click(function() {
  var discount = parseFloat($('#discount').val() , 10);
  update_amounts(discount);
 });
});

function update_amounts(discount) {
 $('#table_one tbody tr').each(function() {
   //:nth-last-child(2) Find the second last child
   var pricea = parseFloat($(this).find(':nth-last-child(2)').text(), 10);
   var priceb = (pricea - discount);
  //:last-child Find the last child
  $(this).find(':last-child').text(priceb);
 });
}
</code>```

Body:
I am jQuery/JS newbie, trying substract discount value (user input) from prices of one column and put the result to another column of the table.

HTML

    Name
    No
    Qty
    Price A
    Price B

<form id="discount_form">Discount:
 <input type="text" id="discount">
 <input id="submit" type="button" value="Count">
</form>

JS

var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

data = $.parseJSON(data);

$(function() {
 $.each(data, function(i, item) {
  $('
').append(
  $('').text(item.Name),
  $('').text(item.No),
  $('').text(item.Qty),
  $('').text(item.Price_A),
  $('').text(item.Price_B)).appendTo('#table_one');
 });
});

$(document).ready(function() {
 $('#submit').click(function() {
  var discount = parseFloat($('#discount').val() , 10);
  update_amounts();
 });
});

function update_amounts() {
 $('#table_one tr').each(function() {
  var pricea = parseFloat($(this).find(item.Price_A).val(), 10);
  var priceb = (pricea - discount);
  $(this).find(item.Price_B).text(''+priceb);
  alert($(this).text(priceb));
 });
}

I think this I am doing wrong, getting values from column Price_A:

var pricea = parseFloat($(this).find(item.Price_A).val(), 10);

Also this, it suppose to put result data to column Price_B

$(this).find(item.Price_B).text(''+priceb);

Help will be much appreciated.

https://jsfiddle.net/w42zk7uy/

Body:
You can use the code,

HTML:

<div>
 <table id='table_one' border='1'>
  <thead>
   <tr>
    <th>Name</th>
    <th>No</th>
    <th>Qty</th>
    <th>Price A</th>
    <th>Price B</th>
   </tr>
  </thead>
 </table>
</div><br>

<form id="discount_form">Discount:
 <input type="text" id="discount">
 <input id="submit" type="button" value="Count">
</form>

JS:

var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

data = $.parseJSON(data);

$(function() {
 $.each(data, function(i, item) {
  $('<tr>').append(
  $('<td>').text(item.Name),
  $('<td>').text(item.No),
  $('<td>').text(item.Qty),
  $('<td>').text(item.Price_A),
  $('<td>').text(item.Price_B)).appendTo('#table_one');
 });
});

$(document).ready(function() {
 $('#submit').click(function() {
  var discount = parseFloat($('#discount').val() , 10);
  update_amounts(discount);
 });
});

function update_amounts(discount) {
 $('#table_one tbody tr').each(function() {
   //:nth-last-child(2) Find the second last child
   var pricea = parseFloat($(this).find(':nth-last-child(2)').text(), 10);
   var priceb = (pricea - discount);
  //:last-child Find the last child
  $(this).find(':last-child').text(priceb);
 });
}


来源: stackexchange

问:
How to apply gradient clipping in TensorFlow?
Considering the example code.

I would like to know How to apply gradient clipping on this network on the RNN where there is a possibility of exploding gradients.

```<code>tf.clip_by_value(t, clip_value_min, clip_value_max, name=None)
</code>```

This is an example that could be used but where do I introduce this ?
In the def of RNN

```<code>    lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
    # Split data because rnn cell needs a list of inputs for the RNN inner loop
    _X = tf.split(0, n_steps, _X) # n_steps
tf.clip_by_value(_X, -1, 1, name=None)
</code>```

But this doesn't make sense as the tensor _X is the input and not the grad what is to be clipped?

Do I have to define my own Optimizer for this or is there a simpler option?

答:
For those who would like to understand the idea of gradient clipping (by norm):

Whenever the gradient norm is greater than a particular threshold, we clip the gradient norm so that it stays within the threshold. This threshold is sometimes set to 5.

Let the gradient be g and the max_norm_threshold be j.

Now, if ||g|| > j , we do:

g = (  j * g ) /  ||g||

This is the implementation done in tf.clip_by_norm

ContentLicense: CC BY-SA 3.0

Body:
Considering the example code.

I would like to know How to apply gradient clipping on this network on the RNN where there is a possibility of exploding gradients.

tf.clip_by_value(t, clip_value_min, clip_value_max, name=None)

This is an example that could be used but where do I introduce this ?
In the def of RNN

    lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
    # Split data because rnn cell needs a list of inputs for the RNN inner loop
    _X = tf.split(0, n_steps, _X) # n_steps
tf.clip_by_value(_X, -1, 1, name=None)

But this doesn't make sense as the tensor _X is the input and not the grad what is to be clipped?

Do I have to define my own Optimizer for this or is there a simpler option?

ContentLicense: CC BY-SA 4.0


问:
HTML Form not passing data to php processor
learning PHP and have hit a wall early with passing data in an HTML form in to PHP.  When I hit submit, the form page acts like it submits properly but when the processorder.php page opens, the data is not visible.  When I do a dump on the page, I am able to see the values displayed but they are not showing in the script.  Below is the code I'm using.  I've searched online and at SO and feel like I've pretty much exhausted all options.  Any assistance you can provide is much appreciated.</p>

```<code>HTML:
<form action="processorder.php" method="POST">

<table>
    <tr>
        <td>Item</td>
        <td>Quantity</td>
    </tr>
    <tr>
        <td>Tires</td>
        <td><input type="text" name="tireqty" id="tireqty" size="3" /></td>
    </tr>
    <tr>
        <td>Oil</td>
        <td><input type="text" name="oilqty" id="oilqty" size="3" /></td>
    </tr>
    <tr>
        <td>Spark Plugs</td>
        <td><input type="text" name="sparkqty" id="sparkqty" size="3" /></td>
    </tr>
    <tr>
        <td colspan="2" text-align"2"><input type="submit" value="Submit Order">
        </td>
    </tr>
</table>

</form>

PHP:
<?php

var_dump( $_POST );

/*var_dump($GLOBALS);*/

$tireqty = $_POST['$tireqty'];
$oilqty = $_POST['$oilqty'];
$sparkqty = $_POST['$sparkqty'];

/*echo phpinfo();*/

?>

<h1 />Bob's Auto Parts
<h2>Order Results</h2>

<?php

/*
ini_set('display_errors',1);
error_reporting(E_ALL);
*/

   echo "<p>Your Order is as Follows: </p>";
   echo htmlspecialchars($tireqty).' tires<br />';
   echo htmlspecialchars($oilqty).' bottles of oil<br />';
   echo htmlspecialchars($sparkqty).' spark plugs<br />';

    echo "<p>Order Processed at ";
    echo date('H:i, jS F Y');
    echo "</p>";

print_r($_POST);

/*var_dump($_REQUEST)*/

?>
</code>```

答:
Remove the $ of your $_POST methods. Change:

```<code>$tireqty = $_POST['$tireqty'];
$oilqty = $_POST['$oilqty'];
$sparkqty = $_POST['$sparkqty'];
</code>```

to:

```<code>$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
</code>```

Body:
learning PHP and have hit a wall early with passing data in an HTML form in to PHP.  When I hit submit, the form page acts like it submits properly but when the processorder.php page opens, the data is not visible.  When I do a dump on the page, I am able to see the values displayed but they are not showing in the script.  Below is the code I'm using.  I've searched online and at SO and feel like I've pretty much exhausted all options.  Any assistance you can provide is much appreciated.

HTML:
<form action="processorder.php" method="POST">

        Item
        Quantity

        Tires
        <input type="text" name="tireqty" id="tireqty" size="3" />

        Oil
        <input type="text" name="oilqty" id="oilqty" size="3" />

        Spark Plugs
        <input type="text" name="sparkqty" id="sparkqty" size="3" />

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

</form>

PHP:
<?php

var_dump( $_POST );

/*var_dump($GLOBALS);*/

$tireqty = $_POST['$tireqty'];
$oilqty = $_POST['$oilqty'];
$sparkqty = $_POST['$sparkqty'];

/*echo phpinfo();*/

?>

Bob's Auto Parts

Order Results

<?php

/*
ini_set('display_errors',1);
error_reporting(E_ALL);
*/

   echo "
Your Order is as Follows:
";
   echo htmlspecialchars($tireqty).' tires
';
   echo htmlspecialchars($oilqty).' bottles of oil
';
   echo htmlspecialchars($sparkqty).' spark plugs
';

    echo "
Order Processed at ";
    echo date('H:i, jS F Y');
    echo "
";

print_r($_POST);

/*var_dump($_REQUEST)*/

?>

Body:
Remove the $ of your $_POST methods. Change:

$tireqty = $_POST['$tireqty'];
$oilqty = $_POST['$oilqty'];
$sparkqty = $_POST['$sparkqty'];

to:

$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];


问:
Modify the request body with a FiddlerScript rule
I have several rules for testing that modify responses from a server, but can't figure out how to modify the body of a POST request with a FiddlerScript rule. oSession.GetRequestBodyAsString() sounds useful, but I can't see any way to set the request body after I've modified it.

Am I missing something, or is there no way to do this?

答:
```<code>var strBody=oSession.GetRequestBodyAsString();
strBody=strBody.replace("foo","bar");
oSession.utilSetRequestBody(strBody);
</code>```

Use this code to do that, in this sample foo is replaced by bar.

Body:
var strBody=oSession.GetRequestBodyAsString();
strBody=strBody.replace("foo","bar");
oSession.utilSetRequestBody(strBody);

Use this code to do that, in this sample foo is replaced by bar.


问:
enctype=multipart/form-data gives null values for text fileds in java
i have declared encoding type "multi part/form-data" in java server page. i tried to get values of text filed with a file.All the text field,i get has null.If i removed encoding type text fields are retrieved properly.

答:
hei, that cause jsp is not support method request.getparameter(""); to get value from textfield with form use enctype="multipart/form-data". i recommended you use apache common to upload text field type file, and for get input field text use this example coding.</p>

```<code>  for (FileItem item : formitem) {
      // proces only fields thats are not from fields
      String s1 = item.getFieldName();
      if(s1.equals("id")){
       String sid = item.getString();
       //System.out.println(sid);
       if(sid == null || sid.isEmpty()){

        id_data2 = sid;
       } else{
        id_data2 = sid.toString();
        id_data = Integer.parseInt(id_data2);
       }

      }if(s1.equals("name")){
       String sid = item.getString();
       //System.out.println(sid);
       String invoicenumber = sid;
       if(invoicenumber == null || invoicenumber.isEmpty()){
        multiple_invoice_model.setInvoice_number(333);
       }else{
        int id_invoice  = Integer.parseInt(invoicenumber);
        multiple_invoice_model.setInvoice_number(id_invoice);

       }
      }if(s1.equals("file")){
       String sid = item.getString();
       //System.out.println(sid);

      if (!item.isFormField()) {
       String filename = new File(new Date().getTime() + "_" + item.getName()).toString();
       File store_file = new File(uploaddir.toString(), filename);

       // save file on disk
       item.write(store_file);

       document_model document_model = new document_model();
       document_model.setNama_document(filename);
       document_model = multiple_invoice_dao.simpan_document(document_model);

       System.out.println("Id Document" + document_model.getId());

      }
     }
    }

   } catch (Exception e) {
    //request.setAttribute("message", "there has benn error :" + e.getMessage());
    e.printStackTrace();
   }
</code>```

Body:
hei, that cause jsp is not support method request.getparameter(""); to get value from textfield with form use enctype="multipart/form-data". i recommended you use apache common to upload text field type file, and for get input field text use this example coding.

  for (FileItem item : formitem) {
      // proces only fields thats are not from fields
      String s1 = item.getFieldName();
      if(s1.equals("id")){
       String sid = item.getString();
       //System.out.println(sid);
       if(sid == null || sid.isEmpty()){

        id_data2 = sid;
       } else{
        id_data2 = sid.toString();
        id_data = Integer.parseInt(id_data2);
       }

      }if(s1.equals("name")){
       String sid = item.getString();
       //System.out.println(sid);
       String invoicenumber = sid;
       if(invoicenumber == null || invoicenumber.isEmpty()){
        multiple_invoice_model.setInvoice_number(333);
       }else{
        int id_invoice  = Integer.parseInt(invoicenumber);
        multiple_invoice_model.setInvoice_number(id_invoice);

       }
      }if(s1.equals("file")){
       String sid = item.getString();
       //System.out.println(sid);

      if (!item.isFormField()) {
       String filename = new File(new Date().getTime() + "_" + item.getName()).toString();
       File store_file = new File(uploaddir.toString(), filename);

       // save file on disk
       item.write(store_file);

       document_model document_model = new document_model();
       document_model.setNama_document(filename);
       document_model = multiple_invoice_dao.simpan_document(document_model);

       System.out.println("Id Document" + document_model.getId());

      }
     }
    }

   } catch (Exception e) {
    //request.setAttribute("message", "there has benn error :" + e.getMessage());
    e.printStackTrace();
   }


问:
Formtastic non-model form, integration with external site, override/specify the input ID values
I'm using formtastic to collect information from a form and post dirctly to an external site.

I have no problem generating the form itself.  However, since this is being submitted to an external site, they require that each input field have the specific IDs they specify, eg email or last_name -- not the closest Formtastic form, eg _email_input or _last_name_input.

I've looked at the Formtastic v1.2.3 code and I'm 90% sure the answer is "sorry, can't do that." I figured it couldn't hurt to check if I'm missing something.  I would like some way to specify the ID completely, as in:

```<code>= semantic_form_for('', :url => "https://external_site.com/handler, :method => "post") do |form|
  = form.input :last_name, :id => "last_name"
  [etc]
</code>```

Is this possible?

(I will note that I recognize that another, arguably superior approach would be to create an appropriate controller, sanity check the parameters locally, and dispatch the remote call from within the app only when it's well formed; however, that's not what I'm trying to do at the moment.)

答:
Firstly i think you need to use semantic_fields_for for non-model forms. Next, to pass ids to each field, you can use the input_html options to specify them. for eg</p>

```<code>form.input :email, :input_html => {:name => 'email', :id => 'email' }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using formtastic to collect information from a form and post dirctly to an external site.

I have no problem generating the form itself.  However, since this is being submitted to an external site, they require that each input field have the specific IDs they specify, eg email or last_name -- not the closest Formtastic form, eg _email_input or _last_name_input.

I've looked at the Formtastic v1.2.3 code and I'm 90% sure the answer is "sorry, can't do that." I figured it couldn't hurt to check if I'm missing something.  I would like some way to specify the ID completely, as in:

= semantic_form_for('', :url => "https://external_site.com/handler, :method => "post") do |form|
  = form.input :last_name, :id => "last_name"
  [etc]

Is this possible?

(I will note that I recognize that another, arguably superior approach would be to create an appropriate controller, sanity check the parameters locally, and dispatch the remote call from within the app only when it's well formed; however, that's not what I'm trying to do at the moment.)

Body:
Firstly i think you need to use semantic_fields_for for non-model forms. Next, to pass ids to each field, you can use the input_html options to specify them. for eg

form.input :email, :input_html => {:name => 'email', :id => 'email' }


问:
Activerecord: find nth row in table
```<code>{ topic: "Foo", opportunity: Opportunity.limit(15)[0] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[2] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[7] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[9] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[11]}
</code>```

Instead of doing Opportunity.limit(15)[n], does active record offer any convenience functions?

答:
You are looking for offset.

Also note that not passing an order to your query does not guarantee that the query will return the instances ordered by the primary key. So it is best to pass an explicit order.

Opportunity.order(:id).limit(1).offset(2)

Title: Activerecord: find nth row in table

Body:
{ topic: "Foo", opportunity: Opportunity.limit(15)[0] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[2] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[7] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[9] },
{ topic: "Foo", opportunity: Opportunity.limit(15)[11]}

Instead of doing Opportunity.limit(15)[n], does active record offer any convenience functions?


问:
replace multiple elements with .splice() in javascript
I am pretty new to Javascript and i am doing a course on it atm. I am searching for a way to replace multiple items in an array with 1 item but i only know how to replace a single one.here is my snipped:

let secretMessage = ["Learning", "isn't", "about", "what", "you", "get", "easily", "the", "first", "time,", "it's", "about", "what", "you", "can", "figure", "out.", "-2015,", "Chris", "Pine,", "Learn", "JavaScript"];

secretMessage.pop();
secretMessage.push('to','program');
secretMessage[6] = 'right';
secretMessage.shift();
secretMessage.unshift('Programming');```

and this is what i am supposed to do:
Use an array method to remove the strings get, right, the, first, time,, and replace them with the single string know,.

答:
The .splice() method lets you replace multiple elements in an array with one, two, or however many elements you like. Just use the syntax:

.splice(startingIndex, numDeletions, replacement1, replacement2, ... )

where:

startingIndex is the index of the array that contains the first element you want to remove

numDeletions is the number of consecutive items in the array you want to remove

replacement1, replacement2, ... (however many) are the elements you wish to add to the array, beginning at startingIndex

In your case:

get is at index 5

get, easily, the, first, time is 5 Strings consecutively

only want one replacement: the String know

So you would say .splice(5, 5, "know")

Can also refer to MDN here. Cheers!

Body:
I am pretty new to Javascript and i am doing a course on it atm. I am searching for a way to replace multiple items in an array with 1 item but i only know how to replace a single one.here is my snipped:

let secretMessage = ["Learning", "isn't", "about", "what", "you", "get", "easily", "the", "first", "time,", "it's", "about", "what", "you", "can", "figure", "out.", "-2015,", "Chris", "Pine,", "Learn", "JavaScript"];

secretMessage.pop();
secretMessage.push('to','program');
secretMessage[6] = 'right';
secretMessage.shift();
secretMessage.unshift('Programming');

and this is what i am supposed to do:
Use an array method to remove the strings get, right, the, first, time,, and replace them with the single string know,.


问:
Sorting a JSON object in Android studios (java)
I've been searching for a while on how to sort a JSON object like this.  It has a lot of attributes but I'm just trying to sort the objects into alphabetical order by "name":

I'm really new to java so you have any information to get started that'll be great!

//update:

So I figured out how to extract the attributes of each restaurant and now I'm trying to implement a comparator to sort the json objects but I'm confused on how to call the comparator and what arg to input

This is the comparator I'm using (got it from the internet)

```<code>public class AlphabeticalComparator  implements Comparator<String> {
        public int compare(String obj1, String obj2) {
            if (obj1 == null) {
                return -1;
            }
            if (obj2 == null) {
                return 1;
            }
            if (obj1.equals( obj2 )) {
                return 0;
            }
            return obj1.compareTo(obj2);
        }
    }
</code>```

I'm also a little confused on how this sorts the objects since it will only return an integer.  The json object im trying to sort is below

This is the JSON Object I get in response when I connect to the zomato API

``

```<code>{
  "results_found": 10573,
  "results_start": 0,
  "results_shown": 20,
  "restaurants": [
    {
      "restaurant": {
        "R": {
          "res_id": 16795271
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16795271",
        "name": "Craigie On Main", //This is what I want to sort it by
        "url": "https://www.zomato.com/boston/craigie-on-main-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "853 Main St, Cambridge 02139",
          "locality": "Central Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3634820000",
          "longitude": "-71.0985660000",
          "zipcode": "02139",
          "country_id": 216,
          "locality_verbose": "Central Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "European, French",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "342"
        },
        "photos_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16795271",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798941
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798941",
        "name": "O Ya",
        "url": "https://www.zomato.com/boston/o-ya-boston?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "9 East St, Boston 02111",
          "locality": "Leather District",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3513170000",
          "longitude": "-71.0570370000",
          "zipcode": "02111",
          "country_id": 216,
          "locality_verbose": "Leather District, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Japanese, Sushi",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.3",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "192"
        },
        "photos_url": "https://www.zomato.com/boston/o-ya-boston/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/o-ya-boston/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?output-format=webp",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798941",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/o-ya-boston/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798079
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798079",
        "name": "Solea Restaurant and Tapas Bar",
        "url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "388 Moody St, Waltham 02453",
          "locality": "Waltham",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3695490000",
          "longitude": "-71.2370130000",
          "zipcode": "02453",
          "country_id": 216,
          "locality_verbose": "Waltham, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Spanish, Tapas",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "303"
        },
        "photos_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798079",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
"restaurant": {
        "R": {
          "res_id": 16796139
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16796139",
        "name": "Harvest",
        "url": "https://www.zomato.com/boston/harvest-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "44 Brattle St, Cambridge 02138",
          "locality": "Harvard Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3742680000",
          "longitude": "-71.1219960000",
          "zipcode": "02138",
          "country_id": 216,
          "locality_verbose": "Harvard Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "American, Breakfast",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "3.9",
          "rating_text": "Good",
          "rating_color": "9ACD32",
          "votes": "190"
        },
        "photos_url": "https://www.zomato.com/boston/harvest-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/harvest-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16796139",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/harvest-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
</code>```

答:
I'm only familiar with using Google's gson library which is a bit old.  If there are better json parsers available I'm sure somebody can chime in.
You'd use it like this to extract the information:

```<code>String restaurantName;
JsonElement restaurantJSONElement;
JsonPrimitive restaurantJSONPrimitive;

JsonParser parser = new JsonParser();
// myJSONstring is the raw JSON data
JsonElement parentJSONElement = parser.parse(myJSONstring);
JsonObject parentJSONObject = parentJSONElement.getAsJsonObject();
JsonArray restaurantsJSONArray = (JsonArray) parentJSONObject.get("restaurants");
for(int i=0;i<restaurantsJSONArray.size();i++){
  //get the element
  restaurantJSONElement = ((JsonObject)restaurantsJSONArray.get(i)).get("restaurant");
  //get the restaurant name
  restaurantJSONPrimitive = ((JsonObject)restaurantJSONElement.getAsJsonObject()).getAsJsonPrimitive("name");
  restaurantName = restaurantJSONPrimitive.getAsString();
}
</code>```

You could extract all the members and do whatever you want with them, put them in custom object arrays and sort them by restaurantName as the comparitor

Body:
I've been searching for a while on how to sort a JSON object like this.  It has a lot of attributes but I'm just trying to sort the objects into alphabetical order by "name":

I'm really new to java so you have any information to get started that'll be great!

//update:

So I figured out how to extract the attributes of each restaurant and now I'm trying to implement a comparator to sort the json objects but I'm confused on how to call the comparator and what arg to input

This is the comparator I'm using (got it from the internet)

public class AlphabeticalComparator  implements Comparator<String> {
        public int compare(String obj1, String obj2) {
            if (obj1 == null) {
                return -1;
            }
            if (obj2 == null) {
                return 1;
            }
            if (obj1.equals( obj2 )) {
                return 0;
            }
            return obj1.compareTo(obj2);
        }
    }

I'm also a little confused on how this sorts the objects since it will only return an integer.  The json object im trying to sort is below

This is the JSON Object I get in response when I connect to the zomato API

``

{
  "results_found": 10573,
  "results_start": 0,
  "results_shown": 20,
  "restaurants": [
    {
      "restaurant": {
        "R": {
          "res_id": 16795271
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16795271",
        "name": "Craigie On Main", //This is what I want to sort it by
        "url": "https://www.zomato.com/boston/craigie-on-main-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "853 Main St, Cambridge 02139",
          "locality": "Central Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3634820000",
          "longitude": "-71.0985660000",
          "zipcode": "02139",
          "country_id": 216,
          "locality_verbose": "Central Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "European, French",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "342"
        },
        "photos_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16795271_CHAIN_bd36a0893cde3f70ab4a67f1e086d5f5.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16795271",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/craigie-on-main-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798941
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798941",
        "name": "O Ya",
        "url": "https://www.zomato.com/boston/o-ya-boston?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "9 East St, Boston 02111",
          "locality": "Leather District",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3513170000",
          "longitude": "-71.0570370000",
          "zipcode": "02111",
          "country_id": 216,
          "locality_verbose": "Leather District, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Japanese, Sushi",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "4.3",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "192"
        },
        "photos_url": "https://www.zomato.com/boston/o-ya-boston/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/o-ya-boston/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16798941_CHAIN_d58be7a0f56ad4fbad498ba65b746a67.jpg?output-format=webp",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798941",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/o-ya-boston/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
    {
      "restaurant": {
        "R": {
          "res_id": 16798079
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16798079",
        "name": "Solea Restaurant and Tapas Bar",
        "url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "388 Moody St, Waltham 02453",
          "locality": "Waltham",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3695490000",
          "longitude": "-71.2370130000",
          "zipcode": "02453",
          "country_id": 216,
          "locality_verbose": "Waltham, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Spanish, Tapas",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "",
        "user_rating": {
          "aggregate_rating": "4.2",
          "rating_text": "Very Good",
          "rating_color": "5BA829",
          "votes": "303"
        },
        "photos_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16798079",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/solea-restaurant-and-tapas-bar-waltham/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },
"restaurant": {
        "R": {
          "res_id": 16796139
        },
        "apikey": "fa221c30c201daf8380ac435cedfebe9",
        "id": "16796139",
        "name": "Harvest",
        "url": "https://www.zomato.com/boston/harvest-cambridge?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "44 Brattle St, Cambridge 02138",
          "locality": "Harvard Square",
          "city": "Boston",
          "city_id": 289,
          "latitude": "42.3742680000",
          "longitude": "-71.1219960000",
          "zipcode": "02138",
          "country_id": 216,
          "locality_verbose": "Harvard Square, Boston"
        },
        "switch_to_order_menu": 0,
        "cuisines": "American, Breakfast",
        "average_cost_for_two": 275,
        "price_range": 4,
        "currency": "$",
        "offers": [],
        "thumb": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "3.9",
          "rating_text": "Good",
          "rating_color": "9ACD32",
          "votes": "190"
        },
        "photos_url": "https://www.zomato.com/boston/harvest-cambridge/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "menu_url": "https://www.zomato.com/boston/harvest-cambridge/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/16796139_RESTAURANT_4f9960714d6bd153a4571dd062c4ff45.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "deeplink": "zomato://restaurant/16796139",
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/boston/harvest-cambridge/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "establishment_types": []
      }
    },

Body:
I'm only familiar with using Google's gson library which is a bit old.  If there are better json parsers available I'm sure somebody can chime in.
You'd use it like this to extract the information:

String restaurantName;
JsonElement restaurantJSONElement;
JsonPrimitive restaurantJSONPrimitive;

JsonParser parser = new JsonParser();
// myJSONstring is the raw JSON data
JsonElement parentJSONElement = parser.parse(myJSONstring);
JsonObject parentJSONObject = parentJSONElement.getAsJsonObject();
JsonArray restaurantsJSONArray = (JsonArray) parentJSONObject.get("restaurants");
for(int i=0;i<restaurantsJSONArray.size();i++){
  //get the element
  restaurantJSONElement = ((JsonObject)restaurantsJSONArray.get(i)).get("restaurant");
  //get the restaurant name
  restaurantJSONPrimitive = ((JsonObject)restaurantJSONElement.getAsJsonObject()).getAsJsonPrimitive("name");
  restaurantName = restaurantJSONPrimitive.getAsString();
}

You could extract all the members and do whatever you want with them, put them in custom object arrays and sort them by restaurantName as the comparitor


问:
MS Access 2016 UPDATE query with ALIKE
I'm trying to run the following UPDATE query in MS Access 2016 VBA:

```<code>UPDATE M_Subscriber
    SET M_Subscriber.RatingID = t.RatingID
    FROM
        ( SELECT M_Subscriber.ID AS SubscriberID, E_SubscriberRating.ID AS RatingID
              FROM M_Subscriber, E_SubscriberRating
              WHERE M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
        ) AS t
    WHERE M_Subscriber.ID = t.SubscriberID
</code>```

However, when trying to execute it I get a "syntax error (missing operator) in query expression" error.

I know that the SELECT part of the query by itself works just as expected (though using LIKE instead of ALIKE does not, even when using * for the wildcard...).

I've also tried this version of the query:

```<code>UPDATE M_Subscriber
    SET M_Subscriber.RatingID = E_SubscriberRating.ID
    FROM M_Subscriber
        INNER JOIN E_SubscriberRating
        ON M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
</code>```

But again the same error message (and again, a standalone SELECT statement using the INNER JOIN works just fine).

Some info on what I'm trying to do:

I have a field of labels (just at string of various words) for my subscribers (in M_Subscriber) and one of those words can be a rating. On the other hand I have a table (E_SubscriberRatings) of all possible words for ratings (E_SubscriberRating.Description). I'm now trying to set the M_Subscriber.RatingID field based on the ID of the SubscriberRating whose description shows up in the M_Subscriber.Labels field (if it actually contains any such description).

At this point, I've really run out of ideas what to tweak to figure out what I'm doing wrong. I've found various examples that join by column = column but none that join using LIKE.

答:
Try using this syntax:</p>

```<code>UPDATE M_Subscriber INNER JOIN
       E_SubscriberRating
       ON M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
    SET M_Subscriber.RatingID = E_SubscriberRating.ID;
</code>```

Title: MS Access 2016 UPDATE query with ALIKE

Body:
I'm trying to run the following UPDATE query in MS Access 2016 VBA:

UPDATE M_Subscriber
    SET M_Subscriber.RatingID = t.RatingID
    FROM
        ( SELECT M_Subscriber.ID AS SubscriberID, E_SubscriberRating.ID AS RatingID
              FROM M_Subscriber, E_SubscriberRating
              WHERE M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
        ) AS t
    WHERE M_Subscriber.ID = t.SubscriberID

However, when trying to execute it I get a "syntax error (missing operator) in query expression" error.

I know that the SELECT part of the query by itself works just as expected (though using LIKE instead of ALIKE does not, even when using * for the wildcard...).

I've also tried this version of the query:

UPDATE M_Subscriber
    SET M_Subscriber.RatingID = E_SubscriberRating.ID
    FROM M_Subscriber
        INNER JOIN E_SubscriberRating
        ON M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'

But again the same error message (and again, a standalone SELECT statement using the INNER JOIN works just fine).

Some info on what I'm trying to do:

I have a field of labels (just at string of various words) for my subscribers (in M_Subscriber) and one of those words can be a rating. On the other hand I have a table (E_SubscriberRatings) of all possible words for ratings (E_SubscriberRating.Description). I'm now trying to set the M_Subscriber.RatingID field based on the ID of the SubscriberRating whose description shows up in the M_Subscriber.Labels field (if it actually contains any such description).

At this point, I've really run out of ideas what to tweak to figure out what I'm doing wrong. I've found various examples that join by column = column but none that join using LIKE.

Body:
Try using this syntax:

UPDATE M_Subscriber INNER JOIN
       E_SubscriberRating
       ON M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
    SET M_Subscriber.RatingID = E_SubscriberRating.ID;


问:
WCF REST: Encrypting credentials when using my own custom validator - UserNamePasswordValidator?
I am using my own custom validator by inheriting from UserNamePasswordValidator. The service is hosted in a windows service. Is there a way to encrypt the username / password and descrypt it on the service?

What are my other options, do i have to create a key combination?

答:
If you have configured your service to use the UserName clientCredentialType, your credentials will already be encrypted.

WCF does not allow us to transmit UserName and Password in plain text without extending the framework with your own binding (as is demonstrated on CodeProject).


问:
Not all CSS functioning in Vuetify with Vue.js and Webpack
I suspect this has something to do with me failing to pull the JS file for vuetify in properly, but I've not managed to drill down to any error anything. It appears that some CSS features of Vuetify such as list highlight events are not functioning in my app, in which I'm attempting to use Vuetify with Vue.js and Webpack.

The example I'm trying to implement is the default navigation drawer.

In my implementation, hovering over a list item does not trigger a background color change or a cursor type change.

My code:

Main.js

```<code>import Vue from 'vue'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import vuetify_css from 'vuetify/dist/vuetify.min.css';

Vue.use(Vuetify)

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})
</code>```

App.vue

```<code><template>
  <div id="app">
    <v-app>
      <navigation></navigation>
      <v-toolbar app></v-toolbar>
      <v-content>
        <v-container fluid>
          <router-view></router-view>
        </v-container>
      </v-content>
      <v-footer app></v-footer>
    </v-app>
  </div>
</template>

<script>
import Navigation from '@/views/Navigation'

export default {
  name: 'app',
  components: {Navigation},
}
</script>

<style>
</style>
</code>```

Navigation.js

```<code><template>
   <v-navigation-drawer app permanent light>
    <v-toolbar flat>
      <v-list>
        <v-list-tile>
          <v-list-tile-title class="title">
            Application
          </v-list-tile-title>
        </v-list-tile>
      </v-list>
    </v-toolbar>
    <v-divider></v-divider>
    <v-list dense class="pt-0">
      <v-list-tile v-for="item in items" :key="item.title" >
        <v-list-tile-content>
          <v-list-tile-title>{{ item.title }}</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>
    </v-list>
  </v-navigation-drawer>
</template>

<script>
export default {
  data () {
    return {
        items: [
          { title: 'Home', },
          { title: 'About', }
        ]
    }
  }
}
</script>

<style scoped>
</style>
</code>```

What's weird is I can see that the entire Vuetify css file is being injected properly as a style tag by webpack, and I don't think I'm overwriting with any custom styles (in that I have none!)

What am I missing to properly get Vuetify styles working?

(some extraneous code stripped, let me know if you need to see more of my project files / code)

答:
The problem is that you did not add a handler for any mouse event. Try to just add an empty:</p>

```<code><v-list dense class="pt-0">
  <v-list-tile v-for="item in items" :key="item.title" @click="">
    <v-list-tile-content>
      <v-list-tile-title>{{ item.title }}</v-list-tile-title>
    </v-list-tile-content>
  </v-list-tile>
</v-list>
</code>```

Body:
I suspect this has something to do with me failing to pull the JS file for vuetify in properly, but I've not managed to drill down to any error anything. It appears that some CSS features of Vuetify such as list highlight events are not functioning in my app, in which I'm attempting to use Vuetify with Vue.js and Webpack.

The example I'm trying to implement is the default navigation drawer.

In my implementation, hovering over a list item does not trigger a background color change or a cursor type change.

My code:

Main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import vuetify_css from 'vuetify/dist/vuetify.min.css';

Vue.use(Vuetify)

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

App.vue

<template>

    <v-app>
      <navigation></navigation>
      <v-toolbar app></v-toolbar>
      <v-content>
        <v-container fluid>
          <router-view></router-view>
        </v-container>
      </v-content>
      <v-footer app></v-footer>
    </v-app>

</template>

Navigation.js

<template>
   <v-navigation-drawer app permanent light>
    <v-toolbar flat>
      <v-list>
        <v-list-tile>
          <v-list-tile-title class="title">
            Application
          </v-list-tile-title>
        </v-list-tile>
      </v-list>
    </v-toolbar>
    <v-divider></v-divider>
    <v-list dense class="pt-0">
      <v-list-tile v-for="item in items" :key="item.title" >
        <v-list-tile-content>
          <v-list-tile-title>{{ item.title }}</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>
    </v-list>
  </v-navigation-drawer>
</template>

What's weird is I can see that the entire Vuetify css file is being injected properly as a style tag by webpack, and I don't think I'm overwriting with any custom styles (in that I have none!)

What am I missing to properly get Vuetify styles working?

(some extraneous code stripped, let me know if you need to see more of my project files / code)

Body:
The problem is that you did not add a handler for any mouse event. Try to just add an empty:

<v-list dense class="pt-0">
  <v-list-tile v-for="item in items" :key="item.title" @click="">
    <v-list-tile-content>
      <v-list-tile-title>{{ item.title }}</v-list-tile-title>
    </v-list-tile-content>
  </v-list-tile>
</v-list>


问:
Opening Android SDK manager on mac
Trying to open the android SDK manager on mac, but when I get to the terminal window and go to direct to tools like it says, I don't know what to do.

These are the instructions per the site

Mac/Linux: Open a terminal and navigate to the tools/ directory in the location where the Android SDK was installed, then execute android sdk.

And it's in my downloads. What do I need to type into the terminal to find it?

答:
As Android Studio 3, the android command is deprecated. So, developers should use Android SDK which has been provided in Android Studio.

```<code>Tools > Android > SDK Manager
</code>```

or for command-line usage,
- on MAC

```<code>~/Library/Android/sdk/tools/bin/
</code>```

on Linux

/Path/To/SDK/tools/bin/

then run sdkmanager.

Title: Opening Android SDK manager on mac

Body:
As Android Studio 3, the android command is deprecated. So, developers should use Android SDK which has been provided in Android Studio.

Tools > Android > SDK Manager

or for command-line usage,
- on MAC

~/Library/Android/sdk/tools/bin/

on Linux

/Path/To/SDK/tools/bin/

then run sdkmanager.


问:
File handling operetions in C
Can anyone point me to a reference or a beginner's tutorial for file handling in C.</p>

答: A complete reference to the C standard IO functions.</p>

Title: File handling operetions in C


问:
Combined nodes to a single one based on a common property
I'm trying to learn more about Neo4j. Is there a way to group nodes that have the same name/number/etc.?

In standard RDBMS one can use the "Group by" clause to combine specific values into one.  Have a look at the picture for a better understanding.

I'd like to combine these two nodes ("EE", "EE") into one, which has both sub-nodes.

Code for the image output:

```<code>match (A:Place)-[:`->`]-(B:Typ)
where A.name ='City1'
return A, B
</code>```

答:
Just in case you were not aware: if you are looking to permanently merge nodes into 1 merging the relationships too, you can use APOC. If all the properties (except for the internal node id) are the same, then maybe.</p>

```<code>CALL apoc.refactor.mergeNodes([node1, node2])
</code>```

Body:
I'm trying to learn more about Neo4j. Is there a way to group nodes that have the same name/number/etc.?

In standard RDBMS one can use the "Group by" clause to combine specific values into one.  Have a look at the picture for a better understanding.

I'd like to combine these two nodes ("EE", "EE") into one, which has both sub-nodes.

Code for the image output:

match (A:Place)-[:`->`]-(B:Typ)
where A.name ='City1'
return A, B

Body:
Just in case you were not aware: if you are looking to permanently merge nodes into 1 merging the relationships too, you can use APOC. If all the properties (except for the internal node id) are the same, then maybe.

CALL apoc.refactor.mergeNodes([node1, node2])


问:
Categorize data by name with python
I have this data (Small Example) that i import into a script.

```<code>LastName    StartTime   EndTime Duration  Period    TeamAbbrev  Position
Bouwmeester     0:00    0:37    0:37         1         STL         D
Schwartz        0:00    0:40    0:40         1         STL         W
Foligno         0:00    0:40    0:40         1         MIN         W
Pietrangelo     0:00    0:48    0:48         1         STL         D
Suter           0:00    0:40    0:40         1         MIN         D
Staal           0:00    0:40    0:40         1         MIN         C
Niederreiter    0:00    0:40    0:40         1         MIN         W
Allen           0:00    20:00   20:00        1         STL         G
Steen           0:00    0:30    0:30         1         STL         W
Tarasenko       0:30    1:27    0:57         1         STL         W
Parayko         0:37    1:43    1:06         1         STL         D
</code>```

This is the script

```<code>import csv
from itertools import combinations, product

#Header = LastName  StartTime  EndTime  Duration Period TeamAbbrev Position

#Import Game
with open('2017020397.csv', newline='') as f:
    next(f)
    skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
    data = skaters.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)
print()

# Determine the amount of overlapping time for each combination of players
for p1, p2, p3 in combinations(sorted(players), 3):
    total = 0
    # Check each pair of times for this pair of players
    for t1, t2, t3 in product(players[p1], players[p2], players[p3]):
        # Compute the overlap in this pair of times and
        # add it to the total for this pair of players
        start, end = zip(t1, t2, t3)
        total += max(0, min(end) - max(start))
    if total:
        print(p1, p2, p3, total)
</code>```

Output:

```<code>Allen Niederreiter Pietrangelo 5481
Allen Niederreiter Prosser 2088
Allen Niederreiter Reilly 1464
</code>```

The Purpose of this is to see what Team Mate played with each other. From the Output we can see that Allen from STL is Paired up with Niederreiter from MIN. I only want like team combinations to combine. The TeamAbbrev is how that can be identified. The other stipulation is that the TeamAbbrev will change game by game depending on what teams are playing that night. Open to any and all suggestions, Thanks!

Edit: If an int() is easier than a str() for TeamAbbrev I can scrape the teamId instead which is a number.

答:
Add after your ʼfor row in dataʼ...</p>

```<code>teams = row.split()[4]
# if the number of occurrences of the first item (which is a team)... is equal to the length of the list of teams, then, all the players are from the same team.
if teams.count(teams[0]) == len(teams):
    #same lines, but one indentation block due to the `if` condition.
</code>```

Title: Categorize data by name with python

Body:
I have this data (Small Example) that i import into a script.

LastName    StartTime   EndTime Duration  Period    TeamAbbrev  Position
Bouwmeester     0:00    0:37    0:37         1         STL         D
Schwartz        0:00    0:40    0:40         1         STL         W
Foligno         0:00    0:40    0:40         1         MIN         W
Pietrangelo     0:00    0:48    0:48         1         STL         D
Suter           0:00    0:40    0:40         1         MIN         D
Staal           0:00    0:40    0:40         1         MIN         C
Niederreiter    0:00    0:40    0:40         1         MIN         W
Allen           0:00    20:00   20:00        1         STL         G
Steen           0:00    0:30    0:30         1         STL         W
Tarasenko       0:30    1:27    0:57         1         STL         W
Parayko         0:37    1:43    1:06         1         STL         D

This is the script

import csv
from itertools import combinations, product

#Header = LastName  StartTime  EndTime  Duration Period TeamAbbrev Position

#Import Game
with open('2017020397.csv', newline='') as f:
    next(f)
    skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
    data = skaters.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)
print()

# Determine the amount of overlapping time for each combination of players
for p1, p2, p3 in combinations(sorted(players), 3):
    total = 0
    # Check each pair of times for this pair of players
    for t1, t2, t3 in product(players[p1], players[p2], players[p3]):
        # Compute the overlap in this pair of times and
        # add it to the total for this pair of players
        start, end = zip(t1, t2, t3)
        total += max(0, min(end) - max(start))
    if total:
        print(p1, p2, p3, total)

Output:

Allen Niederreiter Pietrangelo 5481
Allen Niederreiter Prosser 2088
Allen Niederreiter Reilly 1464

The Purpose of this is to see what Team Mate played with each other. From the Output we can see that Allen from STL is Paired up with Niederreiter from MIN. I only want like team combinations to combine. The TeamAbbrev is how that can be identified. The other stipulation is that the TeamAbbrev will change game by game depending on what teams are playing that night. Open to any and all suggestions, Thanks!

Edit: If an int() is easier than a str() for TeamAbbrev I can scrape the teamId instead which is a number.

Body:
Add after your ʼfor row in dataʼ...

teams = row.split()[4]
# if the number of occurrences of the first item (which is a team)... is equal to the length of the list of teams, then, all the players are from the same team.
if teams.count(teams[0]) == len(teams):
    #same lines, but one indentation block due to the `if` condition.


问:
Sublime Text consecutive snippets
Whenever I type a keyword and press tab to use my snippet, I have to place the cursor somewhere else with a mouse click to use another snippet.
Thats not good at all. I want to be able to type tk;tab to get

```<code>\begin{tikzpicture}
  |
\end{tikzpicture}
</code>```

Where my cursor is at the pipe. This works so far. But now I would like to for example type dr to be completed to \draw at this place. although I wrote this snippet, it doesn't work. So how can I use multiple snippets consecutively?

Very glad for every help

答:
My guess would be that you're using $1 in your first snippet, so that it looks something like this (except I didn't use a latex scope):

<snippet>
    <content><![CDATA[
\begin{tikzpicture}
  $1
\end{tikzpicture}
]]></content>
    <tabTrigger>tk</tabTrigger>
</snippet>
```

When Sublime expands a snippet, it lets you tab through all of the fields in numerical order, and then "exits" the snippet. The default exit point for a snippet is after the last character in the snippet.

So if you were to expand this snippet, it would insert with the cursor at the position of $1, and now it's waiting for you to enter the content of field $1. If you look in the status line, you'll see it saying Field 1 of 2 to tell you that you're in the middle of a snippet (field 2 is where the snippet "ends").

If your snippet works like that, you have to manually tell Sublime that you're done with the snippet, such as by moving the cursor or pressing Escape.

The special snippet field $0 tells Sublime where you want the cursor to end up once you're done with the snippet. If you don't specify it explicitly, it's assumed to be at the end of the snippet text.

If the whole of the snippet is just meant to expand to that text to let you enter what's inside, you can change the snippet to use $0 instead of $1.

When you do that, after the initial text expansion Sublime finds no fields for you to enter and just exits the snippet immediately, leaving the cursor at position $0. From that point you can use a new snippet without any problems:

Title: Sublime Text consecutive snippets

Body:
Whenever I type a keyword and press tab to use my snippet, I have to place the cursor somewhere else with a mouse click to use another snippet.
Thats not good at all. I want to be able to type tk;tab to get

\begin{tikzpicture}
  |
\end{tikzpicture}

Where my cursor is at the pipe. This works so far. But now I would like to for example type dr to be completed to \draw at this place. although I wrote this snippet, it doesn't work. So how can I use multiple snippets consecutively?

Very glad for every help

Body:
My guess would be that you're using $1 in your first snippet, so that it looks something like this (except I didn't use a latex scope):

<snippet>
    <content><![CDATA[
\begin{tikzpicture}
  $1
\end{tikzpicture}
]]></content>
    <tabTrigger>tk</tabTrigger>
</snippet>

When Sublime expands a snippet, it lets you tab through all of the fields in numerical order, and then "exits" the snippet. The default exit point for a snippet is after the last character in the snippet.

So if you were to expand this snippet, it would insert with the cursor at the position of $1, and now it's waiting for you to enter the content of field $1. If you look in the status line, you'll see it saying Field 1 of 2 to tell you that you're in the middle of a snippet (field 2 is where the snippet "ends").

If your snippet works like that, you have to manually tell Sublime that you're done with the snippet, such as by moving the cursor or pressing Escape.

The special snippet field $0 tells Sublime where you want the cursor to end up once you're done with the snippet. If you don't specify it explicitly, it's assumed to be at the end of the snippet text.

If the whole of the snippet is just meant to expand to that text to let you enter what's inside, you can change the snippet to use $0 instead of $1.

When you do that, after the initial text expansion Sublime finds no fields for you to enter and just exits the snippet immediately, leaving the cursor at position $0. From that point you can use a new snippet without any problems:


问:
How do you specifiy a nonlinearity parameter when using FastICA algorithm in MATLAB?
I have downloaded and successfully installed the MATLAB FastICA package.

The main algorithm is implemented in fastica.m

The author has generously provided sample demo code which I was able to successfully run shown below:

```<code>N=500; %data size

v=[0:N-1];

sig(1,:)=sin(v/2); %sinusoid
sig(2,:)=((rem(v,23)-11)/9).^5; %funny curve
sig(3,:)=((rem(v,27)-13)/9); %saw-tooth
sig(4,:)=((rand(1,N)<.5)*2-1).*log(rand(1,N)); %impulsive noise

%create mixtures

Aorig=rand(size(sig,1));
mixedsig=(Aorig*sig);

%preform ica to unmix signal
ica = fastica(mixedsig);

subplot(2,4,1); plot(sig(1,:));
title('1')
subplot(2,4,2); plot(sig(2,:));
title('2')
subplot(2,4,3); plot(sig(3,:));
title('3')
subplot(2,4,4); plot(sig(4,:));
title('4')
subplot(2,4,5); plot(ica(3,:));
title('5')
subplot(2,4,6); plot(ica(1,:));
title('6')
subplot(2,4,7); plot(ica(2,:));
title('7')
subplot(2,4,8); plot(ica(4,:));
title('8')
</code>```

The output plot I get is:

The first row of plots are the original signals. The second row are the recovered signals after they were mixed with a random matrix A

My question is: How do I modify the code above to specify different nonlinearity settings?

If you look at line 51 in fastica.m, there are 4 different options:

```<code>'pow3' (default)   g(u)=u^3
'tanh'             g(u)=tanh(a1*u)
'gauss             g(u)=u*exp(-a2*u^2/2)
'skew'             g(u)=u^2
</code>```

I tried to do:

```<code>g='tanh'
</code>```

and then I re-ran my code above, but it did not look like anything changed (got the same plots).

Then I tried to do:

```<code>g='gauss'
</code>```

Again, same plots.

Would appreciate any help / feedback from the MATLAB community.

答:
I think it would be better if you overlapped both results, I was not able to differentiate between the two results without holding on one of them,

check the following for both 'pow3' and 'gauss',

EDIT

Code used,

```<code>% change g in fastica (line 247) g='pow3'
N=500; %data size
v=[0:N-1];
sig(1,:)=sin(v/2); %sinusoid
sig(2,:)=((rem(v,23)-11)/9).^5; %funny curve
sig(3,:)=((rem(v,27)-13)/9); %saw-tooth
sig(4,:)=((rand(1,N)<.5)*2-1).*log(rand(1,N)); %impulsive noise
%create mixtures
Aorig=rand(size(sig,1));
mixedsig=(Aorig*sig);
%preform ica to unmix signal
ica = fastica(mixedsig);
figure(1)
plot(ica(3,:));
title('5')
figure(2)
plot(ica(1,:));
title('6')
figure(3)
plot(ica(2,:));
title('7')
figure(4)
plot(ica(4,:));
title('8')

% Change g in fastica (line 247),  g= 'gauss';

ica = fastica(mixedsig);

figure(1)
hold on
plot(ica(3,:),'r:');
figure(2)
hold on
plot(ica(1,:),'r:');
figure(3)
hold on
plot(ica(2,:),'r:');
figure(4)
hold on
plot(ica(4,:),'r:');
</code>```

Body:
I have downloaded and successfully installed the MATLAB FastICA package.

The main algorithm is implemented in fastica.m

The author has generously provided sample demo code which I was able to successfully run shown below:

N=500; %data size

v=[0:N-1];

sig(1,:)=sin(v/2); %sinusoid
sig(2,:)=((rem(v,23)-11)/9).^5; %funny curve
sig(3,:)=((rem(v,27)-13)/9); %saw-tooth
sig(4,:)=((rand(1,N)<.5)*2-1).*log(rand(1,N)); %impulsive noise

%create mixtures

Aorig=rand(size(sig,1));
mixedsig=(Aorig*sig);

%preform ica to unmix signal
ica = fastica(mixedsig);

subplot(2,4,1); plot(sig(1,:));
title('1')
subplot(2,4,2); plot(sig(2,:));
title('2')
subplot(2,4,3); plot(sig(3,:));
title('3')
subplot(2,4,4); plot(sig(4,:));
title('4')
subplot(2,4,5); plot(ica(3,:));
title('5')
subplot(2,4,6); plot(ica(1,:));
title('6')
subplot(2,4,7); plot(ica(2,:));
title('7')
subplot(2,4,8); plot(ica(4,:));
title('8')

The output plot I get is:

The first row of plots are the original signals. The second row are the recovered signals after they were mixed with a random matrix A

My question is: How do I modify the code above to specify different nonlinearity settings?

If you look at line 51 in fastica.m, there are 4 different options:

'pow3' (default)   g(u)=u^3
'tanh'             g(u)=tanh(a1*u)
'gauss             g(u)=u*exp(-a2*u^2/2)
'skew'             g(u)=u^2

I tried to do:

g='tanh'

and then I re-ran my code above, but it did not look like anything changed (got the same plots).

Then I tried to do:

g='gauss'

Again, same plots.

Would appreciate any help / feedback from the MATLAB community.

Body:
I think it would be better if you overlapped both results, I was not able to differentiate between the two results without holding on one of them,

check the following for both 'pow3' and 'gauss',

EDIT

Code used,

% change g in fastica (line 247) g='pow3'
N=500; %data size
v=[0:N-1];
sig(1,:)=sin(v/2); %sinusoid
sig(2,:)=((rem(v,23)-11)/9).^5; %funny curve
sig(3,:)=((rem(v,27)-13)/9); %saw-tooth
sig(4,:)=((rand(1,N)<.5)*2-1).*log(rand(1,N)); %impulsive noise
%create mixtures
Aorig=rand(size(sig,1));
mixedsig=(Aorig*sig);
%preform ica to unmix signal
ica = fastica(mixedsig);
figure(1)
plot(ica(3,:));
title('5')
figure(2)
plot(ica(1,:));
title('6')
figure(3)
plot(ica(2,:));
title('7')
figure(4)
plot(ica(4,:));
title('8')

% Change g in fastica (line 247),  g= 'gauss';

ica = fastica(mixedsig);

figure(1)
hold on
plot(ica(3,:),'r:');
figure(2)
hold on
plot(ica(1,:),'r:');
figure(3)
hold on
plot(ica(2,:),'r:');
figure(4)
hold on
plot(ica(4,:),'r:');


问:
Keras - CNN Regression + additional input into final fully-connected layers
Let's say that I am trying to guess AGE from profile pictures.  After performing convolutions/pooling, I would like to add another piece of information such as HEART RATE before making the final prediction.

So instead of
profile picture --> Convolutions/Pooling  -->  Fully-connected layers --> AGE

I would like:
profile picture --> Convolutions/Pooling  --> Fully-connected layer where new input regarding HEART RATE is added --> AGE

To do so, I created a function as follows:

```<code>def Add_to_FinalLayers(X, Additional):
    X = concatenate([X, Additional])
    return X

def AgeModel(input_shape):
    X_input = Input(input_shape)
    X = ZeroPadding2D((3,3))(X_input)
    X = Conv2D(32, (7,7) strides=(1,1), name ='conv0')(X)
    X = BatchNormalization(axis =3, name = 'bn0')(X)
    X = Activation('relu')(X)
    X = MaxPooling2D((2,2), name='max_pool')(X)
    X = Flatten()(X)
    X = Add_to_FinalLayers(X, HeartRateData_train)
    X = Dense(1, activation='linear', name='fc')(X)
    model = Model(inputs=[X_input, HeartRate_train], outputs=X,   name='AgeModel')
    return model

ageModel = AgeModel(X_train.shape[1:])
ageModel.compile(optimizer="RMSprop", loss="mse", metrics=["mse"])
ageModel.fit(x=[X_train,HeartRate_train], y=Y_train, epochs=30, batch_size=32)
preds = happyModel.predict(X_test)
</code>```

The sizes of my data are,

```<code>number of training examples = 600
number of test examples = 150
X_train shape: (600, 64, 64, 3)
Y_train shape: (600, 1)
X_test shape: (150, 64, 64, 3)
Y_test shape: (150, 1)
HeartRate_train shape: (600, 1)
HeartRate_test shape: (150, 1)
</code>```

The error messages I am getting are:

```<code>ValueError: Error when checking input: expected input_22 to have shape (None, 10) but got array with shape (600, 1)
ValueError: The model expects 2 arrays, but only received one array.  Found: array with shape (150, 64, 64, 3)
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected.  Expected to see 1 arrays) but in stead got the following list of 2 arrays:...
</code>```

Any advice would be much appreciated.  Thank you.

答:
First, you need to define Heartbeat as the input to your model by specifying it as:

```<code>input2 = Input(shape=[1], name='heart_rate')
</code>```

Then, you can concatenate it after the flatten layer as:

```<code> X = Concatenate(name='concat_layer')[X, input_2]
</code>```

Your model accepts two inputs now, an image and hear beat. Make sure you pass both at the test time to get the predictions.

Body:
Let's say that I am trying to guess AGE from profile pictures.  After performing convolutions/pooling, I would like to add another piece of information such as HEART RATE before making the final prediction.

So instead of
profile picture --> Convolutions/Pooling  -->  Fully-connected layers --> AGE

I would like:
profile picture --> Convolutions/Pooling  --> Fully-connected layer where new input regarding HEART RATE is added --> AGE

To do so, I created a function as follows:

def Add_to_FinalLayers(X, Additional):
    X = concatenate([X, Additional])
    return X

def AgeModel(input_shape):
    X_input = Input(input_shape)
    X = ZeroPadding2D((3,3))(X_input)
    X = Conv2D(32, (7,7) strides=(1,1), name ='conv0')(X)
    X = BatchNormalization(axis =3, name = 'bn0')(X)
    X = Activation('relu')(X)
    X = MaxPooling2D((2,2), name='max_pool')(X)
    X = Flatten()(X)
    X = Add_to_FinalLayers(X, HeartRateData_train)
    X = Dense(1, activation='linear', name='fc')(X)
    model = Model(inputs=[X_input, HeartRate_train], outputs=X,   name='AgeModel')
    return model

ageModel = AgeModel(X_train.shape[1:])
ageModel.compile(optimizer="RMSprop", loss="mse", metrics=["mse"])
ageModel.fit(x=[X_train,HeartRate_train], y=Y_train, epochs=30, batch_size=32)
preds = happyModel.predict(X_test)

The sizes of my data are,

number of training examples = 600
number of test examples = 150
X_train shape: (600, 64, 64, 3)
Y_train shape: (600, 1)
X_test shape: (150, 64, 64, 3)
Y_test shape: (150, 1)
HeartRate_train shape: (600, 1)
HeartRate_test shape: (150, 1)

The error messages I am getting are:

ValueError: Error when checking input: expected input_22 to have shape (None, 10) but got array with shape (600, 1)
ValueError: The model expects 2 arrays, but only received one array.  Found: array with shape (150, 64, 64, 3)
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected.  Expected to see 1 arrays) but in stead got the following list of 2 arrays:...

Any advice would be much appreciated.  Thank you.

Body:
First, you need to define Heartbeat as the input to your model by specifying it as:

input2 = Input(shape=[1], name='heart_rate')

Then, you can concatenate it after the flatten layer as:

 X = Concatenate(name='concat_layer')[X, input_2]

Your model accepts two inputs now, an image and hear beat. Make sure you pass both at the test time to get the predictions.


问:
T-SQL, how to get IDs that visit X amount of location within X amount of time?
T-SQL question, I been trying to find the best/optimal solution for this one.

Say we have this theoritical table

```<code>-----------------------------------
ID | DATETIME | Location
11 | 1/27 3:30pm | a
11 | 1/27 3:31pm | b
11 | 1/27 3:32pm | c
22 | 2/14 1:10pm | g
22 | 2/14 1:12pm | i
22 | 2/15 5:48pm | w
55 | 3/18 8:48pm | d
55 | 3/18 9:48pm | e
---------------------------
</code>```

I want to create a query that return IDs that have been in 2 or more different locations within 5 minutes. In this case if you look at the table, ID: 11 and 22 visits 2 or more different location within 5 minutes, thus it should return ID 11 and 22. How do I develop a query that returns the IDs that been to X amount of location within X amount of time in minutes?

答:
If you assume that the locations are different on each row for a given id, you can use lead()/lag():

```<code>select id, datetime
from (select t.*,
             lead(datetime) over (partition by id order by datetime) as next_datetime
      from t
     ) t
where next_datetime < dateadd(minute, 5, datetime);
</code>```

This is not a general solution to the problem.  But it does solve the particular example you have in your question.

Body:
T-SQL question, I been trying to find the best/optimal solution for this one.

Say we have this theoritical table

-----------------------------------
ID | DATETIME | Location
11 | 1/27 3:30pm | a
11 | 1/27 3:31pm | b
11 | 1/27 3:32pm | c
22 | 2/14 1:10pm | g
22 | 2/14 1:12pm | i
22 | 2/15 5:48pm | w
55 | 3/18 8:48pm | d
55 | 3/18 9:48pm | e
---------------------------

I want to create a query that return IDs that have been in 2 or more different locations within 5 minutes. In this case if you look at the table, ID: 11 and 22 visits 2 or more different location within 5 minutes, thus it should return ID 11 and 22. How do I develop a query that returns the IDs that been to X amount of location within X amount of time in minutes?

Body:
If you assume that the locations are different on each row for a given id, you can use lead()/lag():

select id, datetime
from (select t.*,
             lead(datetime) over (partition by id order by datetime) as next_datetime
      from t
     ) t
where next_datetime < dateadd(minute, 5, datetime);

This is not a general solution to the problem.  But it does solve the particular example you have in your question.


问:
How do I get the parent context from within a component in glimmer?
Let's say I have a simple component in glimmer with a list of items

```<code><todo-list @items={{ items }}></todo-list>
</code>```

template.hbs

```<code><ul>
  {{#each @items key="@index" as |item|}}
    <li onclick={{ action clickme }}>{{ item }}</li>
  {{/each}}
</ul>
</code>```

component.ts

```<code>import Component, { tracked }  from '@glimmer/component';

export default class TodoList extends Component {
  constructor(options) {
    super(options);
  }
  clickme() {
     // how do I access the parent context from here?
  }
}
</code>```

Even if I pass in an action from the parent

```<code><todo-list @items={{ items }} @rootclickme={{ rootclickme }}></todo-list>
</code>```

updated, template.hbs

```<code><ul>
  {{#each @items key="@index" as |item|}}
    <li onclick={{ action @rootclickme }}>{{ item }}</li>
  {{/each}}
</ul>
</code>```

in my outer component.ts

```<code>rootclickme () {
    // I don't have access to parent variables here either?
    // only what's within the scope of the function itself?
}
</code>```

What I'm trying to do is have a component with a list. When a list item is clicked, I want it to bubble up a click event to the top, so that the parent component can decide to hide the list and show a more detailed view for this selected item.

How do I go about doing this in glimmer? In react I'd be passing

Note: I'm not using full ember.js, just glimmer.js standalone

答:
Something I learned from React, that works in my Glimmer app as well: you can bind your functions in the constructor. That way, when you pass them around to different objects, they won't lose their context.

```<code>export default class WhateverRootComponent extends Component {
  constructor(options) {
    super(options);
    this.rootClickMe = this.rootClickMe.bind(this)
  }
  rootClickMe() {
    console.log(this instanceof WhateverRootComponent)
  }
}
</code>```

Now you can pass that function in directly as you were doing before, without using the extra action helper.

```<code><!-- WhateverRootComponent template -->
<SomeChild @actionToTake={{ rootClickMe }} />
</code>```

then...

```<code><!-- SomeChild template -->
<button onclick={{ action @actionToTake }}> Click Me </button>
</code>```

When clicked, the console will log true because the function still is being called in the parent class's context.

Body:
Let's say I have a simple component in glimmer with a list of items

<todo-list @items={{ items }}></todo-list>

template.hbs

  {{#each @items key="@index" as |item|}}

{{ item }}

  {{/each}}

component.ts

import Component, { tracked }  from '@glimmer/component';

export default class TodoList extends Component {
  constructor(options) {
    super(options);
  }
  clickme() {
     // how do I access the parent context from here?
  }
}

Even if I pass in an action from the parent

<todo-list @items={{ items }} @rootclickme={{ rootclickme }}></todo-list>

updated, template.hbs

  {{#each @items key="@index" as |item|}}

{{ item }}

  {{/each}}

in my outer component.ts

rootclickme () {
    // I don't have access to parent variables here either?
    // only what's within the scope of the function itself?
}

What I'm trying to do is have a component with a list. When a list item is clicked, I want it to bubble up a click event to the top, so that the parent component can decide to hide the list and show a more detailed view for this selected item.

How do I go about doing this in glimmer? In react I'd be passing

Note: I'm not using full ember.js, just glimmer.js standalone

Body:
Something I learned from React, that works in my Glimmer app as well: you can bind your functions in the constructor. That way, when you pass them around to different objects, they won't lose their context.

export default class WhateverRootComponent extends Component {
  constructor(options) {
    super(options);
    this.rootClickMe = this.rootClickMe.bind(this)
  }
  rootClickMe() {
    console.log(this instanceof WhateverRootComponent)
  }
}

Now you can pass that function in directly as you were doing before, without using the extra action helper.

<!-- WhateverRootComponent template -->
<SomeChild @actionToTake={{ rootClickMe }} />

then...

<!-- SomeChild template -->
<button onclick={{ action @actionToTake }}> Click Me </button>

When clicked, the console will log true because the function still is being called in the parent class's context.


问:
If statement inside while loops not printing correctly
I'm trying to compare a string, pass, to a dictionary file list.  If it directly matches a word, it is considered weak (balloon). If it contains the word from the dictionary file (#balloon232), it is considered moderate. If neither, its strong.  In this code, weak and moderate both work correctly, but when a strong pass is entered, it says it is moderate. Thanks for the help.</p>

```<code>public static void passwordStrength(String pass, String file2) {
    boolean found2 = false;
    boolean found3 = false;
    try {
        y = new Scanner(new File(file2));
        z = new Scanner(new File(file2));
        while (y.hasNextLine()) {
            if (pass.equals(y.nextLine().trim())) {
                System.out.println("\nYour password is weak");
                found2 = true;
                break;
            }
        }
        while (z.hasNextLine()) {
            if (pass.contains(z.nextLine().trim()) && !found2) {
                System.out.println("\nYour password is moderate");
                found3 = true;
                break;
            }
        }
        if (!found3 && !found2) {
            System.out.println("\nYour password is strong");
        }
        y.close();
        z.close();
    } catch (Exception e) {
        System.out.print("Error");
    }
}
</code>```

答:
The logic seems fine it should print password is strong.  You should print out all lines that you read in from the file to debug and see both when the password and the word from the file doesn't match.

I don't think it makes sense to create multiple scanners and read the file twice.  You can read in the file once and test the pass to see if it's a week or moderate and return the string and if not found return strong.  You can throw the exception so that main up to you.  Unless you specifically want to print out the password strength in this function.

Here is a sample.

```<code>import java.io.File;
import java.util.Scanner;

public class PasswordTest {
    public static String passwordStrength(String pass, String file2) {

        try {
            Scanner fileScanner = new Scanner(new File(file2));

            while (fileScanner.hasNextLine()) {
                String passInFile = fileScanner.nextLine().trim();
                if (pass.equals(passInFile)) {
                    return ("Your password is weak");
                }
                if (pass.contains(passInFile)) {
                    return "Your password is moderate";
                }

            }
        } catch (Exception e) {
            return e.getMessage();

        }
        return "Your Password is strong";
    }

    public static void main(String[] args) {
        System.out.println(passwordStrength("test", "test.txt"));
    }
}
</code>```

Body:
I'm trying to compare a string, pass, to a dictionary file list.  If it directly matches a word, it is considered weak (balloon). If it contains the word from the dictionary file (#balloon232), it is considered moderate. If neither, its strong.  In this code, weak and moderate both work correctly, but when a strong pass is entered, it says it is moderate. Thanks for the help.

public static void passwordStrength(String pass, String file2) {
    boolean found2 = false;
    boolean found3 = false;
    try {
        y = new Scanner(new File(file2));
        z = new Scanner(new File(file2));
        while (y.hasNextLine()) {
            if (pass.equals(y.nextLine().trim())) {
                System.out.println("\nYour password is weak");
                found2 = true;
                break;
            }
        }
        while (z.hasNextLine()) {
            if (pass.contains(z.nextLine().trim()) && !found2) {
                System.out.println("\nYour password is moderate");
                found3 = true;
                break;
            }
        }
        if (!found3 && !found2) {
            System.out.println("\nYour password is strong");
        }
        y.close();
        z.close();
    } catch (Exception e) {
        System.out.print("Error");
    }
}

Body:
The logic seems fine it should print password is strong.  You should print out all lines that you read in from the file to debug and see both when the password and the word from the file doesn't match.

I don't think it makes sense to create multiple scanners and read the file twice.  You can read in the file once and test the pass to see if it's a week or moderate and return the string and if not found return strong.  You can throw the exception so that main up to you.  Unless you specifically want to print out the password strength in this function.

Here is a sample.

import java.io.File;
import java.util.Scanner;

public class PasswordTest {
    public static String passwordStrength(String pass, String file2) {

        try {
            Scanner fileScanner = new Scanner(new File(file2));

            while (fileScanner.hasNextLine()) {
                String passInFile = fileScanner.nextLine().trim();
                if (pass.equals(passInFile)) {
                    return ("Your password is weak");
                }
                if (pass.contains(passInFile)) {
                    return "Your password is moderate";
                }

            }
        } catch (Exception e) {
            return e.getMessage();

        }
        return "Your Password is strong";
    }

    public static void main(String[] args) {
        System.out.println(passwordStrength("test", "test.txt"));
    }
}


问:
Bootstrap tab-panels not having active class removed, but only sometimes
I'm having trouble with bootstraps tabs and tabpanels not working with the active class as intended. I know there are many questions about this, but in all the ones I have read, adding and removing the inactive class is not working at all. In my case, it works... but kind of. First I'll provide the HTML:

```<code><ul class="nav nav-pills hr-divider-content hr-divider-nav">
    <li class="nav-item">
        <a class="nav-link" data-toggle="pill" href="#a-tab" aria-expanded="false">A</a>
    </li>
    <li class="nav-item">
        <a class="nav-link active" data-toggle="pill" href="#b-tab" aria-expanded="true">B</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="pill" href="#c-tab" aria-expanded="false">C</a>
    </li>
</ul>

<div class="tab-content">
    <div id="a-tab" class="tab-pane highlight active" aria-expanded="true">

    </div>
    <div id="b-tab" class="tab-pane highlight" aria-expanded="false">

    </div>
    <div id="c-tab" class="tab-pane highlight" aria-expanded="false">

    </div>
</div>
</code>```

The JavaScript comes from just including all the bootstrap 4 stuff.

So here's the thing, it starts off with some issues, being that as you click between the 3 tabs it will usually show 2 of them, but after clicking around for about 10 seconds it seems to fix itself and work completely as intended, showing only the content for the currently selected tab. I also use the same exact code with different names in other locations on my site, and it works perfectly fine.

Does anyone have any intuition into what would be causing the content to show incorrectly only the first 10 or so times clicking through the tabs, but then it works perfectly well until the page is refreshed?

答:
First of all you have to apply active class properly.You have given active class to a link but it should be into li.nav-item and also in your nav items you have given your active class to #b-tab and in below given active class to a-tab content. Look at updated HTML code

        A

        B

        C

    a-tab content

  b-tab content

  c-tab content

```

Body:
I'm having trouble with bootstraps tabs and tabpanels not working with the active class as intended. I know there are many questions about this, but in all the ones I have read, adding and removing the inactive class is not working at all. In my case, it works... but kind of. First I'll provide the HTML:

        A

        B

        C

The JavaScript comes from just including all the bootstrap 4 stuff.

So here's the thing, it starts off with some issues, being that as you click between the 3 tabs it will usually show 2 of them, but after clicking around for about 10 seconds it seems to fix itself and work completely as intended, showing only the content for the currently selected tab. I also use the same exact code with different names in other locations on my site, and it works perfectly fine.

Does anyone have any intuition into what would be causing the content to show incorrectly only the first 10 or so times clicking through the tabs, but then it works perfectly well until the page is refreshed?

Body:
First of all you have to apply active class properly.You have given active class to a link but it should be into li.nav-item and also in your nav items you have given your active class to #b-tab and in below given active class to a-tab content. Look at updated HTML code

<ul class="nav nav-pills hr-divider-content hr-divider-nav">
    <li class="nav-item active">
        <a class="nav-link" data-toggle="pill" href="#a-tab" aria-expanded="false">A</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="pill" href="#b-tab" aria-expanded="true">B</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="pill" href="#c-tab" aria-expanded="false">C</a>
    </li>
</ul>

<div class="tab-content">
    <div id="a-tab" class="tab-pane highlight active" aria-expanded="true">
    a-tab content
    </div>
    <div id="b-tab" class="tab-pane highlight" aria-expanded="false">
  b-tab content
    </div>
    <div id="c-tab" class="tab-pane highlight" aria-expanded="false">
  c-tab content
    </div>
</div>


问:
Invalid default value for 'date_available'
I am trying to alter catalog_no, but while altering it I am getting error regarding 'date_available' column

My SQL for altering catalog_no is:

```<code>ALTER TABLE `product` CHANGE `catalog_no` `catalogno` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;
</code>```

But this is giving me error #1067- Invalid default value for 'date_available'

What is the reason for this error and how can I solve it, Please help.

Thanks

答:
The problem is because of sql_modes. Please check your current sql_modes by command:

```<code>show variables like 'sql_mode' ;
</code>```

And remove the sql_mode "NO_ZERO_IN_DATE,NO_ZERO_DATE" to make it work.

This is the default sql_mode in mysql new versions.

Source

Body:
I am trying to alter catalog_no, but while altering it I am getting error regarding 'date_available' column

My SQL for altering catalog_no is:

ALTER TABLE `product` CHANGE `catalog_no` `catalogno` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

But this is giving me error #1067- Invalid default value for 'date_available'

What is the reason for this error and how can I solve it, Please help.

Thanks

Body:
The problem is because of sql_modes. Please check your current sql_modes by command:

show variables like 'sql_mode' ;

And remove the sql_mode "NO_ZERO_IN_DATE,NO_ZERO_DATE" to make it work.

This is the default sql_mode in mysql new versions.

Source


问:
regex expression in Notepad++
In the following code:

```<code> name="DCF3600" id="DCF3600" onclick="toggle3600dcf()" <?php if($row_getInfo3600["DCF"]==1){
</code>```

I am struggling to figure out how to change the two "DCF3600" to "Admin3600". Every line has a different number which I want to keep. The closet I got was

Find: DCF(\d)

Replace: Admin

But this deletes the 3 from 3600. How do I find DCF next to a digit but leave the digit?

答:
You can find DCF next to a digit by searching for

```<code>DCF(?=\d)
</code>```

The part in parentheses is a look-ahead expression that checks for a digit after DCF, but doesn’t include it in the match.

Title: regex expression in Notepad++

Body:
In the following code:

 name="DCF3600" id="DCF3600" onclick="toggle3600dcf()" <?php if($row_getInfo3600["DCF"]==1){

I am struggling to figure out how to change the two "DCF3600" to "Admin3600". Every line has a different number which I want to keep. The closet I got was

Find: DCF(\d)

Replace: Admin

But this deletes the 3 from 3600. How do I find DCF next to a digit but leave the digit?

Body:
You can find DCF next to a digit by searching for

DCF(?=\d)

The part in parentheses is a look-ahead expression that checks for a digit after DCF, but doesn’t include it in the match.


问:
Why does cx_Freeze use Win32GUI rather than Win64GUI?
The command line of an application built with cx_Freeze can be hidden with Win32GUI.

Why does cx_Freeze choose to reference Win32GUI rather than Win64GUI?

This suggests that cx_Freeze has either not been updated to include this feature, or is calling a 32 bit command and yet almost all Windows computers are now 64 bit.

Is there a reason why the inplamenters chose to call it this?

I have researched for a long time but have not found any answer, any thoughts would be appreciated.  Thank you.

答: It is simply because that is how it started. Even now it is called the "Win32" subsystem, even though it is 64-bit!</p>