问:
PHP Ajax live search with load more
I would like if I scroll bottom of .dropdown-menu, load more 7 row in database. I don't know why not using this script.
I'm using bootstrap css and js.
I tried the bootstrap-select.js with live search, but I have 2000 row in "town" database, and bootstrap-select doesn't have "load more" function.

```<code><meta charset="utf-8">

<link rel="stylesheet" href="bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="bootstrap.js"></script>

<style>.dropdown-menu{height: auto;max-height: 150px;overflow-x:hidden;}</style>

<div class="dropdown">

    <input class="dropdown-toggle" data-toggle="dropdown" id="live" placeholder="Town">
    <ul class="dropdown-menu"></ul>

</div>

<script>

$(document).ready(function () {

    var limit = 7;
    var start = 0;
    var action = 'inactive';
    var location = $('#live').val();

    $('.dropdown-menu').hide();

    function search() {

        var limit = 7;
        var start = 0;
        var action = 'inactive';
        var location = $('#live').val();

        if (location != '') {

            $('.dropdown-menu').show();

            $.ajax({

                url: "search.php",
                type: "POST",
                data: {location:location, limit:limit, start:start},
                cache: false,
                success: function(data) {

                    $('.dropdown-menu').html(data);

                    if(data == '') {

                        $('#load').text('No more data.');
                        action = 'active';

                    } else {

                        $('#load').text('Loading...');
                        action = 'inactive';

                    }

                    $('.dropdown-menu li a').click(function() {

                        $('.dropdown-menu li a').removeClass('active');

                        $(this).addClass('active');

                        var active = $('li a.active').html();

                        $('#live').val(active);

                    });

                }

            });

        } else {

            $('.dropdown-menu').hide();

            $('.dropdown-menu li a').removeClass('active');

        }

    };

    if (action == 'inactive') {

        action = 'active';
        $('#live').on('keyup change', search);

    }

    $(window).scroll(function(){

        if ($(window).scrollTop() + $(window).height() > $(".dropdown-menu").height() && action == 'inactive') {

            action = 'active';
            start = start + limit;
            setTimeOut(function(){
                $('#live').on('keyup change', search);
            }, 1000);

        }

    });

});

</script>
</code>```

search.php:

```<code><?php

$connect = mysqli_connect("localhost", "root", "", "mydb");

$location = $connect->real_escape_string($_POST["location"]);

if (isset($_POST["location"])) {

    $data = mysqli_query($connect, "SELECT * FROM towns WHERE town LIKE '%".$location."%' ORDER BY id LIMIT ".$_POST["start"].", ".$_POST["limit"]."");

    $data_count = mysqli_num_rows($data);

    if ($data->num_rows === 0) {

        echo '<li>No data!</li>';

    } else {

        while ($row = mysqli_fetch_array($data)) {

            echo '<li><a href="#">'.$row["town"].'</a></li>';

        }

        echo '<div id="load"></div>';

    }

}

?>
</code>```

答:
Maybe this is not neatly finished code, but I've added a loadMore button & attached search function to the click event of it.

The modified HTML code:

```<code><html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="bootstrap.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="bootstrap.js"></script>
    <style>.dropdown-menu{height: auto;max-height: 150px;overflow-x:hidden;}</style>
</head>
<body>
    <div class="dropdown">
        <input class="dropdown-toggle" data-toggle="dropdown" id="live" placeholder="Town">
        <ul class="dropdown-menu"></ul>
        <button type="button" id="loadMore" style="display: none;"></button>
    </div>
    <script>
    function search() {
        if (location != '') {
            $('.dropdown-menu').show();
            $.ajax({
                url: "search.php",
                type: "POST",
                data: {location:location, limit:limit, start:start},
                cache: false,
                success: function(data) {
                    $('.dropdown-menu').html(data);
                    if(!data) {
                        $('#load').text('No more data.');
                        action = 'active';
                    } else {
                        $('#load').text('Loading...');
                        action = 'inactive';
                    }
                    $('.dropdown-menu li a').click(function() {
                        $('.dropdown-menu li a').removeClass('active');
                        $(this).addClass('active');
                        var active = $('li a.active').html();
                        $('#live').val(active);
                    });
                    start = start + limit;
                    $('#loadMore').show();
                }
            });
        } else {
            $('.dropdown-menu').hide();
            $('.dropdown-menu li a').removeClass('active');
        }
    }

    $(document).ready(function () {
        limit = 7;
        start = 0;
        action = 'inactive';
        location = $('#live').val();
        $('.dropdown-menu').hide();

        if (action == 'inactive') {
            action = 'active';
            $('#loadMore').on('click', search);
            $('#live').on('keyup change', search);
        }

        $(window).scroll(function(){
            if ($(window).scrollTop() + $(window).height() > $(".dropdown-menu").height() && action == 'inactive') {
                action = 'active';
                start = start + limit;
                setTimeOut(function(){
                    $('#live').on('keyup change', search);
                    $('#loadMore').on('click', search);
                }, 1000);

            }
        });
    });
</script>
</body>
</html>
</code>```

Title: PHP Ajax live search with load more

Body:
I would like if I scroll bottom of .dropdown-menu, load more 7 row in database. I don't know why not using this script.
I'm using bootstrap css and js.
I tried the bootstrap-select.js with live search, but I have 2000 row in "town" database, and bootstrap-select doesn't have "load more" function.

<meta charset="utf-8">

<link rel="stylesheet" href="bootstrap.css">

    <input class="dropdown-toggle" data-toggle="dropdown" id="live" placeholder="Town">

search.php:

<?php

$connect = mysqli_connect("localhost", "root", "", "mydb");

$location = $connect->real_escape_string($_POST["location"]);

if (isset($_POST["location"])) {

    $data = mysqli_query($connect, "SELECT * FROM towns WHERE town LIKE '%".$location."%' ORDER BY id LIMIT ".$_POST["start"].", ".$_POST["limit"]."");

    $data_count = mysqli_num_rows($data);

    if ($data->num_rows === 0) {

        echo '
No data!
';

    } else {

        while ($row = mysqli_fetch_array($data)) {

            echo '
'.$row["town"].'
';

        }

        echo '

';

    }

}

?>

Body:
Maybe this is not neatly finished code, but I've added a loadMore button & attached search function to the click event of it.

The modified HTML code:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="bootstrap.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="bootstrap.js"></script>
    <style>.dropdown-menu{height: auto;max-height: 150px;overflow-x:hidden;}</style>
</head>
<body>
    <div class="dropdown">
        <input class="dropdown-toggle" data-toggle="dropdown" id="live" placeholder="Town">
        <ul class="dropdown-menu"></ul>
        <button type="button" id="loadMore" style="display: none;"></button>
    </div>
    <script>
    function search() {
        if (location != '') {
            $('.dropdown-menu').show();
            $.ajax({
                url: "search.php",
                type: "POST",
                data: {location:location, limit:limit, start:start},
                cache: false,
                success: function(data) {
                    $('.dropdown-menu').html(data);
                    if(!data) {
                        $('#load').text('No more data.');
                        action = 'active';
                    } else {
                        $('#load').text('Loading...');
                        action = 'inactive';
                    }
                    $('.dropdown-menu li a').click(function() {
                        $('.dropdown-menu li a').removeClass('active');
                        $(this).addClass('active');
                        var active = $('li a.active').html();
                        $('#live').val(active);
                    });
                    start = start + limit;
                    $('#loadMore').show();
                }
            });
        } else {
            $('.dropdown-menu').hide();
            $('.dropdown-menu li a').removeClass('active');
        }
    }

    $(document).ready(function () {
        limit = 7;
        start = 0;
        action = 'inactive';
        location = $('#live').val();
        $('.dropdown-menu').hide();

        if (action == 'inactive') {
            action = 'active';
            $('#loadMore').on('click', search);
            $('#live').on('keyup change', search);
        }

        $(window).scroll(function(){
            if ($(window).scrollTop() + $(window).height() > $(".dropdown-menu").height() && action == 'inactive') {
                action = 'active';
                start = start + limit;
                setTimeOut(function(){
                    $('#live').on('keyup change', search);
                    $('#loadMore').on('click', search);
                }, 1000);

            }
        });
    });
</script>
</body>
</html>


来源: stackexchange

问:
spring boot with hibernate, I can't take away table name with underscore
I have tried all alternatives in application.properties (see below) I have found so far but my application is still creating the table with "_" instead of camel case as I set up.

Any suggestion will be highly appreciated.

```<code>1
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.cfg.DefaultNamingStrategy

output
DefaultNamingStrategy cannot be cast to org.hibernate.boot.model.naming.ImplicitNamingStrategy

2
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.cfg.DefaultNamingStrategy
output
org.hibernate.cfg.DefaultNamingStrategy cannot be cast to org.hibernate.boot.model.naming.PhysicalNamingStrategy

3
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.DefaultNamingStrategy
output
org.hibernate.SQL                        : drop table tipo_dominio if exists
NOTE: no error but I didn't get the table name without "_"

4
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.EJB3NamingStrategy
output
EJB3NamingStrategy cannot be cast to org.hibernate.boot.model.naming.PhysicalNamingStrategy
</code>```

