答:
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.

MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.

Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards

And to go back to your question ,and to update it a bit.

Instead of doing

```<code>  mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
</code>```

I would do it this way:

```<code><?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //your data
    $id = 1; // id

    $stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $data = $stmt->fetchAll();

    foreach ($data as $row) {
        echo $row["row_name"];
    }

    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
</code>```

Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.

I had the same problem ,but thanks to right people on this site i have managed to learn more.

My suggestion is that you read about PSR,PDO and PHP in general!!!

Also a thing you should consider reading about is security in php.

Good luck mate  :D

Title: How to SELECT column value FROM table?

Body:
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.

MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.

Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards

And to go back to your question ,and to update it a bit.

Instead of doing

  mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");

I would do it this way:

<?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //your data
    $id = 1; // id

    $stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $data = $stmt->fetchAll();

    foreach ($data as $row) {
        echo $row["row_name"];
    }

    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }

Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.

I had the same problem ,but thanks to right people on this site i have managed to learn more.

My suggestion is that you read about PSR,PDO and PHP in general!!!

Also a thing you should consider reading about is security in php.

Good luck mate  :D


来源: stackexchange

问:
SQL Server: Max date query returning nothing but null
I've researched this, but haven't found anything that has worked.  I'm looking to return the max date for multiple columns, some of which have null values. My query is returning nothing but null for every column. How can I get the actual max dates? Thanks in advance.</p>

```<code>create table Results
(
    PatientName varchar(50),
    Bordetella datetime,
    [Canine Distemper] datetime,
    Rabies datetime
);

select
    PatientName, Bordetella, [Canine Distemper], Rabies
from
    (select
         PatientName,
         ReminderName,
         DueDate
     from
         Results) d
pivot
(
  max(DueDate)
  for ReminderName in (Bordetella, [Canine Distemper], Rabies)
)piv
;
</code>```

答:
This should be reading:</p>

```<code>create table Results
(
    PatientName varchar(50)
    ,ReminderName varchar(50)
    ,DueDate datetime
);

select
    PatientName
    ,Bordetella
    ,[Canine Distemper]
    ,Rabies
from (
    select
         PatientName
         ,ReminderName
         ,DueDate
    from Results
) d pivot (
    max(DueDate) for ReminderName in (Bordetella, [Canine Distemper], Rabies)
) pvt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've researched this, but haven't found anything that has worked.  I'm looking to return the max date for multiple columns, some of which have null values. My query is returning nothing but null for every column. How can I get the actual max dates? Thanks in advance.

create table Results
(
    PatientName varchar(50),
    Bordetella datetime,
    [Canine Distemper] datetime,
    Rabies datetime
);

select
    PatientName, Bordetella, [Canine Distemper], Rabies
from
    (select
         PatientName,
         ReminderName,
         DueDate
     from
         Results) d
pivot
(
  max(DueDate)
  for ReminderName in (Bordetella, [Canine Distemper], Rabies)
)piv
;

Body:
This should be reading:

create table Results
(
    PatientName varchar(50)
    ,ReminderName varchar(50)
    ,DueDate datetime
);

select
    PatientName
    ,Bordetella
    ,[Canine Distemper]
    ,Rabies
from (
    select
         PatientName
         ,ReminderName
         ,DueDate
    from Results
) d pivot (
    max(DueDate) for ReminderName in (Bordetella, [Canine Distemper], Rabies)
) pvt


问:
Add a custom header to Aurelia Fetch request
I'm trying to use Aurelia's Fetch Client to add a custom header to all GET and POST request.  The following code (in app.js constructor) works to set the base URL but the headers are not working the way I want:

```<code>constructor(httpClient) {
  // set up httpClient
  httpClient.configure(config => {
    config
      .withBaseUrl(localsettings.api)
      .withDefaults({
        credentials: 'include',
        headers: {
          'my_appkey': 'f2eabc5e7de-a4cdc857e'
        }
      })
  });
  this.httpClient = httpClient;
}
</code>```

Usage:

```<code>this.httpClient.fetch(suburl, {
    credentials: 'include'
  }).then(response => { ... });
</code>```

Through Chrome's development tools, I can see that the "my_appkey" header exists but it's not being created as it's own header and its value is not visible:

Request Headers:

```<code>OPTIONS /index.php/api/v1/keys HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: my_appkey
Accept: */*
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es-419;q=0.6,es;q=0.4
</code>```

What am I doing wrong?  Why is my custom header being moved into Access-Control-Request-Headers?

答:
Adding the my_appkey header to the request triggers the browser to first perform a CORS preflight OPTIONS request before attempting the actual GET/POST request you want to make.

```<code>OPTIONS /index.php/api/v1/keys HTTP/1.1
^^^^^^^
</code>```

As part of that preflight OPTIONS, the browser sends an Access-Control-Request-Headers header whose value includes the names of headers you’ve added to the request from your code.

The Access-Control-Request-Headers request header is used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.

So what you’re seeing is all expected behavior.

And in order for the browser to consider that preflight OPTIONS request a success, the server the request is made to must send a response that has an Access-Control-Allow-Headers response header whose value also includes "my_appkey". If it does not, then the browser stops right there and never proceeds to send the actual GET/POST request you want to make.

Body:
I'm trying to use Aurelia's Fetch Client to add a custom header to all GET and POST request.  The following code (in app.js constructor) works to set the base URL but the headers are not working the way I want:

constructor(httpClient) {
  // set up httpClient
  httpClient.configure(config => {
    config
      .withBaseUrl(localsettings.api)
      .withDefaults({
        credentials: 'include',
        headers: {
          'my_appkey': 'f2eabc5e7de-a4cdc857e'
        }
      })
  });
  this.httpClient = httpClient;
}

Usage:

this.httpClient.fetch(suburl, {
    credentials: 'include'
  }).then(response => { ... });

Through Chrome's development tools, I can see that the "my_appkey" header exists but it's not being created as it's own header and its value is not visible:

Request Headers:

OPTIONS /index.php/api/v1/keys HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: my_appkey
Accept: */*
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es-419;q=0.6,es;q=0.4

What am I doing wrong?  Why is my custom header being moved into Access-Control-Request-Headers?

Body:
Adding the my_appkey header to the request triggers the browser to first perform a CORS preflight OPTIONS request before attempting the actual GET/POST request you want to make.

OPTIONS /index.php/api/v1/keys HTTP/1.1
^^^^^^^

As part of that preflight OPTIONS, the browser sends an Access-Control-Request-Headers header whose value includes the names of headers you’ve added to the request from your code.

The Access-Control-Request-Headers request header is used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.

So what you’re seeing is all expected behavior.

And in order for the browser to consider that preflight OPTIONS request a success, the server the request is made to must send a response that has an Access-Control-Allow-Headers response header whose value also includes "my_appkey". If it does not, then the browser stops right there and never proceeds to send the actual GET/POST request you want to make.


问:
Shapeless not working in generic context
I am still trying to get my head around Shapeless (and, to a lesser extent, Scala!) and I have been writing some simple code to generate random instance data for case classes - predominantly based on the guides here: http://enear.github.io/2016/09/27/bits-of-shapeless-2/ (the example covers a JSON Writer implementation)

I have created a Generator[A] trait and created implicit implementations for simple types, and as per the example in the above link, I have also created implicit implementations to handle HList, HNil, Coproduct and CNil:

```<code>  implicit def hnilGenerator = new Generator[HNil] {
    override def generate(a: HNil) = HNil
  }

  implicit def hconsGenerator[H, T <: HList](implicit headGen: Generator[H], tailGen: Generator[T]) =
    new Generator[H :: T] {
      override def generate(a: H :: T) = headGen.generate(a.head) :: tailGen.generate(a.tail)
    }

  implicit def cnilGenerator: Generator[CNil] =
    new Generator[CNil] {
      override def generate(a: CNil): CNil = throw new RuntimeException("Invalid candidate configuration")
    }

  implicit def cconsGenerator[H, T <: Coproduct] =
    new Generator[H :+: T] {
      override def generate(a: H :+: T) = throw new RuntimeException("Invalid candidate configuration")
    }
</code>```

I can now use this code to generate a random instance based on a case class or a sealed trait:

```<code>    it("should work with a case class to hlist") {
      case class Test(x: IntGene, y: DoubleGene, z: BooleanGene)
      val c = Generic[Test].to(Test(IntGene(), DoubleGene(), BooleanGene()))
      generate(c)
    }
    it("what happens with sealed traits") {
      sealed trait Shape
      case class Square(width: Int, height: Int) extends Shape
      case class Circle(radius: Int) extends Shape

      val c = Generic[Shape].to(Circle(1))
      generate(c)
    }
</code>```

Both of the above work no problem, however, if I try to make this a generic (as in parameter types) I get compilation errors not being able to find the necessary implicts:

```<code>it("should handle generics") {
  case class GenericTest[A: Generic](x: A) {
    def convert() = {
      val c = Generic[A].to(x)
      generate(c)
    }
  }
}
</code>```

So from my understanding, because I have used the Generic context bound A, the compiler knows that is going to be available, so c must be some possible return from the call to(x) - Am I missing something in the implementation to handle that return type from the Generic shapeless call? Or have I wildly misunderstood something?

I am hoping this is possible and I have just missed something - is it that the compiler doesn't know what will be passed in (Im assuming not), or is there another possible type that needs to be handled implicitly from that to(x) call?

EDIT

