问:
Why width: 0 doesn't work
In @media screen and (max-width: 700px), I set aside {width: 0}, but it doesn't disappear. After resizing, the window remains as null space with width: 52px, why is this happening, and how can I fix it?

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    opacity: 0;
    width: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
    <div class="wrapper">
      <header>HEADER</header>
      <main>
        <section>SECTION</section>
        <aside>ASIDE</aside>
      </main>
      <footer>FOOTER</footer>
    </div>
  </body>
</html></code>```

答:
It's because you're using display: table to make the layout.

Tables have their own way to calculating their width, so setting a width doesn't mean that it will be exactly that.

Try using display: none instead

Title: Why width: 0 doesn't work

Body:
In @media screen and (max-width: 700px), I set aside {width: 0}, but it doesn't disappear. After resizing, the window remains as null space with width: 52px, why is this happening, and how can I fix it?

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    opacity: 0;
    width: 0;
  }
}

      HEADER

SECTION

        ASIDE

      FOOTER


来源: stackexchange

问:
nhibernate subclass mapping when both subclasses can be materialized
I have the following classes

```<code>public class Person
{
     public virtual int Id { get; set; }
}
public class Employee : Person
{
     public virtual int EmployeeProperty { get; set; }
}
public class Customer : Person
{
     public virtual int CustomerProperty { get; set; }
}
</code>```

Conceptually a the same Person can be both an Employee and a Customer. Also a Person can exist without either an Employee or Customer record. Using Table Per Subclass how can I get this to work.

As it stands now I don't see a way to get NHibernate to work this way. If I create a Person, and then try to create an Employee using an existing Person Id, NHibernate still tries to insert into Person. Is there a way to get NHibernate to realize that I already have a Person and just want to add the Employee record?

I would prefer to not go to Table Per Class or Table Per Hierarchy if possible.

答:
This doesn't work in practice in OO. You would probably want to follow a route that says a person has the roles of being a Customer and also has the role of being an Employee.

Here is a simple example of why this can't work in general OO terms.

```<code>Person a = new Employee();
Customer b = (Customer)a; // exception
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following classes

public class Person
{
     public virtual int Id { get; set; }
}
public class Employee : Person
{
     public virtual int EmployeeProperty { get; set; }
}
public class Customer : Person
{
     public virtual int CustomerProperty { get; set; }
}

Conceptually a the same Person can be both an Employee and a Customer. Also a Person can exist without either an Employee or Customer record. Using Table Per Subclass how can I get this to work.

As it stands now I don't see a way to get NHibernate to work this way. If I create a Person, and then try to create an Employee using an existing Person Id, NHibernate still tries to insert into Person. Is there a way to get NHibernate to realize that I already have a Person and just want to add the Employee record?

I would prefer to not go to Table Per Class or Table Per Hierarchy if possible.

Body:
This doesn't work in practice in OO. You would probably want to follow a route that says a person has the roles of being a Customer and also has the role of being an Employee.

Here is a simple example of why this can't work in general OO terms.

Person a = new Employee();
Customer b = (Customer)a; // exception


问:
all time conserv same bytes in python
I wouldlike to have same digit/bytes all time (8 bytes)

Example : My first number have 5 decimals after comma : 95.12345 so 8 bytes
          If this number is now 100.12345, I have got 9 bytes. Is it possible to delete the last number to conserv all time 8 bytes like this :

```<code>         100.12345 ===> 100.1234
         1000.1234 ===> 1000.123
</code>```

Thanks for your help !

答:
```<code>x = 95.12345
print(str(x)[:8])
</code>```

95.12345

and, to avoid problem with too short strings, you might do:

```<code>x = 1.00
print("{:0>8s}".format(str(x)[:8]))
</code>```

000001.0

ContentLicense: CC BY-SA 3.0

Title: all time conserv same bytes in python

Body:
I wouldlike to have same digit/bytes all time (8 bytes)

Example : My first number have 5 decimals after comma : 95.12345 so 8 bytes
          If this number is now 100.12345, I have got 9 bytes. Is it possible to delete the last number to conserv all time 8 bytes like this :

         100.12345 ===> 100.1234
         1000.1234 ===> 1000.123

Thanks for your help !

Body:
x = 95.12345
print(str(x)[:8])

95.12345

and, to avoid problem with too short strings, you might do:

x = 1.00
print("{:0>8s}".format(str(x)[:8]))

000001.0


问:
Exclude URLs from Django REST Swagger
I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons/django-rest-swagger) doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in settings.py, but there is no real explanation or example of how to use this.

Simply put, I want to exclude any URLs from the docs that start with the following:

```<code>/api/jobs/status/
/api/jobs/parameters/
</code>```

How could I go about doing this?

Thanks in advance for any help offered :P

答:
With new version of django swagger, we don't need to create view to exclude some urls. Below code will disable test2 url.</p>

```<code>from rest_framework_swagger.views import get_swagger_view
urlpatterns1 = [
    url(r'^', include(router.urls)),
    url(r'^test/', include('test.urls')),
    url(r'^test1/', Test2.as_view()),
]

schema_view = get_swagger_view(title='API Documentation', patterns=urlpatterns1)

urlpatterns = urlpatterns1 + [
    url(r'^docs/', schema_view),
    url(r'^test2/', Test2.as_view()),
]
</code>```

Title: Exclude URLs from Django REST Swagger

Body:
I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons/django-rest-swagger) doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in settings.py, but there is no real explanation or example of how to use this.

Simply put, I want to exclude any URLs from the docs that start with the following:

/api/jobs/status/
/api/jobs/parameters/

How could I go about doing this?

Thanks in advance for any help offered :P

Body:
With new version of django swagger, we don't need to create view to exclude some urls. Below code will disable test2 url.

from rest_framework_swagger.views import get_swagger_view
urlpatterns1 = [
    url(r'^', include(router.urls)),
    url(r'^test/', include('test.urls')),
    url(r'^test1/', Test2.as_view()),
]

schema_view = get_swagger_view(title='API Documentation', patterns=urlpatterns1)

urlpatterns = urlpatterns1 + [
    url(r'^docs/', schema_view),
    url(r'^test2/', Test2.as_view()),
]


问:
Issue compiling with different version of gcc and g++
I want to compile a program by entering through SSH the computer at my institution. I want to compile this program by using a different version of gcc and g++, namely a more recent one with repsect to the default installed one. This means that instead of using gcc-4.9.2 and g++-4.9.2 I would like to use gcc-6.3 and g++-6.3. I can find them already on my computer, in fact I have the folder /opt/gcc-6.3, so I don't have to download them. So what I do is the following

```<code>export PATH=/opt/gcc-6.3/bin/:$PATH
export LD_LIBRARY_PATH=/opt/gcc-6.3/lib/:$LD_LIBRARY_PATH
</code>```

but while gcc seems to work, when I try to compile a c++ program with g++ I get

```<code>./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by ./[name_of_the_program].x)
./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./[name_of_the_program].x)
</code>```

Obviously, if that's relevant information, I am not root on this machine.

答:
If you are running on a 64bit machine, you must add

```<code>/opt/linux-gnu_6.x.x/lib64
</code>```

path also to you environment. ( or which path on your machine is used for the libs of this compiler version )

If you get root access you should better add ( or maybe your admin should do! )
your library path information to

```<code>/etc/ld.so.conf.d/gcc63.conf
</code>```

and run sudo ldconfig.

After that you should check with ldd comand, that all chained requirements are fulfilled.

Body:
I want to compile a program by entering through SSH the computer at my institution. I want to compile this program by using a different version of gcc and g++, namely a more recent one with repsect to the default installed one. This means that instead of using gcc-4.9.2 and g++-4.9.2 I would like to use gcc-6.3 and g++-6.3. I can find them already on my computer, in fact I have the folder /opt/gcc-6.3, so I don't have to download them. So what I do is the following

export PATH=/opt/gcc-6.3/bin/:$PATH
export LD_LIBRARY_PATH=/opt/gcc-6.3/lib/:$LD_LIBRARY_PATH

but while gcc seems to work, when I try to compile a c++ program with g++ I get

./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by ./[name_of_the_program].x)
./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./[name_of_the_program].x)

Obviously, if that's relevant information, I am not root on this machine.

Body:
If you are running on a 64bit machine, you must add

/opt/linux-gnu_6.x.x/lib64

path also to you environment. ( or which path on your machine is used for the libs of this compiler version )

If you get root access you should better add ( or maybe your admin should do! )
your library path information to

/etc/ld.so.conf.d/gcc63.conf

and run sudo ldconfig.

After that you should check with ldd comand, that all chained requirements are fulfilled.


问:
Make Label Straight using AWCollectionViewDialLayout – Cocoa Controls
I am using AWCollectionViewDialLayout demo provided on git below is the link:- https://github.com/awdigital/AWCollectionViewDialLayout
I want to make labels straight.
Please Help.

答:
In your specific example, your cell itself is rotated, not just the label. So you cannot only make the label straight and keep the image rotated.

If you still wants to make both element straight, take a look on the source file of the libarary. You are looking for variable called rotationT
 on line 181. Just keep its value to 0 and have a try


问:
Place Autocomplete API returns predictions with incorrect matched_substrings
I am making the following query (key param omitted):

```<code>curl -v 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Helloo&types=geocode'
</code>```

In the results I get, the first prediction is:

