问:
Can I access the collection an instance method was called on in ruby on rails
I'm working on implementing a search form in a ruby on rails application. The general idea is to use form_tag to submit the search fields (via params) to a search function in the model of the class I'm trying to search. The search function will then iterate through each of the params and execute a scoping function if the name of the function appears in params.

The issue is that when I call the search on a collection like so:

```<code>@calendar.reservations.search({:search_email => "test"})
</code>```

I don't know how to refer to the collection of @calendar.reservations from within the search function.

Additionally I'm confused as to why @calendar.reservations.search(...) works, but Reservations.all.search gives me an error saying you can't call an instance method on an array.

I've got the details of the search method over here: https://gist.github.com/783964

Any help would be greatly appreciated!

答:
I would strongly encourage you to look at the MetaSearch GEM by Ernie Miller. It handles the kind of thing you're working on very elegantly and is quite easy to implement. I suspect that your view code would almost accomplish what the GEM needs already, and this would take care of all your model searching needs very nicely.

Take a look and see if it will solve your problem. Good luck!

Body:
I'm working on implementing a search form in a ruby on rails application. The general idea is to use form_tag to submit the search fields (via params) to a search function in the model of the class I'm trying to search. The search function will then iterate through each of the params and execute a scoping function if the name of the function appears in params.

The issue is that when I call the search on a collection like so:

@calendar.reservations.search({:search_email => "test"})

I don't know how to refer to the collection of @calendar.reservations from within the search function.

Additionally I'm confused as to why @calendar.reservations.search(...) works, but Reservations.all.search gives me an error saying you can't call an instance method on an array.

I've got the details of the search method over here: https://gist.github.com/783964

Any help would be greatly appreciated!


来源: stackexchange

问:
changing an ng-option on button click
I have been working on this jsfiddle and I know I have mistakes in it.

what I want to be able to do is to pre-populate the ng-options from the URL.

There is 9 drop menus and my best attempt was to append the split to the "id" but that didnt work. I have tried to bind to the ng-model using $scope."ng-model name" = something but because I need to set an initial value for calculations it wouldnt work. (and because the model name is the array, not an individual item in the array).

Could I ask the community for help with it.

```<code> $("#loadURL").click(function () {
var checkURL = $(location).attr("href")
var fiddleURL = '   http://www.ahoymearty.co.uk/waynestest/menu/links.html?&i&a&a&a&a&b&b&b&c' //temp URL for testing - delete this line on live site

//var domain = checkURL.split('&');     //use this line for live site as it will use the URL
var domain = fiddleURL.split('&');      //delete this line on live site as URL doesnt show properly on JSFiddle

//this bit is wrong as apending doesnt work for angular
        $("#loadedplatform").append('<option value="" selected>' + domain[1] +'</option>')
    $("#loadedweapon").append('<option value="" selected>' + domain[2] +'</option>')
    $("#loadedarmour1").append('<option value="" selected>' + domain[3] +'</option>')
    $("#loadedarmour2").append('<option value="" selected>' + domain[4] +'</option>')
    $("#loadedarmour3").append('<option value="" selected>' + domain[5] +'</option>')
    $("#loadedspecial1").append('<option value="" selected>' + domain[6] +'</option>')
    $("#loadedspecial2").append('<option value="" selected>' + domain[7] +'</option>')
    $("#loadedspecial3").append('<option value="" selected>' + domain[8] +'</option>')
    $("#loadedtrans1").append('<option value="" selected>' + domain[9] +'</option>')

 $scope.platform = "level 5" //this is a test to check that loadURL works but the actual ng-model is an array, it doesnt and secondly because of line 73 of this script (added so it can calculate), it changes it back
</code>```

答:
You can get the data from the URL and parse it, but you have to make sure that the URL is consistently the same. I created a way of dynamically creating <select> fields based on how many characters are between the & in the URL. You can easily modify it to meet your needs.