Compile error added below - I'm really just trying to understand: Is it that there is some return case from the to(x) shapeless call that I have not catered for, or is it because the compiler doesn't have any idea what will be passed in and there are some types not catered for (e.g. I haven't added a Date generator implicit - and a case class could potentially have any type included? I was hoping that was not the case, and as the compiler knows nothing is actually being passed to the class/method it knows there are no issues?)

```<code>GeneratorSpec.scala:44: could not find implicit value for parameter gen: io.github.robhinds.genotype.Generator[GenericTest.this.evidence$1.Repr]
          generate(c)
</code>```

And my generate method is just a simple helper method that gets given the implicit Generator :

```<code>def generate[A](a: A)(implicit gen: Generator[A]) = gen.generate(a)
</code>```

答:
I think you are missing the Generator type bound.</p>

```<code>it("should handle generics") {
  case class GenericTest[A: Generic : Generator](x: A) {
    def convert() = {
      val c = Generic[A].to(x)
      generate(c)
    }
  }
}
</code>```

Body:
I am still trying to get my head around Shapeless (and, to a lesser extent, Scala!) and I have been writing some simple code to generate random instance data for case classes - predominantly based on the guides here: http://enear.github.io/2016/09/27/bits-of-shapeless-2/ (the example covers a JSON Writer implementation)

I have created a Generator[A] trait and created implicit implementations for simple types, and as per the example in the above link, I have also created implicit implementations to handle HList, HNil, Coproduct and CNil:

  implicit def hnilGenerator = new Generator[HNil] {
    override def generate(a: HNil) = HNil
  }

  implicit def hconsGenerator[H, T <: HList](implicit headGen: Generator[H], tailGen: Generator[T]) =
    new Generator[H :: T] {
      override def generate(a: H :: T) = headGen.generate(a.head) :: tailGen.generate(a.tail)
    }

  implicit def cnilGenerator: Generator[CNil] =
    new Generator[CNil] {
      override def generate(a: CNil): CNil = throw new RuntimeException("Invalid candidate configuration")
    }

  implicit def cconsGenerator[H, T <: Coproduct] =
    new Generator[H :+: T] {
      override def generate(a: H :+: T) = throw new RuntimeException("Invalid candidate configuration")
    }

I can now use this code to generate a random instance based on a case class or a sealed trait:

    it("should work with a case class to hlist") {
      case class Test(x: IntGene, y: DoubleGene, z: BooleanGene)
      val c = Generic[Test].to(Test(IntGene(), DoubleGene(), BooleanGene()))
      generate(c)
    }
    it("what happens with sealed traits") {
      sealed trait Shape
      case class Square(width: Int, height: Int) extends Shape
      case class Circle(radius: Int) extends Shape

      val c = Generic[Shape].to(Circle(1))
      generate(c)
    }

Both of the above work no problem, however, if I try to make this a generic (as in parameter types) I get compilation errors not being able to find the necessary implicts:

it("should handle generics") {
  case class GenericTest[A: Generic](x: A) {
    def convert() = {
      val c = Generic[A].to(x)
      generate(c)
    }
  }
}

So from my understanding, because I have used the Generic context bound A, the compiler knows that is going to be available, so c must be some possible return from the call to(x) - Am I missing something in the implementation to handle that return type from the Generic shapeless call? Or have I wildly misunderstood something?

I am hoping this is possible and I have just missed something - is it that the compiler doesn't know what will be passed in (Im assuming not), or is there another possible type that needs to be handled implicitly from that to(x) call?

EDIT

Compile error added below - I'm really just trying to understand: Is it that there is some return case from the to(x) shapeless call that I have not catered for, or is it because the compiler doesn't have any idea what will be passed in and there are some types not catered for (e.g. I haven't added a Date generator implicit - and a case class could potentially have any type included? I was hoping that was not the case, and as the compiler knows nothing is actually being passed to the class/method it knows there are no issues?)

GeneratorSpec.scala:44: could not find implicit value for parameter gen: io.github.robhinds.genotype.Generator[GenericTest.this.evidence$1.Repr]
          generate(c)

And my generate method is just a simple helper method that gets given the implicit Generator :

def generate[A](a: A)(implicit gen: Generator[A]) = gen.generate(a)

Body:
I think you are missing the Generator type bound.

it("should handle generics") {
  case class GenericTest[A: Generic : Generator](x: A) {
    def convert() = {
      val c = Generic[A].to(x)
      generate(c)
    }
  }
}


问:
Why does not this table take the rowspan? Html rowspan
I have a problem with the rowspan on a table, html the problem is that the last 4 columns the rowspan is 9 but I do not understand why it is not taking it.

```<code><!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <title>Ejemplo del uso de tablas- aprenderaprogramar.com</title>
  </head>

  <body>

    <table border="2px">
      <!-- Lo cambiaremos por CSS -->
      <div class="with-left-panel" id="MainContent">
        <table border='1'>
          <tr>
            <td>Factura</td>
            <td>Cliente</td>
            <td>Total unidades</td>
            <td>Total venta</td>
            <td>Fecha</td>
            <td>No</td>
            <td>Referencia</td>
            <td>Nombre</td>
            <td>Detalle</td>
            <td>Cantidad</td>
            <td>Precio</td>
            <td>Iva</td>
            <td>Total</td>
          </tr>
          <tr>
            <td rowspan=11>Factura</td>
            <td rowspan=11>Nombre</td>
            <td rowspan=11>2</td>
            <td rowspan=11>161978</td>
            <td rowspan=11>2017-06-01 01:41:06</td>
            rowm spamn 1
            <td rowspan=1> 1</td>
            <td rowspan=1> 12501</td>
            <td rowspan=1> Leche x 25</td>
            <td>Sin Detalle </td>
            <td rowspan=1> 1</td>
            <td rowspan=1> 22686</td>
            <td rowspan=1> 19</td>
            <td rowspan=1> 26996</tr>

          <td rowspan=10> 2</td>
          <td rowspan=10> 12518</td>

          <td rowspan=10> Kit</td>

          <tr>
            <td>K2</td>
            <tr>
              <td>K3</td>
              <tr>
                <td>K4</td>
                <tr>
                  <td>K5</td>
                  <tr>
                    <td>K6</td>
                    <tr>
                      <td>K7</td>
                      <tr>
                        <td>K8</td>
                        <tr>
                          <td>K9</td>
                          <tr>
                            <td>K10</td>

                          <td rowspan=9> 1</td>
                          <td rowspan=9> 456</td>
                          <td rowspan=9> 19</td>
                          <td rowspan=9> 4567

     </tr>

        </table>
  </body>

</html>
</code>```

答: Put those rowspan=9 s (1, 456, 19, 4567) in the same row as K2.

Body:
I have a problem with the rowspan on a table, html the problem is that the last 4 columns the rowspan is 9 but I do not understand why it is not taking it.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Ejemplo del uso de tablas- aprenderaprogramar.com</title>

            Factura
            Cliente
            Total unidades
            Total venta
            Fecha
            No
            Referencia
            Nombre
            Detalle
            Cantidad
            Precio
            Iva
            Total

            Factura
            Nombre
            2
            161978
            2017-06-01 01:41:06
            rowm spamn 1
             1
             12501
             Leche x 25
            Sin Detalle
             1
             22686
             19
             26996

           2
           12518

           Kit

            K2

              K3

                K4

                  K5

                    K6

                      K7

                        K8

                          K9

                            K10

                           1
                           456
                           19
                           4567

Body: Put those rowspan=9 <td>s (1, 456, 19, 4567) in the same row as K2.


问:
SVG 'tspan' element and content not matching
I'm having trouble getting a .on("click") event to work, probably because the displayed text of an element I'm trying to click seems to mismatch its actual DOM element.

The picture illustrates the issue: when my mouse is on the .sublabel2 element (in the example, simply the string []), using Chrome's dev tool, the DOM element is highlighted in another position (blue rectangle upper left).
Any ideas what could be causing this?

The code below is what I am using. Here is how I create the main svg:text node:

```<code>pc.createAxes = function() {
  if (g) pc.removeAxes();

  // Add a group element for each dimension.
  g = pc.svg.selectAll(".dimension")
      .data(pc.getOrderedDimensionKeys(), function(d) {
        return d;
      })
    .enter().append("svg:g")
      .attr("class", "dimension")
      .attr("transform", function(d) {
        return "translate(" + xscale(d) + ")";
      });

 // Add an axis and title.
  myLabelNode = g.append("svg:g")
      .attr("class", "axis")
      .attr("transform", "translate(0,0)")
      .each(function(d) {
        var axisElement = d3.select(this).call( pc.applyAxisConfig(axis, __.dimensions[d]) );

        axisElement.selectAll("path")
            .style("fill", "none")
            .style("stroke", "#222")
            .style("shape-rendering", "crispEdges");

        axisElement.selectAll("line")
            .style("fill", "none")
            .style("stroke", "#222")
            .style("shape-rendering", "crispEdges");
      })
    .append('svg:text') //create a node to append tspans

    setLabels(myLabelNode);
//I skip more less relevant code here for brevity
}
</code>```

And how I position the labels/sublabels in a separate setLabels() function:

```<code>function setLabels(svg_text_node)  {
 svg_text_node.append('tspan')
          .attr({
                "text-anchor": "middle",
                "y": -40,
                "x": 0,
                "dy": 0,
                "class": "label"
          })

        .on("dblclick", flipAxisAndUpdatePCP)
        .on("wheel", rotateLabels)

    svg_text_node.append('tspan')
        .attr({
            "text-anchor": "middle",
            "x": 0,
            "dy": 17,
            "class": "sublabel1"
      })

    svg_text_node.append('tspan')
        .attr({
            "text-anchor": "middle",
            "x": 0,
            "dy": 14,
            "class": "sublabel2"
      })
 }
</code>```

答:
It is showing the highlight in the location that the object would be in had you not repositioned it using your either absolute or relative positioning. The reason the click handler is not working is likely a z-index issue. Try giving the div a z-index higher than the rest of the items on the page and see if your click handler starts working properly.

Whenever you reposition something using absolute or relative positioning, you always need to consider how this will impact z-index and adjust for it accordingly.

Body:
I'm having trouble getting a .on("click") event to work, probably because the displayed text of an element I'm trying to click seems to mismatch its actual DOM element.

The picture illustrates the issue: when my mouse is on the .sublabel2 element (in the example, simply the string []), using Chrome's dev tool, the DOM element is highlighted in another position (blue rectangle upper left).
Any ideas what could be causing this?

The code below is what I am using. Here is how I create the main svg:text node:

pc.createAxes = function() {
  if (g) pc.removeAxes();

  // Add a group element for each dimension.
  g = pc.svg.selectAll(".dimension")
      .data(pc.getOrderedDimensionKeys(), function(d) {
        return d;
      })
    .enter().append("svg:g")
      .attr("class", "dimension")
      .attr("transform", function(d) {
        return "translate(" + xscale(d) + ")";
      });

 // Add an axis and title.
  myLabelNode = g.append("svg:g")
      .attr("class", "axis")
      .attr("transform", "translate(0,0)")
      .each(function(d) {
        var axisElement = d3.select(this).call( pc.applyAxisConfig(axis, __.dimensions[d]) );

        axisElement.selectAll("path")
            .style("fill", "none")
            .style("stroke", "#222")
            .style("shape-rendering", "crispEdges");

        axisElement.selectAll("line")
            .style("fill", "none")
            .style("stroke", "#222")
            .style("shape-rendering", "crispEdges");
      })
    .append('svg:text') //create a node to append tspans

    setLabels(myLabelNode);
//I skip more less relevant code here for brevity
}

And how I position the labels/sublabels in a separate setLabels() function:

function setLabels(svg_text_node)  {
 svg_text_node.append('tspan')
          .attr({
                "text-anchor": "middle",
                "y": -40,
                "x": 0,
                "dy": 0,
                "class": "label"
          })

        .on("dblclick", flipAxisAndUpdatePCP)
        .on("wheel", rotateLabels)

    svg_text_node.append('tspan')
        .attr({
            "text-anchor": "middle",
            "x": 0,
            "dy": 17,
            "class": "sublabel1"
      })

    svg_text_node.append('tspan')
        .attr({
            "text-anchor": "middle",
            "x": 0,
            "dy": 14,
            "class": "sublabel2"
      })
 }


问:
Search/filter for an array
I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.

How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.

What I have:

```<code>var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeydown = function(evt) {
      $("#autocomplete").empty();

      // INSERT CODE FOR SEARCH FUNCTION

}
</code>```

I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?

```<code>var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];

inputBox.onkeydown = function(evt) {
    $("#autocomplete").empty();

    var input, filter, a, i;
    input = document.getElementById("myInput");
    filter = inputBox.value.toUpperCase();
    for (i = 0; i < ingredienten.length; i++) {
        a = ingredienten[i];
        if (a.toUpperCase().indexOf(filter) > -1) {
        //console.log(a);
        $("#autocomplete").append("<li>" + a + "</li>");
        } else {
        }
    }
</code>```

答:
Going under the instructions, you can use a regular expression filter here on your array.

```<code>const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case
</code>```

This will iterate the array and return all the results that match the regex "starts with 'ban'".

You can also do a 0-2 substring match == 'ban' but that's a bit more manual.

Title: Search/filter for an array

Body:
I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.

How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.

What I have:

var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeydown = function(evt) {
      $("#autocomplete").empty();

      // INSERT CODE FOR SEARCH FUNCTION

}

I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?

var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];

inputBox.onkeydown = function(evt) {
    $("#autocomplete").empty();

    var input, filter, a, i;
    input = document.getElementById("myInput");
    filter = inputBox.value.toUpperCase();
    for (i = 0; i < ingredienten.length; i++) {
        a = ingredienten[i];
        if (a.toUpperCase().indexOf(filter) > -1) {
        //console.log(a);
        $("#autocomplete").append("
" + a + "
");
        } else {
        }
    }

Body:
Going under the instructions, you can use a regular expression filter here on your array.

const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case

This will iterate the array and return all the results that match the regex "starts with 'ban'".

You can also do a 0-2 substring match == 'ban' but that's a bit more manual.


问:
React stateless component clearTimeout does not seem to work
I'm having a issue with a component I've built.  One value (inclVal) must be larger than another (exclVal) if both are entered.  I wanted to run the function that handles this with a setTimeout() so that it wouldn't update for a second after the props stop changing to ensure it wouldn't change the value the user is entering while she is entering it.  To this end, I put in a clearTimeout() in an else block to prevent the function from executing if the props change so as to make it redundant.  The problem is that clearTimeout() isn't working for some reason and the update function is running whenever the if block is entered, even though the else block is being entered within the timeout interval.

The component is a stateless functional component and is using redux for state management.  I've read a bunch on how to make these things work, but nothing seems to be helping.  Any help is appreciated!

Here is the code:

```<code>import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import SelectPickerPulldown from '../../components/SelectPickerPulldown'
import TextInput from '../../components/TextInput'

import { odOptions } from '../../config/'
import { setODProperty } from '../../actions/odAnalyzerActions'
import { getConversion, getGreaterVal } from '../../utils/'

const InclusionExclusionOptions = ({  name,
                                      analysisPoint,
                                      paths,
                                      exclVal,
                                      exclUnit,
                                      inclVal,
                                      inclUnit,
                                      getVal,
                                      getUnit,
                                      setSafeInclVal,
                                    }) => {

  const disabled = analysisPoint !== null || paths ? false : true

  let inclEntryTimer = null

  const exclCompare = getConversion(exclUnit)(exclVal)
  const inclCompare = getConversion(inclUnit)(inclVal)

  if (exclVal > 0 && inclVal > 0 && exclCompare > inclCompare) {
    const safeInclVal = getGreaterVal(exclVal, exclUnit, inclUnit)
    console.log('entering timeout');
    inclEntryTimer = setTimeout( () => {
      console.log('dispatching timeout action');
      setSafeInclVal(safeInclVal)
    }, 1000)
  }
  else {
    console.log('clearing timeout');
    clearTimeout(inclEntryTimer)
    inclEntryTimer = null
  }

  return (
    <div className="form-group" >
      <h4>Inclusion/Exclusion Options</h4>
      <ul className={name}>
        <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
          <p>Exclusion Radius</p>
          <div className="radius-setting">
            <TextInput
              type="number"
              name="exclVal"
              value={exclVal}
              onChange={getVal}
              />
            <SelectPickerPulldown
              value={'exclUnit'}
              options={odOptions.units}
              selected={exclUnit}
              getSelected={getUnit}
              />
          </div>
        </li>
        <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
          <p>Inclusion Radius</p>
          <div className="radius-setting">
            <TextInput
              type="number"
              name="inclVal"
              value={inclVal}
              onChange={getVal}
              />
            <SelectPickerPulldown
              value={'inclUnit'}
              options={odOptions.units}
              selected={inclUnit}
              getSelected={getUnit}
              />
          </div>
        </li>
      </ul>
    </div>
  )
}

InclusionExclusionOptions.propTypes = {
  name: PropTypes.string,
  exclVal: PropTypes.number,
  exclUnit: PropTypes.string,
  inclVal: PropTypes.number,
  inclUnit: PropTypes.string,
  getVal: PropTypes.func,
  getUnit: PropTypes.func,
}

const mapStateToProps = (state, ownProps) => {
  const name = 'inclusion-exclusion-options'
  const { analysisPoint,
          paths,
          exclVal,
          exclUnit,
          inclVal,
          inclUnit } = state.odAnalyzerState

  return {
    name,
    analysisPoint,
    paths,
    exclVal,
    exclUnit,
    inclVal,
    inclUnit,
  }
}

const mapDispatchToProps = dispatch => {
  return {
    getUnit: option => dispatch(setODProperty(option)),
    getVal: (e, name) => dispatch(setODProperty({[name]: parseInt(e.target.value)})),
    setSafeInclVal: safeInclVal => dispatch(setODProperty({inclVal: safeInclVal}))
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps)(InclusionExclusionOptions)
</code>```

Here is the updated code with a class component using componentDidUpdate():

```<code>class InclusionExclusionOptions extends React.Component{
  constructor(props){
    super(props)
    this.inclEntryTimer = null
  }

  componentDidUpdate(props){
    const { exclVal,
            exclUnit,
            inclVal,
            inclUnit,
          } = this.props

    const exclCompare = getConversion(exclUnit)(exclVal)
    const inclCompare = getConversion(inclUnit)(inclVal)

    if (!!exclVal && !!inclVal && exclCompare > inclCompare) {
      const safeInclVal = getGreaterVal(exclVal, exclUnit, inclUnit)
      console.log('entering timeout')
      this.inclEntryTimer = setTimeout( () => {
        console.log('dispatching timeout action');
        this.props.setSafeInclVal(safeInclVal)
      }, 3000)
    }
    else {
      console.log('clearing timeout');
      clearTimeout(this.inclEntryTimer)
      this.inclEntryTimer = null
    }
  }

  render() {
    const { name,
            analysisPoint,
            paths,
            exclVal,
            exclUnit,
            inclVal,
            inclUnit,
            getVal,
            getUnit,
          } = this.props

    const disabled = analysisPoint !== null || paths ? false : true

    return (
      <div className="form-group" >
        <h4>Inclusion/Exclusion Options</h4>
        <ul className={name}>
          <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
            <p>Exclusion Radius</p>
            <div className="radius-setting">
              <TextInput
                type="number"
                name="exclVal"
                value={exclVal}
                onChange={getVal}
                />
              <SelectPickerPulldown
                value={'exclUnit'}
                options={odOptions.units}
                selected={exclUnit}
                getSelected={getUnit}
                />
            </div>
          </li>
          <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>
            <p>Inclusion Radius</p>
            <div className="radius-setting">
              <TextInput
                type="number"
                name="inclVal"
                value={inclVal}
                onChange={getVal}
                />
              <SelectPickerPulldown
                value={'inclUnit'}
                options={odOptions.units}
                selected={inclUnit}
                getSelected={getUnit}
                />
            </div>
          </li>
        </ul>
      </div>
    )
  }
}
</code>```

Per Brandon's suggestion, I was able to get the timeout cleared by simply clearing it before redeclaring it.  I broke out a clear timeout function as

```<code>  clearInclEntryTimer(){
    clearTimeout(this.inclEntryTimer)
    this.inclEntryTimer = null
  }
</code>```

then called it at the top of the if block and in the else block.  That worked well.  Thanks for the help!

答:
The actual problem is that everytime your component renders, it generates a new instance of inclEntryTimer (and all other local variables) and so there's no way for a subsequent call to ever clear the timeout started in a previous call.

The conceptual problem is that your component is stateful, not stateless.  Your requirements are such that the component needs to track time as state (specifically the timer).  Change your stateless component to a traditional stateful component and you'll be able to store the timer id as a property of the class instance.  You can then use componentDidUpdate(prevProps) life cycle event to clear the timeout if the conditions are met.

Update:

Based on what you've tried, the real problem is that you aren't clearing the old timers on every prop change.  So think about what happens if the props change and you start a timer, the props change again and it is still higher so you start a 2nd timer and never clear the first, the props change again and you start a 3rd timer and so on.  Finally the props change and you stop the last timer.  But the first 5 timers are still running.  So you should clear the existing timer everytime you start a new one.

But if you step back from the problem slightly...you don't need to implement this pattern yourself.  What you are doing is something known as "debouncing".  So use someone else's debounce algorithm.

Here's how to do it with lodash:

```<code>import debounce from 'lodash/debounce';

export default class Component from React.Component {

    componentDidMount() {
       this.correctValues(this.props);
    }

    componentDidUpdate() {
        this.correctValues(this.props);
    }

    componentWillUnmount() {
        // prevent the debounced method from running after we unmount
        this._unmounted = true;
    }

    render() {
       return <div>...</div>;
    }

    // we use debounce to essentially only run this function 3000 ms after
    // it is called.  If it gets called a 2nd time, stop the first timer
    // and start a new one.  and so on.
    correctValues = debounce(props => {
        // make sure we are still mounted
        if (!this._unmounted) {
            // need to correct the values!
            if (props.a < props.b) {
                props.setCorrectValue(props.a);
            }
        }
    }, 3000);
}
</code>```

Body:
I'm having a issue with a component I've built.  One value (inclVal) must be larger than another (exclVal) if both are entered.  I wanted to run the function that handles this with a setTimeout() so that it wouldn't update for a second after the props stop changing to ensure it wouldn't change the value the user is entering while she is entering it.  To this end, I put in a clearTimeout() in an else block to prevent the function from executing if the props change so as to make it redundant.  The problem is that clearTimeout() isn't working for some reason and the update function is running whenever the if block is entered, even though the else block is being entered within the timeout interval.

The component is a stateless functional component and is using redux for state management.  I've read a bunch on how to make these things work, but nothing seems to be helping.  Any help is appreciated!

Here is the code:

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import SelectPickerPulldown from '../../components/SelectPickerPulldown'
import TextInput from '../../components/TextInput'

import { odOptions } from '../../config/'
import { setODProperty } from '../../actions/odAnalyzerActions'
import { getConversion, getGreaterVal } from '../../utils/'

const InclusionExclusionOptions = ({  name,
                                      analysisPoint,
                                      paths,
                                      exclVal,
                                      exclUnit,
                                      inclVal,
                                      inclUnit,
                                      getVal,
                                      getUnit,
                                      setSafeInclVal,
                                    }) => {

  const disabled = analysisPoint !== null || paths ? false : true

  let inclEntryTimer = null

  const exclCompare = getConversion(exclUnit)(exclVal)
  const inclCompare = getConversion(inclUnit)(inclVal)

  if (exclVal > 0 && inclVal > 0 && exclCompare > inclCompare) {
    const safeInclVal = getGreaterVal(exclVal, exclUnit, inclUnit)
    console.log('entering timeout');
    inclEntryTimer = setTimeout( () => {
      console.log('dispatching timeout action');
      setSafeInclVal(safeInclVal)
    }, 1000)
  }
  else {
    console.log('clearing timeout');
    clearTimeout(inclEntryTimer)
    inclEntryTimer = null
  }

  return (

Inclusion/Exclusion Options

        <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>

Exclusion Radius

            <TextInput
              type="number"
              name="exclVal"
              value={exclVal}
              onChange={getVal}
              />
            <SelectPickerPulldown
              value={'exclUnit'}
              options={odOptions.units}
              selected={exclUnit}
              getSelected={getUnit}
              />

        <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>

Inclusion Radius

            <TextInput
              type="number"
              name="inclVal"
              value={inclVal}
              onChange={getVal}
              />
            <SelectPickerPulldown
              value={'inclUnit'}
              options={odOptions.units}
              selected={inclUnit}
              getSelected={getUnit}
              />

  )
}

InclusionExclusionOptions.propTypes = {
  name: PropTypes.string,
  exclVal: PropTypes.number,
  exclUnit: PropTypes.string,
  inclVal: PropTypes.number,
  inclUnit: PropTypes.string,
  getVal: PropTypes.func,
  getUnit: PropTypes.func,
}

const mapStateToProps = (state, ownProps) => {
  const name = 'inclusion-exclusion-options'
  const { analysisPoint,
          paths,
          exclVal,
          exclUnit,
          inclVal,
          inclUnit } = state.odAnalyzerState

  return {
    name,
    analysisPoint,
    paths,
    exclVal,
    exclUnit,
    inclVal,
    inclUnit,
  }
}

const mapDispatchToProps = dispatch => {
  return {
    getUnit: option => dispatch(setODProperty(option)),
    getVal: (e, name) => dispatch(setODProperty({[name]: parseInt(e.target.value)})),
    setSafeInclVal: safeInclVal => dispatch(setODProperty({inclVal: safeInclVal}))
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps)(InclusionExclusionOptions)

Here is the updated code with a class component using componentDidUpdate():

class InclusionExclusionOptions extends React.Component{
  constructor(props){
    super(props)
    this.inclEntryTimer = null
  }

  componentDidUpdate(props){
    const { exclVal,
            exclUnit,
            inclVal,
            inclUnit,
          } = this.props

    const exclCompare = getConversion(exclUnit)(exclVal)
    const inclCompare = getConversion(inclUnit)(inclVal)

    if (!!exclVal && !!inclVal && exclCompare > inclCompare) {
      const safeInclVal = getGreaterVal(exclVal, exclUnit, inclUnit)
      console.log('entering timeout')
      this.inclEntryTimer = setTimeout( () => {
        console.log('dispatching timeout action');
        this.props.setSafeInclVal(safeInclVal)
      }, 3000)
    }
    else {
      console.log('clearing timeout');
      clearTimeout(this.inclEntryTimer)
      this.inclEntryTimer = null
    }
  }

  render() {
    const { name,
            analysisPoint,
            paths,
            exclVal,
            exclUnit,
            inclVal,
            inclUnit,
            getVal,
            getUnit,
          } = this.props

    const disabled = analysisPoint !== null || paths ? false : true

    return (

Inclusion/Exclusion Options

          <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>

Exclusion Radius

              <TextInput
                type="number"
                name="exclVal"
                value={exclVal}
                onChange={getVal}
                />
              <SelectPickerPulldown
                value={'exclUnit'}
                options={odOptions.units}
                selected={exclUnit}
                getSelected={getUnit}
                />

          <li className={`text-select-group ${disabled ? name + ' disabled' : name}`}>

Inclusion Radius

              <TextInput
                type="number"
                name="inclVal"
                value={inclVal}
                onChange={getVal}
                />
              <SelectPickerPulldown
                value={'inclUnit'}
                options={odOptions.units}
                selected={inclUnit}
                getSelected={getUnit}
                />

    )
  }
}

Per Brandon's suggestion, I was able to get the timeout cleared by simply clearing it before redeclaring it.  I broke out a clear timeout function as

  clearInclEntryTimer(){
    clearTimeout(this.inclEntryTimer)
    this.inclEntryTimer = null
  }

then called it at the top of the if block and in the else block.  That worked well.  Thanks for the help!

Body:
The actual problem is that everytime your component renders, it generates a new instance of inclEntryTimer (and all other local variables) and so there's no way for a subsequent call to ever clear the timeout started in a previous call.

The conceptual problem is that your component is stateful, not stateless.  Your requirements are such that the component needs to track time as state (specifically the timer).  Change your stateless component to a traditional stateful component and you'll be able to store the timer id as a property of the class instance.  You can then use componentDidUpdate(prevProps) life cycle event to clear the timeout if the conditions are met.

Update:

Based on what you've tried, the real problem is that you aren't clearing the old timers on every prop change.  So think about what happens if the props change and you start a timer, the props change again and it is still higher so you start a 2nd timer and never clear the first, the props change again and you start a 3rd timer and so on.  Finally the props change and you stop the last timer.  But the first 5 timers are still running.  So you should clear the existing timer everytime you start a new one.

But if you step back from the problem slightly...you don't need to implement this pattern yourself.  What you are doing is something known as "debouncing".  So use someone else's debounce algorithm.

Here's how to do it with lodash:

import debounce from 'lodash/debounce';

export default class Component from React.Component {

    componentDidMount() {
       this.correctValues(this.props);
    }

    componentDidUpdate() {
        this.correctValues(this.props);
    }

    componentWillUnmount() {
        // prevent the debounced method from running after we unmount
        this._unmounted = true;
    }

    render() {
       return <div>...</div>;
    }

    // we use debounce to essentially only run this function 3000 ms after
    // it is called.  If it gets called a 2nd time, stop the first timer
    // and start a new one.  and so on.
    correctValues = debounce(props => {
        // make sure we are still mounted
        if (!this._unmounted) {
            // need to correct the values!
            if (props.a < props.b) {
                props.setCorrectValue(props.a);
            }
        }
    }, 3000);
}


问:
Web Scraping on a page
I wanted to scrape the table on this link. I was trying to use selenium to get the data after the page loaded but I was unsuccessful. Any other ideas on how I can scrape the table from that webpage?

EDIT -

I tried

```<code>from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("https://steria.taleo.net/careersection/in_cs_ext_fs/jobsearch.ftl?lang=en&radiusType=K&location=462170431401&searchExpanded=true&radius=1")
print(driver.find_element_by_class_name('table').text)
driver.close()
</code>```

答: You can try Beautiful Soup, look at this article: http://srome.github.io/Parsing-HTML-Tables-in-Python-with-BeautifulSoup-and-pandas/</p>

Title: Web Scraping on a page

Body:
I wanted to scrape the table on this link. I was trying to use selenium to get the data after the page loaded but I was unsuccessful. Any other ideas on how I can scrape the table from that webpage?

EDIT -

I tried

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("https://steria.taleo.net/careersection/in_cs_ext_fs/jobsearch.ftl?lang=en&radiusType=K&location=462170431401&searchExpanded=true&radius=1")
print(driver.find_element_by_class_name('table').text)
driver.close()


问:
Unable to add Expires or Cache-Control response headers for JavaScript files via ExpiresFilter
I have a website running on Tomcat 8.0.36 on Windows. I followed this link

https://tomcat.apache.org/tomcat-8.0-doc/config/filter.html

to add Expires and Cache-Control response headers. Here is what I did:

```<code><filter>
 <filter-name>ExpiresFilter</filter-name>
 <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
 <init-param>
    <param-name>ExpiresByType image</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
 <init-param>
    <param-name>ExpiresByType text/css</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
 <init-param>
    <param-name>ExpiresByType application/javascript</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
</filter>
...
<filter-mapping>
 <filter-name>ExpiresFilter</filter-name>
 <url-pattern>/*</url-pattern>
 <dispatcher>REQUEST</dispatcher>
</filter-mapping>
</code>```

After adding the above in web.xml, I am able to see Expires and Cache-Control response headers for css files. However, I am not able to see such response headers for Javascript files.

Anything I did is wrong or missing?

答:
After my tests, it seems that the correct init code for javascript should be (x-javascript):

```<code> <init-param>
    <param-name>ExpiresByType application/x-javascript</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a website running on Tomcat 8.0.36 on Windows. I followed this link

https://tomcat.apache.org/tomcat-8.0-doc/config/filter.html

to add Expires and Cache-Control response headers. Here is what I did:

<filter>
 <filter-name>ExpiresFilter</filter-name>
 <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
 <init-param>
    <param-name>ExpiresByType image</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
 <init-param>
    <param-name>ExpiresByType text/css</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
 <init-param>
    <param-name>ExpiresByType application/javascript</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
</filter>
...
<filter-mapping>
 <filter-name>ExpiresFilter</filter-name>
 <url-pattern>/*</url-pattern>
 <dispatcher>REQUEST</dispatcher>
</filter-mapping>

After adding the above in web.xml, I am able to see Expires and Cache-Control response headers for css files. However, I am not able to see such response headers for Javascript files.

Anything I did is wrong or missing?

Body:
After my tests, it seems that the correct init code for javascript should be (x-javascript):

 <init-param>
    <param-name>ExpiresByType application/x-javascript</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>


问:
Subsetting on a tibble using "[]" gives "object not found" error
The article on dplyr here says "[]" (square brackets) can be used to subset filtered Tibbles like this:

```<code>filter(mammals, adult_body_mass_g > 1e7)[ , 3]
</code>```

But I am getting an "object not found" error.
Here is the replication of the error on a more known dataset "iris"

```<code>library(dplyr)
iris %>% filter(Sepal.Length>6) [,c(1:3)]
</code>```

Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) :
    object 'Sepal.Length' not found

I also want to mention that I am deliberately not preferring to use the native subsetting in dplyr using select() as I need a vector output and not a data frame on a single column. Unfortunately, dplyr always forces a data frame output (for good reasons).

答:
The dplyr-native way of doing this is to use select:

```<code>iris %>% filter(Sepal.Length > 6) %>% select(1:3)
</code>```

You could also use {} so that the filtering is done before [ is applied:

```<code>{iris %>% filter(Sepal.Length>6)}[,c(1:3)]
</code>```

Or, as suggested in another answer, use the . notation to indicated where the data should go in relation to [:

```<code>iris %>% filter(Sepal.Length>6) %>% .[,1:3]
</code>```

You can also load magrittr explicitly and use extract, which is a "pipe-able" version of [:

```<code>library(magrittr)
iris %>% filter(Sepal.Length>6) %>% extract( ,1:3)
</code>```

The blog entry you reference is old in dplyr time - about 3 years old. dplyr has been changing a lot. I don't know whether the blog's suggestion worked at the time it was written or not, but I'd recommend finding more recent sources to learn about this frequently changing package.

Body:
The article on dplyr here says "[]" (square brackets) can be used to subset filtered Tibbles like this:

filter(mammals, adult_body_mass_g > 1e7)[ , 3]

But I am getting an "object not found" error.
Here is the replication of the error on a more known dataset "iris"

library(dplyr)
iris %>% filter(Sepal.Length>6) [,c(1:3)]

Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) :
    object 'Sepal.Length' not found

I also want to mention that I am deliberately not preferring to use the native subsetting in dplyr using select() as I need a vector output and not a data frame on a single column. Unfortunately, dplyr always forces a data frame output (for good reasons).

Body:
The dplyr-native way of doing this is to use select:

iris %>% filter(Sepal.Length > 6) %>% select(1:3)

You could also use {} so that the filtering is done before [ is applied:

{iris %>% filter(Sepal.Length>6)}[,c(1:3)]

Or, as suggested in another answer, use the . notation to indicated where the data should go in relation to [:

iris %>% filter(Sepal.Length>6) %>% .[,1:3]

You can also load magrittr explicitly and use extract, which is a "pipe-able" version of [:

library(magrittr)
iris %>% filter(Sepal.Length>6) %>% extract( ,1:3)

The blog entry you reference is old in dplyr time - about 3 years old. dplyr has been changing a lot. I don't know whether the blog's suggestion worked at the time it was written or not, but I'd recommend finding more recent sources to learn about this frequently changing package.


问:
Self invoking function in react js ? (as in regular javascript)
I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function.
Here is an example

```<code>import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(
          <div>
             good();
          </div>
      );
   }
}

export default App;
</code>```

答:
Few Points:

1. You need to use this keyword to call any function from any other function.

2. To put js code inside JSX, we need to use {}.

Write it like this:

```<code>import React from 'react';

class App extends React.Component {

    good(){
        console.log('I was triggered during good')
        return <div> Hello </div>
    }

    render() {
        console.log('I was triggered during render')
        return(
            <div>
                {this.good()}
            </div>
        );
    }
}
</code>```

Check React DOC: https://facebook.github.io/react/docs/introducing-jsx.html

Check these answers for more details:

How does the "this" keyword work?

What do curly braces mean in JSX (React)?

Body:
I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function.
Here is an example

import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(

             good();

      );
   }
}

export default App;

Body:
Few Points:

1. You need to use this keyword to call any function from any other function.

2. To put js code inside JSX, we need to use {}.

Write it like this:

import React from 'react';

class App extends React.Component {

    good(){
        console.log('I was triggered during good')
        return <div> Hello </div>
    }

    render() {
        console.log('I was triggered during render')
        return(
            <div>
                {this.good()}
            </div>
        );
    }
}

Check React DOC: https://facebook.github.io/react/docs/introducing-jsx.html

Check these answers for more details:

How does the "this" keyword work?

What do curly braces mean in JSX (React)?


问:
uninitialized constant CommitsController::GitHub
I am running JRuby rails. I am trying to access all the commit information (such as commit comments, committer, time of commit), given a github repositiry url for a file using mbleigh-ruby-github ruby gem. When initializing to the github namesapce, I am getting the following error: "uninitialized constant CommitsController::GitHub"

In my controller, I have the following line

```<code> user = GitHub::API.user('mbleigh')
</code>```

In gem file I have the following line

```<code>source 'http://gems.github.com'
gem 'mbleigh-ruby-github'
</code>```

Any help would be appreciated, thanks.

答:
uninitialized constant CommitsController::GitHub

According to the README you should have require 'ruby-github' in your commits_controller which should solve the error.

```<code>#commits_controller.rb
require 'ruby-github'
user = GitHub::API.user('mbleigh')
</code>```

Body:
I am running JRuby rails. I am trying to access all the commit information (such as commit comments, committer, time of commit), given a github repositiry url for a file using mbleigh-ruby-github ruby gem. When initializing to the github namesapce, I am getting the following error: "uninitialized constant CommitsController::GitHub"

In my controller, I have the following line

 user = GitHub::API.user('mbleigh')

In gem file I have the following line

source 'http://gems.github.com'
gem 'mbleigh-ruby-github'

Any help would be appreciated, thanks.

Body:
uninitialized constant CommitsController::GitHub

According to the README you should have require 'ruby-github' in your commits_controller which should solve the error.

#commits_controller.rb
require 'ruby-github'
user = GitHub::API.user('mbleigh')


问:
Idiomatic Revealing Module Pattern for ES6
In the past I've used the revealing module pattern.

```<code>function myModule() {
  function foo() ...
  function bar() ...

  return {
    foo: foo,
    bar: bar
  };
}
</code>```

With ES6, this was improved with object shorthand.

```<code>function myModule() {
  function foo() ...
  function bar() ...

  return { foo, bar };
}
</code>```

Now with built-in module syntax, I'm struggling to find the preferred pattern that is most similar to the above.

Option #1 named exports

```<code>// export file
function foo() ...
function bar() ...

export { foo, bar };

// import file
import { foo, bar } from './export-file';

foo();
bar();
</code>```

Option #2 default export/import with destructuring

```<code>// export file
function foo() ...
function bar() ...

export default { foo, bar };

// import file
import baz from './export-file';

const { foo, bar } = baz;

foo();
bar();
</code>```

Option #3 default export/import with name spacing

```<code>// export file
function foo() ...
function bar() ...

export default { foo, bar };

//import file
import baz from './export-file';

baz.foo();
baz.bar();
</code>```

I like Option #1 with the named exports for the simplicity it offers in the "destructuring" import syntax.

```<code>import { foo, bar } from './export-file';
</code>```

I also want to continue to make the module's exported API explicitly defined at the bottom of the exporting file in the export object.

```<code>export { foo, bar };
// OR
export default { foo, bar };
</code>```

I read all the time that default exports are preferred, and so I've been trying to find a preferred pattern that includes default exports, but I'm reluctant to adopt as it just seems more verbose with few advantages (other than the need for name-spacing, or the inclusion of both named and default exports in some cases).

Is there an idiomatic pattern for the revealing module pattern with ES6 module syntax?

答:
I read all the time that default exports are preferred

No, they are not. They are simpler and have shorter syntax, and might be used more often (since there are more small, single-export modules), but they are not generally preferred.

Use the right tool for the job. You already know the advantages you want.

Is there an idiomatic pattern for the revealing module pattern with ES6 module syntax?

Yes, Option #1. When you have multiple things to export, always use named exports.

You get both explicit aliasing and tree shaking from the picky syntax

```<code>import { foo, bar } from './export-file';
</code>```

as well as namespaces

```<code>import * as baz from './export-file';
</code>```

Body:
In the past I've used the revealing module pattern.

function myModule() {
  function foo() ...
  function bar() ...

  return {
    foo: foo,
    bar: bar
  };
}

With ES6, this was improved with object shorthand.

function myModule() {
  function foo() ...
  function bar() ...

  return { foo, bar };
}

Now with built-in module syntax, I'm struggling to find the preferred pattern that is most similar to the above.

Option #1 named exports

// export file
function foo() ...
function bar() ...

export { foo, bar };

// import file
import { foo, bar } from './export-file';

foo();
bar();

Option #2 default export/import with destructuring

// export file
function foo() ...
function bar() ...

export default { foo, bar };

// import file
import baz from './export-file';

const { foo, bar } = baz;

foo();
bar();

Option #3 default export/import with name spacing

// export file
function foo() ...
function bar() ...

export default { foo, bar };

//import file
import baz from './export-file';

baz.foo();
baz.bar();

I like Option #1 with the named exports for the simplicity it offers in the "destructuring" import syntax.

import { foo, bar } from './export-file';

I also want to continue to make the module's exported API explicitly defined at the bottom of the exporting file in the export object.

export { foo, bar };
// OR
export default { foo, bar };

I read all the time that default exports are preferred, and so I've been trying to find a preferred pattern that includes default exports, but I'm reluctant to adopt as it just seems more verbose with few advantages (other than the need for name-spacing, or the inclusion of both named and default exports in some cases).

Is there an idiomatic pattern for the revealing module pattern with ES6 module syntax?

Body:
I read all the time that default exports are preferred

No, they are not. They are simpler and have shorter syntax, and might be used more often (since there are more small, single-export modules), but they are not generally preferred.

Use the right tool for the job. You already know the advantages you want.

Is there an idiomatic pattern for the revealing module pattern with ES6 module syntax?

Yes, Option #1. When you have multiple things to export, always use named exports.

You get both explicit aliasing and tree shaking from the picky syntax

import { foo, bar } from './export-file';

as well as namespaces

import * as baz from './export-file';


问:
QPainter not drawing consistently
I'm programming a GUI that draws graphs with Qt. My painter is showing some inconsistency: It only paints the graph about 50% of the times that I run the exact same binary after compilation. I do call QPainter's begin(), and I also made sure that the parameters I'm passing to the drawing functions such as drawEllipse() are initialized and have valid values when I call the function.

Below is the relevant code (note that the parameter painter has been initialized and begin() has been called prior to this function):

```<code>void GraphWidget::paintEvent(QPaintEvent *event) {
  QWidget::paintEvent(event);
  this->painter = new QPainter(this);
  painter->setRenderHint(QPainter::Antialiasing);
  // draw graph itself
  painter->translate(xOffset, yOffset);
  painter->scale(graphScale, graphScale);
  paintGraph(painter);
}

void GraphWidget::paintGraph() {
  if (this->graph) {
    // Iterate thought all edges and draw them
    for (Agnode_t *node = agfstnode(graph); node;
         node = agnxtnode(graph, node)) {
      for (Agedge_t *edge = agfstout(graph, node); edge;
           edge = agnxtout(graph, edge)) {
        drawEdge(edge);
      }
    }
    // Iterate through all nodes and draw them
    for (Agnode_t *node = agfstnode(graph); node;
         node = agnxtnode(graph, node)) {
      drawNode(node);
    }
  }
}

void GraphWidget::drawNode(Agnode_t *node) {

  ...

  //Height and width of node, in pixels.
  float scaleWidth = width * this->logicalDpiX();
  float scaleHeight = height * this->logicalDpiY();

  std::cout << "Drawing individual node. x = " << x << ". scaleWidth = " << scaleWidth << ". y = " << y << ". ScaleHeight = " << scaleHeight << "\n";
  //Actual node painting takes place here.
  painter->drawEllipse(x - scaleWidth / 2, y - scaleHeight / 2, scaleWidth, scaleHeight);

  ...

}

void GraphWidget::drawEdge(Agedge_t *edge) {
  // retrieve the position attribute and parse it
  float lastx, lasty, x, y;
  getNodePos(agtail(edge), lastx, lasty);
  auto spline_list = ED_spl(edge)->list;
  for (int i = 0; i < spline_list->size; i++) {
    x = spline_list->list[i].x;
    y = spline_list->list[i].y;
    painter->drawLine(lastx, lasty, x, y);
    lastx = x;
    lasty = y;
  }
  getNodePos(aghead(edge), x, y);
  painter->drawLine(lastx, lasty, x, y);
}
</code>```

答: Found the problem. Calling painter->translate(xOffset, yOffset) was causing the painter issues because when I first opened the window, xOffset and yOffset were uninitialized so my guess is they took random values and the graph was being translated to some random spot where I couldn't see it. I just made sure to initialize the offset variables to 0 in the constructor and this fixed the problem.

Title: QPainter not drawing consistently

Body:
I'm programming a GUI that draws graphs with Qt. My painter is showing some inconsistency: It only paints the graph about 50% of the times that I run the exact same binary after compilation. I do call QPainter's begin(), and I also made sure that the parameters I'm passing to the drawing functions such as drawEllipse() are initialized and have valid values when I call the function.

Below is the relevant code (note that the parameter painter has been initialized and begin() has been called prior to this function):

void GraphWidget::paintEvent(QPaintEvent *event) {
  QWidget::paintEvent(event);
  this->painter = new QPainter(this);
  painter->setRenderHint(QPainter::Antialiasing);
  // draw graph itself
  painter->translate(xOffset, yOffset);
  painter->scale(graphScale, graphScale);
  paintGraph(painter);
}

void GraphWidget::paintGraph() {
  if (this->graph) {
    // Iterate thought all edges and draw them
    for (Agnode_t *node = agfstnode(graph); node;
         node = agnxtnode(graph, node)) {
      for (Agedge_t *edge = agfstout(graph, node); edge;
           edge = agnxtout(graph, edge)) {
        drawEdge(edge);
      }
    }
    // Iterate through all nodes and draw them
    for (Agnode_t *node = agfstnode(graph); node;
         node = agnxtnode(graph, node)) {
      drawNode(node);
    }
  }
}

void GraphWidget::drawNode(Agnode_t *node) {

  ...

  //Height and width of node, in pixels.
  float scaleWidth = width * this->logicalDpiX();
  float scaleHeight = height * this->logicalDpiY();

  std::cout << "Drawing individual node. x = " << x << ". scaleWidth = " << scaleWidth << ". y = " << y << ". ScaleHeight = " << scaleHeight << "\n";
  //Actual node painting takes place here.
  painter->drawEllipse(x - scaleWidth / 2, y - scaleHeight / 2, scaleWidth, scaleHeight);

  ...

}

void GraphWidget::drawEdge(Agedge_t *edge) {
  // retrieve the position attribute and parse it
  float lastx, lasty, x, y;
  getNodePos(agtail(edge), lastx, lasty);
  auto spline_list = ED_spl(edge)->list;
  for (int i = 0; i < spline_list->size; i++) {
    x = spline_list->list[i].x;
    y = spline_list->list[i].y;
    painter->drawLine(lastx, lasty, x, y);
    lastx = x;
    lasty = y;
  }
  getNodePos(aghead(edge), x, y);
  painter->drawLine(lastx, lasty, x, y);
}


问:
Java: Long result = -1: cannot convert from int to long
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

```<code>Long result = -1;
</code>```

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

答:
```<code> Long result = -1L;

 Long result = (long) -1;

 Long result
     = Long.valueOf(-1);  // this is what auto-boxing does under the hood
</code>```

How it happened in the first place is that the literal -1 is an int. As of Java5, you can have it auto-boxed into an Integer, when you use it as on Object, but it will not be turned into a Long (only longs are).

Note that an int is automatically widened into a long when needed:

```<code>long result = -1;   // this is okay
</code>```

The opposite way needs an explicit cast:

```<code>int number = (int) result;
</code>```

Body:
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

Long result = -1;

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

Body:
 Long result = -1L;

 Long result = (long) -1;

 Long result
     = Long.valueOf(-1);  // this is what auto-boxing does under the hood

How it happened in the first place is that the literal -1 is an int. As of Java5, you can have it auto-boxed into an Integer, when you use it as on Object, but it will not be turned into a Long (only longs are).

Note that an int is automatically widened into a long when needed:

long result = -1;   // this is okay

The opposite way needs an explicit cast:

int number = (int) result;

ContentLicense: CC BY-SA 2.5


问:
Java Main - Calling another method
I have the following code below:

```<code>public static void main(String args[])
{
start();
}
</code>```

i get this error: Non-static method start() cannot be referenced from a static context.

How can i go about doing this?

答:
For non-static (& instance) methods, you may need an instance
  of class to access it.

Try this:

```<code>public class TestClass {

    public static void main(String[] args) {
        start();

       TestClass tc = new TestClass();
       tc.start1()
    }

    // Static method
    private static void start() {
        System.out.println("start");
    }

    // Non-static method
    private void start1() {
        System.out.println("start1");
    }

}
</code>```

Title: Java Main - Calling another method

Body:
I have the following code below:

public static void main(String args[])
{
start();
}

i get this error: Non-static method start() cannot be referenced from a static context.

How can i go about doing this?

Body:
For non-static (& instance) methods, you may need an instance
  of class to access it.

Try this:

public class TestClass {

    public static void main(String[] args) {
        start();

       TestClass tc = new TestClass();
       tc.start1()
    }

    // Static method
    private static void start() {
        System.out.println("start");
    }

    // Non-static method
    private void start1() {
        System.out.println("start1");
    }

}


答:
Using jQuery UI autocomplete this task can be done very easily:

$('#ingredient').autocomplete({
    source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<input id="ingredient"></code>```

Title: Search/filter for an array

Body:
I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.

How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.

What I have:

var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeydown = function(evt) {
      $("#autocomplete").empty();

      // INSERT CODE FOR SEARCH FUNCTION

}

I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?

var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];

inputBox.onkeydown = function(evt) {
    $("#autocomplete").empty();

    var input, filter, a, i;
    input = document.getElementById("myInput");
    filter = inputBox.value.toUpperCase();
    for (i = 0; i < ingredienten.length; i++) {
        a = ingredienten[i];
        if (a.toUpperCase().indexOf(filter) > -1) {
        //console.log(a);
        $("#autocomplete").append("
" + a + "
");
        } else {
        }
    }

Body:
Using jQuery UI autocomplete this task can be done very easily:

$('#ingredient').autocomplete({
    source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
});

<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<input id="ingredient">


问:
Modeling a three-way many-to-many relation in Firebase
I'm currently working on an app for sports statistics and I'm investigating if/how Firebase can handle the data and relationships I need.

Because Firebase does not seem to support the equivalent of WHERE a = x AND b = y, I'm not sure what a good / the best approach is for my use case.

I have the following entities in my system:

Country - a country of the world.

Sport - a sport.

Region - a region in a country. For each sport, the way the country is separated in regions is different.

There will be a page where you can select a country and a sport, and a list of regions will be shown.

For Country and Sport it seems easy:

```<code>{
    "countries": {
        "-Kl9JB-XRzZyz_GkRiW8": {
            "name": "The Netherlands"
        }
    },
    "sports": {
        "-Kl9JB-XRzZyz_GkA83b": {
            "name": "football"
        }
    }
}
</code>```

But what about regions? Since a region is tied to a country and a sport, something like this seems logical:

```<code>{
    "regions": {
        "-Kl9JB-XRzZyz_GkRiWa": {
            "name": "West",
            "country_key": "-Kl9JB-XRzZyz_GkRiW8",
            "sport_key": "-Kl9JB-XRzZyz_GkA83b"
        }
    }
}
</code>```

However, this leads to problems, because as far as I know, I cannot query for db.ref().child('regions') and then filter by country_key = a and sport_key = b server-side. I could get all regions for a country, and filter by sport client-side (or vice versa), but that's not a very elegant (or scalable) solution.

I thought about a few solutions:

Adding to each region a compound country/sport key, e.g. "country_key:sport_key": "-Kl9JB-XRzZyz_GkRiW8:-Kl9JB-XRzZyz_GkA83b"

Adding a new entity sports_countries, and have each region point to one of those entities.

Of course, this is just a part of my whole model. The full model has many more relationships, for example regions have competitions, countries have clubs, clubs have teams, teams are on competitions, players are on teams, etc etc.

How would you solve this in Firebase? Or, also looking at the rest of the data model, would you tell me that I should stick with a relational database instead of Firebase?

答:
For a three way relationship you can combine country_key and sports_key (not advisable for more than 2).

```<code>{
    "regions": {
        "-Kl9JB-XRzZyz_GkRiWa": {
            "name": "West",
            "combined_key": "-Kl9JB-XRzZyz_GkRiW8-Kl9JB-XRzZyz_GkA83b"
        }
    }
}
</code>```

And then query them together:

```<code>...ref("regions").orderBy("combined_key").equalTo(country_key + sports_key)
</code>```

Again, not advisable if you are trying to filter by more than 2 fields, but works well for 2.

This question has more insights.

Body:
I'm currently working on an app for sports statistics and I'm investigating if/how Firebase can handle the data and relationships I need.

Because Firebase does not seem to support the equivalent of WHERE a = x AND b = y, I'm not sure what a good / the best approach is for my use case.

I have the following entities in my system:

Country - a country of the world.

Sport - a sport.

Region - a region in a country. For each sport, the way the country is separated in regions is different.

There will be a page where you can select a country and a sport, and a list of regions will be shown.

For Country and Sport it seems easy:

{
    "countries": {
        "-Kl9JB-XRzZyz_GkRiW8": {
            "name": "The Netherlands"
        }
    },
    "sports": {
        "-Kl9JB-XRzZyz_GkA83b": {
            "name": "football"
        }
    }
}

But what about regions? Since a region is tied to a country and a sport, something like this seems logical:

{
    "regions": {
        "-Kl9JB-XRzZyz_GkRiWa": {
            "name": "West",
            "country_key": "-Kl9JB-XRzZyz_GkRiW8",
            "sport_key": "-Kl9JB-XRzZyz_GkA83b"
        }
    }
}

However, this leads to problems, because as far as I know, I cannot query for db.ref().child('regions') and then filter by country_key = a and sport_key = b server-side. I could get all regions for a country, and filter by sport client-side (or vice versa), but that's not a very elegant (or scalable) solution.

I thought about a few solutions:

Adding to each region a compound country/sport key, e.g. "country_key:sport_key": "-Kl9JB-XRzZyz_GkRiW8:-Kl9JB-XRzZyz_GkA83b"

Adding a new entity sports_countries, and have each region point to one of those entities.

Of course, this is just a part of my whole model. The full model has many more relationships, for example regions have competitions, countries have clubs, clubs have teams, teams are on competitions, players are on teams, etc etc.

How would you solve this in Firebase? Or, also looking at the rest of the data model, would you tell me that I should stick with a relational database instead of Firebase?

Body:
For a three way relationship you can combine country_key and sports_key (not advisable for more than 2).

{
    "regions": {
        "-Kl9JB-XRzZyz_GkRiWa": {
            "name": "West",
            "combined_key": "-Kl9JB-XRzZyz_GkRiW8-Kl9JB-XRzZyz_GkA83b"
        }
    }
}

And then query them together:

...ref("regions").orderBy("combined_key").equalTo(country_key + sports_key)

Again, not advisable if you are trying to filter by more than 2 fields, but works well for 2.

This question has more insights.


问:
Loading static files like CSS and JS to ejs
I am trying to load some static files to ejs (I was able to load in HTML file but not here in ejs file). Not just static files. I am not even able to load the CDN files! Can someone please help me to understand where I am going wrong?
Here is the directory structure:

This is my server.js:

const express=require('express');
var app=express();
const MongoClient = require('mongodb').MongoClient
app.set('view engine', 'ejs')
var path = require('path')
app.use('/static',express.static(__dirname + '/public'));

app.get('/',function(req,res){
 db.collection('testCollection').find().toArray((err, result) => {
    if (err) return console.log(err)
    console.log(result)
    res.render('index.ejs', {testCollection: result})
  })
});```
</div>
</div>
</p>

<p>This is my index.ejs:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/main.css"/>
</head>
<body>
<form>
<div id="container"></div>
<ul class="quotes">
 <% for(var i=0; i<testCollection.length; i++) {%>
    <li class="quote">
      <span><%= testCollection[i].name %></span>
    </li>
  <% } %>
</ul>
</form>
</body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="/static/main.js"></script>
</html></code>```

In the console I can see only index.ejs file loaded:

答:
<link rel="stylesheet" href="/main.css"/>

Above is how you should call your files in index.ejs. You are going to do so because you declare in your server.js file
app.use('/static',express.static(__dirname + '/public'));

Body:
I am trying to load some static files to ejs (I was able to load in HTML file but not here in ejs file). Not just static files. I am not even able to load the CDN files! Can someone please help me to understand where I am going wrong?
Here is the directory structure:

This is my server.js:

const express=require('express');
var app=express();
const MongoClient = require('mongodb').MongoClient
app.set('view engine', 'ejs')
var path = require('path')
app.use('/static',express.static(__dirname + '/public'));

app.get('/',function(req,res){
 db.collection('testCollection').find().toArray((err, result) => {
    if (err) return console.log(err)
    console.log(result)
    res.render('index.ejs', {testCollection: result})
  })
});

This is my index.ejs:

<!DOCTYPE html>

<link rel="stylesheet" href="/static/main.css"/>

<form>

 <% for(var i=0; i<testCollection.length; i++) {%>

      <%= testCollection[i].name %>

  <% } %>

</form>

In the console I can see only index.ejs file loaded:

Body:
<link rel="stylesheet" href="/main.css"/>

<script src="/main.js"></script>

Above is how you should call your files in index.ejs. You are going to do so because you declare in your server.js file
app.use('/static',express.static(__dirname + '/public'));


问:
Qt driver for PostgreSQL compilation error
When compiling psql with following command:

```<code>cd %QTDIR%\src\plugins\sqldrivers\psql
qmake "INCLUDEPATH+=D:\Program Files\PostgreSQL\8.3\include" "LIBS+=D:\Program Files\PostgreSQL\8.3\lib\libpq.lib" psql.pro
make
</code>```

I got following message:

```<code>... g++: Files\PostgreSQL\8.3\lib -Lc:\Qt\2010.05\qt\lib tmp\obj\debug_shared\qsqlpsqld_resource_res.o D:\Progra~1\PostgreSQL\8.3\lib\libpq.lib -lQtSqld4 -lQtCored4 : Invalid argument
make[1]: *** [..\..\..\..\plugins\sqldrivers\qsqlpsqld4.dll] Error 1
make[1]: Leaving directory `C:/Qt/2010.05/qt/src/plugins/sqldrivers/psql'
make: *** [debug-all] Error 2
</code>```

Replacement D:\Program Files -> D:\Progra~1 doesn't change anything. How to solve that problem?

答:
Commands should be:

```<code>cd %QTDIR%\src\plugins\sqldrivers\psql
qmake "INCLUDEPATH+=D:\Progra~1\PostgreSQL\8.3\include" "LIBS+=D:\Progra~1\PostgreSQL\8.3\lib\libpq.lib" psql.pro
</code>```

then it is needed to manually fix Makefiles (Debug and Release) to exclude all occurencies of space in dirname, then run

```<code>make
</code>```

Body:
When compiling psql with following command:

cd %QTDIR%\src\plugins\sqldrivers\psql
qmake "INCLUDEPATH+=D:\Program Files\PostgreSQL\8.3\include" "LIBS+=D:\Program Files\PostgreSQL\8.3\lib\libpq.lib" psql.pro
make

I got following message:

... g++: Files\PostgreSQL\8.3\lib -Lc:\Qt\2010.05\qt\lib tmp\obj\debug_shared\qsqlpsqld_resource_res.o D:\Progra~1\PostgreSQL\8.3\lib\libpq.lib -lQtSqld4 -lQtCored4 : Invalid argument
make[1]: *** [..\..\..\..\plugins\sqldrivers\qsqlpsqld4.dll] Error 1
make[1]: Leaving directory `C:/Qt/2010.05/qt/src/plugins/sqldrivers/psql'
make: *** [debug-all] Error 2

Replacement D:\Program Files -> D:\Progra~1 doesn't change anything. How to solve that problem?

Body:
Commands should be:

cd %QTDIR%\src\plugins\sqldrivers\psql
qmake "INCLUDEPATH+=D:\Progra~1\PostgreSQL\8.3\include" "LIBS+=D:\Progra~1\PostgreSQL\8.3\lib\libpq.lib" psql.pro

then it is needed to manually fix Makefiles (Debug and Release) to exclude all occurencies of space in dirname, then run

make


问:
Mysql select N of X duplicates, omitting 1 duplicate
Considering this table:

```<code>+-----+--------+
| id  | value  |
+-----+--------+
|  1  |   22   |
+-----+--------+
|  2  |   12   |
+-----+--------+
|  3  |   22   |
+-----+--------+
|  4  |   22   |
+-----+ -------+
</code>```

I can select all where the column value is duplicated like so:

```<code>select value from table having count(value) > 1 ;
</code>```

This will output the Ids 1,3 and 4.

What I'm attempting to do is select where duplicates, but leaving 1 (one) duplicate un selected, so the above would output only the Ids 3 and 4 (or 1 and 3 etc... the duplicate omitted does not matter, only that it is.

How can I achieve this?

This question IS NOT a duplicate of

Using LIMIT within GROUP BY to get N results per group?

答:
You could use an aggregatio  function for filter a value  for id and the select all the others </p>

```<code>  select * from table
  where (value, id) not in (
      select value, max(id)
      from table
      group by value
      having count(value) > 1
  )
  ;
</code>```

Body:
Considering this table:

+-----+--------+
| id  | value  |
+-----+--------+
|  1  |   22   |
+-----+--------+
|  2  |   12   |
+-----+--------+
|  3  |   22   |
+-----+--------+
|  4  |   22   |
+-----+ -------+

I can select all where the column value is duplicated like so:

select value from table having count(value) > 1 ;

This will output the Ids 1,3 and 4.

What I'm attempting to do is select where duplicates, but leaving 1 (one) duplicate un selected, so the above would output only the Ids 3 and 4 (or 1 and 3 etc... the duplicate omitted does not matter, only that it is.

How can I achieve this?

This question IS NOT a duplicate of

Using LIMIT within GROUP BY to get N results per group?

Body:
You could use an aggregatio  function for filter a value  for id and the select all the others

  select * from table
  where (value, id) not in (
      select value, max(id)
      from table
      group by value
      having count(value) > 1
  )
  ;


问:
Creating Non-Lambda Proxy AWS API Gateway in CodePipeline
Created the Lambda Function (POST) and corresponding API Gateway using Code Pipeline. By default the API Gateway got created with lambda Proxy type integration. What parameters in SAM I should give that my API Gateway gets created with Non Lambda Proxy type Integration.

Below is my SAM Template.

```<code>AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-  31 Description: Outputs the time Resources: TimeFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs6.10 CodeUri: ./ Events: MyTimeApi: Type: Api Properties: Path: /TimeResource Method: GET CalculatorFunction: Type: AWS::Serverless::Function Properties: Handler: calc.calculator Runtime: nodejs6.10 CodeUri: ./ Events: MyCalculatorApi: Type: Api Properties: Path: /Calculator Method: POST
</code>```

Please advise

答:
You should be able to define any Swagger definition you want if you use the AWS::Serverless::Api resource. There are examples of swagger definitions in our developer guide and you can also export your existing API to swagger from the Stages page. In this case, the type field on the x-amazon-apigateway-integration structure in Swagger should be aws rather than aws_proxy.

There is no way to set this field when you are setting the API Event type inline on the Lambda function in SAM.

Body:
Created the Lambda Function (POST) and corresponding API Gateway using Code Pipeline. By default the API Gateway got created with lambda Proxy type integration. What parameters in SAM I should give that my API Gateway gets created with Non Lambda Proxy type Integration.

Below is my SAM Template.

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-  31 Description: Outputs the time Resources: TimeFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs6.10 CodeUri: ./ Events: MyTimeApi: Type: Api Properties: Path: /TimeResource Method: GET CalculatorFunction: Type: AWS::Serverless::Function Properties: Handler: calc.calculator Runtime: nodejs6.10 CodeUri: ./ Events: MyCalculatorApi: Type: Api Properties: Path: /Calculator Method: POST

Please advise