```<code>  {
     "description" : "Clinton, New York, NY, United States",
     "id" : "e5c6298aafa5b208354b16aecd163ac85eda40ae",
     "matched_substrings" : [
        {
           "length" : 7,
           "offset" : 0
        }
     ],
     "place_id" : "ChIJUWBgpFBYwokRAprvYGCydhk",
     "reference" : "CkQ8AAAAKW4NgbXbTCXL8MuOOUohazn6TzvRlt8eurqW4QPFCMQXDZDP7nUQXT3c2rb4BYTcIc6fdZH2sQOj-MdNifcsZhIQFK85n69ce3b1Ec93MNxpBBoU4O778Tm2b8-tHTyCiUAZmh00QBI",
     "structured_formatting" : {
        "main_text" : "Clinton",
        "main_text_matched_substrings" : [
           {
              "length" : 7,
              "offset" : 0
           }
        ],
        "secondary_text" : "New York, NY, United States"
     },
     "terms" : [
        {
           "offset" : 0,
           "value" : "Clinton"
        },
        {
           "offset" : 9,
           "value" : "New York"
        },
        {
           "offset" : 19,
           "value" : "NY"
        },
        {
           "offset" : 23,
           "value" : "United States"
        }
     ],
     "types" : [ "neighborhood", "political", "geocode" ]
  },
</code>```

You'll notice "Clinton" does not appear in my input string. Where is this result coming from? Why am I getting it? The docs say that matched_subtrings

contains an array with offset value and length. These describe the location of the entered term in the prediction result text, so that the term can be highlighted if desired.

which is clearly not the case here.

答:
You must have messed something up, your request does not actually return those predictions, it returns 2 geocodes that match your input:

```<code>"predictions" : [
   {
      "description" : "Helloo Creek, Halls Creek, New South Wales, Australia",
      "matched_substrings" : [
         {
            "length" : 6,
            "offset" : 0
         }
      ],
      "place_id" : "ChIJWVba98sSoGsRZDAiQHlxv6I",
      ...
  },
  {
      "description" : "Helloop, Achtmaal, Netherlands",
      "id" : "5f9eb5caffb95c218e8c9ef002aabf7ae85d597e",
      "matched_substrings" : [
         {
            "length" : 6,
            "offset" : 0
         }
      ],
      "place_id" : "ChIJQdEGANsaxEcRUJeH7LZlmBk",
      ...
</code>```

If you ever have a similar problem again, please file a bug here.

Body:
I am making the following query (key param omitted):

curl -v 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Helloo&types=geocode'

In the results I get, the first prediction is:

  {
     "description" : "Clinton, New York, NY, United States",
     "id" : "e5c6298aafa5b208354b16aecd163ac85eda40ae",
     "matched_substrings" : [
        {
           "length" : 7,
           "offset" : 0
        }
     ],
     "place_id" : "ChIJUWBgpFBYwokRAprvYGCydhk",
     "reference" : "CkQ8AAAAKW4NgbXbTCXL8MuOOUohazn6TzvRlt8eurqW4QPFCMQXDZDP7nUQXT3c2rb4BYTcIc6fdZH2sQOj-MdNifcsZhIQFK85n69ce3b1Ec93MNxpBBoU4O778Tm2b8-tHTyCiUAZmh00QBI",
     "structured_formatting" : {
        "main_text" : "Clinton",
        "main_text_matched_substrings" : [
           {
              "length" : 7,
              "offset" : 0
           }
        ],
        "secondary_text" : "New York, NY, United States"
     },
     "terms" : [
        {
           "offset" : 0,
           "value" : "Clinton"
        },
        {
           "offset" : 9,
           "value" : "New York"
        },
        {
           "offset" : 19,
           "value" : "NY"
        },
        {
           "offset" : 23,
           "value" : "United States"
        }
     ],
     "types" : [ "neighborhood", "political", "geocode" ]
  },

You'll notice "Clinton" does not appear in my input string. Where is this result coming from? Why am I getting it? The docs say that matched_subtrings

contains an array with offset value and length. These describe the location of the entered term in the prediction result text, so that the term can be highlighted if desired.

which is clearly not the case here.

Body:
You must have messed something up, your request does not actually return those predictions, it returns 2 geocodes that match your input:

"predictions" : [
   {
      "description" : "Helloo Creek, Halls Creek, New South Wales, Australia",
      "matched_substrings" : [
         {
            "length" : 6,
            "offset" : 0
         }
      ],
      "place_id" : "ChIJWVba98sSoGsRZDAiQHlxv6I",
      ...
  },
  {
      "description" : "Helloop, Achtmaal, Netherlands",
      "id" : "5f9eb5caffb95c218e8c9ef002aabf7ae85d597e",
      "matched_substrings" : [
         {
            "length" : 6,
            "offset" : 0
         }
      ],
      "place_id" : "ChIJQdEGANsaxEcRUJeH7LZlmBk",
      ...

If you ever have a similar problem again, please file a bug here.


问:
how can i send http post request from localhost:5000 to localhost:3000
I'm trying to send a http post request from application running on localhost:5000 to my server at localhost:3000

this angular script is running on localhost:5000

```<code>    var data = {name:"john", description:"100"};
    var url = 'localhost:3000/razor';

    $http.post(url, data).then(function(response){
      if(response.data){
        console.log("success");
      } else {
        console.log("failure");
      }
    });
</code>```

localhost:3000 is not receiving any POST request. What should I do?
Error in console -

```<code>Error: A network error occurred.
rg/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:107:276
p@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:102:434
n/b<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:100:207
h/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:133:460
$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:309
$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:144:412
$evalAsync/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:398
f@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:47:146
kg/k.defer/c<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:50:68
 Possibly unhandled rejection: {}
</code>```

答: Without http in front of the url, the url becomes relative to the current url which is 'http://localhost:5000', so the url that you're posting to becomes 'http://localhost:5000/localhost:3000/razor', but when you add http in front of the url, it becomes absolute url .

Body:
I'm trying to send a http post request from application running on localhost:5000 to my server at localhost:3000

this angular script is running on localhost:5000

    var data = {name:"john", description:"100"};
    var url = 'localhost:3000/razor';

    $http.post(url, data).then(function(response){
      if(response.data){
        console.log("success");
      } else {
        console.log("failure");
      }
    });

localhost:3000 is not receiving any POST request. What should I do?
Error in console -

Error: A network error occurred.
rg/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:107:276
p@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:102:434
n/b<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:100:207
h/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:133:460
$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:309
$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:144:412
$evalAsync/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:398
f@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:47:146
kg/k.defer/c<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:50:68
 Possibly unhandled rejection: {}


问:
Cannot allocate a new connection: 16 connections already opened RMySQL
I am very new to shiny and R but using shiny I am trying to connect to a database fetch the data from there. When I try to access my RShiny work on browser continuously I got an error like Cannot allocate a new connection: 16 connections already opened. How can I overcome this error or RShiny only expecting 16 users at a time? I have got another stack post here RStudio Shiny Error mysqlNewConnection maximum of 16 connections but the explanation was not clear on the above URL.

答:
Fast solution

If you get this issue, you should first run the following code interactively to disconnect all your connexions to the MySQL database:

```<code>lapply(dbListConnections(MySQL()), dbDisconnect)
</code>```

(Note that you can replace MySQL() by another DBI Driver, if you use another database management system).

Faster solution

Just restart R session : command/ctrl + shift + F10 on RStudio

How to avoid this issue

You need to tell shiny how to disconnect properly. That part depends on the use case. If you start a connexion each time you start shiny, you could add inside server.ui:

```<code>session$onSessionEnded(function(){
    dbDisconnect(con)
}
</code>```

Where con is your connexion.
If you start a connexion each time you run a query, you must disconnect immediately after the query has run.

You should also take a look at the pool package which is suggested by the shiny team to manage connexions.
There is also a very helpful section on Shiny Articles on database.

ContentLicense: CC BY-SA 4.0

Body:
Fast solution

If you get this issue, you should first run the following code interactively to disconnect all your connexions to the MySQL database:

lapply(dbListConnections(MySQL()), dbDisconnect)

(Note that you can replace MySQL() by another DBI Driver, if you use another database management system).

Faster solution

Just restart R session : command/ctrl + shift + F10 on RStudio

How to avoid this issue

You need to tell shiny how to disconnect properly. That part depends on the use case. If you start a connexion each time you start shiny, you could add inside server.ui:

session$onSessionEnded(function(){
    dbDisconnect(con)
}

Where con is your connexion.
If you start a connexion each time you run a query, you must disconnect immediately after the query has run.

You should also take a look at the pool package which is suggested by the shiny team to manage connexions.
There is also a very helpful section on Shiny Articles on database.


问:
PowerShell length function
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}
```

<p>Loop is not working, it was working till yesterday.</p>

```Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'
```

答:
```<code>$select1 = Select-String -Pattern "Final result:" -Path $filePath |
    Out-File D:\temp\pattern.txt
</code>```

but Out-File does not generate any output. Hence, $select1 is always $null. Use Tee-Object cmdlet instead as follows:

```<code>$select1 = Select-String -Pattern "Final result:" -Path $filePath |
               Tee-Object -FilePath  "D:\temp\pattern.txt"
</code>```

Tee-Object SYNOPSIS:

Saves command output in a file or variable and also sends it down the
  pipeline.

Edit.

Select-String Finds text in strings and files:

INPUTS:

```<code>System.Management.Automation.PSObject
</code>```

You can pipe any object that has a ToString method to
  Select-String.

OUTPUTS:

Microsoft.PowerShell.Commands.MatchInfo or System.Boolean

By default, the output is a set of MatchInfo objects, one for
  each match found. If you use the Quiet parameter, the output is a
  Boolean value indicating whether the pattern was found.

A set: one needs to distinguish

an empty set from

a one-element set and from

a multi-element set

For instance, the following code snippet could help:

```<code>Function getMatchInfoInfo ( $MatchInfoObject )
{
    $MatchInfoObjectLength=0
    $MatchInfoObjectCount =0
    if ([string]::IsNullOrEmpty($MatchInfoObject)) {
            # no match
    } else {
        if ( $MatchInfoObject.GetType().Name -eq 'MatchInfo') {
            # one match
            $MatchInfoObjectCount =1
            $MatchInfoObjectLength=$MatchInfoObject.Line.Length
        } else  {
            # multiple matches
            $MatchInfoObjectCount =$MatchInfoObject.Line.Count
            $MatchInfoObject | ForEach-Object { $MatchInfoObjectLength += $_.Line.Length}
        }
    }
    ($MatchInfoObjectCount, $MatchInfoObjectLength)                   ### return array
}

$filePath = 'D:\PShell\SO\Files\f44943410.txt'                        ### individual
$select0 = Select-String -Pattern "XFinal Xresult:" -Path $filePath
$x0 = getMatchInfoInfo $select0
Write-Host "select0: $($x0[0]) match(es) of summary length $($x0[1])"

$select1 = Select-String -Pattern "Final result:" -Path $filePath |
               Tee-Object -FilePath "$env:TEMP\pattern.txt"
$x1 = getMatchInfoInfo $select1
Write-Host "select1: $($x1[0]) match(es) of summary length $($x1[1])"

$select2 = $select1.Line | Select-String -Pattern "Passed"             ### pipe
$x2 = getMatchInfoInfo $select2
Write-Host "select2: $($x2[0]) match(es) of summary length $($x2[1])"
</code>```

Output:

```<code>PS D:\PShell> .\SO\q44943410.ps1

select0: 0 match(es) of summary length 0
select1: 2 match(es) of summary length 60
select2: 1 match(es) of summary length 24
</code>```

Title: PowerShell length function

Body:
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}

Loop is not working, it was working till yesterday.

Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'

Body:
$select1 = Select-String -Pattern "Final result:" -Path $filePath |
    Out-File D:\temp\pattern.txt

but Out-File does not generate any output. Hence, $select1 is always $null. Use Tee-Object cmdlet instead as follows:

$select1 = Select-String -Pattern "Final result:" -Path $filePath |
               Tee-Object -FilePath  "D:\temp\pattern.txt"

Tee-Object SYNOPSIS:

Saves command output in a file or variable and also sends it down the
  pipeline.

Edit.

Select-String Finds text in strings and files:

INPUTS:

System.Management.Automation.PSObject

You can pipe any object that has a ToString method to
  Select-String.

OUTPUTS:

Microsoft.PowerShell.Commands.MatchInfo or System.Boolean

By default, the output is a set of MatchInfo objects, one for
  each match found. If you use the Quiet parameter, the output is a
  Boolean value indicating whether the pattern was found.

A set: one needs to distinguish

an empty set from

a one-element set and from

a multi-element set

For instance, the following code snippet could help:

Function getMatchInfoInfo ( $MatchInfoObject )
{
    $MatchInfoObjectLength=0
    $MatchInfoObjectCount =0
    if ([string]::IsNullOrEmpty($MatchInfoObject)) {
            # no match
    } else {
        if ( $MatchInfoObject.GetType().Name -eq 'MatchInfo') {
            # one match
            $MatchInfoObjectCount =1
            $MatchInfoObjectLength=$MatchInfoObject.Line.Length
        } else  {
            # multiple matches
            $MatchInfoObjectCount =$MatchInfoObject.Line.Count
            $MatchInfoObject | ForEach-Object { $MatchInfoObjectLength += $_.Line.Length}
        }
    }
    ($MatchInfoObjectCount, $MatchInfoObjectLength)                   ### return array
}

$filePath = 'D:\PShell\SO\Files\f44943410.txt'                        ### individual
$select0 = Select-String -Pattern "XFinal Xresult:" -Path $filePath
$x0 = getMatchInfoInfo $select0
Write-Host "select0: $($x0[0]) match(es) of summary length $($x0[1])"

$select1 = Select-String -Pattern "Final result:" -Path $filePath |
               Tee-Object -FilePath "$env:TEMP\pattern.txt"
$x1 = getMatchInfoInfo $select1
Write-Host "select1: $($x1[0]) match(es) of summary length $($x1[1])"

$select2 = $select1.Line | Select-String -Pattern "Passed"             ### pipe
$x2 = getMatchInfoInfo $select2
Write-Host "select2: $($x2[0]) match(es) of summary length $($x2[1])"

Output:

PS D:\PShell> .\SO\q44943410.ps1

select0: 0 match(es) of summary length 0
select1: 2 match(es) of summary length 60
select2: 1 match(es) of summary length 24


问:
iOS Mapkit Annotation is not getting draggable
I am new to iOS development and I need to implement a draggable annotation in iOS maps. my code is given below.whater ever I do I can't get a draggable annotation can anyone help with the annotations  after that  I need  to get address of the location where the pin is pointing

RegistrationViewController.swift

```<code>class RegistrationViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        var centerLocation = CLLocationCoordinate2DMake(12.964370125970357, 77.59643554937497)
        var mapspan = MKCoordinateSpanMake(0.01, 0.01)
        var mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
        self.mapView.setRegion(mapregion, animated: true)

        let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
        mapView.addAnnotation(pin)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        if annotation is MKPointAnnotation {
            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
            pinAnnotationView.pinColor = .purple
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            return pinAnnotationView
        }

        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch newState {
        case .starting:
            view.dragState = .dragging
        case .ending, .canceling:
            view.dragState = .none
        default: break
        }
    }
</code>```

pinAnnotation.swift

```<code>import MapKit

class pinAnnotation:NSObject,MKAnnotation {
    var title:String?
    var subtitle: String?
    var coordinate: CLLocationCoordinate2D
    init(title:String,subtitle:String,coordinate:CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}
</code>```

答:
You have the first step done by setting the isDraggable property to true.
Now you only need to handle when the user stops dragging and drops the annotation, see:
how to manage drag and drop for MKAnnotationView on IOS

Besides, your pinAnnotation should have a settable coordinates.

From Apple documentation:

Marking Your Annotation View as Draggable Annotation views provide
  built-in dragging support, which makes it very easy to drag
  annotations around the map and to ensure that the annotation data is
  updated accordingly. To implement minimal support for dragging:

In your annotation objects, implement the setCoordinate: method to
  allow the map view to update the annotation’s coordinate point. When
  creating your annotation view, set its draggable property to YES. When
  the user touches and holds a draggable annotation view, the map view
  begins a drag operation for it. As the drag operation progresses, the
  map view calls the
  mapView:annotationView:didChangeDragState:fromOldState: method of its
  delegate to notify it of changes to the drag state of your view. You
  can use this method to affect or respond to the drag operation.

To animate your view during a drag operation, implement a custom
  dragState method in your annotation view. As the map view processes
  drag-related touch events, it updates the dragState property of the
  affected annotation view. Implementing a custom dragState method gives
  you a chance to intercept these changes and perform additional
  actions, such as animating the appearance of your view. For example,
  the MKPinAnnotationView class raises the pin off the map when a drag
  operation starts and drops the pin back down on the map when it ends.

You are missing the mapView:annotationView:didChangeDragState:fromOldState: method

Body:
I am new to iOS development and I need to implement a draggable annotation in iOS maps. my code is given below.whater ever I do I can't get a draggable annotation can anyone help with the annotations  after that  I need  to get address of the location where the pin is pointing

RegistrationViewController.swift

class RegistrationViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,MKMapViewDelegate{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        var centerLocation = CLLocationCoordinate2DMake(12.964370125970357, 77.59643554937497)
        var mapspan = MKCoordinateSpanMake(0.01, 0.01)
        var mapregion = MKCoordinateRegionMake(centerLocation, mapspan)
        self.mapView.setRegion(mapregion, animated: true)

        let pin = pinAnnotation(title:"hello",subtitle:"how are you",coordinate:centerLocation)
        mapView.addAnnotation(pin)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        if annotation is MKPointAnnotation {
            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
            pinAnnotationView.pinColor = .purple
            pinAnnotationView.isDraggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true

            return pinAnnotationView
        }

        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch newState {
        case .starting:
            view.dragState = .dragging
        case .ending, .canceling:
            view.dragState = .none
        default: break
        }
    }

pinAnnotation.swift

import MapKit

class pinAnnotation:NSObject,MKAnnotation {
    var title:String?
    var subtitle: String?
    var coordinate: CLLocationCoordinate2D
    init(title:String,subtitle:String,coordinate:CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}


问:
Store mysql query rows in variable for later use
I'm doing a monitoring system project in which I have Arduino sensors data being sent to a node.js server (thru GET requests) and then stored in a MySQL DB.

Whenvever I successfully send data to the server, it connects to the MySQL DB and queries the last 5 received records to do some processing.

Therefore, I need to store the rows of those 5 records in a variable for later use. Meaning that I have to get rows from a connection.query in a variable.

I read that the fact that I'm not able to do this is because node.js being async. So my questions are:

Is it possible to do the described tasks the way I'm trying?

If not, is there any other way to do so?

I'm not putting the whole code here but I'm running a separated test that also doesn't run properly. Here it is:

```<code>var mysql = require('mysql');

var con = mysql.createConnection({
      host    : "127.0.0.1",
      user    : "root",
      password: "xxxx",
      database: "mydb",
      port    : 3306
});
var queryString = "SELECT id, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM tempdata ORDER BY id DESC LIMIT 5";

con.connect(function(err) {
  if (err) throw err;
});

var result_arr = [];
function setValue (value) {
  result_arr = value;
}

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});

console.log(result_arr);
</code>```

It logs:

```<code>[]
</code>```

But if I uncomment console.log(rows); it logs what I need to store in the variable result_arr.

Thanks in advance to all.

答:
You're seeing this behaviour because con.query(...) is an asynchronous function. That means that:

```<code>console.log(result_arr);
</code>```

Runs before:

```<code>con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});
</code>```

(Specifically, the setValue(rows) call)

To fix this in your example, you can just do:

```<code>con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    setValue(rows);
    console.log(result_arr);
  }
});
</code>```

If you want to do more than just log the data, then you can call a function which depends on result_arr from the con.query callback, like this:

```<code>con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    setValue(rows);
    doCleverStuffWithData();
  }
});