(function() {
  var app = angular.module("TestModule", []);

  var TestController = function() {
      var vm = this;
      var fiddleURL = 'http://www.ahoymearty.co.uk/waynestest/menu/links.html?&i&a&a&a&a&b&b&b&c';

      var shortURL = fiddleURL.split("&");

      vm.selectOptions = [{
        id: "loadedplatform",
        urlChar: "foo"
      }, {
        id: "loadedweapon",
        urlChar: "foo"
      }, {
        id: "loadedarmour1",
        urlChar: "foo"
      }, {
        id: "loadedarmour2",
        urlChar: "foo"
      }, {
        id: "loadedarmour3",
        urlChar: "foo"
      }, {
        id: "loadedspecial1",
        urlChar: "foo"
      }, {
        id: "loadedspecial2",
        urlChar: "foo"
      }, {
        id: "loadedspecial3",
        urlChar: "foo"
      }, {
        id: "loadedtrans1",
        urlChar: "foo"
      }, ];

      for(var i = 0; i < vm.selectOptions.length; i++){
        vm.selectOptions[i].urlChar = shortURL[i + 1]; // i + 1 because shortURL at 0 contains the url before the first &. Can easily be modified to ignore this
      }
    } // End of TestController

  app.controller("TestController", [TestController]);
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="TestModule">

<head>
  <script data-require="angular.js@1.6.5" data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="TestController as vm">
  <div ng-repeat="select in vm.selectOptions">

    <label for="{{ select.id }}">{{ select.id }}</label>
    <select id="{{ select.id }}">
      <option value="{{ select.urlChar }}" selected>{{ select.urlChar }}</option>
    </select>
    <br />
  </div>
</body>

</html></code>```

This example assumes that you want to assign the characters in the URL sequentially. If you don't then you might want to change the order of the objects in vm.selectedOptions.

EDIT:

If you want to append to certain elements in a jQuery fashion, you can use AngularJS's way of doing it. Call angular.element('someid').append('something');

ContentLicense: CC BY-SA 3.0

Title: changing an ng-option on button click

Body:
I have been working on this jsfiddle and I know I have mistakes in it.

what I want to be able to do is to pre-populate the ng-options from the URL.

There is 9 drop menus and my best attempt was to append the split to the "id" but that didnt work. I have tried to bind to the ng-model using $scope."ng-model name" = something but because I need to set an initial value for calculations it wouldnt work. (and because the model name is the array, not an individual item in the array).

Could I ask the community for help with it.

 $("#loadURL").click(function () {
var checkURL = $(location).attr("href")
var fiddleURL = '   http://www.ahoymearty.co.uk/waynestest/menu/links.html?&i&a&a&a&a&b&b&b&c' //temp URL for testing - delete this line on live site

//var domain = checkURL.split('&');     //use this line for live site as it will use the URL
var domain = fiddleURL.split('&');      //delete this line on live site as URL doesnt show properly on JSFiddle

//this bit is wrong as apending doesnt work for angular
        $("#loadedplatform").append('<option value="" selected>' + domain[1] +'</option>')
    $("#loadedweapon").append('<option value="" selected>' + domain[2] +'</option>')
    $("#loadedarmour1").append('<option value="" selected>' + domain[3] +'</option>')
    $("#loadedarmour2").append('<option value="" selected>' + domain[4] +'</option>')
    $("#loadedarmour3").append('<option value="" selected>' + domain[5] +'</option>')
    $("#loadedspecial1").append('<option value="" selected>' + domain[6] +'</option>')
    $("#loadedspecial2").append('<option value="" selected>' + domain[7] +'</option>')
    $("#loadedspecial3").append('<option value="" selected>' + domain[8] +'</option>')
    $("#loadedtrans1").append('<option value="" selected>' + domain[9] +'</option>')

 $scope.platform = "level 5" //this is a test to check that loadURL works but the actual ng-model is an array, it doesnt and secondly because of line 73 of this script (added so it can calculate), it changes it back

Body:
You can get the data from the URL and parse it, but you have to make sure that the URL is consistently the same. I created a way of dynamically creating <select> fields based on how many characters are between the & in the URL. You can easily modify it to meet your needs.

(function() {
  var app = angular.module("TestModule", []);

  var TestController = function() {
      var vm = this;
      var fiddleURL = 'http://www.ahoymearty.co.uk/waynestest/menu/links.html?&i&a&a&a&a&b&b&b&c';

      var shortURL = fiddleURL.split("&");

      vm.selectOptions = [{
        id: "loadedplatform",
        urlChar: "foo"
      }, {
        id: "loadedweapon",
        urlChar: "foo"
      }, {
        id: "loadedarmour1",
        urlChar: "foo"
      }, {
        id: "loadedarmour2",
        urlChar: "foo"
      }, {
        id: "loadedarmour3",
        urlChar: "foo"
      }, {
        id: "loadedspecial1",
        urlChar: "foo"
      }, {
        id: "loadedspecial2",
        urlChar: "foo"
      }, {
        id: "loadedspecial3",
        urlChar: "foo"
      }, {
        id: "loadedtrans1",
        urlChar: "foo"
      }, ];

      for(var i = 0; i < vm.selectOptions.length; i++){
        vm.selectOptions[i].urlChar = shortURL[i + 1]; // i + 1 because shortURL at 0 contains the url before the first &. Can easily be modified to ignore this
      }
    } // End of TestController

  app.controller("TestController", [TestController]);
})();

<!DOCTYPE html>
<html ng-app="TestModule">

<head>
  <script data-require="angular.js@1.6.5" data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="TestController as vm">
  <div ng-repeat="select in vm.selectOptions">

    <label for="{{ select.id }}">{{ select.id }}</label>
    <select id="{{ select.id }}">
      <option value="{{ select.urlChar }}" selected>{{ select.urlChar }}</option>
    </select>
    <br />
  </div>
</body>

</html>

This example assumes that you want to assign the characters in the URL sequentially. If you don't then you might want to change the order of the objects in vm.selectedOptions.

EDIT:

If you want to append to certain elements in a jQuery fashion, you can use AngularJS's way of doing it. Call angular.element('someid').append('something');


问:
Convert firebase json to typescript array
I can easily get the data working in my HTML, but when I have to convert it for visualization purposes it is a struggle.

I get the data as a FirebaseListObservable. In my case there's 3 value-types in each List, but it is only one of them there has to be part of the array. How do I convert a FirebaseListObservable to an array in typescript?

The reason of converting is to use graphs in my app.

Typescript getting the data:

```<code>this.measure= this.db.list('/Users/'+this.username+'/Measure');
enter code here
</code>```

Typescript for chartjs

```<code>this.data = [12, 24, 91, 23]
</code>```

The data has to be the data from the firebase

答:
FirebaseListObservable is an observable. That means you will get the list itself (=the array you want) when you subscribe to it.

```<code>this.measure: FirebaseListObservable<Measure[]> = this.db.list('/Users/'+this.username+'/Measure');
this.measure
    .map(measurement => measurement.numbers) // this extracts only numbers field so we have basically array of arrays
    .map(numbersArrays => numbersArrays.reduce((curr, prev) => curr.concat(prev))) // so lets concat all those arrays into a single one
    .subscribe(numbersArray: number[] => {
        console.log(numbersArray);
    });

interface Measure {
    data: Date;
    geolocation: string;
    numbers: number[];
}
</code>```

Body:
I can easily get the data working in my HTML, but when I have to convert it for visualization purposes it is a struggle.

I get the data as a FirebaseListObservable. In my case there's 3 value-types in each List, but it is only one of them there has to be part of the array. How do I convert a FirebaseListObservable to an array in typescript?

The reason of converting is to use graphs in my app.

Typescript getting the data:

this.measure= this.db.list('/Users/'+this.username+'/Measure');
enter code here

Typescript for chartjs

this.data = [12, 24, 91, 23]

The data has to be the data from the firebase

Body:
FirebaseListObservable is an observable. That means you will get the list itself (=the array you want) when you subscribe to it.

this.measure: FirebaseListObservable<Measure[]> = this.db.list('/Users/'+this.username+'/Measure');
this.measure
    .map(measurement => measurement.numbers) // this extracts only numbers field so we have basically array of arrays
    .map(numbersArrays => numbersArrays.reduce((curr, prev) => curr.concat(prev))) // so lets concat all those arrays into a single one
    .subscribe(numbersArray: number[] => {
        console.log(numbersArray);
    });

interface Measure {
    data: Date;
    geolocation: string;
    numbers: number[];
}


问:
ping: http://google.com: Name or service not known
I'm using centos7 in virtualbox on windows. And vagrant made it, got ping error with http or https. also curl. someone can help me how to fix it and let it work.

```<code>[root@localhost ~]# ping google.com
PING google.com (61.91.161.217) 56(84) bytes of data.
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=1 ttl=43 time=404 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=2 ttl=43 time=408 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=3 ttl=43 time=407 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=4 ttl=43 time=408 ms
^C
--- google.com ping statistics ---
5 packets transmitted, 4 received, 20% packet loss, time 4000ms
rtt min/avg/max/mdev = 404.297/407.234/408.956/1.887 ms
[root@localhost ~]# ping https://google.com
ping: https://google.com: Name or service not known
[root@localhost ~]# ping https://61.91.161.217
ping: https://61.91.161.217: Name or service not known
</code>```

`

resolv.conf

```<code>[root@localhost ~]# cat /etc/resolv.conf
nameserver 10.0.2.3
nameserver 8.8.8.8
nameserver 8.8.4.4
search localhost
</code>```

`

ifconfig

```<code>[root@localhost ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 fe80::5054:ff:fe73:fb1  prefixlen 64  scopeid 0x20<link>
        ether 52:54:00:73:0f:b1  txqueuelen 1000  (Ethernet)
        RX packets 610587  bytes 48453952 (46.2 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 468759  bytes 41290880 (39.3 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.33.10  netmask 255.255.255.0  broadcast 192.168.33.255
        inet6 fe80::a00:27ff:fe0e:ae16  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:0e:ae:16  txqueuelen 1000  (Ethernet)
        RX packets 3069145  bytes 2674132747 (2.4 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2531212  bytes 213727091 (203.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code>```

network file automatically created from vagrant

```<code>[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
NAME="eth0"
ONBOOT=yes
NETBOOT=yes
UUID="704aa015-53dd-4ba7-9689-b9b8bf6e09a5"
IPV6INIT=yes
BOOTPROTO=dhcp
TYPE=Ethernet
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
PEERDNS=yes
PEERROUTES=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
HWADDR=52:54:00:73:0f:b1
DNS1=8.8.8.8
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1
NM_CONTROLLED=no
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.33.10
NETMASK=255.255.255.0
DEVICE=eth1
PEERDNS=no
DNS1=8.8.8.8
</code>```

答:
First make sure you have your network adapter enabled in virtual box settings.

Your network interface which you use it for connecting to internet might not be active.

To check this,use "sudo nmcli d" command.

If it is disconnected,use "sudo nmtui"->Edit a connection,select your network interface and choose "Automatically connect" option(by
pressing Space key) and select OK.

Do "sudo reboot now" After logging in,do "ping www.google.com".

You should be able to connect now.

Body:
I'm using centos7 in virtualbox on windows. And vagrant made it, got ping error with http or https. also curl. someone can help me how to fix it and let it work.

[root@localhost ~]# ping google.com
PING google.com (61.91.161.217) 56(84) bytes of data.
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=1 ttl=43 time=404 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=2 ttl=43 time=408 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=3 ttl=43 time=407 ms
64 bytes from chatenabled.mail.google.com (61.91.161.217): icmp_seq=4 ttl=43 time=408 ms
^C
--- google.com ping statistics ---
5 packets transmitted, 4 received, 20% packet loss, time 4000ms
rtt min/avg/max/mdev = 404.297/407.234/408.956/1.887 ms
[root@localhost ~]# ping https://google.com
ping: https://google.com: Name or service not known
[root@localhost ~]# ping https://61.91.161.217
ping: https://61.91.161.217: Name or service not known

`

resolv.conf

[root@localhost ~]# cat /etc/resolv.conf
nameserver 10.0.2.3
nameserver 8.8.8.8
nameserver 8.8.4.4
search localhost

`

ifconfig

[root@localhost ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 fe80::5054:ff:fe73:fb1  prefixlen 64  scopeid 0x20<link>
        ether 52:54:00:73:0f:b1  txqueuelen 1000  (Ethernet)
        RX packets 610587  bytes 48453952 (46.2 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 468759  bytes 41290880 (39.3 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.33.10  netmask 255.255.255.0  broadcast 192.168.33.255
        inet6 fe80::a00:27ff:fe0e:ae16  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:0e:ae:16  txqueuelen 1000  (Ethernet)
        RX packets 3069145  bytes 2674132747 (2.4 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2531212  bytes 213727091 (203.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

network file automatically created from vagrant

[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
NAME="eth0"
ONBOOT=yes
NETBOOT=yes
UUID="704aa015-53dd-4ba7-9689-b9b8bf6e09a5"
IPV6INIT=yes
BOOTPROTO=dhcp
TYPE=Ethernet
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
PEERDNS=yes
PEERROUTES=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
HWADDR=52:54:00:73:0f:b1
DNS1=8.8.8.8
[root@localhost ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1
NM_CONTROLLED=no
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.33.10
NETMASK=255.255.255.0
DEVICE=eth1
PEERDNS=no
DNS1=8.8.8.8


问:
how to find linux process uptime in days
Can any one please let me know how can I find the uptime of a unix process in days?
I am able to get the date time of the process with below command

```<code>[zdkafadm@toplxkafp005 sa]$ ps -eo pid,lstart,cmd |grep server.properties | grep -v auto | awk 'NR==1;'|awk '{print $3" "$4" " $5" "$6}'
Oct 29 12:47:24 2017
</code>```

Somehow I need the output something like 15 days.

Thanks,
Chandan

答:
This is a fun solution:</p>

```<code>ps -o etime= ${pid?} | rev |
sed -e 's/^/ .sdnoces /' -e 's/:/ ,setunim /' \
    -e 's/:/ ,sruoh /' -e 's/-/ ,syad /' | rev
</code>```

Body:
Can any one please let me know how can I find the uptime of a unix process in days?
I am able to get the date time of the process with below command

[zdkafadm@toplxkafp005 sa]$ ps -eo pid,lstart,cmd |grep server.properties | grep -v auto | awk 'NR==1;'|awk '{print $3" "$4" " $5" "$6}'
Oct 29 12:47:24 2017

Somehow I need the output something like 15 days.

Thanks,
Chandan

Body:
This is a fun solution:

ps -o etime= ${pid?} | rev |
sed -e 's/^/ .sdnoces /' -e 's/:/ ,setunim /' \
    -e 's/:/ ,sruoh /' -e 's/-/ ,syad /' | rev


问:
JavaScript Restart Counter
I am probably overthinking the question, but how do I restart a counter? Also, as you will see in my code, the counter is supposed to match but doesn't. I want the cell to have a shared value of the row that it is in, for example the first rows cells should have the ID: cell 0.0, cell 0.1, but rather it has skipped one where the first number is one row ahead.

var rowCount = 0;
var cellCount = 0;

function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
    row = table.insertRow(table.rows.length); // append table row
  row.setAttribute('id', style);
  var i;
  row.id = 'row' + rowCount;
  rowCount++
  console.log(rowCount, cellCount);
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
    createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + cellCount); // doesn't start over once row changes
    cellCount++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode('_'); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('id', style); // set DIV class attribute
  div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  text-align: center;
}
td {
  width: 100px;
}</code>```

<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

      Customers
      Main Location

      Someone
      something

```

答:
I'm not sure this is what you want, but if you put rowCount++ after the for loop it starts off the first element at 0 then increments from there.

If you want the cells to start over then change createCell to use i instead of cellCount:

```<code>createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);
</code>```

Title: JavaScript Restart Counter

Body:
I am probably overthinking the question, but how do I restart a counter? Also, as you will see in my code, the counter is supposed to match but doesn't. I want the cell to have a shared value of the row that it is in, for example the first rows cells should have the ID: cell 0.0, cell 0.1, but rather it has skipped one where the first number is one row ahead.

var rowCount = 0;
var cellCount = 0;

function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
    row = table.insertRow(table.rows.length); // append table row
  row.setAttribute('id', style);
  var i;
  row.id = 'row' + rowCount;
  rowCount++
  console.log(rowCount, cellCount);
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
    createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + cellCount); // doesn't start over once row changes
    cellCount++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode('_'); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('id', style); // set DIV class attribute
  div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
}

table {
  text-align: center;
}
td {
  width: 100px;
}

<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

      Customers
      Main Location

      Someone
      something

Body:
I'm not sure this is what you want, but if you put rowCount++ after the for loop it starts off the first element at 0 then increments from there.

If you want the cells to start over then change createCell to use i instead of cellCount:

createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);


问:
Beginner HTML/CSS Mistake
I'm taking a beginning web design class on Treehouse, and I have a question about centering a class in HTML with CSS, It's not coming out right, even though I have checked instructions. Can someone please look at this code and tell me what I've done wrong?

Here's the HTML:

```<code><main class="flex">
  <div class="card">
    <h2>class="card-title">Background</h2>
</code>```

And, Here's the CSS:

```<code>.card-title {
   text-align:center;
}
</code>```

The output is like this: "class="card-title">Background"

I'm sure the answer is something super simple, because this is a simple course. But I'm just learning, and I'm rather nervous, so any help you can provide will be awesome!

答:
The mistake is here

```<code><h2>class="card-title">Background</h2>
</code>```

should be

```<code><h2 class="card-title">Background</h2>
</code>```

Title: Beginner HTML/CSS Mistake

Body:
I'm taking a beginning web design class on Treehouse, and I have a question about centering a class in HTML with CSS, It's not coming out right, even though I have checked instructions. Can someone please look at this code and tell me what I've done wrong?

Here's the HTML:

class="card-title">Background

And, Here's the CSS:

.card-title {
   text-align:center;
}

The output is like this: "class="card-title">Background"

I'm sure the answer is something super simple, because this is a simple course. But I'm just learning, and I'm rather nervous, so any help you can provide will be awesome!

Body:
The mistake is here

<h2>class="card-title">Background</h2>

should be

<h2 class="card-title">Background</h2>


问:
Java comparators and comparable
I have only class files and no source code in java, Now I have to sort them, what shall I use Comparator or Comparable?

Appreciate your help.

答:
Simple Answer

Go for Comparator.

Summary of two concepts

(extracted from http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html)

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implement the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Consider your existing class

Your current class is already implemented. Even if it already has a Comparable implementation, you are not aware how that comparison is implemented; hence you cannot predict your sorting. When you are not modifying the source of the class which you are trying to sort, the only option is to go with Comparator.

Title: Java comparators and comparable


问:
insert data to column based on query
I have two tables. The table I am trying to update is table A which doesn't have some IDs ProfileIDs. At the other hand table B has all the IDs. I am trying to update the column in Table A based on a query. When I join the tables I get all the results in my query and as i try to update/insert the results in my column I get a cannot insert into my table. I am intending to insert my results with the following query  </p>

```<code> insert into TableA a
(profileID)

select b.profileID
from tableA
join TableB B on B.userID = A.userID

where a.profileID = '' or a.profileID is null

    Table A                                                            Table B

UserID | profileID | lastname | Firstname               UserID | profileID | lastname | Firstname
0012356               Wung      Clara                   0012356   15963         Wung      Clara
0512356    14753      Williams  Michael                 0512356   14753      Williams     Michael
0956356               Walters   Jeff                    0956356   94356      Walters      Jeff
0486312    68956      Wwagner   George                  0486312   68956      Wwagner   George

select A.*, B.profileID
from TableA A
join TableB B on B.userID = A.userID

Results

UserID | profileID | lastname | Firstname
0012356   15963         Wung      Clara
0512356   14753      Williams     Michael
0956356   94356      Walters      Jeff
0486312   68956      Wwagner   George
</code>```

答:
You need to update your table (TableA) using UPDATE statement not INSERT INTO :

```<code>UPDATE TableA
SET  TableA.profileID = TableB.profileID
FROM TableB
     INNER JOIN TableA ON TableA.userID = TableB.userID
WHERE TableA.profileID = '' OR TableA.profileID IS NULL
</code>```

Title: insert data to column based on query

Body:
I have two tables. The table I am trying to update is table A which doesn't have some IDs ProfileIDs. At the other hand table B has all the IDs. I am trying to update the column in Table A based on a query. When I join the tables I get all the results in my query and as i try to update/insert the results in my column I get a cannot insert into my table. I am intending to insert my results with the following query

 insert into TableA a
(profileID)

select b.profileID
from tableA
join TableB B on B.userID = A.userID

where a.profileID = '' or a.profileID is null

    Table A                                                            Table B

UserID | profileID | lastname | Firstname               UserID | profileID | lastname | Firstname
0012356               Wung      Clara                   0012356   15963         Wung      Clara
0512356    14753      Williams  Michael                 0512356   14753      Williams     Michael
0956356               Walters   Jeff                    0956356   94356      Walters      Jeff
0486312    68956      Wwagner   George                  0486312   68956      Wwagner   George

select A.*, B.profileID
from TableA A
join TableB B on B.userID = A.userID

Results

UserID | profileID | lastname | Firstname
0012356   15963         Wung      Clara
0512356   14753      Williams     Michael
0956356   94356      Walters      Jeff
0486312   68956      Wwagner   George

Body:
You need to update your table (TableA) using UPDATE statement not INSERT INTO :

UPDATE TableA
SET  TableA.profileID = TableB.profileID
FROM TableB
     INNER JOIN TableA ON TableA.userID = TableB.userID
WHERE TableA.profileID = '' OR TableA.profileID IS NULL


问:
Do server-side encrypted files in S3 get transitioned to AWS Glacier?
Question:
Do server-side encrypted (with S3 managed or KMS managed keys) files get transitioned to Glacier ?
If yes, are they decrypted using S3 or KMS key and then encrypted again using Glacier's internal key as all objects in Glacier are encrypted using an internal AES 256 keys ?

Problem statement:
I have some files in S3 encrypted using KMS managed key. I have a lifecycle rule to archive to Glacier after 1 day, but the files still show Storage class as 'Standard' even after 3 days.

答:
I checked in AWS docs and forums, but could not find a direct answer to this question.

But what I found was, even the CRR does not handle SSE-C and SSE-KMS encrypted objects (under what is not replicated section). Hence I would assume the transition rule also cannot handle SSE-C and SSE-KMS encrypted files as Glacier supports only AES-256 encryption.

Link for AWS Replication Documentation


问:
Compare dates linq c#
I cant seem to get my query to check the database if a date exists. Please help.

```<code> DateTime value = new DateTime(2018, 10, 26);
 item = await table.Where(todoItem => todoItem.Date == value.date)
                   .ToListAsync();
</code>```

I think the format which c# writes their dates and SQL are different so it cant find a match. Also the database is correctly linked to the app as I am able to query other rows in the same table.

答:
As said before, this is likely due to the fact that your DateTime column in the database includes time information.

Rewrite your query like this:

```<code>DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => todoItem.Date >= value &&
                                     todoItem.Date < value.AddDays(1))
                   .ToListAsync();
</code>```

This will retrieve all records that fall within the specified range (that is, dates that match the given day, and the DBMS will be able to use indexes that might be defined on the date-column.

Title: Compare dates linq c#

Body:
I cant seem to get my query to check the database if a date exists. Please help.

 DateTime value = new DateTime(2018, 10, 26);
 item = await table.Where(todoItem => todoItem.Date == value.date)
                   .ToListAsync();

I think the format which c# writes their dates and SQL are different so it cant find a match. Also the database is correctly linked to the app as I am able to query other rows in the same table.

Body:
As said before, this is likely due to the fact that your DateTime column in the database includes time information.

Rewrite your query like this:

DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => todoItem.Date >= value &&
                                     todoItem.Date < value.AddDays(1))
                   .ToListAsync();

This will retrieve all records that fall within the specified range (that is, dates that match the given day, and the DBMS will be able to use indexes that might be defined on the date-column.


问:
How can I generate database tables from C# classes?
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

I'd expect the following SQL:

```<code>CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)
</code>```

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

答:
It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point:

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace TableGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            List<TableClass> tables = new List<TableClass>();

            // Pass assembly name via argument
            Assembly a = Assembly.LoadFile(args[0]);

            Type[] types = a.GetTypes();

            // Get Types in the assembly.
            foreach (Type t in types)
            {
                TableClass tc = new TableClass(t);
                tables.Add(tc);
            }

            // Create SQL for each table
            foreach (TableClass table in tables)
            {
                Console.WriteLine(table.CreateTableScript());
                Console.WriteLine();
            }

            // Total Hacked way to find FK relationships! Too lazy to fix right now
            foreach (TableClass table in tables)
            {
                foreach (KeyValuePair<String, Type> field in table.Fields)
                {
                    foreach (TableClass t2 in tables)
                    {
                        if (field.Value.Name == t2.ClassName)
                        {
                            // We have a FK Relationship!
                            Console.WriteLine("GO");
                            Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK");
                            Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)");
                            Console.WriteLine("GO");

                        }
                    }
                }
            }
        }
    }

    public class TableClass
    {
        private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();
        private string _className = String.Empty;

        private Dictionary<Type, String> dataMapper
        {
            get
            {
                // Add the rest of your CLR Types to SQL Types mapping here
                Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();
                dataMapper.Add(typeof(int), "BIGINT");
                dataMapper.Add(typeof(string), "NVARCHAR(500)");
                dataMapper.Add(typeof(bool), "BIT");
                dataMapper.Add(typeof(DateTime), "DATETIME");
                dataMapper.Add(typeof(float), "FLOAT");
                dataMapper.Add(typeof(decimal), "DECIMAL(18,0)");
                dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER");

                return dataMapper;
            }
        }

        public List<KeyValuePair<String, Type>> Fields
        {
            get { return this._fieldInfo; }
            set { this._fieldInfo = value; }
        }

        public string ClassName
        {
            get { return this._className; }
            set { this._className = value; }
        }

        public TableClass(Type t)
        {
            this._className = t.Name;

            foreach (PropertyInfo p in t.GetProperties())
            {
                KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);

                this.Fields.Add(field);
            }
        }

        public string CreateTableScript()
        {
            System.Text.StringBuilder script = new StringBuilder();

            script.AppendLine("CREATE TABLE " + this.ClassName);
            script.AppendLine("(");
            script.AppendLine("\t ID BIGINT,");
            for (int i = 0; i < this.Fields.Count; i++)
            {
                KeyValuePair<String, Type> field = this.Fields[i];

                if (dataMapper.ContainsKey(field.Value))
                {
                    script.Append("\t " + field.Key + " " + dataMapper[field.Value]);
                }
                else
                {
                    // Complex Type?
                    script.Append("\t " + field.Key + " BIGINT");
                }

                if (i != this.Fields.Count - 1)
                {
                    script.Append(",");
                }

                script.Append(Environment.NewLine);
            }

            script.AppendLine(")");

            return script.ToString();
        }
    }
}
</code>```

I put these classes in an assembly to test it:

```<code>public class FakeDataClass
{
    public int AnInt
    {
        get;
        set;
    }

    public string AString
    {
        get;
        set;
    }

    public float AFloat
    {
        get;
        set;
    }

    public FKClass AFKReference
    {
        get;
        set;
    }
}

public class FKClass
    {
        public int AFKInt
        {
            get;
            set;
        }
    }
</code>```

And it generated the following SQL:

```<code>CREATE TABLE FakeDataClass
(
         ID BIGINT,
         AnInt BIGINT,
         AString NVARCHAR(255),
         AFloat FLOAT,
         AFKReference BIGINT
)

CREATE TABLE FKClass
(
         ID BIGINT,
         AFKInt BIGINT
)

GO
ALTER TABLE FakeDataClass WITH NOCHECK
ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)
GO
</code>```

Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.

OwnerDisplayName: VanOrman

Body:
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

I'd expect the following SQL:

CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

Body:
It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace TableGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            List<TableClass> tables = new List<TableClass>();

            // Pass assembly name via argument
            Assembly a = Assembly.LoadFile(args[0]);

            Type[] types = a.GetTypes();

            // Get Types in the assembly.
            foreach (Type t in types)
            {
                TableClass tc = new TableClass(t);
                tables.Add(tc);
            }

            // Create SQL for each table
            foreach (TableClass table in tables)
            {
                Console.WriteLine(table.CreateTableScript());
                Console.WriteLine();
            }

            // Total Hacked way to find FK relationships! Too lazy to fix right now
            foreach (TableClass table in tables)
            {
                foreach (KeyValuePair<String, Type> field in table.Fields)
                {
                    foreach (TableClass t2 in tables)
                    {
                        if (field.Value.Name == t2.ClassName)
                        {
                            // We have a FK Relationship!
                            Console.WriteLine("GO");
                            Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK");
                            Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)");
                            Console.WriteLine("GO");

                        }
                    }
                }
            }
        }
    }

    public class TableClass
    {
        private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();
        private string _className = String.Empty;

        private Dictionary<Type, String> dataMapper
        {
            get
            {
                // Add the rest of your CLR Types to SQL Types mapping here
                Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();
                dataMapper.Add(typeof(int), "BIGINT");
                dataMapper.Add(typeof(string), "NVARCHAR(500)");
                dataMapper.Add(typeof(bool), "BIT");
                dataMapper.Add(typeof(DateTime), "DATETIME");
                dataMapper.Add(typeof(float), "FLOAT");
                dataMapper.Add(typeof(decimal), "DECIMAL(18,0)");
                dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER");

                return dataMapper;
            }
        }

        public List<KeyValuePair<String, Type>> Fields
        {
            get { return this._fieldInfo; }
            set { this._fieldInfo = value; }
        }

        public string ClassName
        {
            get { return this._className; }
            set { this._className = value; }
        }

        public TableClass(Type t)
        {
            this._className = t.Name;

            foreach (PropertyInfo p in t.GetProperties())
            {
                KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);

                this.Fields.Add(field);
            }
        }

        public string CreateTableScript()
        {
            System.Text.StringBuilder script = new StringBuilder();

            script.AppendLine("CREATE TABLE " + this.ClassName);
            script.AppendLine("(");
            script.AppendLine("\t ID BIGINT,");
            for (int i = 0; i < this.Fields.Count; i++)
            {
                KeyValuePair<String, Type> field = this.Fields[i];

                if (dataMapper.ContainsKey(field.Value))
                {
                    script.Append("\t " + field.Key + " " + dataMapper[field.Value]);
                }
                else
                {
                    // Complex Type?
                    script.Append("\t " + field.Key + " BIGINT");
                }

                if (i != this.Fields.Count - 1)
                {
                    script.Append(",");
                }

                script.Append(Environment.NewLine);
            }

            script.AppendLine(")");

            return script.ToString();
        }
    }
}