my entity

```<code>import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity(name="TipoDominio")
@Table(name="TipoDominio")
public class TipoDominio implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;
</code>```

pom

```<code>    <properties>
        <main.basedir>${basedir}/../..</main.basedir>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Compile -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <!-- Runtime -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
            <version>1.4.193</version>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.1.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

main

```<code>@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

*** Edited
I tried

```<code>@SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class
</code>```

without success as well

答:
With SpringBoot 1.5.x the hibernate version is "5.x". This means that the naming strategy classes for tables without underscores has changed. This should work for what you have.

```<code>spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code>```

Note that the configuration property name changed as well as the class.

ContentLicense: CC BY-SA 3.0

Body:
I have tried all alternatives in application.properties (see below) I have found so far but my application is still creating the table with "_" instead of camel case as I set up.

Any suggestion will be highly appreciated.

1
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.cfg.DefaultNamingStrategy

output
DefaultNamingStrategy cannot be cast to org.hibernate.boot.model.naming.ImplicitNamingStrategy

2
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.cfg.DefaultNamingStrategy
output
org.hibernate.cfg.DefaultNamingStrategy cannot be cast to org.hibernate.boot.model.naming.PhysicalNamingStrategy

3
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.DefaultNamingStrategy
output
org.hibernate.SQL                        : drop table tipo_dominio if exists
NOTE: no error but I didn't get the table name without "_"

4
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.EJB3NamingStrategy
output
EJB3NamingStrategy cannot be cast to org.hibernate.boot.model.naming.PhysicalNamingStrategy

my entity

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity(name="TipoDominio")
@Table(name="TipoDominio")
public class TipoDominio implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

pom

    <properties>
        ${basedir}/../..

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
            <version>1.4.193</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.1.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

main

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

*** Edited
I tried

@SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class

without success as well

Body:
With SpringBoot 1.5.x the hibernate version is "5.x". This means that the naming strategy classes for tables without underscores has changed. This should work for what you have.

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Note that the configuration property name changed as well as the class.


问:
Excel VBA to insert rows based on cell value and copy columns down based on that number
I know there are several questions and answers about using Excel VBA to copy and insert rows based on a cell value but I have an additional requirement that makes it difficult to find a solution. I'm stuck at this point and need help.

I have a spreadsheet along the lines of the following:

```<code>Name    Unit    Count   Req1    Req2    Req3    Req4    ...  ...    Req25
Apple   304     5       Apple1  Apple2  Apple3  Apple4  ... Apple5
Pear    562     2       Pear1   Pear2
Kiwi    471     4       Kiwi1   Kiwi2   Kiwi3   Kiwi4
</code>```

The spreadsheet has columns for "Req1" through "Req25." If the"count" is 5, then "Req1" through "Req5" columns will have data. The "count" will vary per row leaving the reminder of the columns to "Req25" blank. I need to insert rows based on "count" -1, copy down all columns up to "count" column, and then move "Req2," "Req3," etc. down to the corresponding inserted row in the "Req1" column. I'm probably not explaining it very well.

I need the end result to look like:

```<code>Name    Unit    Count   Req1
Apple   304     5       Apple1
Apple   304     5       Apple2
Apple   304     5       Apple3
Apple   304     5       Apple4
Apple   304     5       Apple5
Pear    562     2       Pear1
Pear    562     2       Pear2
Kiwi    471     4       Kiwi1
Kiwi    471     4       Kiwi2
Kiwi    471     4       Kiwi3
Kiwi    471     4       Kiwi4
</code>```

I am able to insert the correct number of rows but I'm stuck on looping through the columns and moving them down into the "Req1" column.

Any help is GREATLY appreciated!! Thanks in advance!

答:
This macro will do what you want but instead of inserting rows it will put the data into a new sheet; You just need to add a sheet for output and change the name for input and output sheets in the code.

```<code>Dim mOut As Worksheet
Dim mInp As Worksheet
Dim num As Integer
Dim i As Integer
Dim j As Integer
Dim c As Integer

Sub Copy()

Set mInp = Worksheets("Your Sheet Name")
Set mOut = Worksheets("Create Another Sheet for Output")

mOut.Cells(1, 1) = mInp.Cells(1, 1)
mOut.Cells(1, 2) = mInp.Cells(1, 2)
mOut.Cells(1, 3) = mInp.Cells(1, 3)
mOut.Cells(1, 4) = "Req"

i = 2
num = 2

While mInp.Cells(i, 1) <> ""
c = mInp.Cells(i, 3)

For j = 1 To c

mOut.Cells(num, 1) = mInp.Cells(i, 1)
mOut.Cells(num, 2) = mInp.Cells(i, 2)
mOut.Cells(num, 3) = mInp.Cells(i, 3)
mOut.Cells(num, 4) = mInp.Cells(i, j + 3)

num = num + 1
Next j

i = i + 1
Wend

End Sub
</code>```

If you want to pursue the solution that you had by inserting the rows you need to add this loop after you inserted them. Also, you need to count number of rows while adding them. I do not have your code to see how it can be done but am sure it is easy to do so.

```<code> For i = 2 To NumRows 'Number of rows (Sum of the inserted and original rows)
         If mInp.Cells(i, 1) <> "" Then

             irow = i
             Count = 1

         Else

             mInp.Cells(i, 1) = mInp.Cells(irow, 1)
             mInp.Cells(i, 2) = mInp.Cells(irow, 2)
             mInp.Cells(i, 3) = mInp.Cells(irow, 3)
             mInp.Cells(i, 4) = mInp.Cells(irow, 4 + Count)

             Count = Count + 1

         End If
 Next i
</code>```

Body:
I know there are several questions and answers about using Excel VBA to copy and insert rows based on a cell value but I have an additional requirement that makes it difficult to find a solution. I'm stuck at this point and need help.

I have a spreadsheet along the lines of the following:

Name    Unit    Count   Req1    Req2    Req3    Req4    ...  ...    Req25
Apple   304     5       Apple1  Apple2  Apple3  Apple4  ... Apple5
Pear    562     2       Pear1   Pear2
Kiwi    471     4       Kiwi1   Kiwi2   Kiwi3   Kiwi4

The spreadsheet has columns for "Req1" through "Req25." If the"count" is 5, then "Req1" through "Req5" columns will have data. The "count" will vary per row leaving the reminder of the columns to "Req25" blank. I need to insert rows based on "count" -1, copy down all columns up to "count" column, and then move "Req2," "Req3," etc. down to the corresponding inserted row in the "Req1" column. I'm probably not explaining it very well.

I need the end result to look like:

Name    Unit    Count   Req1
Apple   304     5       Apple1
Apple   304     5       Apple2
Apple   304     5       Apple3
Apple   304     5       Apple4
Apple   304     5       Apple5
Pear    562     2       Pear1
Pear    562     2       Pear2
Kiwi    471     4       Kiwi1
Kiwi    471     4       Kiwi2
Kiwi    471     4       Kiwi3
Kiwi    471     4       Kiwi4

I am able to insert the correct number of rows but I'm stuck on looping through the columns and moving them down into the "Req1" column.

Any help is GREATLY appreciated!! Thanks in advance!

Body:
This macro will do what you want but instead of inserting rows it will put the data into a new sheet; You just need to add a sheet for output and change the name for input and output sheets in the code.

Dim mOut As Worksheet
Dim mInp As Worksheet
Dim num As Integer
Dim i As Integer
Dim j As Integer
Dim c As Integer

Sub Copy()

Set mInp = Worksheets("Your Sheet Name")
Set mOut = Worksheets("Create Another Sheet for Output")

mOut.Cells(1, 1) = mInp.Cells(1, 1)
mOut.Cells(1, 2) = mInp.Cells(1, 2)
mOut.Cells(1, 3) = mInp.Cells(1, 3)
mOut.Cells(1, 4) = "Req"

i = 2
num = 2

While mInp.Cells(i, 1) <> ""
c = mInp.Cells(i, 3)

For j = 1 To c

mOut.Cells(num, 1) = mInp.Cells(i, 1)
mOut.Cells(num, 2) = mInp.Cells(i, 2)
mOut.Cells(num, 3) = mInp.Cells(i, 3)
mOut.Cells(num, 4) = mInp.Cells(i, j + 3)

num = num + 1
Next j

i = i + 1
Wend

End Sub

If you want to pursue the solution that you had by inserting the rows you need to add this loop after you inserted them. Also, you need to count number of rows while adding them. I do not have your code to see how it can be done but am sure it is easy to do so.

 For i = 2 To NumRows 'Number of rows (Sum of the inserted and original rows)
         If mInp.Cells(i, 1) <> "" Then

             irow = i
             Count = 1

         Else

             mInp.Cells(i, 1) = mInp.Cells(irow, 1)
             mInp.Cells(i, 2) = mInp.Cells(irow, 2)
             mInp.Cells(i, 3) = mInp.Cells(irow, 3)
             mInp.Cells(i, 4) = mInp.Cells(irow, 4 + Count)

             Count = Count + 1

         End If
 Next i


问:
HTML5 - vertical layout: flexible height + fill the rest
I have a dreaded height problem in html, IE9 and above, avoiding flex-box:

I have header of one to three lines heigth (highly depends)

the vertical rest of the page shall be filled a section. With scrollbars to that section, in case it's contents grow to long.

In simplied stylus syntax, or as a full codepen:

```<code>html, body, header, section
  padding 0
  margin 0
  font-size 40px
  box-sizing border-box

html
  background #f99
  height 100%

body
  background #9f9
  border 4px solid green
  height 100%

header
  border 4px solid darkred

section
  background #99f
  overflow auto
</code>```

If the header height was known, life would be easy. I could easily resort to „corner pinning“:

```<code>  position absolute
  top 100px
  bottom 0
</code>```

(Or have a fat top padding, and place the header above that, etc, etc...)

But sadly: its height varies. Any suggestions other than a vertical flexbox?

— looks like I need a corner pin with a little help from javascript regarding the top attribute?

答:
You can do it with JS, or in my example, jQuery:

http://codepen.io/anon/pen/ZeVbBR

Get the heights of the window and the header and apply their difference as min-height to the section.

Body:
I have a dreaded height problem in html, IE9 and above, avoiding flex-box:

I have header of one to three lines heigth (highly depends)

the vertical rest of the page shall be filled a section. With scrollbars to that section, in case it's contents grow to long.

In simplied stylus syntax, or as a full codepen:

html, body, header, section
  padding 0
  margin 0
  font-size 40px
  box-sizing border-box

html
  background #f99
  height 100%

body
  background #9f9
  border 4px solid green
  height 100%

header
  border 4px solid darkred

section
  background #99f
  overflow auto

If the header height was known, life would be easy. I could easily resort to „corner pinning“:

  position absolute
  top 100px
  bottom 0

(Or have a fat top padding, and place the header above that, etc, etc...)

But sadly: its height varies. Any suggestions other than a vertical flexbox?

— looks like I need a corner pin with a little help from javascript regarding the top attribute?


问:
Pointer instantly 0x0
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

```<code>TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */
</code>```

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

```<code>151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()
</code>```

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

答: preview->get_column(); returns NULL, before that, its just some random value, since you didn't initialize the col variable

ContentLicense: CC BY-SA 2.5

Title: Pointer instantly 0x0

Body:
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.


问:
Camera shaking on rotating player while crouching in unity
I am having a problem with the camera following the player. When the player moves, the camera shakes and this effect is more noticeable when the player is in the crouched position. I am using root motion for the player with animations by mixamo.

Player Script:

```<code>Transform cameraT;
void Start () {
cameraT = Camera.main.transform;
}
void FixedUpdate ()
{
float sideMotion = Input.GetAxis("SideMotion");
float straightMotion= Input.GetAxis("StraightMotion");
if (Mathf.Abs(sideMotion) > 0 || Mathf.Abs(straightMotion) > 0)
     {
         transform.eulerAngles = new Vector3(transform.eulerAngles.x,
cameraT.eulerAngles.y);

     }
}
</code>```

Camera Script:

```<code>public float distanceFromPlayer=2f;

 public float mouseSensitivity=6;

 public Transform player;

 public Vector2 pitchConstraint= new Vector2(-30,80);

 Vector3 rotationSmoothVelocity;
 Vector3 currentRotation;
 public float rotationSmoothTime = 0.2f;

 float yaw; //Rotation around the vertical axis is called yaw

 float pitch; //Rotation around the side-to-side axis is called pitch

 private void LateUpdate()
 {
     yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
     pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
     pitch = Mathf.Clamp(pitch, pitchConstraint.x, pitchConstraint.y);

     currentRotation = Vector3.SmoothDamp
         (currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);

     transform.eulerAngles = currentRotation;

     transform.position = player.position - transform.forward * distanceFromPlayer;
 }
</code>```

For public transform I just added an empty game object to player chest level and parented it to the player. I got the rotating camera smoothly trick from an online tutorial but that exact thing won't work on player rotation though.

A character controller is attached to player without any rigidbody or collider.

答:
You are going to want to use Lerp on the camera in order to smooth its motion from one position to another. The Scripting API has a good example of Vector3.Lerp.

So in your case, you could add a public variable for smoothing position as well. Something like positionSmoothTime. Then make a "Desired Position" variable, we'll call it destPosition.

```<code>Vector3 destPosition = player.position - transform.forward * distanceFromPlayer;

transform.position = Vector3.Lerp(transform.position, destPosition, positionSmoothTime);
</code>```

This should effectively smooth it to where the stuttering should go away. Another thing that will help that someone else mentioned is using a part of the body that moves less (Like the head) as the target. This combined with the Lerp function will give you a smooth camera movement.

Another large help would be to move things into the Update() function. The reason being is FixedUpdate() doesn't get called every frame. So you could potentially get stutter as a result. If you move everything into Update() it will update every frame and help smooth things out. If you do this though you will need to multiply all movement by Time.deltaTime as shown in the example below.

```<code>Vector3 destPosition = (player.position - transform.forward * distanceFromPlayer) * Time.deltaTime;
</code>```

For more examples, check the links to each function to see Unity's documentation on it. It has examples of everything I've shown here.

Body:
I am having a problem with the camera following the player. When the player moves, the camera shakes and this effect is more noticeable when the player is in the crouched position. I am using root motion for the player with animations by mixamo.

Player Script:

Transform cameraT;
void Start () {
cameraT = Camera.main.transform;
}
void FixedUpdate ()
{
float sideMotion = Input.GetAxis("SideMotion");
float straightMotion= Input.GetAxis("StraightMotion");
if (Mathf.Abs(sideMotion) > 0 || Mathf.Abs(straightMotion) > 0)
     {
         transform.eulerAngles = new Vector3(transform.eulerAngles.x,
cameraT.eulerAngles.y);

     }
}

Camera Script:

public float distanceFromPlayer=2f;

 public float mouseSensitivity=6;

 public Transform player;

 public Vector2 pitchConstraint= new Vector2(-30,80);

 Vector3 rotationSmoothVelocity;
 Vector3 currentRotation;
 public float rotationSmoothTime = 0.2f;

 float yaw; //Rotation around the vertical axis is called yaw

 float pitch; //Rotation around the side-to-side axis is called pitch

 private void LateUpdate()
 {
     yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
     pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
     pitch = Mathf.Clamp(pitch, pitchConstraint.x, pitchConstraint.y);

     currentRotation = Vector3.SmoothDamp
         (currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);

     transform.eulerAngles = currentRotation;

     transform.position = player.position - transform.forward * distanceFromPlayer;
 }

For public transform I just added an empty game object to player chest level and parented it to the player. I got the rotating camera smoothly trick from an online tutorial but that exact thing won't work on player rotation though.

A character controller is attached to player without any rigidbody or collider.

Body:
You are going to want to use Lerp on the camera in order to smooth its motion from one position to another. The Scripting API has a good example of Vector3.Lerp.

So in your case, you could add a public variable for smoothing position as well. Something like positionSmoothTime. Then make a "Desired Position" variable, we'll call it destPosition.

Vector3 destPosition = player.position - transform.forward * distanceFromPlayer;

transform.position = Vector3.Lerp(transform.position, destPosition, positionSmoothTime);

This should effectively smooth it to where the stuttering should go away. Another thing that will help that someone else mentioned is using a part of the body that moves less (Like the head) as the target. This combined with the Lerp function will give you a smooth camera movement.

Another large help would be to move things into the Update() function. The reason being is FixedUpdate() doesn't get called every frame. So you could potentially get stutter as a result. If you move everything into Update() it will update every frame and help smooth things out. If you do this though you will need to multiply all movement by Time.deltaTime as shown in the example below.

Vector3 destPosition = (player.position - transform.forward * distanceFromPlayer) * Time.deltaTime;

For more examples, check the links to each function to see Unity's documentation on it. It has examples of everything I've shown here.


问:
How would I create grayed-out text in a JavaFX TextArea that disappears when the user begins adding text?
This is a feature that I have noticed in many web apps and I would like it to be in a TextArea on my JavaFX app.

The desktop version of Hemingway provides a good example:

答:
Set promptText on the TextArea.

```<code> textArea.setPromptText("Type or paste something to get started...");
</code>```

If you want a more sophisticated solution that transfers the PromptText to a label above the TextField, so the prompt text is still visible when the user types, then the 3rd party Gluon glisten library does that, or MaterialFX has many text field prompt and label options.  From your description, though you probably don't need the glisten functionality and the standard promptText implementation in JavaFX TextAreas is probably fine for you.

Related:

Clear prompt text in JavaFX TextField only when user starts typing

Body:
Set promptText on the TextArea.

 textArea.setPromptText("Type or paste something to get started...");

If you want a more sophisticated solution that transfers the PromptText to a label above the TextField, so the prompt text is still visible when the user types, then the 3rd party Gluon glisten library does that, or MaterialFX has many text field prompt and label options.  From your description, though you probably don't need the glisten functionality and the standard promptText implementation in JavaFX TextAreas is probably fine for you.

Related:

Clear prompt text in JavaFX TextField only when user starts typing

ContentLicense: CC BY-SA 4.0