function doCleverStuffWithData() {
    // Do something with result_arr
}
</code>```

Body:
I'm doing a monitoring system project in which I have Arduino sensors data being sent to a node.js server (thru GET requests) and then stored in a MySQL DB.

Whenvever I successfully send data to the server, it connects to the MySQL DB and queries the last 5 received records to do some processing.

Therefore, I need to store the rows of those 5 records in a variable for later use. Meaning that I have to get rows from a connection.query in a variable.

I read that the fact that I'm not able to do this is because node.js being async. So my questions are:

Is it possible to do the described tasks the way I'm trying?

If not, is there any other way to do so?

I'm not putting the whole code here but I'm running a separated test that also doesn't run properly. Here it is:

var mysql = require('mysql');

var con = mysql.createConnection({
      host    : "127.0.0.1",
      user    : "root",
      password: "xxxx",
      database: "mydb",
      port    : 3306
});
var queryString = "SELECT id, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM tempdata ORDER BY id DESC LIMIT 5";

con.connect(function(err) {
  if (err) throw err;
});

var result_arr = [];
function setValue (value) {
  result_arr = value;
}

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});

console.log(result_arr);

It logs:

[]

But if I uncomment console.log(rows); it logs what I need to store in the variable result_arr.

Thanks in advance to all.

Body:
You're seeing this behaviour because con.query(...) is an asynchronous function. That means that:

console.log(result_arr);

Runs before:

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});

(Specifically, the setValue(rows) call)

To fix this in your example, you can just do:

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    setValue(rows);
    console.log(result_arr);
  }
});

If you want to do more than just log the data, then you can call a function which depends on result_arr from the con.query callback, like this:

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    setValue(rows);
    doCleverStuffWithData();
  }
});

function doCleverStuffWithData() {
    // Do something with result_arr
}


问:
Zuul prefix when more than a single /path
I have a service with this path http://myhost.com/v2/1234/brand/order/issues/123 that needs to send the actual call to http://anotherhost.com/issues/123.

If I want to avoid the solution to write a ZuulFilter

Is there a way, with the configuration to say: the prefix is /v2/*/*/order/issues and just use 123?

```<code>zuul:
  routes:
    test2:
      path: /v2/*/*/orders/issues/**
      url: http://anotherhost.com/issues/
      stripPrefix: true
</code>```

答:
No, there's no way to configure such behaviour. You need to create custom ZuulFilter

By default Zuul will only strip prefixes that do not contain special characters. e.g.

```<code>zuul:
  routes:
    test1:
      path: /orders/**   <--- '/orders' is stripped
      url: http://anotherhost.com/issues/
    test2:
      path: /*/orders/**   <--- nothing is stripped
      url: http://anotherhost.com/issues/
</code>```

Body:
I have a service with this path http://myhost.com/v2/1234/brand/order/issues/123 that needs to send the actual call to http://anotherhost.com/issues/123.

If I want to avoid the solution to write a ZuulFilter

Is there a way, with the configuration to say: the prefix is /v2/*/*/order/issues and just use 123?