I put these classes in an assembly to test it:

public class FakeDataClass
{
    public int AnInt
    {
        get;
        set;
    }

    public string AString
    {
        get;
        set;
    }

    public float AFloat
    {
        get;
        set;
    }

    public FKClass AFKReference
    {
        get;
        set;
    }
}

public class FKClass
    {
        public int AFKInt
        {
            get;
            set;
        }
    }

And it generated the following SQL:

CREATE TABLE FakeDataClass
(
         ID BIGINT,
         AnInt BIGINT,
         AString NVARCHAR(255),
         AFloat FLOAT,
         AFKReference BIGINT
)

CREATE TABLE FKClass
(
         ID BIGINT,
         AFKInt BIGINT
)

GO
ALTER TABLE FakeDataClass WITH NOCHECK
ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)
GO

Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.

OwnerDisplayName: Jonathan Holland

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Holland


问:
Monitoring Apache Tomcat applications in production environment
How do you ensure that your applications in production are up and running?
How do you alert your team of developers if something goes wrong?

I'm asking this because I'm writing a bash script to check for this issue, I'd like to know if there is a smarter or more complete way to achieve this.
The idea behind is this command: wget -q -O - APPLICATION_URL_HERE | grep 'ERROR 404, I still have to check all kinds of HTTP errors, but you can get the point of what I mean.
If an application is recognized to not be running a mail is sent to the list of the team it belongs to.