问:
A flexbox grid of two flex items next to one
I am trying to have one div on the left and two on the right. The bottomright should always be below the topRight div. The topRight is the only div with a variable height.

I am currently trying to achieve this using flexbox als you can see in my code below.

I would like to have some directions.

.wrapper {
  display: flex;
  height: 100px;
}

.left {
  background-color: green
}

.topRight {
  background-color: yellow
}

.bottomright {
  background-color: red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">Left</div>
  <div class="topRight">TopRight</div>
  <div class="bottomright">Bottom</div>
  </div</code>```

答:
For infos

display:grid is made for this .... very soon available for most browsers and yet for a few

A tutorial among others : https://css-tricks.com/snippets/css/complete-guide-grid/

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  /* any height s */
  background-color: green;
}

.leftspan {
  grid-row: span 2;/* if 2 rows avalaible */
}

.topRight {
  background-color: yellow;
  grid-column: 2 /-1
}

.bottomright {
  background-color: red;
  grid-column: 2 /-1
}

.bottomfull {
  background-color: red;
  grid-column: 1 /-1
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="leftspan">Left spanning 2 rows</div>
  <div class="topRight">Top <br/>Right</div>
  <div class="bottomright">Bottom <br/>Right</div>
  </div>
  <p> or did you mean ?
  <div class="wrapper">
  <div class="left">Left</div>
  <div class="topRight">Top Right</div>
  <div class="bottomfull">Bottom <br/>Right</div>
  </div></code>```

render if your browsers understand grid:

Body:
I am trying to have one div on the left and two on the right. The bottomright should always be below the topRight div. The topRight is the only div with a variable height.

I am currently trying to achieve this using flexbox als you can see in my code below.

I would like to have some directions.

.wrapper {
  display: flex;
  height: 100px;
}

.left {
  background-color: green
}

.topRight {
  background-color: yellow
}

.bottomright {
  background-color: red
}

Left

TopRight

Bottom

  </div

Body:
For infos

display:grid is made for this .... very soon available for most browsers and yet for a few

A tutorial among others : https://css-tricks.com/snippets/css/complete-guide-grid/

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  /* any height s */
  background-color: green;
}

.leftspan {
  grid-row: span 2;/* if 2 rows avalaible */
}

.topRight {
  background-color: yellow;
  grid-column: 2 /-1
}

.bottomright {
  background-color: red;
  grid-column: 2 /-1
}

.bottomfull {
  background-color: red;
  grid-column: 1 /-1
}

<div class="wrapper">
  <div class="leftspan">Left spanning 2 rows</div>
  <div class="topRight">Top <br/>Right</div>
  <div class="bottomright">Bottom <br/>Right</div>
  </div>
  <p> or did you mean ?
  <div class="wrapper">
  <div class="left">Left</div>
  <div class="topRight">Top Right</div>
  <div class="bottomfull">Bottom <br/>Right</div>
  </div>

render if your browsers understand grid:


问:
IntentService Error: No default Constructor
I am a newbie to Android, and I am trying to use the IntentService but I get an error that it has no default constructor.
I tried restarting the Android Studio it doesn't work.

package com.example.hitesh.kuchbhi;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;

import java.util.TreeSet;

public class DisplayNotification extends IntentService {
    public DisplayNotification(String name) {
        super("DisplayNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // my code which even after deleting gives the same error
    }
```
<p>log cat error</p>
```E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hitesh.kuchbhi, PID: 28899
                  java.lang.RuntimeException: Unable to instantiate service com.example.hitesh.kuchbhi.DisplayNotification: java.lang.InstantiationException: class com.example.hitesh.kuchbhi.DisplayNotification has no zero argument constructor
                      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2728)
                      at android.app.ActivityThread.access$1800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

```

AndroidManifest file Screenshot

答:
Seems that you need a no parameter constructor, like so:

```<code>public DisplayNotification() {
    super("DisplayNotification");
}
</code>```

Let me know if it helps.

Body:
I am a newbie to Android, and I am trying to use the IntentService but I get an error that it has no default constructor.
I tried restarting the Android Studio it doesn't work.

package com.example.hitesh.kuchbhi;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;

import java.util.TreeSet;

public class DisplayNotification extends IntentService {
    public DisplayNotification(String name) {
        super("DisplayNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // my code which even after deleting gives the same error
    }

log cat error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hitesh.kuchbhi, PID: 28899
                  java.lang.RuntimeException: Unable to instantiate service com.example.hitesh.kuchbhi.DisplayNotification: java.lang.InstantiationException: class com.example.hitesh.kuchbhi.DisplayNotification has no zero argument constructor
                      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2728)
                      at android.app.ActivityThread.access$1800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

AndroidManifest file Screenshot

Body:
Seems that you need a no parameter constructor, like so:

public DisplayNotification() {
    super("DisplayNotification");
}

Let me know if it helps.


问:
Having Issues with Angular Components
I understand that this is an existing thread here: How to import component into another root component in Angular 2, however this does not solve my problem.

I have the same problem here.

I'm trying to figure out Angular-Cli - successfully created a new project, and added component. All the tips found in the post above are automatically implemented.

When try using the component as represented (adding a <superman></superman>) to the template,  I get this error:

```<code>Unhandled Promise rejection: Template parse errors:
'superman' is not a known element:
1. If 'superman' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<h1>
  {{title}}
  [ERROR ->]<superman></superman>
</h1>
"):
</code>```

答:
You need to register that component in a module. Look at the top answer of this

e.g.

```<code>@NgModule({
  imports:      [BrowserModule],
  declarations: [AppComponent, SupermanComponent],  //<----here
  providers:    [],
  bootstrap:    [AppComponent]
})
</code>```

And make sure the selector of SupermanComponent is superman

e.g.

```<code>@Component({
  selector: 'superman',
  template: '...'
  ...
})
export class SupermanComponent { ...
</code>```

Title: Having Issues with Angular Components

Body:
I understand that this is an existing thread here: How to import component into another root component in Angular 2, however this does not solve my problem.

I have the same problem here.

I'm trying to figure out Angular-Cli - successfully created a new project, and added component. All the tips found in the post above are automatically implemented.

When try using the component as represented (adding a <superman></superman>) to the template,  I get this error:

Unhandled Promise rejection: Template parse errors:
'superman' is not a known element:
1. If 'superman' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

  {{title}}
  [ERROR ->]<superman></superman>

"):

Body:
You need to register that component in a module. Look at the top answer of this

e.g.

@NgModule({
  imports:      [BrowserModule],
  declarations: [AppComponent, SupermanComponent],  //<----here
  providers:    [],
  bootstrap:    [AppComponent]
})

And make sure the selector of SupermanComponent is superman

e.g.

@Component({
  selector: 'superman',
  template: '...'
  ...
})
export class SupermanComponent { ...


问:
inlining failed in call to always_inline ‘_mm_mullo_epi32’: target specific option mismatch
I am trying to compile a C program using cmake which uses SIMD intrinsics.  When I try to compile it, I get two errors

/usr/lib/gcc/x86_64-linux-gnu/5/include/smmintrin.h:326:1: error: inlining failed in call to always_inline ‘_mm_mullo_epi32’: target specific option mismatch
 _mm_mullo_epi32 (__m128i __X, __m128i __Y)

/usr/lib/gcc/x86_64-linux-gnu/5/include/tmmintrin.h:136:1: error: inlining failed in call to always_inline ‘_mm_shuffle_epi8’: target specific option mismatch
 _mm_shuffle_epi8 (__m128i __X, __m128i __Y)

This issue has already been solved here StackOverflow by setting

```<code>set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1")
</code>```

I try the very same and many other options. But my project still fails to compile.

```<code>set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -sse4_1")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=nehalem")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1 -msse4.2")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ssse3")
</code>```

答:
Since you are compiling C code, not C++, you need:

```<code>set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse4.1")
</code>```

You can get rid of all the other -march XXX and -msseXXX settings.

If you're using a mix of C and C++ then you could also add:

```<code>set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1")
</code>```

Body:
I am trying to compile a C program using cmake which uses SIMD intrinsics.  When I try to compile it, I get two errors

/usr/lib/gcc/x86_64-linux-gnu/5/include/smmintrin.h:326:1: error: inlining failed in call to always_inline ‘_mm_mullo_epi32’: target specific option mismatch
 _mm_mullo_epi32 (__m128i __X, __m128i __Y)

/usr/lib/gcc/x86_64-linux-gnu/5/include/tmmintrin.h:136:1: error: inlining failed in call to always_inline ‘_mm_shuffle_epi8’: target specific option mismatch
 _mm_shuffle_epi8 (__m128i __X, __m128i __Y)

This issue has already been solved here StackOverflow by setting

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1")

I try the very same and many other options. But my project still fails to compile.

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -sse4_1")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=nehalem")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1 -msse4.2")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ssse3")

Body:
Since you are compiling C code, not C++, you need:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse4.1")

You can get rid of all the other -march XXX and -msseXXX settings.

If you're using a mix of C and C++ then you could also add:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1")


问:
How to combine C# code with JavaScript code in onclick?
I want to use C# code and JavaScript in the same onclientclick event.

```<code><asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>'
    OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>; window.close();' />