zuul:
  routes:
    test2:
      path: /v2/*/*/orders/issues/**
      url: http://anotherhost.com/issues/
      stripPrefix: true

Body:
No, there's no way to configure such behaviour. You need to create custom ZuulFilter

By default Zuul will only strip prefixes that do not contain special characters. e.g.

zuul:
  routes:
    test1:
      path: /orders/**   <--- '/orders' is stripped
      url: http://anotherhost.com/issues/
    test2:
      path: /*/orders/**   <--- nothing is stripped
      url: http://anotherhost.com/issues/


问:
Restricting number of cores used
I'm trying to restrict the number of cores that a tf session uses but it's not working. This is how I'm initializing the session:

```<code>sess = tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=1,
                                        intra_op_parallelism_threads=1,
                                        use_per_session_threads=True))
</code>```

The system has 12 cores / 24 threads, and I can see that 40-60% of them are being used at any given point in time. The system also has 8 GPUs, but I construct the whole graph with tf.device('/cpu:0').

UPDATE: To clarify, the graph itself is a simple LSTM-RNN, that hews very closely to the examples in the tf source code. For completeness here's the full graph:

```<code>node_input  = tf.placeholder(tf.float32, [n_steps, batch_size, input_size],  name = 'input')
list_input  = [tf.reshape(i, (batch_size, input_size)) for i in tf.split(0, n_steps, node_input)]
node_target = tf.placeholder(tf.float32, [n_steps, batch_size, output_size], name = 'target')
node_target_flattened = tf.reshape(tf.transpose(node_target, perm = [1, 0, 2]), [-1, output_size])
node_max_length = tf.placeholder(tf.int32, name = 'batch_max_length')
node_cell_initializer = tf.random_uniform_initializer(-0.1, 0.1)
node_cell = LSTMCell(state_size, input_size, initializer = node_cell_initializer)
node_initial_state = node_cell.zero_state(batch_size, tf.float32)
nodes_output, nodes_state = rnn(node_cell,
                                list_input,
                                initial_state = node_initial_state,
                                sequence_length = node_max_length)
node_output_flattened = tf.reshape(tf.concat(1, nodes_output), [-1, state_size])
node_softmax_w = tf.Variable(tf.random_uniform([state_size, output_size]), name = 'softmax_w')
node_softmax_b = tf.Variable(tf.zeros([output_size]), name = 'softmax_b')
node_logit = tf.matmul(node_output_flattened, node_softmax_w) + node_softmax_b
node_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(node_logit, node_target_flattened, name = 'cross_entropy')
node_loss = tf.reduce_mean(node_cross_entropy, name = 'loss')
node_optimizer = tf.train.AdamOptimizer().minimize(node_loss)
node_op_initializer = tf.initialize_all_variables()
</code>```

One important thing to note is that if the first time I call tf.Session, I pass in the appropriate parameters, then the session does only run on a single core. The problem is that in subsequent runs, I am unable to change the behavior, even though I use use_per_session_threads which is supposed to specifically allow for session-specific settings. I.e. even after I close the session using sess.close() and start a new one with new options, the original behavior remains unchanged unless I restart the python kernel (which is very costly because it takes it nearly an hour to load my data).

答:
use_per_session_threads will only affect the inter_op_parallelism_threads but not the intra_op_parallelism_threads. The intra_op_parallelism_threads will be used for the Eigen thread pool (see here) which is always global, thus subsequent sessions will not influence this anymore.

Note that there are other TF functions which can also trigger the initialization of the Eigen thread pool, so it can happen that it's already initialized before you create the first tf.Session. One example is tensorflow.python.client.device_lib.list_local_devices().

I solve this in a way that very early in my Python script, I create a dummy session with the appropriate values.

Title: Restricting number of cores used

Body:
I'm trying to restrict the number of cores that a tf session uses but it's not working. This is how I'm initializing the session:

sess = tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=1,
                                        intra_op_parallelism_threads=1,
                                        use_per_session_threads=True))

The system has 12 cores / 24 threads, and I can see that 40-60% of them are being used at any given point in time. The system also has 8 GPUs, but I construct the whole graph with tf.device('/cpu:0').

UPDATE: To clarify, the graph itself is a simple LSTM-RNN, that hews very closely to the examples in the tf source code. For completeness here's the full graph:

node_input  = tf.placeholder(tf.float32, [n_steps, batch_size, input_size],  name = 'input')
list_input  = [tf.reshape(i, (batch_size, input_size)) for i in tf.split(0, n_steps, node_input)]
node_target = tf.placeholder(tf.float32, [n_steps, batch_size, output_size], name = 'target')
node_target_flattened = tf.reshape(tf.transpose(node_target, perm = [1, 0, 2]), [-1, output_size])
node_max_length = tf.placeholder(tf.int32, name = 'batch_max_length')
node_cell_initializer = tf.random_uniform_initializer(-0.1, 0.1)
node_cell = LSTMCell(state_size, input_size, initializer = node_cell_initializer)
node_initial_state = node_cell.zero_state(batch_size, tf.float32)
nodes_output, nodes_state = rnn(node_cell,
                                list_input,
                                initial_state = node_initial_state,
                                sequence_length = node_max_length)
node_output_flattened = tf.reshape(tf.concat(1, nodes_output), [-1, state_size])
node_softmax_w = tf.Variable(tf.random_uniform([state_size, output_size]), name = 'softmax_w')
node_softmax_b = tf.Variable(tf.zeros([output_size]), name = 'softmax_b')
node_logit = tf.matmul(node_output_flattened, node_softmax_w) + node_softmax_b
node_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(node_logit, node_target_flattened, name = 'cross_entropy')
node_loss = tf.reduce_mean(node_cross_entropy, name = 'loss')
node_optimizer = tf.train.AdamOptimizer().minimize(node_loss)
node_op_initializer = tf.initialize_all_variables()

One important thing to note is that if the first time I call tf.Session, I pass in the appropriate parameters, then the session does only run on a single core. The problem is that in subsequent runs, I am unable to change the behavior, even though I use use_per_session_threads which is supposed to specifically allow for session-specific settings. I.e. even after I close the session using sess.close() and start a new one with new options, the original behavior remains unchanged unless I restart the python kernel (which is very costly because it takes it nearly an hour to load my data).


问:
JavaFX returning null when getting objects from FXML
Ok, so I made my layout and I'm trying to get 2 labels, progressbar and 2 textFields.

I get them like this:

```<code>@FXML private TextField instDir;
@FXML private TextField jsonDir;
@FXML private ProgressBar progressBar;
@FXML private Label pText;
@FXML private Label error;
</code>```

But only ones that aren't null are instDir and jsonDir.
My FXML file: https://hastebin.com/cohuhidobi.xml
Parts of Java class where I'm using objects:

```<code>void setProgressBar(float i, float max) {
    if(progressBar != null) {
        progressBar.setProgress(i / max);
    }else{
        System.out.println("progressBar is null");
    }
    if(pText != null) {
        pText.setText((int) i + "/" + (int) max);
    }else{
        System.out.println("pText is null");
    }
    System.out.println((int) i + "/" + (int) max);
    //text = (int)i+"/"+(int)max;
}
</code>```

Which always returns both as null.

All of the Objects I want are registered in the controller

Thanks for the help!

答:
Check if your controller implements Initializable and has this structure:</p>

```<code>public class FXMLController implements Initializable {

    @FXML private TextField instDir;
    @FXML private TextField jsonDir;
    @FXML private ProgressBar progressBar;
    @FXML private Label pText;
    @FXML private Label error;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // ...
    }

    //Getters and setters
}
</code>```

Body:
Ok, so I made my layout and I'm trying to get 2 labels, progressbar and 2 textFields.

I get them like this:

@FXML private TextField instDir;
@FXML private TextField jsonDir;
@FXML private ProgressBar progressBar;
@FXML private Label pText;
@FXML private Label error;

But only ones that aren't null are instDir and jsonDir.
My FXML file: https://hastebin.com/cohuhidobi.xml
Parts of Java class where I'm using objects:

void setProgressBar(float i, float max) {
    if(progressBar != null) {
        progressBar.setProgress(i / max);
    }else{
        System.out.println("progressBar is null");
    }
    if(pText != null) {
        pText.setText((int) i + "/" + (int) max);
    }else{
        System.out.println("pText is null");
    }
    System.out.println((int) i + "/" + (int) max);
    //text = (int)i+"/"+(int)max;
}

Which always returns both as null.

All of the Objects I want are registered in the controller

Thanks for the help!

Body:
Check if your controller implements Initializable and has this structure:

public class FXMLController implements Initializable {

    @FXML private TextField instDir;
    @FXML private TextField jsonDir;
    @FXML private ProgressBar progressBar;
    @FXML private Label pText;
    @FXML private Label error;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // ...
    }

    //Getters and setters
}


问:
Error while installing Bot Framework Emulator on Ubuntu
I am unable to install microsoft emulator on ubuntu 16.04.

I downloaded BotFramework-Emulator-3.5.29.zip file from the portal, then extracted it and run npm install successfully (but got the following message):

```<code>npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-mac@^1.0.1(node_modules/7zip-bin/node_modules/7zip-bin-mac):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-mac@1.0.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-win@^2.1.0 (node_modules/7zip-bin/node_modules/7zip-bin-win):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-win@2.1.0: wanted {"os":"win32","arch":"any"} (current: {"os":"linux","arch":"x64"})
</code>```

Then gulp build-app throws the following error:

```<code>[14:32:40] Using gulpfile /var/www/BotFramework-Emulator-3.5.29/gulpfile.js
[14:32:40] Starting 'clean'...
[14:32:40] Finished 'clean' after 23 ms
[14:32:40] Starting 'build-app'...
[14:32:40] Compiling TypeScript files using tsc version 2.1.5
[14:32:46] [tsc] > node_modules/botframework-directlinejs/built/directLine.d.ts(204,13): error TS2304: Cannot find name 'object'.
[14:32:46] Failed to compile TypeScript: Error: tsc command has exited with code:1

  events.js:160
  throw er; // Unhandled 'error' event
  ^
Error: Failed to compile: tsc command has exited with code:1
</code>```

答:
Maybe one strange thing: in package.json there is a dependency "typescript": "2.2.2", but in your log it says Compiling TypeScript files using tsc version 2.1.5. Isn't there a problem of TypeScript version?

Can you try to update Typescript to 2.2 and run everything again?

It seems that your error error TS2304: Cannot find name 'object'. is due to the fact that object is keyword in TS2.2 (see for example this reply stating the same)

Body:
I am unable to install microsoft emulator on ubuntu 16.04.

I downloaded BotFramework-Emulator-3.5.29.zip file from the portal, then extracted it and run npm install successfully (but got the following message):

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-mac@^1.0.1(node_modules/7zip-bin/node_modules/7zip-bin-mac):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-mac@1.0.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-win@^2.1.0 (node_modules/7zip-bin/node_modules/7zip-bin-win):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-win@2.1.0: wanted {"os":"win32","arch":"any"} (current: {"os":"linux","arch":"x64"})

Then gulp build-app throws the following error:

[14:32:40] Using gulpfile /var/www/BotFramework-Emulator-3.5.29/gulpfile.js
[14:32:40] Starting 'clean'...
[14:32:40] Finished 'clean' after 23 ms
[14:32:40] Starting 'build-app'...
[14:32:40] Compiling TypeScript files using tsc version 2.1.5
[14:32:46] [tsc] > node_modules/botframework-directlinejs/built/directLine.d.ts(204,13): error TS2304: Cannot find name 'object'.
[14:32:46] Failed to compile TypeScript: Error: tsc command has exited with code:1

  events.js:160
  throw er; // Unhandled 'error' event
  ^
Error: Failed to compile: tsc command has exited with code:1


问:
Unable to upload excel in AngularJS UI Grid using SheetJS in IE11
I am trying to Upload an excel file at client side in AngularJS UI Grid using SheetJS. The code works fine in Chrome and Firefox, but on IE it gives the following error Object doesn't support property or method 'readAsBinaryString'

I tried various solution on stack overflow like using readAsBinaryArray or readAsText instead of using readAsBinaryString but I am unable to solve my problem.

I am sharing my code below it consists of 3 files: index.html, app.js and main.css

Code for index.html is as below

```<code>  <!DOCTYPE html>
    <html ng-app="app">

  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=11" />
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
    <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
    <script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/xlsx.full.min.js"></script>
    <script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/ods.js"></script>
    <script src="https://github.com/SheetJS/js-xlsx/blob/master/shim.js"></script>
    <script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.js"></script>
    <link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.css" />
    <link rel="stylesheet" href="css/main.css" type="text/css" />
  </head>

  <body>
    <div ng-controller="MainCtrl as vm">

      <div id="grid1" ui-grid="vm.gridOptions" class="grid">
        <div class="grid-msg-overlay" ng-show="!vm.gridOptions.data.length">
          <div class="msg">
            <div class="center">
              <span class="muted">Select Excel File</span>
              <br />
              <input ng-attr-type="{{'file'}}" accept=".xls,.xlsx,.csv" fileread="" opts="vm.gridOptions" multiple="false" />
            </div>
          </div>
        </div>
      </div>
          <br />
          <br />
          <button type="button" class="btn btn-success" ng-    click="vm.reset()">Reset Grid</button>
          <span>  </span>

         <button type="button" class="btn btn-success" ng-click="">Save</button>

    </div>
    <script src="js/app.js"></script>
  </body>

   </html>
</code>```

Code for app.js is as below

```<code> (function (angular) {
    "use strict";

    angular.module('app', ['ui.grid']).controller('MainCtrl', ['$scope',          function ($scope) {
     var vm = this;
     vm.gridOptions = {};

     vm.reset = reset;

    function reset() {
      vm.gridOptions.data = [];
      vm.gridOptions.columnDefs = [];
     }
    }])

    .directive("fileread", [function () {
    return {
    scope: {
      opts: '='
    },
      link: function ($scope, $elm, $attrs) {
      $elm.on('change', function (changeEvent) {
        var reader = new FileReader();

        reader.onload = function (evt) {
          $scope.$apply(function () {
            var data = evt.target.result;

            var workbook = XLSX.read(data, {type: 'binary'});

            var headerNames = XLSX.utils.sheet_to_json(   workbook.Sheets[workbook.SheetNames[0]], { header: 1 })[0];

            var data = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]]);

            $scope.opts.columnDefs = [];
            headerNames.forEach(function (h) {
              $scope.opts.columnDefs.push({ field: h });
            });

            $scope.opts.data = data;

            $elm.val(null);
          });
        };

        reader.readAsBinaryString(changeEvent.target.files[0]);
      });
     }
    }
    }]);
</code>```

Code for main.css

```<code>body {
 padding: 20px;
 }

 .grid {
 width: 100%;
 height: 250px;
 }

 .grid-msg-overlay {
 position: absolute;
 top: 0;
 bottom: 0;
 width: 100%;
 background: rgba(0, 0, 0, 0.4);
 }

 .grid-msg-overlay .msg {
 opacity: 1;
 position: absolute;
 top: 20%;
 left: 20%;
 width: 60%;
 height: 50%;
 background-color: #eee;
 border-radius: 4px;
 border: 1px solid #555;
 text-align: center;
 font-size: 24px;
 display: table;
 }

 .grid-msg-overlay .msg > .center {
 display: table-cell;
 vertical-align: middle;
 }

.grid input[type="file"] {
font-size: 14px;
display: inline-block;
}
</code>```

Please can someone help me to understand how can I resolve this issue

答:
IE does not implement the FileReader readAsBinaryString() method. However, as per the SheetJS documentation, you can test for support, and fallback to readAsArrayBuffer() instead.

```<code>var readAsBinary = "readAsBinaryString" in FileReader;
if (readAsBinary) {
  reader.readAsBinaryString(changeEvent.target.files[0]);
} else {
  reader.readAsArrayBuffer(changeEvent.target.files[0]);
}
</code>```

Then in the unload method you have to handle the result as follows:

```<code>var workbook;
if (readAsBinary) {
  workbook = XLSX.read(data, {type: 'binary'});
} else {
  function fixdata(data) {
    var o = "", l = 0, w = 10240;
    for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
    o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
    return o;
  }
  workbook = XLSX.read(btoa(fixdata(data)), {type: 'base64'});
}
</code>```

Body:
I am trying to Upload an excel file at client side in AngularJS UI Grid using SheetJS. The code works fine in Chrome and Firefox, but on IE it gives the following error Object doesn't support property or method 'readAsBinaryString'

I tried various solution on stack overflow like using readAsBinaryArray or readAsText instead of using readAsBinaryString but I am unable to solve my problem.

I am sharing my code below it consists of 3 files: index.html, app.js and main.css

Code for index.html is as below

  <!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=11" />
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
    <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />

    <link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.css" />
    <link rel="stylesheet" href="css/main.css" type="text/css" />

              Select Excel File

              <input ng-attr-type="{{'file'}}" accept=".xls,.xlsx,.csv" fileread="" opts="vm.gridOptions" multiple="false" />

          <button type="button" class="btn btn-success" ng-    click="vm.reset()">Reset Grid</button>

         <button type="button" class="btn btn-success" ng-click="">Save</button>

Code for app.js is as below

 (function (angular) {
    "use strict";

    angular.module('app', ['ui.grid']).controller('MainCtrl', ['$scope',          function ($scope) {
     var vm = this;
     vm.gridOptions = {};

     vm.reset = reset;

    function reset() {
      vm.gridOptions.data = [];
      vm.gridOptions.columnDefs = [];
     }
    }])

    .directive("fileread", [function () {
    return {
    scope: {
      opts: '='
    },
      link: function ($scope, $elm, $attrs) {
      $elm.on('change', function (changeEvent) {
        var reader = new FileReader();

        reader.onload = function (evt) {
          $scope.$apply(function () {
            var data = evt.target.result;

            var workbook = XLSX.read(data, {type: 'binary'});

            var headerNames = XLSX.utils.sheet_to_json(   workbook.Sheets[workbook.SheetNames[0]], { header: 1 })[0];

            var data = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]]);

            $scope.opts.columnDefs = [];
            headerNames.forEach(function (h) {
              $scope.opts.columnDefs.push({ field: h });
            });

            $scope.opts.data = data;

            $elm.val(null);
          });
        };

        reader.readAsBinaryString(changeEvent.target.files[0]);
      });
     }
    }
    }]);

Code for main.css

body {
 padding: 20px;
 }

 .grid {
 width: 100%;
 height: 250px;
 }

 .grid-msg-overlay {
 position: absolute;
 top: 0;
 bottom: 0;
 width: 100%;
 background: rgba(0, 0, 0, 0.4);
 }

 .grid-msg-overlay .msg {
 opacity: 1;
 position: absolute;
 top: 20%;
 left: 20%;
 width: 60%;
 height: 50%;
 background-color: #eee;
 border-radius: 4px;
 border: 1px solid #555;
 text-align: center;
 font-size: 24px;
 display: table;
 }

 .grid-msg-overlay .msg > .center {
 display: table-cell;
 vertical-align: middle;
 }

.grid input[type="file"] {
font-size: 14px;
display: inline-block;
}

Please can someone help me to understand how can I resolve this issue

Body:
IE does not implement the FileReader readAsBinaryString() method. However, as per the SheetJS documentation, you can test for support, and fallback to readAsArrayBuffer() instead.

var readAsBinary = "readAsBinaryString" in FileReader;
if (readAsBinary) {
  reader.readAsBinaryString(changeEvent.target.files[0]);
} else {
  reader.readAsArrayBuffer(changeEvent.target.files[0]);
}

Then in the unload method you have to handle the result as follows:

var workbook;
if (readAsBinary) {
  workbook = XLSX.read(data, {type: 'binary'});
} else {
  function fixdata(data) {
    var o = "", l = 0, w = 10240;
    for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
    o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
    return o;
  }
  workbook = XLSX.read(btoa(fixdata(data)), {type: 'base64'});
}


问:
How can I get a child component's watcher's updated value from parent component in Vue 2?
I have two components that are in a parent-child relationship. In the child select component I've defined a watcher for the currently selected value and I want the parent to get the updated value whenever it changes. I tried to use events but the parent can only listen to its own vm.

In the child component

```<code>watch: {
  selected (value) {
    this.$emit('selectedYearChange', value)
  }
}
</code>```

In the parent

```<code>mounted () {
  this.$on('selectedYearChange', function (value) {
    this.selectedYear = value
  })
}
</code>```

This obviously doesn't work because of the reason I mentioned above.

I wasn't able to find relevant examples in the documentation.

答:
html:

```<code><Parent>
  <Child @selected-year-change=HandleChange(data)></Child>
</Parent>
</code>```

Javascript/Child Component:

```<code>watch: {
  selected (value) {
    this.$emit('selectedYearChange', value)
  }
}
</code>```

Javascript/Parent Component:

```<code>   HandleChange: function(data){}
</code>```

good luck. maybe work!

Body:
I have two components that are in a parent-child relationship. In the child select component I've defined a watcher for the currently selected value and I want the parent to get the updated value whenever it changes. I tried to use events but the parent can only listen to its own vm.

In the child component

watch: {
  selected (value) {
    this.$emit('selectedYearChange', value)
  }
}

In the parent

mounted () {
  this.$on('selectedYearChange', function (value) {
    this.selectedYear = value
  })
}

This obviously doesn't work because of the reason I mentioned above.

I wasn't able to find relevant examples in the documentation.

Body:
html:

<Parent>
  <Child @selected-year-change=HandleChange(data)></Child>
</Parent>

Javascript/Child Component:

watch: {
  selected (value) {
    this.$emit('selectedYearChange', value)
  }
}

Javascript/Parent Component:

   HandleChange: function(data){}

good luck. maybe work!


问:
update multiple columns with case/if statement?
Thank you in advance:

I have a table1:

```<code>id       ||   batches  || IC_chips

DRG001   ||   JHL001   || layer1
DRG001   ||   JHL001   || layer2
DRG001   ||   JHL001   || layer3
DRG001   ||   JHL001   || layer4
DRG001   ||   JHL001   || layer5
DRG001   ||   JHL001   || layer6
DRG001   ||   JHL002   || layer7
DRG001   ||   JHL002   || layer8
DRG001   ||   JHL002   || layer9
DRG001   ||   JHL002   || layer10
POQ001   ||   ADG001   || layer1
POQ001   ||   ADG001   || layer2
POQ001   ||   ADG001   || layer3
POQ001   ||   ADG001   || layer4
POQ001   ||   ADG001   || layer5
POQ001   ||   ADG001   || layer6
</code>```

the output table is :

```<code>ID     ||   print_batch_1   ||  Print_batch_2  ||  Count_print_batch_1  || Count_print_batch_2  ||  Batch_count
DRG001 ||   JHL001          ||  JHL002         ||  06                   || 04                    ||  02
POQ001 ||   ADG001          ||  Null           ||  06                   || Null                  ||  01
</code>```

i tried it with an update statement but i am facing an issue when their are more than one Print batches.

this is the code i tried with :

```<code>update tab
set Count_name=b.Count_name
,batch_count=b.batch_count
from
table1 tab
inner join
(
select Name, count(batches) as Count_name, count(distinct batches) as
batch_count
from table1
group by batches) b
on tab.batches=b.batches
</code>```

答:
Please try this -</p>

```<code>update tab B
set Count_name = a.batches, batch_count = batch_cnt
from    (
            select  batches, count(*) batch_cnt
            from    table1 A
            where   a.batches = b.batches
        )
where
    exists (
                select  1
                from    table1 A
                where   a.batches = b.batches
            )
</code>```

Body:
Thank you in advance:

I have a table1:

id       ||   batches  || IC_chips

DRG001   ||   JHL001   || layer1
DRG001   ||   JHL001   || layer2
DRG001   ||   JHL001   || layer3
DRG001   ||   JHL001   || layer4
DRG001   ||   JHL001   || layer5
DRG001   ||   JHL001   || layer6
DRG001   ||   JHL002   || layer7
DRG001   ||   JHL002   || layer8
DRG001   ||   JHL002   || layer9
DRG001   ||   JHL002   || layer10
POQ001   ||   ADG001   || layer1
POQ001   ||   ADG001   || layer2
POQ001   ||   ADG001   || layer3
POQ001   ||   ADG001   || layer4
POQ001   ||   ADG001   || layer5
POQ001   ||   ADG001   || layer6

the output table is :

ID     ||   print_batch_1   ||  Print_batch_2  ||  Count_print_batch_1  || Count_print_batch_2  ||  Batch_count
DRG001 ||   JHL001          ||  JHL002         ||  06                   || 04                    ||  02
POQ001 ||   ADG001          ||  Null           ||  06                   || Null                  ||  01

i tried it with an update statement but i am facing an issue when their are more than one Print batches.

this is the code i tried with :

update tab
set Count_name=b.Count_name
,batch_count=b.batch_count
from
table1 tab
inner join
(
select Name, count(batches) as Count_name, count(distinct batches) as
batch_count
from table1
group by batches) b
on tab.batches=b.batches

Body:
Please try this -

update tab B
set Count_name = a.batches, batch_count = batch_cnt
from    (
            select  batches, count(*) batch_cnt
            from    table1 A
            where   a.batches = b.batches
        )
where
    exists (
                select  1
                from    table1 A
                where   a.batches = b.batches
            )


问:
Get Authenticated info in liferay portlet
How can I get liferay logged-in user info in a portlet? I have the PortletRequest, but I don't know what can I get authenticated-info from request.
getUser is not enough, I need to use again authentication. </p>

答:
If - by saying "authenticated-info" - you mean the username and password: Do not bother. They should never be kept in the session for security reasons (anybody could have access) and you should rather look up protocols like OAuth or use Single-Sign-On Tokens. In fact, if Liferay authentication is done through Single Sign On, Liferay will never even see the password.

If you mean extended information about the user, e.g. the full user object or the permission checker, you can get it from the themeDisplay object, which you can obtain from portalRequest:

```<code>    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
</code>```

Look up the ThemeDisplay interface to get an idea what you can do with it. And don't get irritated by its name, take it as "current context".

Body:
If - by saying "authenticated-info" - you mean the username and password: Do not bother. They should never be kept in the session for security reasons (anybody could have access) and you should rather look up protocols like OAuth or use Single-Sign-On Tokens. In fact, if Liferay authentication is done through Single Sign On, Liferay will never even see the password.

If you mean extended information about the user, e.g. the full user object or the permission checker, you can get it from the themeDisplay object, which you can obtain from portalRequest:

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

Look up the ThemeDisplay interface to get an idea what you can do with it. And don't get irritated by its name, take it as "current context".


问:
File upload fails with angularjs and spring boot
I want to upload file

controller.js

```<code>userService.saveProfile($scope.user.profile.companyLogo).then(function(response){
    if(response.status==201){
        $('#profileModal').hide();
        $scope.load();
    }
});
</code>```

service.js

```<code>saveProfile:function(logo){
            var formData = new FormData();
            formData.append("file",logo);
            var retVal = $http({
                method : 'POST',
                url : '/api/user/profile',
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined},
                data: formData
            }).then(function(response){
                return response;
            });
            return retVal;
        }
</code>```

Controller.java

```<code>@RequestMapping(value="/profile",method = RequestMethod.POST,headers="'Content-Type':'multipart/form-data'")
    public ResponseEntity saveProfile(@RequestBody MultipartFile file){
        System.out.println(file);
        return new ResponseEntity(HttpStatus.CREATED);
    }
</code>```

if I add headers to @RequestMapping I'm getting 404 and if I remove it I'm getting file null

Please suggest me the correct way of doing file upload

答:
It worked!

I removed headers from @RequestMapping and used @RequestPart instead of @RequestBody

```<code>@RequestMapping(value="/profile",method = RequestMethod.POST)
    public ResponseEntity saveProfile(@RequestPart("file") MultipartFile file){
        System.out.println(file);
        return new ResponseEntity(HttpStatus.CREATED);
    }
</code>```

Body:
I want to upload file

controller.js

userService.saveProfile($scope.user.profile.companyLogo).then(function(response){
    if(response.status==201){
        $('#profileModal').hide();
        $scope.load();
    }
});

service.js

saveProfile:function(logo){
            var formData = new FormData();
            formData.append("file",logo);
            var retVal = $http({
                method : 'POST',
                url : '/api/user/profile',
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined},
                data: formData
            }).then(function(response){
                return response;
            });
            return retVal;
        }

Controller.java

@RequestMapping(value="/profile",method = RequestMethod.POST,headers="'Content-Type':'multipart/form-data'")
    public ResponseEntity saveProfile(@RequestBody MultipartFile file){
        System.out.println(file);
        return new ResponseEntity(HttpStatus.CREATED);
    }

if I add headers to @RequestMapping I'm getting 404 and if I remove it I'm getting file null

Please suggest me the correct way of doing file upload

Body:
It worked!

I removed headers from @RequestMapping and used @RequestPart instead of @RequestBody

@RequestMapping(value="/profile",method = RequestMethod.POST)
    public ResponseEntity saveProfile(@RequestPart("file") MultipartFile file){
        System.out.println(file);
        return new ResponseEntity(HttpStatus.CREATED);
    }


问:
Javascript sending data via POST in firefox addon
I have a mysql database, with a php form.  Normally, people use the php form on my website to add to the mysql database.  I have been building a firefox addon to let them use the form without visiting the site directly to add data to the mysql database.  Now I am stuck...

I have the form data I want to add to the mysql database, but how can I send it to the mysql database from the addon?  What's the best way to do this?  Would you send it to the php form first or is there a direct way?  Is it possible to go straight to mysql?  The firefox addon is coded in javascript.

Thanks!

答: It sounds like Ajax would be the way to go. This post may be helpful to you: HTTP POST in javascript in Firefox Extension.</p>


问:
How to sort table by custom defined method
I'm using rails 5 with PostgeSQL and I have model with 2 columns:

```<code>amount: integer
interval_count: integer
</code>```

I have custom method defined in my model amount_per_interval that basically returns amount/interval_count (it calculates it on app level). Now I need to sort whole table by this amount_per_interval value, but I need to do it on database level, because I'm using pagination (and also I have millions of those records so I don't want to load all of them into memory).

Is there any possibility to define such custom ordering on this model? I can't find any solution.

Update:

I basically want to rewrite this SQL:

```<code>SELECT (amount / interval_count) as amount_per_interval FROM my_table ORDER BY amount_per_interval
</code>```

into ActiveRecord's interface and still keep compatibility with pagination and other AR methods.

答:
You could use select and order methods:

```<code>YourModel.select("*, (amount / interval_count) as amount_per_interval")
         .order("amount_per_interval")
</code>```

To access the amount_per_interval, you could just call it on the object that is loaded with the statement above.

```<code>your_model_object.amount_per_interval
</code>```

Body:
I'm using rails 5 with PostgeSQL and I have model with 2 columns:

amount: integer
interval_count: integer

I have custom method defined in my model amount_per_interval that basically returns amount/interval_count (it calculates it on app level). Now I need to sort whole table by this amount_per_interval value, but I need to do it on database level, because I'm using pagination (and also I have millions of those records so I don't want to load all of them into memory).

Is there any possibility to define such custom ordering on this model? I can't find any solution.

Update:

I basically want to rewrite this SQL:

SELECT (amount / interval_count) as amount_per_interval FROM my_table ORDER BY amount_per_interval

into ActiveRecord's interface and still keep compatibility with pagination and other AR methods.

Body:
You could use select and order methods:

YourModel.select("*, (amount / interval_count) as amount_per_interval")
         .order("amount_per_interval")

To access the amount_per_interval, you could just call it on the object that is loaded with the statement above.

your_model_object.amount_per_interval


问:
Composite Key functions in Hyperledger
I need to implement composite keys in hyperledger so that I could have a unique key based on the attributes put into the ledger. The function CreateCompositeKey(objectType string, attributes []string)(string,error)
takes in objectType and attributes string. I couldnt find any examples of this online, how are the relevant attributes to be made into the composite key passed and in what way is the output given?

 So the way Composite keys should be used is make a key first and then push it to the blockchain with PutState(key string, value []byte) error where the hey in PutState is the output of CreateCompositeKey? If not, then how are composite keys to be used?

Similarly in

```<code>GetStateByPartialCompositeKey(objectType string, keys []string) (StateQueryIteratorInterface, error)
</code>```

How are the keys we want to make queries by passed to the function? And what are the output data types "StateQueryIteratorInterface" and "HistoryQueryIteratorInterface"?

 I am fairly new to programming and have no prior knowledge of databases so am getting confused with really basic things. I'd really appreciate some help!

答:
In Hyperledger Fabric there is an example chaincode which shows how to use composite keys, check it out: Marbles

Basically it almost as you said:

```<code>key, err := stub.CreateCompositeKey(index, []string{key1, key2, key3})

// Skiped

stub.PutState(key, value)
</code>```

Title: Composite Key functions in Hyperledger

Body:
I need to implement composite keys in hyperledger so that I could have a unique key based on the attributes put into the ledger. The function CreateCompositeKey(objectType string, attributes []string)(string,error)
takes in objectType and attributes string. I couldnt find any examples of this online, how are the relevant attributes to be made into the composite key passed and in what way is the output given?

 So the way Composite keys should be used is make a key first and then push it to the blockchain with PutState(key string, value []byte) error where the hey in PutState is the output of CreateCompositeKey? If not, then how are composite keys to be used?

Similarly in

GetStateByPartialCompositeKey(objectType string, keys []string) (StateQueryIteratorInterface, error)

How are the keys we want to make queries by passed to the function? And what are the output data types "StateQueryIteratorInterface" and "HistoryQueryIteratorInterface"?

 I am fairly new to programming and have no prior knowledge of databases so am getting confused with really basic things. I'd really appreciate some help!

Body:
In Hyperledger Fabric there is an example chaincode which shows how to use composite keys, check it out: Marbles

Basically it almost as you said:

key, err := stub.CreateCompositeKey(index, []string{key1, key2, key3})

// Skiped

stub.PutState(key, value)


问:
full-text search condition in sql
```<code> select * from quotestable where contains(RelatedKeyword, 'Benjamin Franklin Quotes')
</code>```

returns an error

```<code> Msg 7630, Level 15, State 3, Line 1
 Syntax error near 'Franklin' in the full-text search condition 'Benjamin Franklin'.
</code>```

I am surprised as to why. It should ideally search for the word but it has returned error message.

答:
Try using like this</p>

```<code>select * from quotestable where RelatedKeyword like '%Benjamin Franklin Quotes%'
</code>```

Title: full-text search condition in sql

Body:
 select * from quotestable where contains(RelatedKeyword, 'Benjamin Franklin Quotes')

returns an error

 Msg 7630, Level 15, State 3, Line 1
 Syntax error near 'Franklin' in the full-text search condition 'Benjamin Franklin'.

I am surprised as to why. It should ideally search for the word but it has returned error message.

Body:
Try using like this

select * from quotestable where RelatedKeyword like '%Benjamin Franklin Quotes%'


问:
How to read "adb shell dumpsys alarm" output
I'm struggling with setting an alarm properly, and understanding the mechanism of cancelling and rescheduling alarms.

I have found, that there is an adb command to retrieve all alarms scheduled on device, but I haven't found a documentation, explaining the format of the output.

I do understand, that I'm asking a lot of explanations here, so if anybody will throw a link with detailed explanation about "adb shell dumpsys alarm", I will really appreciate it.

So, here are the questions:

Pending alarm batches: 23

a. Is '23' a number of currently active, scheduled alarms?

Batch{4293d3a8 num=1 start=1369361 end=1407261}:

  RTC #0: Alarm{4293d358 type 1 com.android.chrome}

    type=1 whenElapsed=1369361 when=+19s304ms window=-1 repeatInterval=0 count=0

    operation=PendingIntent{429e4500: PendingIntentRecord{429dbbc8 com.android.chrome broadcastIntent}}

a. What is 'num=1', 'start=1369361' and 'end=1407261'?

b. 'RTC' stands for RTC alarm, I assume.

c. What '#0' stand for?

d. What means 'type=1'?

e. Is 'when=+19s304ms' meaning that alarm will be triggered in 19 seconds?

f. What means 'window=-1'?

g. Is 'repeatInterval=0' meaning this is non-repeating alarm?

h. Is 'count=0' meaning this alarm wasn't postponed, due to phone sleep state?

i. 'operation=PendingIntent{...}' stands for the pending intent, that will be triggered by alarm, I assume.

Broadcast ref count: 0

a. What is this?

Top Alarms:

a. What is this?

+47s271ms running, 0 wakeups, 2 alarms: com.username.weatherinfo

  act=com.username.receivers.CyclicWeatherUpdater.WEATHER_UPDATE_ACTION

    cmp={com.username.weatherinfo/com.username.receivers.CyclicWeatherUpdater}

a. Is '+47s271ms' meaning this alarm will be triggered in 47 seconds?

b. What is '0 wakeups' - alarm was never triggered?

c. What is '2 alarms'?

d. Is 'com.username.weatherinfo' standing for name of package, that was given to pending intent in context field?

e. Is 'act' meaning the action, that was sent for intent?

f. What is 'cmp'? I see, that it is composed from package name and class name - but from where are they taken? From intent constructor?
g. Why part of the alarms have only 'act' or only 'cmp'? I have assumed, that alarms without 'cmp' fields are for implicit broadcast intents. Yet, why there are alarms without 'act' field?

Alarm Stats:

a. What is this?

答:
Even though morphatic's answer is all you need to know, I've created an open source project for a GUI to show the same information in a visual way. I think it could be useful for others, since it has been for me in the first place.

https://github.com/Dottorhouse/DumpsysAlarm


问:
How to create session in php with a tag on another page?
I am working on php project where i have 2 tables users and
company. user will first registerd himself and then create company
for himself. one user can have multiple companies to access. so that i
have one page that will show authorised companies to particular user.
Now, i have to visit particular company of particular user. let's say
user A have 3 companies COM-1, COM-2, COM-3. I create session for
user.so i can get below query and results:

```<code>$sql = mysqli_query($conn,"select * from company where `userId`= '".$_SESSION['userid']."' ");
while ($row = mysqli_fetch_assoc($sql))
{
    if ($row>0)
    {
        ?>
        <div><a href='dash.php?=<?php echo $row["companyId"];?>' name="" value='<?php echo $row["companyId"];?>'><?php echo $row['companyName'];?></a></div>
       <?php
    }
}
?>
</code>```

Now i have to visit selected company only. for that i have to create
session of company how can get it.

答:
I think there is no need of session, you just need to pass company_id variable via GET. Then you will get company_id easily on dash.php.

simple change this line

```<code><a href='dash.php?company_id='<?php echo $row["companyId"];?>' ><?php echo $row['companyName'];?></a>
</code>```

dash.php

```<code>$_GET["company_id"]; // this is your company id
</code>```

Body:
I am working on php project where i have 2 tables users and
company. user will first registerd himself and then create company
for himself. one user can have multiple companies to access. so that i
have one page that will show authorised companies to particular user.
Now, i have to visit particular company of particular user. let's say
user A have 3 companies COM-1, COM-2, COM-3. I create session for
user.so i can get below query and results:

$sql = mysqli_query($conn,"select * from company where `userId`= '".$_SESSION['userid']."' ");
while ($row = mysqli_fetch_assoc($sql))
{
    if ($row>0)
    {
        ?>

<a href='dash.php?=<?php echo $row["companyId"];?>' name="" value='<?php echo $row["companyId"];?>'><?php echo $row['companyName'];?>

       <?php
    }
}
?>

Now i have to visit selected company only. for that i have to create
session of company how can get it.

Body:
I think there is no need of session, you just need to pass company_id variable via GET. Then you will get company_id easily on dash.php.

simple change this line

<a href='dash.php?company_id='<?php echo $row["companyId"];?>' ><?php echo $row['companyName'];?></a>

dash.php

$_GET["company_id"]; // this is your company id


问:
Match string with prefix and suffix use Logstash grok pattern
I have a ELK cluster to keep my logs below, and i want to extract some fields in the log use logstash grok.

```<code>[info ][170703 10:34:38.998686/832]acct ok,deal_time=122ms;ACCESS_PORT=216179383538692472&ACCESS_TYPE=2&ACCOUNT=07592111916&Acct-Status-Type=3;
</code>```

here is my grok pattern.

```<code>%{SYSLOG5424SD}\[%{DATA:[@metadata][timestamp]}\/%{NUMBER}\]%{WORD:type}\ %{WORD:status}\,%{GREEDYDATA}%{NUMBER:dealtime}ms\;%{GREEDYDATA}(?<acct>(?<=ACCOUNT=).*)
</code>```

i want to extract some field's value and give it to the event variable.
eg. acct = 07592111916

i use (?(?<=ACCOUNT=).*&$) to extract the value, but not works, where is my problem?

i debug the code in this site.
http://grokdebug.herokuapp.com

答:
I think you need to extract this way:

(?<acct>(?<=ACCOUNT=)[^&]+)

Body:
I have a ELK cluster to keep my logs below, and i want to extract some fields in the log use logstash grok.

[info ][170703 10:34:38.998686/832]acct ok,deal_time=122ms;ACCESS_PORT=216179383538692472&ACCESS_TYPE=2&ACCOUNT=07592111916&Acct-Status-Type=3;

here is my grok pattern.

%{SYSLOG5424SD}\[%{DATA:[@metadata][timestamp]}\/%{NUMBER}\]%{WORD:type}\ %{WORD:status}\,%{GREEDYDATA}%{NUMBER:dealtime}ms\;%{GREEDYDATA}(?<acct>(?<=ACCOUNT=).*)

i want to extract some field's value and give it to the event variable.
eg. acct = 07592111916

i use (?(?<=ACCOUNT=).*&$) to extract the value, but not works, where is my problem?

i debug the code in this site.
http://grokdebug.herokuapp.com


问:
SQL "IN subquery" when subquery can be NULL
I have a query that needs to return results that are NOT matched in a sub query.  The sub query can return an empty result, so I need to set a  default value (say 0) if the sub query returns an empty set to prevent IN (NULL) which always returns another NULL.

For example

```<code>SELECT * FROM example_table WHERE id NOT IN (subquery_that_selects_ids)
</code>```

subquery_that_selects_ids can return a set of integers, i.e. (1,2,5,6)
or an empty set if subquery finds no matching results.

COALESCE doesn't work here, since the sub query will likely return more than one result.

Solutions need to work in SQLite or postgresql.
How can I prevent the sub query from returning an empty set?

Everyone is telling me that the query should work as written.  And you are all correct.  The query is being built by Rails3's AREL, as I was about to post the full query here I noticed that AREL was putting NULL in for an empty set when using array conditions.

I.E.  My query in rails looked like:

```<code>Object.where("id NOT IN (?)", Object.where(other_conditions).select(:id))
</code>```

when Object.where(other_conditions) evaluated to [] the ? was being replaced with NULL

So I re-write the query to look like:

```<code>Object.where("id NOT IN (" + Object.where(other_conditions).select(:id).to_sql + ")")
</code>```

Problem solved.

I'm giving credit to @Michael Buen, but also upvoting anyone who told me the query would work as written, since they are correct.  Thanks to @OMG Ponies and @Ted Elliott especially!

答:
I think you are confusing something.  The query you posted works just fine if subquery_that_selects_ids returns an empty set (so every row from example_table is selected).  There are no implicit null values involved here.

You may be thinking of the situation where a subquery is used as a scalar.  In that case, the result value is null if the subquery returns no rows, e.g.,

```<code>SELECT * FROM example_table WHERE id = (SELECT id FROM other_table WHERE name = 'foo')
</code>```

Body:
I have a query that needs to return results that are NOT matched in a sub query.  The sub query can return an empty result, so I need to set a  default value (say 0) if the sub query returns an empty set to prevent IN (NULL) which always returns another NULL.

For example

SELECT * FROM example_table WHERE id NOT IN (subquery_that_selects_ids)

subquery_that_selects_ids can return a set of integers, i.e. (1,2,5,6)
or an empty set if subquery finds no matching results.

COALESCE doesn't work here, since the sub query will likely return more than one result.

Solutions need to work in SQLite or postgresql.
How can I prevent the sub query from returning an empty set?

Everyone is telling me that the query should work as written.  And you are all correct.  The query is being built by Rails3's AREL, as I was about to post the full query here I noticed that AREL was putting NULL in for an empty set when using array conditions.

I.E.  My query in rails looked like:

Object.where("id NOT IN (?)", Object.where(other_conditions).select(:id))

when Object.where(other_conditions) evaluated to [] the ? was being replaced with NULL

So I re-write the query to look like:

Object.where("id NOT IN (" + Object.where(other_conditions).select(:id).to_sql + ")")

Problem solved.

I'm giving credit to @Michael Buen, but also upvoting anyone who told me the query would work as written, since they are correct.  Thanks to @OMG Ponies and @Ted Elliott especially!

Body:
I think you are confusing something.  The query you posted works just fine if subquery_that_selects_ids returns an empty set (so every row from example_table is selected).  There are no implicit null values involved here.

You may be thinking of the situation where a subquery is used as a scalar.  In that case, the result value is null if the subquery returns no rows, e.g.,

SELECT * FROM example_table WHERE id = (SELECT id FROM other_table WHERE name = 'foo')


问:
pentaho, spoon: how to validate text file content and move file after processing
I am doing a work for a master with pentaho and I would like to know hot to di something.

I receive a text file that I have to validate the content(type, lenght,..), if the content is correct the file is proccesed but if there is any bad field I have to wirte  in a log an then move the file to othe folder without processing any row.
Now, I have got that a text input file have an error when a type field is not correct but I cant treat it.

Does anyone a sg¡uggestion how to do this?

Thanks :)

答:
You have to do it in a job (all the steps of a transformation start in parallel, so you may move the files before they are read).

In this job, you first execute the Transformation which 'Set file to resultif and only if the file have to be moved. The next entry on the job is aMove Filewith theCopy previous result to args` checked.