All my applications are running on Apache Tomcat.

答:
Tomcat can typically be monitored via JMX; as can be seen from this documentation. This will normally be the cleanest way to monitor, since this can be integrated into a number of third-party monitoring tools that can support all kinds of notifications and bells and whistles.

This may still not give you the full "outside view" picture if your site is up and visible to customers, since there is a number of other things that can go wrong. Quite a few of the management systems also allow you to install agents that do this and integrate into the total monitoring scheme. There are a number of open source jmx tools

OwnerDisplayName: Montecristo

LastEditorDisplayName: Patrick Cuff

OwnerDisplayName: krosenvold

LastEditorDisplayName: krosenvold


问:
bash: append newline when redirecting file
Here is how I read a file row by row:

```<code>while read ROW
do
...
done < file
</code>```

I don't use the other syntax

```<code>cat file | while read ROW
do
...
done
</code>```

because the pipe creates a subshell and makes me lose the environment variables.
The problem arises if the file doesn't end with a newline: last line is not read. It is easy to solve this in the latter syntax, by echoing just a newline:

```<code>(cat file; echo) | while read ROW
do
...
done
</code>```

How do I do the same in the former syntax, without opening a subshell nor creating a temporary file (the list is quite big)?

答:
The POSIX way to do this is via a named pipe.

```<code>#!/bin/sh

[ -p mypipe ] || mkfifo mypipe

(cat num7; echo) > mypipe &

while read line; do
  echo "-->$line<--"
  export CNT=$((cnt+1))
done < mypipe

rm mypipe

echo "CNT is '$cnt'"
</code>```

Input

```<code>$ cat infile
1
2
3
4
5$
</code>```

Output

```<code>$ (cat infile;echo) > mypipe & while read line; do echo "-->$line<--"; export CNT=$((cnt+1)); done < mypipe; echo "CNT is '$cnt'"
[1] 22260
-->1<--
-->2<--
-->3<--
-->4<--
-->5<--
CNT is '5'
[1]+  Done                    ( cat num7; echo ) > mypipe
</code>```

Body:
Here is how I read a file row by row:

while read ROW
do
...
done < file

I don't use the other syntax

cat file | while read ROW
do
...
done

because the pipe creates a subshell and makes me lose the environment variables.
The problem arises if the file doesn't end with a newline: last line is not read. It is easy to solve this in the latter syntax, by echoing just a newline:

(cat file; echo) | while read ROW
do
...
done

How do I do the same in the former syntax, without opening a subshell nor creating a temporary file (the list is quite big)?

Body:
The POSIX way to do this is via a named pipe.

#!/bin/sh

[ -p mypipe ] || mkfifo mypipe

(cat num7; echo) > mypipe &

while read line; do
  echo "-->$line<--"
  export CNT=$((cnt+1))
done < mypipe

rm mypipe

echo "CNT is '$cnt'"

Input

$ cat infile
1
2
3
4
5$

Output

$ (cat infile;echo) > mypipe & while read line; do echo "-->$line<--"; export CNT=$((cnt+1)); done < mypipe; echo "CNT is '$cnt'"
[1] 22260
-->1<--
-->2<--
-->3<--
-->4<--
-->5<--
CNT is '5'
[1]+  Done                    ( cat num7; echo ) > mypipe