</code>```

But it doesn't work. How to do that?

Thanks.

答:
What are you reying to acheive? Do you wnat to call a javascript function which uses some of server side variables and close at the end.</p>

```<code>function MyF()
{
    var myvar = '<%= myC#Var %>';
    ....do something

   window.close()

}

<asp:LinkButton ID="lbTest" runat="server"  OnClientClick='MyF()' />
</code>```

Body:
I want to use C# code and JavaScript in the same onclientclick event.

<asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>'
    OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>; window.close();' />

But it doesn't work. How to do that?

Thanks.

Body:
What are you reying to acheive? Do you wnat to call a javascript function which uses some of server side variables and close at the end.

function MyF()
{
    var myvar = '<%= myC#Var %>';
    ....do something

   window.close()

}

<asp:LinkButton ID="lbTest" runat="server"  OnClientClick='MyF()' />


问:
How to render a variable in HAML and preserve white-spaces?
This is what I'm doing:

```<code>%pre
  =var
</code>```

The value of var is "foo\nbar". I'm getting this HTML:

```<code><body>
  ```foo
  bar```
</body>
</code>```

Obviously, I'm expecting:

```<code><body>
  ```foo
bar```
</body>
</code>```

What to do?

答:
If you use ugly mode then you shouldn’t have this problem. Note that in (the hopefully coming soon) Haml 5 there only is ugly mode, so this is probably the best option for the future.

This would produce:

```foo
bar```

```

<hr>

<p>For current versions, in non-ugly mode, if you wanted to preserve whitespace like this then normally you would use <code>~</code>, which would call <code>find_and_preserve</code> on the result. However here you are already in a <code>pre</code> block, and so that won’t work (arguably this is a bug, but with the removal of non-ugly mode in Haml 5 I can’t see any benefit of fixing it).</p>

<p>You could use <code>preserve</code> directly though:</p>

<pre class="lang-haml prettyprint-override"><code>%body
  %pre
    =preserve(var)
</code>```

This produces:

  ```foo
bar```

```

which has the same affect as your desired result when rendered.

Body:
This is what I'm doing:

%pre
  =var

The value of var is "foo\nbar". I'm getting this HTML:

foo
  bar

Obviously, I'm expecting:

foo
bar

What to do?

Body:
If you use ugly mode then you shouldn’t have this problem. Note that in (the hopefully coming soon) Haml 5 there only is ugly mode, so this is probably the best option for the future.

This would produce:

<body>
<pre>foo
bar</pre>
</body>

For current versions, in non-ugly mode, if you wanted to preserve whitespace like this then normally you would use ~, which would call find_and_preserve on the result. However here you are already in a pre block, and so that won’t work (arguably this is a bug, but with the removal of non-ugly mode in Haml 5 I can’t see any benefit of fixing it).

You could use preserve directly though:

%body
  %pre
    =preserve(var)

This produces:

<body>
  <pre>foo&#x000A;bar</pre>
</body>

which has the same affect as your desired result when rendered.


问:
Remove duplicates as well as original row
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

```<code>ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove
</code>```

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

答:
You could select them with a join on exactly those rows.

```<code>SELECT ItemNUMBER, ID, from_DATE, to_DATE, fancy_code
FROM [Table] t join (
    SELECT ItemNUMBER, ID, from_DATE, to_DATE, count(1)
    FROM [Table] t
    GROUP BY ItemNUMBER, ID, from_DATE, to_DATE
    HAVING count(1) = 1
) u on (u.ItemNUMBER= t.ItemNUMBER and u.ID=t.ID
    and u.from_DATE=t.from_DATE and u.to_DATE = t.to_DATE)
</code>```

Adjust to taste depending on what the key is in your original table (ID would be a candidate).

Body:
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

Body:
You could select them with a join on exactly those rows.

SELECT ItemNUMBER, ID, from_DATE, to_DATE, fancy_code
FROM [Table] t join (
    SELECT ItemNUMBER, ID, from_DATE, to_DATE, count(1)
    FROM [Table] t
    GROUP BY ItemNUMBER, ID, from_DATE, to_DATE
    HAVING count(1) = 1
) u on (u.ItemNUMBER= t.ItemNUMBER and u.ID=t.ID
    and u.from_DATE=t.from_DATE and u.to_DATE = t.to_DATE)

Adjust to taste depending on what the key is in your original table (ID would be a candidate).


问:
Angular eventListener from Directive
I have directive, essentially a button, that should only show on certain conditions. It uses addEventListener('scroll') to capture the scroll of a <ion-content> element in the containing page. This works fine for one page/view but when navigating to another page/view the scroll event is not fired?

'use strict';
angular.module('Fmpclient')
  .directive('fmpRefreshButton', ['$window', '$ionicScrollDelegate', 'RefreshButtonService', function ($window, $ionicScrollDelegate, RefreshButtonService) {

        var hideDelayTime = 3500;
        var isButtonVisible = false;
        var lastYPos = 0;    // store the last Y Position
        var timerId = null;  // store a setTimeout id for later use
        var $scrollEl = null;
        var refreshButton = null;

/* __ code snipped for brevity __ */

        /**
          Work out the direction of scroll so we can
          either hide or show the refresh button according to AC
          @method onScroll
          @public
        */
        function onScroll () {
          var scrollTop = $ionicScrollDelegate.getScrollPosition().top;

          if(scrollTop > lastYPos) {
            // Scrolling DOWN - hide refresh button
            hideRefreshButton();
          } else {
            // Scrolling UP - show refresh button
            shouldRefreshFeed();
          }
          // Store the last Y position to determine
          // direction of scroll on next iteration
          lastYPos = scrollTop;
        }

        /**
          Setup directive elements on init
          @method init
          @public
        */
        function init (){
          console.log('directive::init()');

          RefreshButtonService.setRefreshFeed(false);

          $scrollEl = document.getElementById('ionContentScroll');

          if($scrollEl){
            $scrollEl.addEventListener('scroll', onScroll);
          }
        }

        function _link(scope, element) {
          refreshButton = element[0];

          init();
        }

        return {
            templateUrl: 'app/app/refresh-button/refresh-button.directive.html',
            restrict: 'AE',
            scope: true,
            link: _link,
        };
    }
]);```

答:
As suggested by Scott, in the comment above, the solution to my rather trivial problem was to pass in the id as a parameter to the directive to ensure the id can be unique for each usage:

In the Directive scope:

```<code>scope: {
   scrollElement: '='
},
</code>```

and passed in on the Directive template:

```<code><my-directive scroll-element="ionFeedScroll">
</code>```

Title: Angular eventListener from Directive

Body:
As suggested by Scott, in the comment above, the solution to my rather trivial problem was to pass in the id as a parameter to the directive to ensure the id can be unique for each usage:

In the Directive scope:

scope: {
   scrollElement: '='
},

and passed in on the Directive template:

<my-directive scroll-element="ionFeedScroll">


答:
would normally just delete the duplicitous entry

step 1: get the duplicate entries

step 2: identify itemnumbers from duplicate entries

step 3: delete those itemnumbers

```<code>DELETE FROM table1
WHERE itemnumber IN (SELECT
    itemNumber
  FROM table1 z
  INNER JOIN (SELECT
    fancy_code,
    id,
    from_date,
    to_date
  FROM table1 x
  GROUP BY fancy_code,
           id,
           from_date,
           to_date
  HAVING COUNT(*) > 1) y
    ON y.fancy_code = z.fancy_code
    AND y.id = z.id
    AND y.from_date = z.from_date
    AND y.to_date = z.to_date)
</code>```

Title: Remove duplicates as well as original row

Body:
would normally just delete the duplicitous entry

step 1: get the duplicate entries

step 2: identify itemnumbers from duplicate entries

step 3: delete those itemnumbers

DELETE FROM table1
WHERE itemnumber IN (SELECT
    itemNumber
  FROM table1 z
  INNER JOIN (SELECT
    fancy_code,
    id,
    from_date,
    to_date
  FROM table1 x
  GROUP BY fancy_code,
           id,
           from_date,
           to_date
  HAVING COUNT(*) > 1) y
    ON y.fancy_code = z.fancy_code
    AND y.id = z.id
    AND y.from_date = z.from_date
    AND y.to_date = z.to_date)


问:
should state be nested or flat
For example,

```<code>constructor(props) {
  super(props);
  this.state = {
    interactions: {
      liked: [],
      saved: [],
      receivedLikeRecently: null
  }
}
</code>```

I'm trying to wrap my head around immutability, so if I wanted to now update receivedLikeRecently to true, would I have to do:

```<code>this.setState({
  interactions: {
    receivedLikeRecently: true
  }
});
</code>```

What about the other values?  Do I need to include them as well?

According to the documentation setState does a shallow merge so I assume the other nested properties would not copy over right?  Or am I misunderstanding?

Thanks

答:
You should keep your state flat in order to avoid deep merging, which must be done manually and can get pretty annoying, besides causing a performance hit if done frequently.

Component.setState uses a simple === to test if properties have changed, which will cause it to always update object-valued properties of the state object.

Title: should state be nested or flat

Body:
For example,

constructor(props) {
  super(props);
  this.state = {
    interactions: {
      liked: [],
      saved: [],
      receivedLikeRecently: null
  }
}

I'm trying to wrap my head around immutability, so if I wanted to now update receivedLikeRecently to true, would I have to do:

this.setState({
  interactions: {
    receivedLikeRecently: true
  }
});

What about the other values?  Do I need to include them as well?

According to the documentation setState does a shallow merge so I assume the other nested properties would not copy over right?  Or am I misunderstanding?

Thanks


问:
pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"
I am very new to Python and trying to > pip install linkchecker on Windows 7. Some notes:

pip install is failing no matter the package. For example, > pip install scrapy also results in the SSL error.

Vanilla install of Python 3.4.1 included pip 1.5.6. The first thing I tried to do was install linkchecker. Python 2.7 was already installed, it came with ArcGIS. python and pip were not available from the command line until I installed 3.4.1.

> pip search linkchecker works. Perhaps that is because pip search does not verify the site's SSL certificate.

I am in a company network but we do not go through a proxy to reach the Internet.

Each company computer (including mine) has a Trusted Root Certificate Authority that is used for various reasons including enabling monitoring TLS traffic to https://google.com. Not sure if that has anything to do with it.

Here are the contents of my pip.log after running pip install linkchecker:

Downloading/unpacking linkchecker
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Getting page https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/: connection error: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/ (Caused by <class 'http.client.CannotSendRequest'>: Request-sent)
  Will skip URL https://pypi.python.org/simple/ when looking for download links for linkchecker
  Cannot fetch index base URL https://pypi.python.org/simple/
  URLs to search for versions for linkchecker:
  * https://pypi.python.org/simple/linkchecker/
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Could not find any downloads that satisfy the requirement linkchecker
Cleaning up...
  Removing temporary dir C:\Users\jcook\AppData\Local\Temp\pip_build_jcook...
No distributions at all found for linkchecker
Exception information:
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "C:\Python34\lib\site-packages\pip\commands\install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "C:\Python34\lib\site-packages\pip\req.py", line 1177, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "C:\Python34\lib\site-packages\pip\index.py", line 277, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
pip.exceptions.DistributionNotFound: No distributions at all found for linkchecker
```

答: for me this is because previously I'm running script which set proxy (to fiddler), reopening console or reboot fix the problem.</p>


问:
RMySQL system error: 10060
I have a project with a connection that was working properly on the same device. I suddenly got the error below. And I could connect from the same device through MySQL workbench.

What could be the reason?

```<code>library(RMySQL)

con <- dbConnect(RMySQL::MySQL(),
                 host = "xxx",
                 dbname="yyy",
                 user = "zzz",
                 password = "############")

Error in .local(drv, ...) :
  Failed to connect to database: Error: Lost connection to MySQL server at 'reading authorization packet', system error: 10060
</code>```

And here's the session info

```<code>> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RMySQL_0.10.10 DBI_0.4-1

loaded via a namespace (and not attached):
[1] tools_3.3.1
</code>```

答:
My code started having this exact problem after doing a system wide package update on 3/29/2017 for the first time since 2/1/2017.

Looking at the versioning for RMySQL,
RMySQL_0.10.9.tar.gz published 2016-05-08 15:39
RMySQL_0.10.10.tar.gz published 2017-03-21 07:50

I reverted my version to 0.10.9 and the problem went away:

```<code>require(devtools)
install_version("RMySQL", version = "0.10.9", repos = "http://cran.us.r-project.org")
</code>```

I posted your issue to the RMySQL bug page, so we'll see if they address it

Title: RMySQL system error: 10060

Body:
I have a project with a connection that was working properly on the same device. I suddenly got the error below. And I could connect from the same device through MySQL workbench.

What could be the reason?

library(RMySQL)

con <- dbConnect(RMySQL::MySQL(),
                 host = "xxx",
                 dbname="yyy",
                 user = "zzz",
                 password = "############")

Error in .local(drv, ...) :
  Failed to connect to database: Error: Lost connection to MySQL server at 'reading authorization packet', system error: 10060

And here's the session info

> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RMySQL_0.10.10 DBI_0.4-1

loaded via a namespace (and not attached):
[1] tools_3.3.1

Body:
My code started having this exact problem after doing a system wide package update on 3/29/2017 for the first time since 2/1/2017.

Looking at the versioning for RMySQL,
RMySQL_0.10.9.tar.gz published 2016-05-08 15:39
RMySQL_0.10.10.tar.gz published 2017-03-21 07:50

I reverted my version to 0.10.9 and the problem went away:

require(devtools)
install_version("RMySQL", version = "0.10.9", repos = "http://cran.us.r-project.org")

I posted your issue to the RMySQL bug page, so we'll see if they address it


问:
WPF Update binding properties of multiple items contained in a list at the same time
I'm binding a list of object to an ItemsControl which contain a TextBox control.

I want to be able to change the textbox background color based on the background color property of the bind object.

It works perfectly with the INotifyPropertyChanged interface but when I need to update let say 1000 objects it takes a huge amount of time I guess because it needs to update the controls one by one.

Does someone has a tip for me to lets say, update all my objects background color and than update the binding in one shot instead of object by object?

Thanks,

Mat

答:
If you use virtualization, it'll only need to update the items that are visible - normally items controls will only track property changes on the items that are currently visible. However, if you're using the base ItemsControl, virtualization will be off by default. To turn it on, you need to provide a custom template that includes a ScrollViewer with CanContentScroll set to True, and you also need to use a VirtualizingStackPanel, either in the control template, or via the ItemsPanel - this shows the former approach:

```<code><ItemsControl ItemsSource="...whatever...">
  <ItemsControl.Template>
    <ControlTemplate TargetType="ItemsControl">
      <ScrollViewer CanContentScroll="True">
        <VirtualizingStackPanel IsItemsHost="True" />
      </ScrollViewer>
    </ControlTemplate>
  </ItemsControl.Template>
</ItemsControl>
</code>```

Virtualization improves performance with large numbers of list items in various ways. It should help your scenario, but it may also improve other aspects of the performance. It's not without its problems, but I'd definitely try it here first before attempting other solutions.

Body:
If you use virtualization, it'll only need to update the items that are visible - normally items controls will only track property changes on the items that are currently visible. However, if you're using the base ItemsControl, virtualization will be off by default. To turn it on, you need to provide a custom template that includes a ScrollViewer with CanContentScroll set to True, and you also need to use a VirtualizingStackPanel, either in the control template, or via the ItemsPanel - this shows the former approach:

<ItemsControl ItemsSource="...whatever...">
  <ItemsControl.Template>
    <ControlTemplate TargetType="ItemsControl">
      <ScrollViewer CanContentScroll="True">
        <VirtualizingStackPanel IsItemsHost="True" />
      </ScrollViewer>
    </ControlTemplate>
  </ItemsControl.Template>
</ItemsControl>

Virtualization improves performance with large numbers of list items in various ways. It should help your scenario, but it may also improve other aspects of the performance. It's not without its problems, but I'd definitely try it here first before attempting other solutions.


问:
Java Stripe API
I'm trying to bind a token as a customer card. So, this token has been created by Stripe.js. So, then I send this code on my backend service and I'm trying to set it up into a customer's cards:

```<code>Card card = Token.retrieve(id).getCard();
</code>```

So, once I've got this token as a card, I'm trying it:

```<code>Customer.retrieve(this.customer).getSources().create(card.getMetadata())
</code>```

Nevertheless, I'm getting this compilation error:

The method create(Map) in the type ExternalAccountCollection is not applicable for the arguments (Map)

Any ideas?

答:
You can find the documentation for adding a card to an existing customer object here: https://stripe.com/docs/api/java#create_card.

The correct code would be:

```<code>Customer customer = Customer.retrieve(this.customer);
Map<String, Object> params = new HashMap<String, Object>();
params.put("source", id);
Card card = customer.getSources().create(params);
</code>```

Title: Java Stripe API

Body:
I'm trying to bind a token as a customer card. So, this token has been created by Stripe.js. So, then I send this code on my backend service and I'm trying to set it up into a customer's cards:

Card card = Token.retrieve(id).getCard();

So, once I've got this token as a card, I'm trying it:

Customer.retrieve(this.customer).getSources().create(card.getMetadata())

Nevertheless, I'm getting this compilation error:

The method create(Map) in the type ExternalAccountCollection is not applicable for the arguments (Map)

Any ideas?

Body:
You can find the documentation for adding a card to an existing customer object here: https://stripe.com/docs/api/java#create_card.

The correct code would be:

Customer customer = Customer.retrieve(this.customer);
Map<String, Object> params = new HashMap<String, Object>();
params.put("source", id);
Card card = customer.getSources().create(params);


问:
List of List - String Java 8 forEach feature. Looking for explanation of the output i got
I am trying to implement forEach function of Java 8. This programs prints lists of list content. (Please go through my code, my question is at the end of this post)
Below is my program:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class OrderOfStrings {

    public static void main(String[] args) {

        List<String> list1 = new ArrayList<String>();
        List<String> list2 = new ArrayList<String>();

        list1.add("a");
        list2.add("b");
        list1.add("c");
        list2.add("d");
        list1.add("e");
        list2.add("f");

        List<ArrayList<String>> list3 = new ArrayList<ArrayList<String>>();
        list3.add((ArrayList<String>) list1);
        list3.add((ArrayList<String>) list2);

        list3.forEach(new Consumer<ArrayList<String>>(){

            @Override
            public void accept(ArrayList<String> t) {
                System.out.println( t.get(0));
                //System.out.println( t.get(1));

            }

        });

    }

}
</code>```

Output of this program:

```<code>a
b
</code>```

My question is : If i call list3.get(0) i should be getting a,c,e ? Isn't? Is this about Data Structure?

答:
The code you wrote is the equivalent to the following in Java 7:

```<code>for (ArrayList<String> t : list3) {
    System.out.println(t.get(0));
}
</code>```

Your contents of list3 are as follows:

```<code>[a,c,e],[b,d,f]
</code>```

For each of these two lists, you are printing the element at index 0.  In the first sublist, that would be a; on the second, that would be b.

Body:
I am trying to implement forEach function of Java 8. This programs prints lists of list content. (Please go through my code, my question is at the end of this post)
Below is my program:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class OrderOfStrings {

    public static void main(String[] args) {

        List<String> list1 = new ArrayList<String>();
        List<String> list2 = new ArrayList<String>();

        list1.add("a");
        list2.add("b");
        list1.add("c");
        list2.add("d");
        list1.add("e");
        list2.add("f");

        List<ArrayList<String>> list3 = new ArrayList<ArrayList<String>>();
        list3.add((ArrayList<String>) list1);
        list3.add((ArrayList<String>) list2);

        list3.forEach(new Consumer<ArrayList<String>>(){

            @Override
            public void accept(ArrayList<String> t) {
                System.out.println( t.get(0));
                //System.out.println( t.get(1));

            }

        });

    }

}

Output of this program:

a
b

My question is : If i call list3.get(0) i should be getting a,c,e ? Isn't? Is this about Data Structure?

Body:
The code you wrote is the equivalent to the following in Java 7:

for (ArrayList<String> t : list3) {
    System.out.println(t.get(0));
}

Your contents of list3 are as follows:

[a,c,e],[b,d,f]

For each of these two lists, you are printing the element at index 0.  In the first sublist, that would be a; on the second, that would be b.


问:
ETag and If-None-Match HTTP Headers are not working
I have a file in my webserver and I am downloading that to my app everytime I access it because its possible that file content might be changed But If it is changed I would like to download that time only so bandwidth can be saved and fortunately that's what this ETag and If-None-Match header fields are for.

When I make a request first time ,I retrieve the ETag from the HTTP response headers

In the subsequent requests to download that file I'd attach the Etag value for If-None-Match headerfield so that if there is no change then I'd get HTTP response status code 304 or else I'd get 200 if there is a change in the file.

Note:

When I try the above steps in Advanced REST Client Application in chrome it works fine as it is supposed to be but when I try that in iOS I always get the response code 200 but it should have given me 304 for the subsequent requests.

Here is the sample code I use

```<code>var request1 =  NSMutableURLRequest(URL:NSURL(string: "http://10.12.1.101/Etag/ringtone1.mp3")!)
let Etagvalue="\"36170-52c1cc36d9b40\""
var session1 = NSURLSession.sharedSession()
request1.HTTPMethod = "GET"
var err: NSError?
request1.addValue(Etagvalue, forHTTPHeaderField: "If-None-Match")

var task = session1.dataTaskWithRequest(request1, completionHandler: {data, response, error -> Void in
       print("response: \(response)")

})
</code>```

Here is the response

response: Optional( { URL:
  http://10.12.1.101/Etag/ringtone1.mp3 } { status code: 200, headers {
      "Accept-Ranges" = bytes;
      Connection = "Keep-Alive";
      "Content-Length" = 221552;
      "Content-Type" = "audio/mpeg";
      Date = "Wed, 24 Feb 2016 14:57:53 GMT";
      Etag = "\"36170-52c1cc36d9b40\"";
      "Keep-Alive" = "timeout=5, max=100";
      "Last-Modified" = "Fri, 19 Feb 2016 10:15:33 GMT";
      Server = "Apache/2.4.16 (Unix) PHP/5.5.29"; } })

What am I doing wrong here ?

答:
CachePolicy naming convention is confusing and better yet it actually does not implement some of them...

This article explains them well. http://nshipster.com/nsurlcache/

Also, if you let the Cache Policy to use UseProtocolCachePolicy then your NSURLSession will receive Status code 200 with response generated from Cache.

Body:
I have a file in my webserver and I am downloading that to my app everytime I access it because its possible that file content might be changed But If it is changed I would like to download that time only so bandwidth can be saved and fortunately that's what this ETag and If-None-Match header fields are for.

When I make a request first time ,I retrieve the ETag from the HTTP response headers

In the subsequent requests to download that file I'd attach the Etag value for If-None-Match headerfield so that if there is no change then I'd get HTTP response status code 304 or else I'd get 200 if there is a change in the file.

Note:

When I try the above steps in Advanced REST Client Application in chrome it works fine as it is supposed to be but when I try that in iOS I always get the response code 200 but it should have given me 304 for the subsequent requests.

Here is the sample code I use

var request1 =  NSMutableURLRequest(URL:NSURL(string: "http://10.12.1.101/Etag/ringtone1.mp3")!)
let Etagvalue="\"36170-52c1cc36d9b40\""
var session1 = NSURLSession.sharedSession()
request1.HTTPMethod = "GET"
var err: NSError?
request1.addValue(Etagvalue, forHTTPHeaderField: "If-None-Match")

var task = session1.dataTaskWithRequest(request1, completionHandler: {data, response, error -> Void in
       print("response: \(response)")

})

Here is the response

response: Optional( { URL:
  http://10.12.1.101/Etag/ringtone1.mp3 } { status code: 200, headers {
      "Accept-Ranges" = bytes;
      Connection = "Keep-Alive";
      "Content-Length" = 221552;
      "Content-Type" = "audio/mpeg";
      Date = "Wed, 24 Feb 2016 14:57:53 GMT";
      Etag = "\"36170-52c1cc36d9b40\"";
      "Keep-Alive" = "timeout=5, max=100";
      "Last-Modified" = "Fri, 19 Feb 2016 10:15:33 GMT";
      Server = "Apache/2.4.16 (Unix) PHP/5.5.29"; } })

What am I doing wrong here ?


问:
Finding the highest COUNT in a GROUP BY query
Hello I am new in postgresql . Here is my code for grouping the options and counting them . I want a way though to get only the option with the max count . Is there any way ?</p>

```<code>SELECT s.option, COUNT(*)
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option
</code>```

答:
You can simplify the query.  Not only by using PROPER, explicit JOIN syntax, but also by getting rid of Set:

```<code>SELECT l.option, COUNT(*)
FROM "Lecture" l JOIN
     "Process" p
     ON l.type = p.type JOIN
     "donation" d
     ON d.code = p.code
GROUP BY l.option
ORDER BY COUNT(*) DESC
FETCH FIRST 1 ROW ONLY;
</code>```

Body:
Hello I am new in postgresql . Here is my code for grouping the options and counting them . I want a way though to get only the option with the max count . Is there any way ?

SELECT s.option, COUNT(*)
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option

Body:
You can simplify the query.  Not only by using PROPER, explicit JOIN syntax, but also by getting rid of Set:

SELECT l.option, COUNT(*)
FROM "Lecture" l JOIN
     "Process" p
     ON l.type = p.type JOIN
     "donation" d
     ON d.code = p.code
GROUP BY l.option
ORDER BY COUNT(*) DESC
FETCH FIRST 1 ROW ONLY;


问:
How to Animate a Border Below a Horizontal Nav Item from Left to Right
Id like to animate a border in a horizontal navigation from left to right on hover.  The closest example I have been able to find is the one here: http://css-tricks.com/examples/MagicLine/ but its not what im looking for.

I just want to hover and have an underline simply draw from left to right.

Thanks for any advice.

答:
a {
  text-decoration: none;
  position: relative;
  color: grey;
  padding: 4px;
  font-size: 2rem;
  font-weight: bold;
}
a:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0%;
  border-bottom: 5px solid red;
  transition: 0.5s;
}
a:hover:after {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Test Link</code>```

Body:
a {
  text-decoration: none;
  position: relative;
  color: grey;
  padding: 4px;
  font-size: 2rem;
  font-weight: bold;
}
a:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0%;
  border-bottom: 5px solid red;
  transition: 0.5s;
}
a:hover:after {
  width: 100%;
}