问:
Identity value for tables with 1 row vs no rows
I created a table (e.g. #test) with an identity column and insert 1 row into it and deleted the row with DELETE FROM #test. Then if I use SELECT IDENT_CURRENT ( '#test' ) it returns 1. However, it also returns 1 if #test is a newly created / truncated table. Note, it doesn't matter if the row is deleted or not but for my case it will be empty tables.

Using DBCC CHECKIDENT ( #test ) returns 1 for the 1 deleted row case and NULL for the newly created / truncated table case, but I can't find a way to capture its output (what I need is the identity value).

I am trying to set the identity value of other tables to the identity value of the old table (e.g. #test) + 1 (just 1 if the old table never had values inserted into it or was truncated), and I can't separate the 2 cases of 1 deleted row vs new / truncated table.

EDIT: as an example, you can use the following code:

```<code>create table #test (col1 int identity (1, 1))
dbcc checkident (#test)
select ident_current ( '#test' )
insert into #test default values
dbcc checkident (#test)
select ident_current ( '#test' )
drop table #test
</code>```

dbcc checkident will return NULL and 1 whereas ident_current will return 1 and 1. (the output of dbcc checkident will be in the messages tab of SSMS)

答:
If all you're trying to do is set the identity value of another table equal to that of an old table, wouldn't something like this work?</p>

```<code>declare @last_value int

select @last_value = last_value
from   sys.identity_columns
where  object_name(object_id) = 'old_table'

dbcc checkident (new_table, RESEED, @last_value)
</code>```

Body:
I created a table (e.g. #test) with an identity column and insert 1 row into it and deleted the row with DELETE FROM #test. Then if I use SELECT IDENT_CURRENT ( '#test' ) it returns 1. However, it also returns 1 if #test is a newly created / truncated table. Note, it doesn't matter if the row is deleted or not but for my case it will be empty tables.

Using DBCC CHECKIDENT ( #test ) returns 1 for the 1 deleted row case and NULL for the newly created / truncated table case, but I can't find a way to capture its output (what I need is the identity value).

I am trying to set the identity value of other tables to the identity value of the old table (e.g. #test) + 1 (just 1 if the old table never had values inserted into it or was truncated), and I can't separate the 2 cases of 1 deleted row vs new / truncated table.

EDIT: as an example, you can use the following code:

create table #test (col1 int identity (1, 1))
dbcc checkident (#test)
select ident_current ( '#test' )
insert into #test default values
dbcc checkident (#test)
select ident_current ( '#test' )
drop table #test

dbcc checkident will return NULL and 1 whereas ident_current will return 1 and 1. (the output of dbcc checkident will be in the messages tab of SSMS)

Body:
If all you're trying to do is set the identity value of another table equal to that of an old table, wouldn't something like this work?

declare @last_value int

select @last_value = last_value
from   sys.identity_columns
where  object_name(object_id) = 'old_table'

dbcc checkident (new_table, RESEED, @last_value)


问:
How to pass reactive form control from child to parent component in angular 2
I Have nested reactive form, like below

parent HTML

```<code><form>
 <child></child>
 <button mat-raised-button color="primary">Save</button>
</form>
</code>```

child HTML

```<code><div [formGroup]="headerSection">
 <input type="text" formControlName="test">
 <!span [hidden]="headerSection.get('test').valid">required</span>
</div>
</code>```

I want to throw error message in child HTML, but when clicking the parent submit button...

答: in angular 2 you must create child's elements as a component with @Input & @Output (as a Emmiter) fields for interaction with parent component.</p>

Body:
I Have nested reactive form, like below

parent HTML

<form>
 <child></child>
 <button mat-raised-button color="primary">Save</button>
</form>

child HTML

 <input type="text" formControlName="test">
 <!span [hidden]="headerSection.get('test').valid">required

I want to throw error message in child HTML, but when clicking the parent submit button...


问:
Counting choice streaks in Python
I have a dataset that looks like the following:

```<code>Subject | Session | Trial | Choice
--------+---------+-------+-------
1       | 1       | 1     | A
1       | 1       | 2     | B
1       | 1       | 3     | B
1       | 1       | 4     | B
1       | 1       | 5     | B
1       | 1       | 6     | A
2       | 1       | 1     | A
2       | 1       | 2     | A
2       | 1       | 3     | A
</code>```

I would like to use a Python script to generate the following table:

```<code>Subject | Session | streak_count
--------+---------+-------------
1       | 1       | 3
2       | 1       | 1
</code>```

Where streak_count is a count of the total number of choice streaks made by a given subject during a given session, and a streak is any number of choices of one particular item in a row (>0).

I've tried using some of the suggestions to similar questions here, but I'm having trouble figuring out how to count these instances, rather than measure their length, etc., which seem to be more common queries.

答:
```<code>def count():
love = []
love1 = []
streak = -1
k = 0
session = 1
subject = raw_input("What is your subject? ")
trials = raw_input("How many trials do you wish to do? ")
trial = 0
for i in range(int(trials)):
    choice = raw_input("What was the choice? ")
    love.append(choice)
    love1.append(choice)
    trial += 1
    print subject, trial, choice
    if love[i] == love1[i-1]:
        streak += 1

print subject, session, streak
</code>```

<p>This may be what you want it takes in how many trials you wish to do and whatever your subject is and if there is a streak it adds one. The reason streak starts at -1 is because when you put your first answer it adds one because of the negative index going back to its self.  </p>

Title: Counting choice streaks in Python

Body:
I have a dataset that looks like the following:

Subject | Session | Trial | Choice
--------+---------+-------+-------
1       | 1       | 1     | A
1       | 1       | 2     | B
1       | 1       | 3     | B
1       | 1       | 4     | B
1       | 1       | 5     | B
1       | 1       | 6     | A
2       | 1       | 1     | A
2       | 1       | 2     | A
2       | 1       | 3     | A

I would like to use a Python script to generate the following table:

Subject | Session | streak_count
--------+---------+-------------
1       | 1       | 3
2       | 1       | 1

Where streak_count is a count of the total number of choice streaks made by a given subject during a given session, and a streak is any number of choices of one particular item in a row (>0).

I've tried using some of the suggestions to similar questions here, but I'm having trouble figuring out how to count these instances, rather than measure their length, etc., which seem to be more common queries.

Body:
def count():
love = []
love1 = []
streak = -1
k = 0
session = 1
subject = raw_input("What is your subject? ")
trials = raw_input("How many trials do you wish to do? ")
trial = 0
for i in range(int(trials)):
    choice = raw_input("What was the choice? ")
    love.append(choice)
    love1.append(choice)
    trial += 1
    print subject, trial, choice
    if love[i] == love1[i-1]:
        streak += 1

print subject, session, streak

This may be what you want it takes in how many trials you wish to do and whatever your subject is and if there is a streak it adds one. The reason streak starts at -1 is because when you put your first answer it adds one because of the negative index going back to its self.


答:
Similar to Brandon's answer.. this is most likely happening due to todoItem.Date including the time portion of the Date property.

I assume the property Date is of type DateTime, so you could do this:

```<code>DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => DbFunctions.TruncateTime(todoItem.Date) ==
  value).ToListAsync();
</code>```

DbFunctions.TruncateTime

When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

Here is more information on DbFunctions.TruncateTime.

Let me know if this helps!

Title: Compare dates linq c#

Body:
Similar to Brandon's answer.. this is most likely happening due to todoItem.Date including the time portion of the Date property.

I assume the property Date is of type DateTime, so you could do this:

DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => DbFunctions.TruncateTime(todoItem.Date) ==
  value).ToListAsync();

DbFunctions.TruncateTime

When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

Here is more information on DbFunctions.TruncateTime.

Let me know if this helps!


问:
How to implement a "Vulcan command" on iOs
I am working on an app where it might be desirable to have a "Vulcan command" available for certain functions.  What is the best way to implement this?

The obvious would be to have a view overlaid on top of the entire UI and use it to detect multi touch events.  If the touch is in the right places the command is triggered.

I also thought of the idea of placing invisible buttons in the corners of the UI and instructing the user to touch two, three or four corners to activate the function.  Can UIButton be used this way?  I can see setting up actions to trigger on touch down and then keeping track of which buttons are also pressed.  Haven't tried it yet.

Thanks,

-Martin

答:
This is a job for UIGestureRecognizer.

Specifically, a UILongPressGestureRecognizer set to recognize only multi-finger touches. You can even hit-test each of those touches and make sure they're within the target regions.


问:
Questions subtracting One from a Vector R
I'm sure this question has been asked but I couldn't find a direct answer.  This should be so easy, however, I'm struggling to find an answer.  Basically I have a df which has 10 columns/vectors.  There is one Vector that I want to subset and then reduce by one.  Below is my code.  I'm sure it would work but I'm thinking there must be an easier way. Thanks in advance for your help.  </p>

```<code>diffuse_objects <- c("Diffuse Nebula", "Elliptical Galaxy", "Spiral Galaxy",      "Galaxy", "Planetary Nebula",
                 "Nebula", "Cluster Nebulosity")

#subset diffuse Ojbects
newdf2 <- newdf[newdf$Type == diffuse_objects,]
#Change from character to Numeric
newdf2$Magnitude <- as.numeric(newdf2$Magnitude)
#Subtract -1
newdf3 <- newdf2[, "Magnitude"] - 1
newdf4 <-cbind(newdf3, newdf2)
</code>```

答:
```<code>diffuse_objects <- c("Diffuse Nebula", "Elliptical Galaxy", "Spiral Galaxy",      "Galaxy", "Planetary Nebula",
                 "Nebula", "Cluster Nebulosity")

#subset diffuse Ojbects
newdf2 <-filter(newdf,Type %in% diffuse_objects)
#Change from character to Numeric
newdf2$Magnitude <- as.numeric(newdf2$Magnitude)-1
</code>```

Body:
I'm sure this question has been asked but I couldn't find a direct answer.  This should be so easy, however, I'm struggling to find an answer.  Basically I have a df which has 10 columns/vectors.  There is one Vector that I want to subset and then reduce by one.  Below is my code.  I'm sure it would work but I'm thinking there must be an easier way. Thanks in advance for your help.

diffuse_objects <- c("Diffuse Nebula", "Elliptical Galaxy", "Spiral Galaxy",      "Galaxy", "Planetary Nebula",
                 "Nebula", "Cluster Nebulosity")

#subset diffuse Ojbects
newdf2 <- newdf[newdf$Type == diffuse_objects,]
#Change from character to Numeric
newdf2$Magnitude <- as.numeric(newdf2$Magnitude)
#Subtract -1
newdf3 <- newdf2[, "Magnitude"] - 1
newdf4 <-cbind(newdf3, newdf2)


问:
Simplified algorithm for calculating remaining space in a circular buffer?
I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?</p>

```<code>int remaining = (end > start)
                ? end-start
                : bufferSize - start + end;
</code>```

答:
Older thread I know but thought this might be helpful.

Not sure how fast this implements in C++ but in rtl we do this if size is n^2

```<code>remaining = (end[n] ^ start[n])
            ? start[n-1:0] - end[n-1:0]
            : end[n-1:0] - start[n-1:0];
</code>```

or

```<code>remaining = if (end[n] ^ start[n]) {
              start[n-1:0] - end[n-1:0]
            } else {
              end[n-1:0] - start[n-1:0]
            };
</code>```

OwnerDisplayName: Dynite

Body:
I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?

int remaining = (end > start)
                ? end-start
                : bufferSize - start + end;

LastEditorDisplayName: Gamecat

Body:
Older thread I know but thought this might be helpful.

Not sure how fast this implements in C++ but in rtl we do this if size is n^2

remaining = (end[n] ^ start[n])
            ? start[n-1:0] - end[n-1:0]
            : end[n-1:0] - start[n-1:0];

or

remaining = if (end[n] ^ start[n]) {
              start[n-1:0] - end[n-1:0]
            } else {
              end[n-1:0] - start[n-1:0]
            };


问:
How to import codes in .html file which are placed in a txt file ?
So, what i want is this. I have an HTML File and i want the code to load from a text file. So, the browser should get the code from that text file and read it as a part of the HTML code. Here is an example:

Suppose I have an HTML File whose code is :-

```<code><html>
<head></head>
<body>

<div src="code.txt"></div> [ I made this code. I know this code does not exist.]

</body>
</html>
</code>```

And i have text file named 'code.text' :

```<code><h2>Welcome</h2>
<img src="sample.jpg">
<p>This is the paragraph.</p>
</code>```

So, instead of writing code in the actual HTML File, i saved the codes in a text file and want to use them whenever i want. I know the following code does not exist.

```<code><div src="code.text"></div>

I made up this code just to show what i want.
</code>```

**

Just tell me the way i can achieve this purpose.

**

Thanks,

Waiting for your answer !

答:
Why not use SHTML?

SHTML is an HTML file that includes server instructions or server side includes and is similar to an ASP file.

It's embedded in a standard XML comment, and looks like this:

```<code><!--#include virtual="../top.shtml" -->
<!--#include virtual="../quote.txt" -->
</code>```

For example, a .shtml page that includes a resource can be as follows:

```<code><!doctype html>
<html lang="en">
<head>
    <title>My SHTML Page</title>
</head>
<body>
    <!--#include virtual="content.html" -->
</body>
</html>
</code>```

You can use to include a common header and footer in your pages, so you don't have to repeat code as much, and changing one included file updates all of your pages at once.

Apache can be configured to parse any file with a particular file extension, such as .shtml, with the following directives in the http.conf file:

```<code>AddType text/html .shtml
AddHandler server-parsed .shtml
</code>```

Body:
So, what i want is this. I have an HTML File and i want the code to load from a text file. So, the browser should get the code from that text file and read it as a part of the HTML code. Here is an example:

Suppose I have an HTML File whose code is :-

 [ I made this code. I know this code does not exist.]

And i have text file named 'code.text' :

Welcome

This is the paragraph.

So, instead of writing code in the actual HTML File, i saved the codes in a text file and want to use them whenever i want. I know the following code does not exist.

I made up this code just to show what i want.

**

Just tell me the way i can achieve this purpose.

**

Thanks,

Waiting for your answer !

Body:
Why not use SHTML?

SHTML is an HTML file that includes server instructions or server side includes and is similar to an ASP file.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="../top.shtml" -->
<!--#include virtual="../quote.txt" -->

For example, a .shtml page that includes a resource can be as follows:

<!doctype html>
<html lang="en">
<head>
    <title>My SHTML Page</title>
</head>
<body>
    <!--#include virtual="content.html" -->
</body>
</html>

You can use to include a common header and footer in your pages, so you don't have to repeat code as much, and changing one included file updates all of your pages at once.

Apache can be configured to parse any file with a particular file extension, such as .shtml, with the following directives in the http.conf file:

AddType text/html .shtml
AddHandler server-parsed .shtml


问:
Get second child using jQuery
```<code>$(t).html()
</code>```

returns

```<code><td>test1</td><td>test2</td>
</code>```

I want to retrieve the second td from the $(t) object. I searched for a solution but nothing worked for me. Any idea how to get the second element?

Title: Get second child using jQuery

Body:
$(t).html()

returns

test1	test2

I want to retrieve the second td from the $(t) object. I searched for a solution but nothing worked for me. Any idea how to get the second element?

Body:
Try this:

$("td:eq(1)", $(t))

or

$("td", $(t)).eq(1)


问:
Reading button's background image
I'm trying to read a button's background image, this is what i'm trying:

```<code>  ImageView btn_java1 = (ImageView)findViewById(R.id.background);
  int draw = R.drawable.ic_launcher;

    btn1.setOnClickListener(new OnClickListener() {
        public void onClick(View var1) {

        if (btn_java1.getBackground().equals(draw)){
            a.setVisibility(View.VISIBLE);
        }
        else{
            a.setVisibility(View.INVISIBLE);
        }

        }
    });
</code>```

But it's not working and I can't see the problem

答:
you dont need to define a int variable;all you need to do is write below code in your if condition:

```<code>if (btn_java1.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_luncher).getConstantState())
</code>```

i dont remember now but check above code with or without getConstantState() and see if its work...

EDIT

for api 21 above you can use this method:

```<code>  @SuppressWarnings("deprecation")
  @SuppressLint("NewApi")
  public static boolean checkImageResource(Context ctx, ImageView  imageView,
    int imageResource) {
boolean result = false;
if (ctx != null && imageView != null && imageView.getDrawable() != null) {
    ConstantState constantState;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        constantState = ctx.getResources()
                .getDrawable(imageResource, ctx.getTheme())
                .getConstantState();
    } else {
        constantState = ctx.getResources().getDrawable(imageResource)
                .getConstantState();
    }

    if (imageView.getDrawable().getConstantState() == constantState) {
        result = true;
    }
}

return result;
</code>```

}

Title: Reading button's background image

Body:
I'm trying to read a button's background image, this is what i'm trying:

  ImageView btn_java1 = (ImageView)findViewById(R.id.background);
  int draw = R.drawable.ic_launcher;

    btn1.setOnClickListener(new OnClickListener() {
        public void onClick(View var1) {

        if (btn_java1.getBackground().equals(draw)){
            a.setVisibility(View.VISIBLE);
        }
        else{
            a.setVisibility(View.INVISIBLE);
        }

        }
    });

But it's not working and I can't see the problem

Body:
you dont need to define a int variable;all you need to do is write below code in your if condition:

if (btn_java1.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_luncher).getConstantState())

i dont remember now but check above code with or without getConstantState() and see if its work...

EDIT

for api 21 above you can use this method:

  @SuppressWarnings("deprecation")
  @SuppressLint("NewApi")
  public static boolean checkImageResource(Context ctx, ImageView  imageView,
    int imageResource) {
boolean result = false;
if (ctx != null && imageView != null && imageView.getDrawable() != null) {
    ConstantState constantState;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        constantState = ctx.getResources()
                .getDrawable(imageResource, ctx.getTheme())
                .getConstantState();
    } else {
        constantState = ctx.getResources().getDrawable(imageResource)
                .getConstantState();
    }

    if (imageView.getDrawable().getConstantState() == constantState) {
        result = true;
    }
}

return result;

}


问:
How to set column C value based on a initial column A,B,C value
I have the following table :

```<code>A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan
</code>```

Desired result :

```<code> A     B       C
food  fruit   apple
food  fruit   apple
food  drink
food  fruit   apple
car   suv     ford
car   sedan   bmw
car   suv     ford
car   sedan   bmw
</code>```

How can complete column C based on the values in both Column A, B?  For example, if the value in Column A = food and Column B = fruit, then Column C should be filled with. Ideally, I want to do it without having to manually enter the column A, B pair and the corresponding column C value since my table has thousands of such combinations.

Would appreciate any help!

答:
Two alternatives using data.table:

```<code>library(data.table)
setDT(d1)[, C := C[C != ''], by = .(A,B)][]
setDT(d1)[, C := ifelse(all(C == ''), '', C[C != '']), by = .(A,B)][]
</code>```

which both give:

```<code>> d1
      A     B     C
1: food fruit apple
2: food fruit apple
3: food drink
4: food fruit apple
5:  car   suv  ford
6:  car sedan   bmw
7:  car   suv  ford
8:  car sedan   bmw
</code>```

An alternative using dplyr:

```<code>library(dplyr)
d1 %>%
  group_by(A, B) %>%
  summarise(C = ifelse(all(C == ''), '', C[C != ''])) %>%
  right_join(., d1, by = c('A','B')) %>%
  select(A, B, C = C.x)
</code>```

which gives a similar result.

Body:
I have the following table :

A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan

Desired result :

 A     B       C
food  fruit   apple
food  fruit   apple
food  drink
food  fruit   apple
car   suv     ford
car   sedan   bmw
car   suv     ford
car   sedan   bmw

How can complete column C based on the values in both Column A, B?  For example, if the value in Column A = food and Column B = fruit, then Column C should be filled with. Ideally, I want to do it without having to manually enter the column A, B pair and the corresponding column C value since my table has thousands of such combinations.

Would appreciate any help!

Body:
Two alternatives using data.table:

library(data.table)
setDT(d1)[, C := C[C != ''], by = .(A,B)][]
setDT(d1)[, C := ifelse(all(C == ''), '', C[C != '']), by = .(A,B)][]

which both give:

> d1
      A     B     C
1: food fruit apple
2: food fruit apple
3: food drink
4: food fruit apple
5:  car   suv  ford
6:  car sedan   bmw
7:  car   suv  ford
8:  car sedan   bmw

An alternative using dplyr:

library(dplyr)
d1 %>%
  group_by(A, B) %>%
  summarise(C = ifelse(all(C == ''), '', C[C != ''])) %>%
  right_join(., d1, by = c('A','B')) %>%
  select(A, B, C = C.x)

which gives a similar result.


问:
Communicating with an external service: internal server error 500
I'm trying to make a GET request to an HTTPS service ( https://broker.bronos.net ). This service is an API that communicates with a client on my LAN. I can't get it to work via functions.https.get(URL, (s,ss) => {});

Please help -- I'm very new to web development, let alone google actions.

I'm using the apiai-starter-app as the base, which functions perfectly fine until I add the line above which returns internal server error 500.

Note: I've tried before adding billing to the project and after as well. Neither work.

Edit:
using this

```<code>        const https = require('https');

https.get('https://broker.bronos.net/v1/CLIENT_ID/ROOM_NAME/ACTION/PARAM', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
            if (requestSource === googleAssistantRequest) {
        sendGoogleResponse(JSON.parse(data).explanation); // Send simple response to user
      } else {
        sendResponse(JSON.parse(data).explanation); // Send simple response to user
      }
  });

}).on("error", (err) => {
                if (requestSource === googleAssistantRequest) {
        sendResponse("Error: " + err.message); // Send simple response to user
      } else {
        sendResponse("Error: " + err.message); // Send simple response to user
      }
});
</code>```

答:
Firebase's functions have limited access to external APIs on the free tier. By upgrading to Blaze or Flame plans you will be able to make external API calls.

Enabling Firebase Blaze plan + the following code worked

```<code>        const https = require('https');

https.get('https://broker.bronos.net/v1/CLIENT_ID/Living%20Room/volume/20', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
            if (requestSource === googleAssistantRequest) {
        sendGoogleResponse(JSON.parse(data).explanation); // Send simple response to user
      } else {
        sendResponse(JSON.parse(data).explanation); // Send simple response to user
      }
  });

}).on("error", (err) => {
                if (requestSource === googleAssistantRequest) {
        sendResponse("Error: " + err.message); // Send simple response to user
      } else {
        sendResponse("Error: " + err.message); // Send simple response to user
      }
});
</code>```

Body:
I'm trying to make a GET request to an HTTPS service ( https://broker.bronos.net ). This service is an API that communicates with a client on my LAN. I can't get it to work via functions.https.get(URL, (s,ss) => {});

Please help -- I'm very new to web development, let alone google actions.

I'm using the apiai-starter-app as the base, which functions perfectly fine until I add the line above which returns internal server error 500.

Note: I've tried before adding billing to the project and after as well. Neither work.

Edit:
using this

        const https = require('https');

https.get('https://broker.bronos.net/v1/CLIENT_ID/ROOM_NAME/ACTION/PARAM', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
            if (requestSource === googleAssistantRequest) {
        sendGoogleResponse(JSON.parse(data).explanation); // Send simple response to user
      } else {
        sendResponse(JSON.parse(data).explanation); // Send simple response to user
      }
  });

}).on("error", (err) => {
                if (requestSource === googleAssistantRequest) {
        sendResponse("Error: " + err.message); // Send simple response to user
      } else {
        sendResponse("Error: " + err.message); // Send simple response to user
      }
});

Body:
Firebase's functions have limited access to external APIs on the free tier. By upgrading to Blaze or Flame plans you will be able to make external API calls.

Enabling Firebase Blaze plan + the following code worked

        const https = require('https');

https.get('https://broker.bronos.net/v1/CLIENT_ID/Living%20Room/volume/20', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
            if (requestSource === googleAssistantRequest) {
        sendGoogleResponse(JSON.parse(data).explanation); // Send simple response to user
      } else {
        sendResponse(JSON.parse(data).explanation); // Send simple response to user
      }
  });

}).on("error", (err) => {
                if (requestSource === googleAssistantRequest) {
        sendResponse("Error: " + err.message); // Send simple response to user
      } else {
        sendResponse("Error: " + err.message); // Send simple response to user
      }
});