<a href ="#">Test Link</a>


问:
I'm Trying to sort a user's post by location and displaying the distance using PFGeopoint and Swift
I'm attempting to sort user's post by distance and hide any that would be over a certain set of miles. I'm also trying to sort from nearest to farthest all in my UITableview:

```<code>class FindAParty:UITableViewController{

    //var partyData:NSMutableArray! = NSMutableArray()
    var partyData = [PFObject]()
    //var user:NSMutableArray = NSMutableArray()

    override init(style: UITableViewStyle){
        super.init(style: style)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //fatalError("init(coder:) has not been implemented")

    }

    @IBAction func loadData(){

        PFGeoPoint.geoPointForCurrentLocation { (geopoint, error) in

            print(geopoint)
            if let geopoint = geopoint {
                PFUser.current()?.remove(forKey: "Location")

                print ("True")
            PFUser.current()? ["Location"] = geopoint
                PFUser.current()?.saveInBackground()

             }

        }

        print ("Load Data went through")
        partyData.removeAll()
        print ("Remove ALL Objeccts")
        let findPartyData = PFQuery(className: "Party")

        print("PFQuery...")
        findPartyData.findObjectsInBackground {
            (objects:[PFObject]?, error:Error?)->Void in

            if error != nil {
                print(error!)
            } else{
                if let objects = objects {
                    self.partyData = objects.reversed()
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        self.loadData()
        print("View Did Appear")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print("ViewDidLoad")
        //self.loadData()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // #pragma mark - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return partyData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FindAPartyCell

       let party = self.partyData[indexPath.row]

        cell.typeOfPartyLabel.alpha = 0
        cell.timeOfPartyLabel.alpha = 0
        cell.usernameLabel.alpha = 0
        cell.alcoholTFLabel.alpha = 0

        cell.typeOfPartyLabel.text = party.object(forKey: "partyTitle") as? String
        cell.timeOfPartyLabel.text = party.object(forKey: "partyTime") as? String
        cell.usernameLabel.text = party.object(forKey: "Usernames") as? String
        cell.alcoholTFLabel.text = party.object(forKey: "ATF") as? String

       // var dataFormatter:NSDateFormatter = NSDateFormatter()
        //dataFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        //cell.timestampLabel.text = dataFormatter.stringFromDate(sweet.createdAt)

       /* let findUser:PFQuery = PFUser.query()!
        findUser.whereKey("objectId", equalTo: party.object(forKey: "Username")!)

        findUser.findObjectsInBackground {
            (objects:[PFObject]?, error: Error?) -> Void in // Changes NSError to Error
            if error == nil{

                let user:PFUser = (objects)!.last as! PFUser
                cell.usernameLabel.text = user.username

               */ UIView.animate(withDuration: 0.5, animations: {
                    cell.typeOfPartyLabel.alpha = 1
                    cell.timeOfPartyLabel.alpha = 1
                    cell.usernameLabel.alpha = 1
                    cell.alcoholTFLabel.alpha = 1
                })
            //}
        //}

        return cell
    }

}
</code>```