问:
(Cucumber) Long Scenarios caused by pre-conditions
I have to write a Gherkin scenario (C# Specflow) that has a large precondition before the test can be run and wondered what is the best approach. I have to complete multiple fields on a form and save it and record the form number created. I then have to do the exactly the same and create a second form.

The main purpose of the scenario is then to test a new function that associates the 2 completed forms.

I thought the best approach would be to do the pre-work as a background:

```<code>Background: Create Form Documents

Given I have logged into the System
And I have accessed the new <formType1> screen
When I complete all the mandatory <formType2> fields
And press the Save button
Then the new document number will be created

    Examples:
    | formType1            | formType2            |
    | Building Certificate | Building Certificate |
    | Building Certificate | Building Certificate |
</code>```

Then the scenario would be:

```<code>Scenario:
Given that I have accessed the "CHILD DOCUMENT NUMBER" screen
When I select "ASSOCIATE FORM DOCUMENTS" from the menu
And click the "ADD PARENT FORM DOCUMENT" button
And I enter the "PARENT SAFETY DOCUMENT NUMBER" in the Search field
And click on the "SEARCH" button
And click the "SELECT" button
Then the diagram should show "PARENT DOCUMENT NUMBER" as a parent of "CHILD DOCUMENT NUMBER"
</code>```

I've read its a bad idea to pass data between scenarios, so is the best way just to lump all this into the one scenario which will in effect be doing the Background steps TWICE and then the main scenario? I'm trying to reuse existing steps and keep the scenarios short and concise. Any advice on the correct approach?

答:
```<code>Given I have two “Building Certificate” document numbers
When I associate the child document with the parent document
Then the parent safety document diagram should show the association
</code>```

Within this, you’ll write the methods for creating the two documents, and assign the document numbers to an array variable.

When doing the associating, take the first to be the parent and associate it with the second.

This way, you’ll only have to complete one scenario.

Body:
I have to write a Gherkin scenario (C# Specflow) that has a large precondition before the test can be run and wondered what is the best approach. I have to complete multiple fields on a form and save it and record the form number created. I then have to do the exactly the same and create a second form.

The main purpose of the scenario is then to test a new function that associates the 2 completed forms.

I thought the best approach would be to do the pre-work as a background:

Background: Create Form Documents

Given I have logged into the System
And I have accessed the new <formType1> screen
When I complete all the mandatory <formType2> fields
And press the Save button
Then the new document number will be created

    Examples:
    | formType1            | formType2            |
    | Building Certificate | Building Certificate |
    | Building Certificate | Building Certificate |

Then the scenario would be:

Scenario:
Given that I have accessed the "CHILD DOCUMENT NUMBER" screen
When I select "ASSOCIATE FORM DOCUMENTS" from the menu
And click the "ADD PARENT FORM DOCUMENT" button
And I enter the "PARENT SAFETY DOCUMENT NUMBER" in the Search field
And click on the "SEARCH" button
And click the "SELECT" button
Then the diagram should show "PARENT DOCUMENT NUMBER" as a parent of "CHILD DOCUMENT NUMBER"

I've read its a bad idea to pass data between scenarios, so is the best way just to lump all this into the one scenario which will in effect be doing the Background steps TWICE and then the main scenario? I'm trying to reuse existing steps and keep the scenarios short and concise. Any advice on the correct approach?

Body:
Given I have two “Building Certificate” document numbers
When I associate the child document with the parent document
Then the parent safety document diagram should show the association

Within this, you’ll write the methods for creating the two documents, and assign the document numbers to an array variable.

When doing the associating, take the first to be the parent and associate it with the second.

This way, you’ll only have to complete one scenario.


问:
Checking approximation of E
MathWorld page gives a simple numeric formula for e that's allegedly correct for first 10^25 digits. It states that e is approximately

```<code>(1 + 9^-4^(7*6))^3^2^85
</code>```

Any idea how to check whether this formula is correct even for the first 10 digits?
Here's another way of writing the right hand side

```<code>Power[Plus[1, Power[9, Times[-1, Power[4, Times[7, 6]]]]], Power[3, Power[2, 85]]]
</code>```

答:
This problem does not need Mathematica at all. First, it is easy to show that 9^(4^(7*6)) is exactly equal to 3^2^85, since

```<code> 9^(4^(7*6)) = 3^(2*4^(7*6)) = 3^(2^(1+2*(7*6))) = 3^2^85
</code>```

Then, we know that one of the ways to represent e is as a limit

```<code>e = lim (1+1/n)^n, n->infinity
</code>```

The only question is what is the error given that n is very large but finite. We have

```<code>(1+1/n)^n = e^log((1+1/n)^n) = e^(n*log(1+1/n)) = e^(1-1/(2n)+O(1/n^2)) = e + O(1/n),
</code>```

Given the n = 3^2^85, i we take the log(10,n) = 2^85 log(10,3) ~ 1.85 *10^25, we get an estimate
similar to the quoted one

Title: Checking approximation of E

Body:
MathWorld page gives a simple numeric formula for e that's allegedly correct for first 10^25 digits. It states that e is approximately

(1 + 9^-4^(7*6))^3^2^85

Any idea how to check whether this formula is correct even for the first 10 digits?
Here's another way of writing the right hand side

Power[Plus[1, Power[9, Times[-1, Power[4, Times[7, 6]]]]], Power[3, Power[2, 85]]]

Body:
This problem does not need Mathematica at all. First, it is easy to show that 9^(4^(7*6)) is exactly equal to 3^2^85, since

 9^(4^(7*6)) = 3^(2*4^(7*6)) = 3^(2^(1+2*(7*6))) = 3^2^85

Then, we know that one of the ways to represent e is as a limit

e = lim (1+1/n)^n, n->infinity

The only question is what is the error given that n is very large but finite. We have

(1+1/n)^n = e^log((1+1/n)^n) = e^(n*log(1+1/n)) = e^(1-1/(2n)+O(1/n^2)) = e + O(1/n),

Given the n = 3^2^85, i we take the log(10,n) = 2^85 log(10,3) ~ 1.85 *10^25, we get an estimate
similar to the quoted one


问:
What is the fastest way to compute an RBF kernel in python?
I would like to compute an RBF or "Gaussian" kernel for a data matrix X with n rows and d columns. The resulting square kernel matrix is given by:

```<code>K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
</code>```

var and gamma are scalars.

What is the fastest way to do this in python?

答:
Well you are doing a lot of optimizations in your answer post. I would like to add few more (mostly tweaks). I would build upon the winner from the answer post, which seems to be numexpr based on.

Tweak #1

First off, np.sum(X ** 2, axis = -1) could be optimized with np.einsum. Though this part isn't the biggest overhead, but optimization of any sort won't hurt. So, that summation could be expressed as -

```<code>X_norm = np.einsum('ij,ij->i',X,X)
</code>```

Tweak #2

Secondly, we could leverage Scipy supported blas functions and if allowed use single-precision dtype for noticeable performance improvement over its double precision one. Hence, np.dot(X, X.T) could be computed with SciPy's sgemm like so -

```<code>sgemm(alpha=1.0, a=X, b=X, trans_b=True)
</code>```

Few more tweaks on rearranging the negative sign with gamma lets us feed more to sgemm. Also, we would push in gamma into the alpha term.

Tweaked implementations

Thus, with these two optimizations, we would have two more variants (if I could put it that way) of the numexpr method, listed below -

```<code>from scipy.linalg.blas import sgemm

def app1(X, gamma, var):
    X_norm = -np.einsum('ij,ij->i',X,X)
    return ne.evaluate('v * exp(g * (A + B + 2 * C))', {\
        'A' : X_norm[:,None],\
        'B' : X_norm[None,:],\
        'C' : np.dot(X, X.T),\
        'g' : gamma,\
        'v' : var\
    })

def app2(X, gamma, var):
    X_norm = -gamma*np.einsum('ij,ij->i',X,X)
    return ne.evaluate('v * exp(A + B + C)', {\
        'A' : X_norm[:,None],\
        'B' : X_norm[None,:],\
        'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
        'g' : gamma,\
        'v' : var\
    })
</code>```

Runtime test

Numexpr based one from your answer post -

```<code>def app0(X, gamma, var):
    X_norm = np.sum(X ** 2, axis = -1)
    return ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
            'A' : X_norm[:,None],
            'B' : X_norm[None,:],
            'C' : np.dot(X, X.T),
            'g' : gamma,
            'v' : var
    })
</code>```

Timings and verification -

```<code>In [165]: # Setup
     ...: X = np.random.randn(10000, 512)
     ...: gamma = 0.01
     ...: var = 5.0

In [166]: %timeit app0(X, gamma, var)
     ...: %timeit app1(X, gamma, var)
     ...: %timeit app2(X, gamma, var)
1 loop, best of 3: 1.25 s per loop
1 loop, best of 3: 1.24 s per loop
1 loop, best of 3: 973 ms per loop

In [167]: np.allclose(app0(X, gamma, var), app1(X, gamma, var))
Out[167]: True

In [168]: np.allclose(app0(X, gamma, var), app2(X, gamma, var))
Out[168]: True
</code>```

Body:
I would like to compute an RBF or "Gaussian" kernel for a data matrix X with n rows and d columns. The resulting square kernel matrix is given by:

K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)

var and gamma are scalars.

What is the fastest way to do this in python?

Body:
Well you are doing a lot of optimizations in your answer post. I would like to add few more (mostly tweaks). I would build upon the winner from the answer post, which seems to be numexpr based on.

Tweak #1

First off, np.sum(X ** 2, axis = -1) could be optimized with np.einsum. Though this part isn't the biggest overhead, but optimization of any sort won't hurt. So, that summation could be expressed as -

X_norm = np.einsum('ij,ij->i',X,X)

Tweak #2

Secondly, we could leverage Scipy supported blas functions and if allowed use single-precision dtype for noticeable performance improvement over its double precision one. Hence, np.dot(X, X.T) could be computed with SciPy's sgemm like so -

sgemm(alpha=1.0, a=X, b=X, trans_b=True)

Few more tweaks on rearranging the negative sign with gamma lets us feed more to sgemm. Also, we would push in gamma into the alpha term.

Tweaked implementations

Thus, with these two optimizations, we would have two more variants (if I could put it that way) of the numexpr method, listed below -

from scipy.linalg.blas import sgemm

def app1(X, gamma, var):
    X_norm = -np.einsum('ij,ij->i',X,X)
    return ne.evaluate('v * exp(g * (A + B + 2 * C))', {\
        'A' : X_norm[:,None],\
        'B' : X_norm[None,:],\
        'C' : np.dot(X, X.T),\
        'g' : gamma,\
        'v' : var\
    })

def app2(X, gamma, var):
    X_norm = -gamma*np.einsum('ij,ij->i',X,X)
    return ne.evaluate('v * exp(A + B + C)', {\
        'A' : X_norm[:,None],\
        'B' : X_norm[None,:],\
        'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
        'g' : gamma,\
        'v' : var\
    })

Runtime test

Numexpr based one from your answer post -

def app0(X, gamma, var):
    X_norm = np.sum(X ** 2, axis = -1)
    return ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
            'A' : X_norm[:,None],
            'B' : X_norm[None,:],
            'C' : np.dot(X, X.T),
            'g' : gamma,
            'v' : var
    })

Timings and verification -

In [165]: # Setup
     ...: X = np.random.randn(10000, 512)
     ...: gamma = 0.01
     ...: var = 5.0

In [166]: %timeit app0(X, gamma, var)
     ...: %timeit app1(X, gamma, var)
     ...: %timeit app2(X, gamma, var)
1 loop, best of 3: 1.25 s per loop
1 loop, best of 3: 1.24 s per loop
1 loop, best of 3: 973 ms per loop

In [167]: np.allclose(app0(X, gamma, var), app1(X, gamma, var))
Out[167]: True

In [168]: np.allclose(app0(X, gamma, var), app2(X, gamma, var))
Out[168]: True


问:
how can i add h3 code from asp.net behind code?
I want show a html code from "else", how can i?

this is my code

```<code>    if (output == "1")
    {

        Session["user"] = textuser.Text;
        Response.Redirect("~/Default2.aspx");
    }
    else
    {

        // show html code <h4  id='error1' runat ='server'></h4>
    }
</code>```

答: There are lots of ways to skin a cat, but one way is to add an HtmlGenericControl to your WebForm, passing the appropriate tag ("h3" or "h4") to the constructor.</p>

Body:
I want show a html code from "else", how can i?

this is my code

    if (output == "1")
    {

        Session["user"] = textuser.Text;
        Response.Redirect("~/Default2.aspx");
    }
    else
    {

        // show html code

    }