I would also like to show the distance if possible.
Thank You for any advice

答:
You could use geo-queries, provided by Parse.

whereKey:nearGeoPoint

Returns an array of objects ordered by distance (nearest to farthest)

whereKey:nearGeoPoint:withinMiles/ whereKey:nearGeoPoint:withinKilometers

Limit the results using distance (m/km)

Query Users by "Location" (you should consider using lowercase for attributes)

let query = PFUser.query()!
query.whereKey("Location", nearGeoPoint: geopoint)

Get their posts...(Separate Posts table ? Uses Relationships?)

Body:
I'm attempting to sort user's post by distance and hide any that would be over a certain set of miles. I'm also trying to sort from nearest to farthest all in my UITableview:

class FindAParty:UITableViewController{

    //var partyData:NSMutableArray! = NSMutableArray()
    var partyData = [PFObject]()
    //var user:NSMutableArray = NSMutableArray()

    override init(style: UITableViewStyle){
        super.init(style: style)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //fatalError("init(coder:) has not been implemented")

    }

    @IBAction func loadData(){

        PFGeoPoint.geoPointForCurrentLocation { (geopoint, error) in

            print(geopoint)
            if let geopoint = geopoint {
                PFUser.current()?.remove(forKey: "Location")

                print ("True")
            PFUser.current()? ["Location"] = geopoint
                PFUser.current()?.saveInBackground()

             }

        }

        print ("Load Data went through")
        partyData.removeAll()
        print ("Remove ALL Objeccts")
        let findPartyData = PFQuery(className: "Party")

        print("PFQuery...")
        findPartyData.findObjectsInBackground {
            (objects:[PFObject]?, error:Error?)->Void in

            if error != nil {
                print(error!)
            } else{
                if let objects = objects {
                    self.partyData = objects.reversed()
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        self.loadData()
        print("View Did Appear")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print("ViewDidLoad")
        //self.loadData()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // #pragma mark - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return partyData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FindAPartyCell

       let party = self.partyData[indexPath.row]

        cell.typeOfPartyLabel.alpha = 0
        cell.timeOfPartyLabel.alpha = 0
        cell.usernameLabel.alpha = 0
        cell.alcoholTFLabel.alpha = 0

        cell.typeOfPartyLabel.text = party.object(forKey: "partyTitle") as? String
        cell.timeOfPartyLabel.text = party.object(forKey: "partyTime") as? String
        cell.usernameLabel.text = party.object(forKey: "Usernames") as? String
        cell.alcoholTFLabel.text = party.object(forKey: "ATF") as? String

       // var dataFormatter:NSDateFormatter = NSDateFormatter()
        //dataFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        //cell.timestampLabel.text = dataFormatter.stringFromDate(sweet.createdAt)

       /* let findUser:PFQuery = PFUser.query()!
        findUser.whereKey("objectId", equalTo: party.object(forKey: "Username")!)

        findUser.findObjectsInBackground {
            (objects:[PFObject]?, error: Error?) -> Void in // Changes NSError to Error
            if error == nil{

                let user:PFUser = (objects)!.last as! PFUser
                cell.usernameLabel.text = user.username

               */ UIView.animate(withDuration: 0.5, animations: {
                    cell.typeOfPartyLabel.alpha = 1
                    cell.timeOfPartyLabel.alpha = 1
                    cell.usernameLabel.alpha = 1
                    cell.alcoholTFLabel.alpha = 1
                })
            //}
        //}

        return cell
    }

}

I would also like to show the distance if possible.
Thank You for any advice


问:
Expression in FOR section of PIVOT
I'm trying to use PIVOT to get the total weight of purchases per product, broken down by year/month in columns. Something like this:

```<code>+------------+--------+--------+--------+
| ProductKey | Jan-14 | Feb-14 | Mar-14 | Etc...
+------------+--------+--------+--------+
|         10 |   5000 |   7000 |   3000 |
|         20 |  10000 |   8000 |   6000 |
|         30 |    250 |    500 |    400 |
+------------+--------+--------+--------+
</code>```

This is my first time trying to use PIVOT, so not sure this is right:

```<code>PIVOT
(
SUM([PO_PurchaseOrderLines].[EstimatedWeight])
FOR
LEFT(DATENAME(MONTH,[PO_Date]),3) & "-" & RIGHT(YEAR([PO_Date]),2)
IN (Jan-14, Feb-14, Mar-14, Apr-14, May-14, Jun-14, Jul-14, Aug-14, Sep-14, Oct-14, Nov-14, Dec-14, Jan-15, Feb-15, Mar-15, Apr-15, May-15, Jun-15, Jul-15, Aug-15, Sep-15, Oct-15, Nov-15, Dec-15, Jan-16, Feb-16, Mar-16, Apr-16, May-16, Jun-16, Jul-16, Aug-16, Sep-16, Oct-16, Nov-16, Dec-16, Jan-17, Feb-17, Mar-17)
) AS POPivot
</code>```

Running this results in:

```<code>[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'LEFT'.
</code>```

Is using an expression like this in the FOR section not possible? Is there something else incorrect?

答: You can't use an expression in the FOR section, it needs to be a column in the query you're trying to pivot. I recommend performing that operation and assigning the value to a column in your initial query and then referencing that column under FOR.

Title: Expression in FOR section of PIVOT

Body:
I'm trying to use PIVOT to get the total weight of purchases per product, broken down by year/month in columns. Something like this:

+------------+--------+--------+--------+
| ProductKey | Jan-14 | Feb-14 | Mar-14 | Etc...
+------------+--------+--------+--------+
|         10 |   5000 |   7000 |   3000 |
|         20 |  10000 |   8000 |   6000 |
|         30 |    250 |    500 |    400 |
+------------+--------+--------+--------+

This is my first time trying to use PIVOT, so not sure this is right:

PIVOT
(
SUM([PO_PurchaseOrderLines].[EstimatedWeight])
FOR
LEFT(DATENAME(MONTH,[PO_Date]),3) & "-" & RIGHT(YEAR([PO_Date]),2)
IN (Jan-14, Feb-14, Mar-14, Apr-14, May-14, Jun-14, Jul-14, Aug-14, Sep-14, Oct-14, Nov-14, Dec-14, Jan-15, Feb-15, Mar-15, Apr-15, May-15, Jun-15, Jul-15, Aug-15, Sep-15, Oct-15, Nov-15, Dec-15, Jan-16, Feb-16, Mar-16, Apr-16, May-16, Jun-16, Jul-16, Aug-16, Sep-16, Oct-16, Nov-16, Dec-16, Jan-17, Feb-17, Mar-17)
) AS POPivot

Running this results in:

[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'LEFT'.

Is using an expression like this in the FOR section not possible? Is there something else incorrect?