问:
Read from file and call function
I have a task in which I need to read from text file and call a function. The text file is following:

```<code>black,20,10,3,1
red,10,20,4,3
blue,10,-20,-4,3
</code>```

My defined function takes five parameters, which are split in the text flile by commas.
This is what I have so far:

```<code>with open(textfile) as source:
    for i in source.readlines():
        a = split(",")
</code>```

But here I have no idea how to call the function with the read line from source.

Any ideas?

答: If your function is f, you could simply call f(*a).

Title: Read from file and call function

Body:
I have a task in which I need to read from text file and call a function. The text file is following:

black,20,10,3,1
red,10,20,4,3
blue,10,-20,-4,3

My defined function takes five parameters, which are split in the text flile by commas.
This is what I have so far:

with open(textfile) as source:
    for i in source.readlines():
        a = split(",")

But here I have no idea how to call the function with the read line from source.

Any ideas?


问:
Remove buttons that are added at runtime
I have a view that allows buttons to be created and added to at runtime.

This seems to be working correctly.

I have a series of background images that are cycled through the application when the user clicks a button on the main form.

This works fine, but the buttons that are added at runtime need to be removed whenever the user switches background images.

How do I remove the buttons that were added at runtime?

答: Send the button [button removeFromSuperview];.


问:
For a custom SSIS component, why do I have to put it into GAC?
I create a Custom SSIS Task according to this article: Developing a Custom SSIS Source Component

Now, after compiling the DLL I need to put it into the PipelineComponents folder of the relevant SQL Server Version. The article states that I also have to register in in the GAC. (in "Deploying the custom component" section)

Why do I need to put it into two different locations ?

答:
First, you have to copy the DLL to the {{ SQLServer Installation Folder}}\110\DTS\ PipelineComponents, because on visual studio startup, the ssis toolbox components are read from this location.

Second, you have to copy these DLL's to GAC, because the visual studio used search for DLL's on GAC when executing the package or when deploying.

So we can say that the first location is to allow using the DLL in design mode, the second location is for executing and deploying the package.

Side Note (The GAC definition):

"The Global Assembly Cache (GAC) is a machine-wide CLI assembly cache for the Common Language Infrastructure (CLI) in Microsoft's .NET Framework. The approach of having a specially controlled central repository addresses the flaws in the shared library concept and helps to avoid pitfalls of other solutions that led to drawbacks like DLL hell" Read more


问:
Codeigniter - how to combine multiple installations into one
When I started my app a few years ago, there where just 2 clients and thus 2 subsites on my domain where I installed the codigniter-built app :

main domain

subsites based on client code # : e.g. main/1448 and main/4457

each subsite containes the same codeingiter app and is run from within the subsite itself ( e.g. main/1448/index.php and main/4457/index.php )

seperate mysql-databases based on client code #

Over the years my app evolved and I got more users and thus more subsites ( atm about 40 subsites ). This is labor-intensive when creating a new subsite and especially when releasing an update since I have to update all 40 subsites manually.

Is there a way to install the codeigniter installation in my main folder and maintain the url for each subsite ? This will have the consequense that in the url the first item isn't the controller but the subsite follewed by the controller and if needed the method etc. Is this possible ?

Second, is there an easy way to use the subsite-code in the url to define which database the app has to use ?

thx

答:
As per documentation you can use few applications setting:

```<code>$application_folder = '/path/to/your/application';
</code>```

More information:
https://www.codeigniter.com/userguide3/general/managing_apps.html

I have a similar issue, but I've decided to keep all the application separately. I am also thinking how to manage all the apps.
I think one of idea could be to make a script which can check if zip file with an upgrade is available on main site. If yes, download and unzip.
SQL migration is more complicated for me, but CI comes with:
https://www.codeigniter.com/userguide3/libraries/migration.html

Body:
As per documentation you can use few applications setting:

$application_folder = '/path/to/your/application';

More information:
https://www.codeigniter.com/userguide3/general/managing_apps.html

I have a similar issue, but I've decided to keep all the application separately. I am also thinking how to manage all the apps.
I think one of idea could be to make a script which can check if zip file with an upgrade is available on main site. If yes, download and unzip.
SQL migration is more complicated for me, but CI comes with:
https://www.codeigniter.com/userguide3/libraries/migration.html