问:
Image change from dropdown using AJAX
Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on  dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.  </p>

```<code><script>
    function getState(val) {
        $.ajax({
            type: "POST",
            url: "check.php",
            data:'id='+val,
            success: function(data){
                $("#style_code").html(data);
            }
        });
    }
</script>
</code>```

<p>Here is check.php </p>

```<code><?php

$con=mysqli_connect("localhost","root","","db") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con,$query);

    while ( ($row=mysqli_fetch_array($results))){?>
        <option value="<?php echo $row["color_name"]; ?>">
            <?php echo $row['size'] ; ?>
        </option>
<?php
    }
}
?>
</code>```

答:
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.

It would be something like that :

check.php

```<code><?php

$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con, $query);

    $data = new stdClass(); // This object will carry the results

    while (($row = mysqli_fetch_object($results))) {
        $data->option[] = $row;
    }

    // Another query to get the image name
    $query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con, $query);

    if ($row = mysqli_fetch_object($results)) {
        $data->image_name = $row->name;
    }

    header('Content-Type: application/json');
    echo json_encode($data);

}
</code>```

HTML & Javascript:

```<code>...

<div class="thumb-image" id="style_image" >
    <img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>

...

<script language="javascript">
function getState(val) {
    $.ajax({
        type: "POST",
        url: "check.php",
        data: {id: val},
        dataType:'json',
        success: function(data) {
            $("#style_code").children().remove(); // empty the dropdown
            // Add new options in the dropdown from the result data
            data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
            });
            // Change the 'src' attribute of the <img>
            $("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
        }
    });
}
</script>
</code>```

Title: Image change from dropdown using AJAX

Body:
Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on  dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.

Here is check.php

<?php

$con=mysqli_connect("localhost","root","","db") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con,$query);

    while ( ($row=mysqli_fetch_array($results))){?>
        <option value="<?php echo $row["color_name"]; ?>">
            <?php echo $row['size'] ; ?>
        </option>
<?php
    }
}
?>

Body:
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.

It would be something like that :

check.php

<?php

$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con, $query);

    $data = new stdClass(); // This object will carry the results

    while (($row = mysqli_fetch_object($results))) {
        $data->option[] = $row;
    }

    // Another query to get the image name
    $query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
    $results = mysqli_query($con, $query);

    if ($row = mysqli_fetch_object($results)) {
        $data->image_name = $row->name;
    }

    header('Content-Type: application/json');
    echo json_encode($data);

}

HTML & Javascript:

...

<div class="thumb-image" id="style_image" >
    <img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>

...

<script language="javascript">
function getState(val) {
    $.ajax({
        type: "POST",
        url: "check.php",
        data: {id: val},
        dataType:'json',
        success: function(data) {
            $("#style_code").children().remove(); // empty the dropdown
            // Add new options in the dropdown from the result data
            data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
            });
            // Change the 'src' attribute of the <img>
            $("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
        }
    });
}
</script>


来源: stackexchange

问:
Apply customized width to a prime-ng p-column in html template in angular
I want to apply a different width to each column of my columns using [style] as shown in the example, I tried [style]="{'width.px':'column.length + 10'}" but column.length isn't working on the template, below an example of my template

```<code><p-column *ngFor="let column of columns"
        [field]="column"
        [header]="label[column] ? label[column] : column"
        [style]="{'width.px':'column.length + 10'}"></p-column>
</code>```

thanks in advance.

答:
try:</p>

```<code> [style]="{'width': column.length + 'px'}"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to apply a different width to each column of my columns using [style] as shown in the example, I tried [style]="{'width.px':'column.length + 10'}" but column.length isn't working on the template, below an example of my template

thanks in advance.

Body:
try:

 [style]="{'width': column.length + 'px'}"


问:
Why do you skip void function calls without catching them?

I want to call a function that calculates the width of a circle.

```<code>#include <stdio.h>
void area(double*);
int main()
{
    void* vp = NULL;
    double r;
    printf("input value : ");
    scanf(" %lf", &r);
    (double*)vp = &r;
    void area(vp);
}
void area(double* dp)
{
    double result;
    result = (*dp) * (*dp) * (3.14);
    printf("circle are is : %.2lf", result);
    return 1;
}*
</code>```

I want to call a function in the //void area (vp)//, but I can not catch the error in visual stdio and proceed as it is. Do you know what the cause is?

答:
There are three problems with the code.

For starters it is unclear why the pointer vp is declared as having the type void * though in the program it is used only to point objects of the type double.

Why not to declare it like

```<code>double *vp = NULL;
</code>```

As result this trick with the pointer

```<code>(double*)vp = &r;
</code>```

will not compile because in the left side the expression (double*)vp is rvalue and may not be assigned.

You could just write

```<code>vp = &r;
</code>```

The second problem is that this statement

```<code>void area(vp);
</code>```

is also invalid. To call the function you should write

```<code>area(vp);
</code>```

And the third problem is that a function that has the return type void shall not specify an expression in the return statement

This statement shall be removed.

```<code>return 1;
</code>```

From the C Standard (6.8.6.4 The return statement)

1 A return statement with an expression shall not appear in a
  function whose return type is void. A return statement without an
  expression shall only appear in a function whose return type is void.

There is no sense to declare the parameter of the function as having a referenced type.

The function definition could look like

```<code>double area( double dp )
{
    const double PI = 3.14;

    return dp * dp * PI;
}
</code>```

The statement with the call pf printf should be moved in main

```<code>printf( "circle are is : %.2lf", area( r ) );
</code>```

Body:
I want to call a function that calculates the width of a circle.

#include <stdio.h>
void area(double*);
int main()
{
    void* vp = NULL;
    double r;
    printf("input value : ");
    scanf(" %lf", &r);
    (double*)vp = &r;
    void area(vp);
}
void area(double* dp)
{
    double result;
    result = (*dp) * (*dp) * (3.14);
    printf("circle are is : %.2lf", result);
    return 1;
}*

I want to call a function in the //void area (vp)//, but I can not catch the error in visual stdio and proceed as it is. Do you know what the cause is?

Body:
There are three problems with the code.

For starters it is unclear why the pointer vp is declared as having the type void * though in the program it is used only to point objects of the type double.

Why not to declare it like

double *vp = NULL;

As result this trick with the pointer

(double*)vp = &r;

will not compile because in the left side the expression (double*)vp is rvalue and may not be assigned.

You could just write

vp = &r;

The second problem is that this statement

void area(vp);

is also invalid. To call the function you should write

area(vp);

And the third problem is that a function that has the return type void shall not specify an expression in the return statement

This statement shall be removed.

return 1;

From the C Standard (6.8.6.4 The return statement)

1 A return statement with an expression shall not appear in a
  function whose return type is void. A return statement without an
  expression shall only appear in a function whose return type is void.

There is no sense to declare the parameter of the function as having a referenced type.

The function definition could look like

double area( double dp )
{
    const double PI = 3.14;

    return dp * dp * PI;
}

The statement with the call pf printf should be moved in main

printf( "circle are is : %.2lf", area( r ) );


问:
Jsonpath for nested JSON objects
I have a JSON with nested fields:

```<code>  [
    {
    "Platform Parent Dato Id": "23768",
    "Platform Dato Id": "24138",
    "Platform Dato Name": "Random Europe",
    "Platform mission Id": "111112",
    "Platform submission Id": "638687",
    "Platform submission Flight Id": "863524",
    "Start Date": "2017-12-01",
    "End Date": "2017-12-02",
    "Platform Compensation": 109.0909,
    "Total Value": 909.0909,
    "Goal": "200000.0000",
    "Value Information": {
      "Platform Compensation": [
        {
          "Platform mission Id": "111112",
          "Platform submission Id": "638687",
          "Platform submission Flight Id": "863524",
          "Value Rate": "14.0000",
          "Value": 109.0909
        }
      ]
    }
  },
  {
    "Platform Parent Dato Id": "23768",
    "Platform Dato Id": "24138",
    "Platform Dato Name": "Random Europe",
    "Platform mission Id": "111113",
    "Platform submission Id": "638687",
    "Platform submission Flight Id": "863524",
    "Start Date": "2017-12-01",
    "End Date": "2017-12-02",
    "Platform Compensation": 109.0909,
    "Total Value": 909.0909,
    "Goal": "200000.0000",
    "Value Information": {
      "Platform Compensation": [
        {
          "Platform mission Id": "111113",
          "Platform submission Id": "638687",
          "Platform submission Flight Id": "863524",
          "Value Rate": "12.0000",
          "Value": 109.0909
        }
      ]
    }
  }
  ]
</code>```

and I am using a JSONPATH in order to get the Value Rate from the Value Information nest.

I have pasted my JSON text in this website: http://jsonpath.com/
and after using this line:

```<code>$[*].['Platform Compensation'].['Value Rate']
</code>```

I am getting this:

and after using this line:

```<code>$.['Value Information'].['Platform Compensation'].['Platform mission Id']
</code>```

I am getting this:

What I am trying to return (output) is the following:

but I cannot find the right syntax to combine those two in one line and return both with one JSONPATH query.

答:
jsonpath can be used to select values for given expressions and - in some implementations - for customised predicates but it does not support projections.

You can use jsonpath to filter your given JSON. For example:

Return an array containing all of the Platform Compensation values:

```<code>$.['Value Information'].['Platform Compensation'].['Platform mission Id']
</code>```

Return an array containing all of the Platform mission Id values:

```<code>$.['Value Information'].['Platform Compensation']
</code>```

But you cannot use jsonpath to a read a sub-set of keys and values. To read a sub-set of keys and values you would need to use JSON de/serialisation library. Commonly used libraries - in the Java world - are such as Jackson and Gson.

Here's an example using Jackson:

```<code>String json = "...";

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> asMap = mapper.readValue(json, Map.class);

Map<String, Object> transformed = new HashMap<>();
transformed.put("Platform mission Id", asMap.get("Platform mission Id"));
transformed.put("Value Rate", asMap.get("Value Rate"));

String result = mapper.writeValueAsString(transformed);
</code>```

Title: Jsonpath for nested JSON objects

Body:
I have a JSON with nested fields:

  [
    {
    "Platform Parent Dato Id": "23768",
    "Platform Dato Id": "24138",
    "Platform Dato Name": "Random Europe",
    "Platform mission Id": "111112",
    "Platform submission Id": "638687",
    "Platform submission Flight Id": "863524",
    "Start Date": "2017-12-01",
    "End Date": "2017-12-02",
    "Platform Compensation": 109.0909,
    "Total Value": 909.0909,
    "Goal": "200000.0000",
    "Value Information": {
      "Platform Compensation": [
        {
          "Platform mission Id": "111112",
          "Platform submission Id": "638687",
          "Platform submission Flight Id": "863524",
          "Value Rate": "14.0000",
          "Value": 109.0909
        }
      ]
    }
  },
  {
    "Platform Parent Dato Id": "23768",
    "Platform Dato Id": "24138",
    "Platform Dato Name": "Random Europe",
    "Platform mission Id": "111113",
    "Platform submission Id": "638687",
    "Platform submission Flight Id": "863524",
    "Start Date": "2017-12-01",
    "End Date": "2017-12-02",
    "Platform Compensation": 109.0909,
    "Total Value": 909.0909,
    "Goal": "200000.0000",
    "Value Information": {
      "Platform Compensation": [
        {
          "Platform mission Id": "111113",
          "Platform submission Id": "638687",
          "Platform submission Flight Id": "863524",
          "Value Rate": "12.0000",
          "Value": 109.0909
        }
      ]
    }
  }
  ]

and I am using a JSONPATH in order to get the Value Rate from the Value Information nest.

I have pasted my JSON text in this website: http://jsonpath.com/
and after using this line:

$[*].['Platform Compensation'].['Value Rate']

I am getting this:

and after using this line:

$.['Value Information'].['Platform Compensation'].['Platform mission Id']

I am getting this:

What I am trying to return (output) is the following:

but I cannot find the right syntax to combine those two in one line and return both with one JSONPATH query.

Body:
jsonpath can be used to select values for given expressions and - in some implementations - for customised predicates but it does not support projections.

You can use jsonpath to filter your given JSON. For example:

Return an array containing all of the Platform Compensation values:

$.['Value Information'].['Platform Compensation'].['Platform mission Id']

Return an array containing all of the Platform mission Id values:

$.['Value Information'].['Platform Compensation']

But you cannot use jsonpath to a read a sub-set of keys and values. To read a sub-set of keys and values you would need to use JSON de/serialisation library. Commonly used libraries - in the Java world - are such as Jackson and Gson.

Here's an example using Jackson:

String json = "...";

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> asMap = mapper.readValue(json, Map.class);

Map<String, Object> transformed = new HashMap<>();
transformed.put("Platform mission Id", asMap.get("Platform mission Id"));
transformed.put("Value Rate", asMap.get("Value Rate"));

String result = mapper.writeValueAsString(transformed);


问:
Paypal API: NOT json response

I'm trying to execute example from here: https://developer.paypal.com/docs/classic/paypal-payments-pro/gs_PayPalPaymentsPro/

```<code>curl -s --insecure https://api-3t.sandbox.paypal.com/nvp -d "USER=platfo_1255077030_biz_api1.gmail.com&PWD=1255077037&SIGNATURE=Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf&METHOD=DoDirectPayment&VERSION=78&PAYMENTACTION=SALE&AMT=5&ACCT=4660997962602322&CREDITCARDTYPE=VISA&CVV2=176&FIRSTNAME=James&LASTNAME=Smith&STREET=FirstStreet&CITY=SanJose&STATE=CA&ZIP=95131&COUNTRYCODE=US&EXPDATE=092015"
</code>```

Documentation says:

```<code>Request method,       format      Response format
 HTTP    GET     Name/value pairs       JSON
</code>```

But I receives:

```<code>TIMESTAMP=2015%2d01%2d30T12%3a14%3a08Z&CORRELATIONID=474de7dae8e82&ACK=Success&VERSION=78&BUILD=15009693&AMT=5%2e00&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=93V64243P1844913T
</code>```

Why? How to get json response?

I tried to set:

```<code>VERSION=95
</code>```

but didn't help.

答:
As document states the paypal NVP api doesn't straight away provide json response.

The way attained to process the response goes like below,
In PHP

```<code>parse_str($response,$responseArray);

$jsonResponse = json_encode($responseArray);
</code>```

helped me to get the array from the response string and in turn converted to json.

Edit : you first need to decode the urlencoded string.

For that

```<code>$response = urldecode($response);
</code>```

Before parsing the response to array.

Title: Paypal API: NOT json response

Body:
I'm trying to execute example from here: https://developer.paypal.com/docs/classic/paypal-payments-pro/gs_PayPalPaymentsPro/

curl -s --insecure https://api-3t.sandbox.paypal.com/nvp -d "USER=platfo_1255077030_biz_api1.gmail.com&PWD=1255077037&SIGNATURE=Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf&METHOD=DoDirectPayment&VERSION=78&PAYMENTACTION=SALE&AMT=5&ACCT=4660997962602322&CREDITCARDTYPE=VISA&CVV2=176&FIRSTNAME=James&LASTNAME=Smith&STREET=FirstStreet&CITY=SanJose&STATE=CA&ZIP=95131&COUNTRYCODE=US&EXPDATE=092015"

Documentation says:

Request method,       format      Response format
 HTTP    GET     Name/value pairs       JSON

But I receives:

TIMESTAMP=2015%2d01%2d30T12%3a14%3a08Z&CORRELATIONID=474de7dae8e82&ACK=Success&VERSION=78&BUILD=15009693&AMT=5%2e00&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=93V64243P1844913T

Why? How to get json response?

I tried to set:

VERSION=95

but didn't help.

Body:
As document states the paypal NVP api doesn't straight away provide json response.

The way attained to process the response goes like below,
In PHP

parse_str($response,$responseArray);

$jsonResponse = json_encode($responseArray);

helped me to get the array from the response string and in turn converted to json.

Edit : you first need to decode the urlencoded string.

For that

$response = urldecode($response);

Before parsing the response to array.


问:
sourcetree - how to quickly resolve multiple merge conflicts and use master code?
I need to merge my master branch with my development branch but there are soooo many conflicts as I have been working on the master and not updating the development branch.

Is there a quick way to resolve these?  I simply want my development branch to be a copy of the master and am not too fussed about keeping the commits etc but am unable to delete the dev branch and start again.

I looked into doing a rebase but would have the same issues with conflicts.

UDATE**

Disaster!! Now I am unable to switch back to the master branch because of all the conflicts. I have tried stashing the merge but that gave an error. So I then used the 'Discard' button and discarded the file changes hoping this would go back to how it was but now when I try to checkout master I get the error, "The following untracked working tree files would be overwritten by checkout:".

Can anyone help me out?  First and foremost I need to be able to switch to master.  Forget about the merge!

答:
Disaster!! Now I am unable to switch back to the master branch because of all the conflicts. I have tried stashing the merge but that gave an error. So I then used the 'Discard' button and discarded the file changes hoping this would go back to how it was but now when I try to checkout master I get the error, "The following untracked working tree files would be overwritten by checkout:". I'm in a pickle!! :(

Run git merge --abort to put yourself back into the state you were before the conflicts appeared.

I simply want my development branch to be a copy of the master and am not too fussed about keeping the commits etc.

If you're not fussed about keeping the commits, you could just copy the files in master to a temporary location, checkout development then paste the contents of the temporary directory into your repository workspace?

ContentLicense: CC BY-SA 4.0


问:
weird issue with time function in C
I'm trying to get my Beaglebone Green to read an input from a certain pin, and when that pin sees a 1 to 0 transition (defined in pulse()), then it should set a timer.
I want to make my timer like this:

In idle, the timer is set to a TIMER_HOLD value (900000)
To start the timer, I set it to something lower then TIMER_HOLD.
Then it should decrement (with the timerupdate() function).
If it reaches 0 or less -which for an unsigned long is higher than TIMER_HOLD - then a trigger action is executed.

To test/debug this, I added: printf("timer 1: %lld \n",timer[1]);
And this works perfect... I see this output:

```<code>  timer 1: 900000
  timer 1: 900000
  PULSE
  timer 1: 5000
  timer 1: 4990
  timer 1: 4975
   ..........<truncated>
  timer 1: 1
  timer 1: 1
  timer 1: 1
  timer 1: 1
  timer 1: 1
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: -1

  TIMER TRIGGER
  timer 1: 900000
  timer 1: 900000
  timer 1: 900000
  timer 1: 900000
</code>```

This is my c code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/timeb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include "../../BBBio_lib/BBBiolib.h"
#include <linux/kernel.h>
#include <sys/sysinfo.h>

#define INPUT_LEN 65
#define TIMER_HOLD 900000 // ms

void pin2array();
void timerupdate(void);
unsigned char pulse(unsigned char chkin);
unsigned char x,y;
unsigned char input[6][INPUT_LEN];

unsigned long long timer[10];
unsigned long long skew, prevtime, currtime;

int main(void)
{

        for (x=0;x<10;x++) timer[x]=TIMER_HOLD;

        iolib_init();

    while(1)
    {
            pin2array();
            timerupdate();
            if (pulse(0))
            {
                    printf("PULSE\n");
                    timer[1]=5000;
            }
             printf("timer 1: %lld \n",timer[1]); //THIS IS THE DEBUG PRINTF !!!
            if (timer[1]>TIMER_HOLD)
            {
                    printf("\nTIMER TRIGGER\n");
                    timer[1]=TIMER_HOLD;
            //      usleep(50000);
            }
            usleep(1); // CPU savings
    }
    iolib_free();
    return(0);
}
   void timerupdate(void)
 {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    unsigned long long millisecondsSinceEpoch=
            (unsigned long long)(tv.tv_sec) * 1000 +
            (unsigned long long)(tv.tv_usec) / 1000;

    currtime=millisecondsSinceEpoch;
    skew=currtime-prevtime;
    prevtime=currtime;
    for (x=0;x<10;x++)
    {
            if (timer[x]<TIMER_HOLD) timer[x]-=skew;
    }
  }
 unsigned char pulse(unsigned char chkin)
  {
    if (input[0][chkin]==0 && input[1][chkin]==1 && input[2][chkin]==1 && input[3][chkin]==1 && input[4][chkin]==1 && input[5][chkin]==1) return 1;
    else return 0;
  }

  void pin2array()
  {
    for (x=0;x<INPUT_LEN;x++) input[5][x]=input[4][x];
    for (x=0;x<INPUT_LEN;x++) input[4][x]=input[3][x];
    for (x=0;x<INPUT_LEN;x++) input[3][x]=input[2][x];
    for (x=0;x<INPUT_LEN;x++) input[2][x]=input[1][x];
    for (x=0;x<INPUT_LEN;x++) input[1][x]=input[0][x];

    input[0][0]=(is_high(8,7));
    input[0][1]=(is_high(8,8));
    input[0][2]=(is_high(8,9));
    input[0][3]=(is_high(8,10));
   }
</code>```

now the weird thing:
When I remove the printf("timer 1: %lld \n",timer[1]);
then I only see
PULSE

on the output... the timer never triggers....

Any idea what's happening?

system info:

```<code>root@beaglebone:/# uname -na
Linux beaglebone 4.4.9-ti-r25 #1 SMP Thu May 5 23:08:13 UTC 2016 armv7l GNU/Linux

root@beaglebone:/# gcc --version
gcc (Debian 4.9.2-10) 4.9.2
</code>```

答:
I fixed it by reading /proc/uptime instead, then multiplying it by 10 (tenth of a second resolution is sufficient for my program)

I think the original thing didn't work because of a rounding error, or a conversion float to int.... not sure though

Title: weird issue with time function in C

Body:
I'm trying to get my Beaglebone Green to read an input from a certain pin, and when that pin sees a 1 to 0 transition (defined in pulse()), then it should set a timer.
I want to make my timer like this:

In idle, the timer is set to a TIMER_HOLD value (900000)
To start the timer, I set it to something lower then TIMER_HOLD.
Then it should decrement (with the timerupdate() function).
If it reaches 0 or less -which for an unsigned long is higher than TIMER_HOLD - then a trigger action is executed.

To test/debug this, I added: printf("timer 1: %lld \n",timer[1]);
And this works perfect... I see this output:

  timer 1: 900000
  timer 1: 900000
  PULSE
  timer 1: 5000
  timer 1: 4990
  timer 1: 4975
   ..........<truncated>
  timer 1: 1
  timer 1: 1
  timer 1: 1
  timer 1: 1
  timer 1: 1
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: 0
  timer 1: -1

  TIMER TRIGGER
  timer 1: 900000
  timer 1: 900000
  timer 1: 900000
  timer 1: 900000

This is my c code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/timeb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include "../../BBBio_lib/BBBiolib.h"
#include <linux/kernel.h>
#include <sys/sysinfo.h>

#define INPUT_LEN 65
#define TIMER_HOLD 900000 // ms

void pin2array();
void timerupdate(void);
unsigned char pulse(unsigned char chkin);
unsigned char x,y;
unsigned char input[6][INPUT_LEN];

unsigned long long timer[10];
unsigned long long skew, prevtime, currtime;

int main(void)
{

        for (x=0;x<10;x++) timer[x]=TIMER_HOLD;

        iolib_init();

    while(1)
    {
            pin2array();
            timerupdate();
            if (pulse(0))
            {
                    printf("PULSE\n");
                    timer[1]=5000;
            }
             printf("timer 1: %lld \n",timer[1]); //THIS IS THE DEBUG PRINTF !!!
            if (timer[1]>TIMER_HOLD)
            {
                    printf("\nTIMER TRIGGER\n");
                    timer[1]=TIMER_HOLD;
            //      usleep(50000);
            }
            usleep(1); // CPU savings
    }
    iolib_free();
    return(0);
}
   void timerupdate(void)
 {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    unsigned long long millisecondsSinceEpoch=
            (unsigned long long)(tv.tv_sec) * 1000 +
            (unsigned long long)(tv.tv_usec) / 1000;

    currtime=millisecondsSinceEpoch;
    skew=currtime-prevtime;
    prevtime=currtime;
    for (x=0;x<10;x++)
    {
            if (timer[x]<TIMER_HOLD) timer[x]-=skew;
    }
  }
 unsigned char pulse(unsigned char chkin)
  {
    if (input[0][chkin]==0 && input[1][chkin]==1 && input[2][chkin]==1 && input[3][chkin]==1 && input[4][chkin]==1 && input[5][chkin]==1) return 1;
    else return 0;
  }

  void pin2array()
  {
    for (x=0;x<INPUT_LEN;x++) input[5][x]=input[4][x];
    for (x=0;x<INPUT_LEN;x++) input[4][x]=input[3][x];
    for (x=0;x<INPUT_LEN;x++) input[3][x]=input[2][x];
    for (x=0;x<INPUT_LEN;x++) input[2][x]=input[1][x];
    for (x=0;x<INPUT_LEN;x++) input[1][x]=input[0][x];

    input[0][0]=(is_high(8,7));
    input[0][1]=(is_high(8,8));
    input[0][2]=(is_high(8,9));
    input[0][3]=(is_high(8,10));
   }

now the weird thing:
When I remove the printf("timer 1: %lld \n",timer[1]);
then I only see
PULSE

on the output... the timer never triggers....

Any idea what's happening?

system info:

root@beaglebone:/# uname -na
Linux beaglebone 4.4.9-ti-r25 #1 SMP Thu May 5 23:08:13 UTC 2016 armv7l GNU/Linux

root@beaglebone:/# gcc --version
gcc (Debian 4.9.2-10) 4.9.2


问:
Unknown column 'p.id' in 'where clause'
When i execute My request:

```<code>UPDATE vm s , (SELECT MAX(id) FROM vm) as p
SET s.title = 'TEST'
WHERE s.id = p.id;
</code>```

I have this error Error:

```<code>Unknown column 'p.id' in 'where clause'
  com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'p.id' in 'where clause'
</code>```

I don't understand

答:
Use an explicit join:

```<code>UPDATE vm s JOIN
       (SELECT MAX(id) as pid FROM vm) p
       ON s.id = p.pid
    SET s.title = 'TEST' ;
</code>```

Or, more simply, use ORDER BY and LIMIT:

```<code>UPDATE vm
    SET title = 'TEST'
    ORDER BY id DESC
    LIMIT 1;
</code>```

Title: Unknown column 'p.id' in 'where clause'

Body:
When i execute My request:

UPDATE vm s , (SELECT MAX(id) FROM vm) as p
SET s.title = 'TEST'
WHERE s.id = p.id;

I have this error Error:

Unknown column 'p.id' in 'where clause'
  com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'p.id' in 'where clause'

I don't understand

Body:
Use an explicit join:

UPDATE vm s JOIN
       (SELECT MAX(id) as pid FROM vm) p
       ON s.id = p.pid
    SET s.title = 'TEST' ;

Or, more simply, use ORDER BY and LIMIT:

UPDATE vm
    SET title = 'TEST'
    ORDER BY id DESC
    LIMIT 1;


问:
Webpack - webpack-dev-server two configs
I have a project, which consists of two parts.. an admin environment and a part of web for regular users. Each part has another assets, so I have two configurations for webpack. First is named webpack-front.config.js and second is named webpack-admin.config.js.

My structure:

```<code>├─┬ dist
│ ├── front.bundle.js
│ └── admin.bundle.js
|
├─┬ src
│ ├─┬ front
| | └── index.js
│ └─┬ admin
|   └── index.js
</code>```

Problem starts, when I try to run "webpack-dev-server --open". Npm prints:

```<code>> webpack-dev-server --open

No configuration file found and no entry configured via CLI option.
When using the CLI you need to provide at least two arguments: entry and output.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.
npm ERR! code ELIFECYCLE
npm ERR! errno 255
npm ERR! www@1.0.0 start: `webpack-dev-server --open`
npm ERR! Exit status 255
npm ERR!
npm ERR! Failed at the www@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-04T14_16_35_084Z-debug.log
</code>```

This problem occurs because my configs are not named "webpack.config.js". Is there any way, how to run webpack-dev-server with another config or with both configs at once?

答:
Yes there is. To specify a configuration file, use the --config flag. So your command would look like

```<code>webpack-dev-server --open --config webpack-front.config.js
</code>```

Unfortunately, I was only able to find reference to it in the webpack 1 docs.
https://webpack.github.io/docs/webpack-dev-server.html#webpack-dev-server-cli

Body:
I have a project, which consists of two parts.. an admin environment and a part of web for regular users. Each part has another assets, so I have two configurations for webpack. First is named webpack-front.config.js and second is named webpack-admin.config.js.

My structure:

├─┬ dist
│ ├── front.bundle.js
│ └── admin.bundle.js
|
├─┬ src
│ ├─┬ front
| | └── index.js
│ └─┬ admin
|   └── index.js

Problem starts, when I try to run "webpack-dev-server --open". Npm prints:

> webpack-dev-server --open

No configuration file found and no entry configured via CLI option.
When using the CLI you need to provide at least two arguments: entry and output.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.
npm ERR! code ELIFECYCLE
npm ERR! errno 255
npm ERR! www@1.0.0 start: `webpack-dev-server --open`
npm ERR! Exit status 255
npm ERR!
npm ERR! Failed at the www@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-04T14_16_35_084Z-debug.log

This problem occurs because my configs are not named "webpack.config.js". Is there any way, how to run webpack-dev-server with another config or with both configs at once?

Body:
Yes there is. To specify a configuration file, use the --config flag. So your command would look like

webpack-dev-server --open --config webpack-front.config.js

Unfortunately, I was only able to find reference to it in the webpack 1 docs.
https://webpack.github.io/docs/webpack-dev-server.html#webpack-dev-server-cli


问:
React native active sidebar menu item
In react native, I made a drawer sidebar menu with the following code:

```<code>import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { Container, Content, List, ListItem, Left, Right, Icon, Body } from 'native-base';

import styles from './styles'

const menuItems = [
    {
        name: "Home",
        route: "Home",
        icon: "home",
    },
    {
        name: "Nieuws",
        route: "News",
        icon: "paper",
    },
    {
        name: "Coureurs",
        route: "Drivers",
        icon: "person",
    },
    {
        name: "Teams",
        route: "Teams",
        icon: "people",
    },
    {
        name: "Foto's",
        route: "Photos",
        icon: "images",
    },
    {
        name: "Resultaten",
        route: "Results",
        icon: "clipboard",
    },
    {
        name: "Kalender",
        route: "Calendar",
        icon: "calendar",
    },
];

export default class SideBar extends Component {
    constructor(props) {
        super(props);
        this.onMenuPress = this.onMenuPress.bind(this);
        this.state = { currentPage: 'Home' };
    }

    componentDidUpdate () {
        this.render();
    }

    onMenuPress = (item) => {
        this.setState({ currentPage: item });
        this.forceUpdate();
    }

    render() {
        return(
            <Container style={styles.container}>
                <Content>
                    <List
                        dataArray={menuItems}
                        renderRow={item =>
                            <ListItem style={this.state.currentPage == item.name ? styles.activeMenuItem : styles.menuItem} button onPress={() => this.onMenuPress(item.name)}>
                                <Icon name={item.icon} style={this.state.currentPage == item.name ? styles.activeMenuIcon : styles.menuIcon} />
                                <Text style={this.state.currentPage == item.name ? styles.activeMenuItemText : styles.menuItemText}>
                                    {item.name}
                                </Text>
                            </ListItem>
                        }
                    />
                </Content>
            </Container>
        );
    }
}
</code>```

My styles:

```<code>export default {
    container: {
        backgroundColor: "#48545A",
        flex: 1,
        justifyContent: 'center',
    },
    menuItem: {
        marginLeft: 0,
        backgroundColor: "#48545A",
        borderBottomWidth: 1,
        borderColor: '#5B686E',
    },
    activeMenuItem: {
        marginLeft: 0,
        backgroundColor: "#FAA41A",
        borderBottomWidth: 1,
        borderColor: '#5B686E',
    },
}
</code>```

This is what I get on the screen

I tried to make an active menu item, so it changes the current menu item and give it different styles. I added a state, which will contain the currentPage.

My listitems have shorthand if statements to check if currentPage is equals to the current item.name.

```<code>style={this.state.currentPage == item.name ? styles.activeMenuItem : styles.menuItem}
</code>```

Now, when I click a menu item, it doesn't update the sidebar. The state does change, checked that with a simple alert

How can I achieve this?

答:
Your using double equals instead of triple equals. Always use triple equals. I would change this first because that could be the issue.

Also double check your press event is getting triggered.

Title: React native active sidebar menu item

Body:
In react native, I made a drawer sidebar menu with the following code:

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { Container, Content, List, ListItem, Left, Right, Icon, Body } from 'native-base';

import styles from './styles'

const menuItems = [
    {
        name: "Home",
        route: "Home",
        icon: "home",
    },
    {
        name: "Nieuws",
        route: "News",
        icon: "paper",
    },
    {
        name: "Coureurs",
        route: "Drivers",
        icon: "person",
    },
    {
        name: "Teams",
        route: "Teams",
        icon: "people",
    },
    {
        name: "Foto's",
        route: "Photos",
        icon: "images",
    },
    {
        name: "Resultaten",
        route: "Results",
        icon: "clipboard",
    },
    {
        name: "Kalender",
        route: "Calendar",
        icon: "calendar",
    },
];

export default class SideBar extends Component {
    constructor(props) {
        super(props);
        this.onMenuPress = this.onMenuPress.bind(this);
        this.state = { currentPage: 'Home' };
    }

    componentDidUpdate () {
        this.render();
    }

    onMenuPress = (item) => {
        this.setState({ currentPage: item });
        this.forceUpdate();
    }

    render() {
        return(
            <Container style={styles.container}>
                <Content>
                    <List
                        dataArray={menuItems}
                        renderRow={item =>
                            <ListItem style={this.state.currentPage == item.name ? styles.activeMenuItem : styles.menuItem} button onPress={() => this.onMenuPress(item.name)}>
                                <Icon name={item.icon} style={this.state.currentPage == item.name ? styles.activeMenuIcon : styles.menuIcon} />
                                <Text style={this.state.currentPage == item.name ? styles.activeMenuItemText : styles.menuItemText}>
                                    {item.name}
                                </Text>
                            </ListItem>
                        }
                    />
                </Content>
            </Container>
        );
    }
}

My styles:

export default {
    container: {
        backgroundColor: "#48545A",
        flex: 1,
        justifyContent: 'center',
    },
    menuItem: {
        marginLeft: 0,
        backgroundColor: "#48545A",
        borderBottomWidth: 1,
        borderColor: '#5B686E',
    },
    activeMenuItem: {
        marginLeft: 0,
        backgroundColor: "#FAA41A",
        borderBottomWidth: 1,
        borderColor: '#5B686E',
    },
}

This is what I get on the screen

I tried to make an active menu item, so it changes the current menu item and give it different styles. I added a state, which will contain the currentPage.

My listitems have shorthand if statements to check if currentPage is equals to the current item.name.

style={this.state.currentPage == item.name ? styles.activeMenuItem : styles.menuItem}

Now, when I click a menu item, it doesn't update the sidebar. The state does change, checked that with a simple alert

How can I achieve this?


问:
How to create a choropleth on a leaflet Map R
Problem

I have loaded in the shapefile of the UK, no issues. Lets call this FILE1.
I also have a data frame file with 2 columns: Longitude, Latitude. lets call this FILE2. I am trying to plot the coordinates of FILE2 onto the shapefile map of FILE1 and create a choropleth map

I am also receiving the following error:

Error in polygonData.default(data) :
    Don't know how to get path data from object of class tbl_df

CODE

I have taken the code from this question: Choropleth maps in R using leaflet package
and adapted it to suit my data

```<code>#Plot the Leaflet map----
mymap <- leaflet() %>%
  addProviderTiles("OpenStreetMap.Mapnik") %>%
  addPolygons(data = coords, #This is data frame of U.K long and lat
              fillColor = ~palette(file$TotalByPostcode),
              fillOpacity = 0.6,
              color = "darkgrey",
              weight = 1.5,
              popup = popup1)%>%
  addLegend(position = 'topleft',
            colors = c('#fee0d2',
                       '#fcbba1',
                       '#fc9272',
                       '#fb6a4a',
                       '#ef3b2c',
                       '#cb181d',
                       '#a50f15',
                       '#67000d'),
            labels = c('0',"","","","","","",'100'),
            opacity = 0.6,
            title = "Totals")

print(map)
</code>```

Here is my data frame:

答:
I do not have your data in my hand. But I guess that you misunderstood one thing about the leaflet package. If you type ?leaflet in your R Console, you would see the following information in the help page.

a data object. Currently supported objects are matrices, data frames, spatial objects from the sp package (SpatialPoints, SpatialPointsDataFrame, Polygon, Polygons, SpatialPolygons, SpatialPolygonsDataFrame, Line, Lines, SpatialLines, and SpatialLinesDataFrame), and spatial data frames from the sf package.

This tells you what kind of data objects leaflet can take. Keeping this point in your mind, and let's check the following two cases.

CASE1: SpatialPolygonsDataFrame

In this case, I downloaded a SpatialPolygonsDataFrame using the raster package, which is called UK in my code. I also create a dummy data frame called mydf. In addPolygons(), I am using a spatial object. A map nicely came out.

```<code>library(raster)
library(leaflet)
library(tidyverse)

# Get UK polygon data
UK <- getData("GADM", country = "GB", level = 2)

### Create dummy data
set.seed(111)
mydf <- data.frame(place = unique(UK$NAME_2),
                   value = sample.int(n = 1000000, size = n_distinct(UK$NAME_2), replace = TRUE))

### Create five colors for fill
mypal <- colorQuantile(palette = "RdYlBu", domain = mydf$value, n = 5, reverse = TRUE)

leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 55, lng = -3, zoom = 6) %>%
addPolygons(data = UK,
            stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
            fillColor = ~mypal(mydf$value),
            popup = paste("Region: ", UK$NAME_2, "<br>",
                          "Value: ", mydf$value, "<br>")) %>%
addLegend(position = "bottomright", pal = mypal, values = mydf$value,
          title = "UK value",
          opacity = 1)
</code>```

CASE2: tbl_df

Now let's see what happens with a regular data frame. I am not sure what kind of data you exactly have. But, one thing for sure is that it has tbl_df in class. I wanted to make sure that an object has tbl_df in class. So I did the following. I converted the polygon data (i.e., UK) to a data frame. Let's check the class.

```<code>x <- as_data_frame(fortify(UK))
class(x)
#[1] "tbl_df"     "tbl"        "data.frame"
</code>```

Before we move on, I want to mention again that you cannot draw a polygon with a normal data frame including one with tbl_df in class. This is what I said at the beginning of this post. Hence, the following code, which I just changed UK to x, returned an error message.

```<code>leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 55, lng = -3, zoom = 6) %>%
addPolygons(data = x,
            stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
            fillColor = ~mypal(mydf$value)) %>%
addLegend(position = "bottomright", pal = mypal, values = mydf$value,
          title = "UK value",
          opacity = 1)
</code>```

Error in polygonData.default(data) :
    Don't know how to get path data from object of class tbl_df

I hope this demonstration clears up your mind. The lesson to take is: Use a spatial class object from the sp or sf package. In your case, you would perhaps want to use FILE1 in addPolygons(). Make sure that it is a spatial object. If you have a right file, you will see polygons on top of the tile map.

Body:
Problem

I have loaded in the shapefile of the UK, no issues. Lets call this FILE1.
I also have a data frame file with 2 columns: Longitude, Latitude. lets call this FILE2. I am trying to plot the coordinates of FILE2 onto the shapefile map of FILE1 and create a choropleth map

I am also receiving the following error:

Error in polygonData.default(data) :
    Don't know how to get path data from object of class tbl_df

CODE

I have taken the code from this question: Choropleth maps in R using leaflet package
and adapted it to suit my data

#Plot the Leaflet map----
mymap <- leaflet() %>%
  addProviderTiles("OpenStreetMap.Mapnik") %>%
  addPolygons(data = coords, #This is data frame of U.K long and lat
              fillColor = ~palette(file$TotalByPostcode),
              fillOpacity = 0.6,
              color = "darkgrey",
              weight = 1.5,
              popup = popup1)%>%
  addLegend(position = 'topleft',
            colors = c('#fee0d2',
                       '#fcbba1',
                       '#fc9272',
                       '#fb6a4a',
                       '#ef3b2c',
                       '#cb181d',
                       '#a50f15',
                       '#67000d'),
            labels = c('0',"","","","","","",'100'),
            opacity = 0.6,
            title = "Totals")

print(map)

Here is my data frame:

Body:
I do not have your data in my hand. But I guess that you misunderstood one thing about the leaflet package. If you type ?leaflet in your R Console, you would see the following information in the help page.

a data object. Currently supported objects are matrices, data frames, spatial objects from the sp package (SpatialPoints, SpatialPointsDataFrame, Polygon, Polygons, SpatialPolygons, SpatialPolygonsDataFrame, Line, Lines, SpatialLines, and SpatialLinesDataFrame), and spatial data frames from the sf package.

This tells you what kind of data objects leaflet can take. Keeping this point in your mind, and let's check the following two cases.

CASE1: SpatialPolygonsDataFrame

In this case, I downloaded a SpatialPolygonsDataFrame using the raster package, which is called UK in my code. I also create a dummy data frame called mydf. In addPolygons(), I am using a spatial object. A map nicely came out.

library(raster)
library(leaflet)
library(tidyverse)

# Get UK polygon data
UK <- getData("GADM", country = "GB", level = 2)

### Create dummy data
set.seed(111)
mydf <- data.frame(place = unique(UK$NAME_2),
                   value = sample.int(n = 1000000, size = n_distinct(UK$NAME_2), replace = TRUE))

### Create five colors for fill
mypal <- colorQuantile(palette = "RdYlBu", domain = mydf$value, n = 5, reverse = TRUE)

leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 55, lng = -3, zoom = 6) %>%
addPolygons(data = UK,
            stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
            fillColor = ~mypal(mydf$value),
            popup = paste("Region: ", UK$NAME_2, "<br>",
                          "Value: ", mydf$value, "<br>")) %>%
addLegend(position = "bottomright", pal = mypal, values = mydf$value,
          title = "UK value",
          opacity = 1)

CASE2: tbl_df

Now let's see what happens with a regular data frame. I am not sure what kind of data you exactly have. But, one thing for sure is that it has tbl_df in class. I wanted to make sure that an object has tbl_df in class. So I did the following. I converted the polygon data (i.e., UK) to a data frame. Let's check the class.

x <- as_data_frame(fortify(UK))
class(x)
#[1] "tbl_df"     "tbl"        "data.frame"

Before we move on, I want to mention again that you cannot draw a polygon with a normal data frame including one with tbl_df in class. This is what I said at the beginning of this post. Hence, the following code, which I just changed UK to x, returned an error message.

leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 55, lng = -3, zoom = 6) %>%
addPolygons(data = x,
            stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
            fillColor = ~mypal(mydf$value)) %>%
addLegend(position = "bottomright", pal = mypal, values = mydf$value,
          title = "UK value",
          opacity = 1)

Error in polygonData.default(data) :
    Don't know how to get path data from object of class tbl_df

I hope this demonstration clears up your mind. The lesson to take is: Use a spatial class object from the sp or sf package. In your case, you would perhaps want to use FILE1 in addPolygons(). Make sure that it is a spatial object. If you have a right file, you will see polygons on top of the tile map.


问:
PG::SyntaxError: ERROR: syntax error at or near "PARALLEL"
i am not able to create this extension "hstore".

rails version: 5

osx version: 10.12.6

when i type this command "postgres -V" it returns:

```<code>postgres (PostgreSQL) 10.1
</code>```

complete error log is:

```<code>bilals-MacBook-Pro-2:testapp bilalbasharat$ bundle exec rails db:setup
Database 'testapp_development' already exists
Database 'testapp_test' already exists
-- enable_extension("plpgsql")
   -> 0.0196s
-- enable_extension("hstore")
rails aborted!
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error         at or near "PARALLEL"
: CREATE EXTENSION IF NOT EXISTS "hstore"
</code>```

答:
I updated my os to "macOS high sierra" . in a fresh OS i setup the rails app starting from brew , than installing postgres , than node and than setup rails app. than when i ran "bundle exec rails db:setup" it fixed and project ran just fine.

this is not an actual solution. it is time consuming. but it worked.

Body:
i am not able to create this extension "hstore".

rails version: 5

osx version: 10.12.6

when i type this command "postgres -V" it returns:

postgres (PostgreSQL) 10.1

complete error log is:

bilals-MacBook-Pro-2:testapp bilalbasharat$ bundle exec rails db:setup
Database 'testapp_development' already exists
Database 'testapp_test' already exists
-- enable_extension("plpgsql")
   -> 0.0196s
-- enable_extension("hstore")
rails aborted!
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error         at or near "PARALLEL"
: CREATE EXTENSION IF NOT EXISTS "hstore"


问:
NotFittedError issue with Sklearn
I'm trying to use the LinearSVC of sklearn and export the decision tree to a .dot file. I can fit the classifier with sample data and then use it on some test data but the export to the .dot file gives a NotFittedError.

```<code>data = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=list(range(0, 41)))
data = data.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

target = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=[41])

dataTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=list(range(0, 41)))
dataTest = dataTest.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

targetTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=[41])
clfSVC = LinearSVC(random_state=0)

clfSVC = clfSVC.fit(data, target.target)
scoreSVC = clfSVC.score(dataTest, targetTest.target)
print(scoreSVC)
tree.export_graphviz(clfSVC, out_file='tree.dot')
</code>```

Here is the output:

```<code>> Traceback (most recent call last):
  File "D:\Documents\Telecom\IA\ai-person-income\project\sklearn_test.py", line 49, in <module>
    tree.export_graphviz(clfSVC, out_file='tree.dot')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\tree\export.py", line 392, in export_graphviz
    check_is_fitted(decision_tree, 'tree_')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\utils\validation.py", line 768, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This LinearSVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
</code>```

What am I missing ?

答:
In sklearn.tree.export_graphviz, the first parameter is a fitted decision tree.
You give a fitted estimator, but not a decision tree.
Indeed, LinearSVC is not a decision tree.

Try with sklearn.tree.DecisionTreeClassifier instead of sklearn.svm.LinearSVC.

Title: NotFittedError issue with Sklearn

Body:
I'm trying to use the LinearSVC of sklearn and export the decision tree to a .dot file. I can fit the classifier with sample data and then use it on some test data but the export to the .dot file gives a NotFittedError.

data = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=list(range(0, 41)))
data = data.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

target = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=[41])

dataTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=list(range(0, 41)))
dataTest = dataTest.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

targetTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=[41])
clfSVC = LinearSVC(random_state=0)

clfSVC = clfSVC.fit(data, target.target)
scoreSVC = clfSVC.score(dataTest, targetTest.target)
print(scoreSVC)
tree.export_graphviz(clfSVC, out_file='tree.dot')

Here is the output:

> Traceback (most recent call last):
  File "D:\Documents\Telecom\IA\ai-person-income\project\sklearn_test.py", line 49, in <module>
    tree.export_graphviz(clfSVC, out_file='tree.dot')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\tree\export.py", line 392, in export_graphviz
    check_is_fitted(decision_tree, 'tree_')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\utils\validation.py", line 768, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This LinearSVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.

What am I missing ?


问:
ramotion expanding collection instructions unclear
I'm trying to use the expanding-collection library and I'm having some trouble understanding the guide. Here's the readme: https://github.com/Ramotion/expanding-collection/blob/master/README.md

I'm having trouble understanding the first instruction

Create UICollectionViewCell inherit from BasePageCollectionCell
  (recommend create cell with xib file)

Does this mean I should add a collectionviewcell to main.storyboard? As I have tried, however, xCode did not allow me to drag and drop an individual uicollectionviewcell into the storyboard or create a class called UICollectionViewCell that inherits from BasePageCollectionCell.

答:
do File -> New -> File -> View this will create an XIB file. From there you can delete the view that shows up in the GUI. Then you can drag a UICollectionViewCell into it and do what you need to do from there. Although I also recommend looking up how to create a custom XIB for views

Something like this could help you out

https://medium.com/@brianclouser/swift-3-creating-a-custom-view-from-a-xib-ecdfe5b3a960


问:
Python Remote Procedure Call (Without the Remote Part)
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.

Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or command line script which runs as root providing guarded access to said features.

However I want put aside stdin/stdout communication and use an RPC style of interaction such as Pyro. But this exposes the RPC interface to anyone with network access to the machine, whereas I know that the process calling the RPC methods will be another process on the same machine.

Is there not a sort of inter-process procedure call standard which could be used in a similar (local machine only) fashion? I imagine the server doing something like this:

```<code># Server not running as root
pythonically, returned, values = other_process_running_as_root.some_method()
</code>```

And the process running as root exposing a method:

```<code># Daemon running as root
@expose_this_method
def some_method():
    # Play with RAW sockets
    return pythonically, returned, values
</code>```

Is anything like this possible?

答: Pyro has a number of security features specifically to limit the access to the RPC interface. Are these too much of a performance burden to use?</p>

Body:
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.

Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or command line script which runs as root providing guarded access to said features.

However I want put aside stdin/stdout communication and use an RPC style of interaction such as Pyro. But this exposes the RPC interface to anyone with network access to the machine, whereas I know that the process calling the RPC methods will be another process on the same machine.

Is there not a sort of inter-process procedure call standard which could be used in a similar (local machine only) fashion? I imagine the server doing something like this:

# Server not running as root
pythonically, returned, values = other_process_running_as_root.some_method()

And the process running as root exposing a method:

# Daemon running as root
@expose_this_method
def some_method():
    # Play with RAW sockets
    return pythonically, returned, values

Is anything like this possible?

ContentLicense: CC BY-SA 2.5


答:
If I understand your question right, you need to give a name to the max(id)</p>

```<code>UPDATE vm s , (SELECT MAX(id) as id FROM vm) as p
SET s.title = 'TEST'
WHERE s.id = p.id;
</code>```

Title: Unknown column 'p.id' in 'where clause'

Body:
If I understand your question right, you need to give a name to the max(id)

UPDATE vm s , (SELECT MAX(id) as id FROM vm) as p
SET s.title = 'TEST'
WHERE s.id = p.id;


问:
Why are epsilon transitions used in NFA?
I'm trying to understand how to create NFA-s from regular expressions, but I am really confused from epsilon transitions. I have this example in my textbook , but I don't understand why epsilon transitions are used and how does one know when to use them.

答:
Epsilon-transitions in NFAs are a natural representation of choice or disjunction or union in regular expressions. That is, a regular expression like r + s (or r | s or r U s depending on your preferred notation) is naturally represented as an NFA consisting of two independent NFAs, one for r and one for s, joined using e-transitions as follows:

```<code>          e
----->q0----->(r)
      |
      | e
      |
      V
     (s)
</code>```

When used to connect states in more complicated ways, the effect may not be as easy or natural to describe, but essentially these transitions let you choose unconditionally among multiple options. So, if I have seen a part of the input already and there are a few different ways the string could end, I can represent that by using e-transitions to states that handle the different possibilities.

In your example, the e-transitions are not really serving any very useful function and are merely artifacts of the conversion algorithm you have used. That algorithm includes them because, in the general case, they may be useful or necessary. In your specific case this was not true, so they look out of place.

Body:
Epsilon-transitions in NFAs are a natural representation of choice or disjunction or union in regular expressions. That is, a regular expression like r + s (or r | s or r U s depending on your preferred notation) is naturally represented as an NFA consisting of two independent NFAs, one for r and one for s, joined using e-transitions as follows:

          e
----->q0----->(r)
      |
      | e
      |
      V
     (s)

When used to connect states in more complicated ways, the effect may not be as easy or natural to describe, but essentially these transitions let you choose unconditionally among multiple options. So, if I have seen a part of the input already and there are a few different ways the string could end, I can represent that by using e-transitions to states that handle the different possibilities.

In your example, the e-transitions are not really serving any very useful function and are merely artifacts of the conversion algorithm you have used. That algorithm includes them because, in the general case, they may be useful or necessary. In your specific case this was not true, so they look out of place.


问:
How to know which handle is getting used in jquery resizable
i am using jquery resizable to resize a div

```<code>$("#mainDiv").resizable({
        handles: 's, e',
        start: function(event, ui) {
        // want to perform some action here
    },
        resize: function(event, ui) {
        // want to perform some action here }
    });
</code>```

now i want to do some stuff based on fact that whether s or e is selected to resize basically resizing is vertical or horizontal how to do that

Thanks

答:
Just to expand on the answer by @user3322509:</p>

```<code>$("#selector").resizable({
    resize: function(e,ui) {
        console.log( ui.element.data("ui-resizable").axis )
    }
});
</code>```

Body:
i am using jquery resizable to resize a div

$("#mainDiv").resizable({
        handles: 's, e',
        start: function(event, ui) {
        // want to perform some action here
    },
        resize: function(event, ui) {
        // want to perform some action here }
    });

now i want to do some stuff based on fact that whether s or e is selected to resize basically resizing is vertical or horizontal how to do that

Thanks

Body:
Just to expand on the answer by @user3322509:

$("#selector").resizable({
    resize: function(e,ui) {
        console.log( ui.element.data("ui-resizable").axis )
    }
});


问:
Minimize space use with a randomized queue
I'm going over an algorithms online course and sometimes they pose ungraded bonus challenges for which no answer is provided. This is one of them:

You are given a positive integer k.

You will read a series of strings from the standard input (a total of n strings; n is not known to you until after you have exhausted all the strings).

You can make use of a randomized queue, which has a basic API: size() returns the number of elements in the queue; enqueue(String) adds the string into the queue; and dequeue() removes and returns a string from inside the queue, chosen uniformly at random.

Read all the input and at the end print k strings chosen uniformly at random from the set of n strings.

Use a randomized queue no larger than k.

I cannot satisfy 4 and 5 at the same time. I can get the distribution of the output to be uniform if I fill the queue with n strings and then make k calls to dequeue() or I can devise an scheme in which I only have k elements at most in the queue at any point, but the output is not uniform since the strings read at the beginning end up having either a greater or a smaller chance of being part of the final chosen set (depending on the algorithm I choose).

If I knew n in advance I could assign a random ID between 0 and n to each string I read, and keep a list of the k smallest IDs and their respective strings (e.g. k_smallest); if a new string is assigned a random ID smaller than any of the k I already have, I can decide to remove the largest element from k_smallest and add the new string to it. However, two problems arise: n is not known until after all strings have been read and the randomized queue does not allow to dequeue the largest element, only one at random.

I am very curious about the solution. How can this be solved using space proportional to k and not n?

答:
The Key:

You need to keep track on how many elements you have read so far.

Algo:
 l : number of enqueue(..)-calls so far.

Take the forst k elements and put them in your internal storage of size k. (e.g an array of size k). Set l:=k

For each enqueue(..) call after the first k, you need to decide which element to drop. If you have already enqueued l elements the probability with witch we need to keep the new element is k/l. If the random generator says keep it, you must remove a random element of the old elements. and replace it with the new one. l:=l+1

At any time you have have k evenly distributed values of the so far enqueued values (l) in your internal storage. At the end is l==n.

P.s.

The algorithm is much more intuitive for k=1. So if you have problems getting the idea, think it through with the simplest case k=1.


问:
highcharts col width and border-top
Hello I have highcharts diagram and some problem.

1) How can I set the width of my column to the width of the area of the month? (I try change "width" in CSS it's no working)

2)How to remove all borders, but the top border save? (I try change "stroke-width" in CSS it's no working)

Maybe some js config solution have for it?

I updated post using answers, it's work! Thank all.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 54.4, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

.highcharts-series rect {
    stroke-dasharray: 45, 1000;
    stroke-width: 3;
    stroke: #00ff00;
}

.highcharts-grid path {
display: none;
}</code>```

```

答:
You can specify the width of the chart by adding the chart: {width: WIDTH}, key value pair to the options object as can be seen below.

As for the chart's borders, there is no configuration. You need to add styles to the container div as I did in the snippet below

Highcharts.chart('container', {
    chart: {
        width: 300
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        type: 'column'
    }]

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}</code>```

```

Title: highcharts col width and border-top

Body:
Hello I have highcharts diagram and some problem.

1) How can I set the width of my column to the width of the area of the month? (I try change "width" in CSS it's no working)

2)How to remove all borders, but the top border save? (I try change "stroke-width" in CSS it's no working)

Maybe some js config solution have for it?

I updated post using answers, it's work! Thank all.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 54.4, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

.highcharts-series rect {
    stroke-dasharray: 45, 1000;
    stroke-width: 3;
    stroke: #00ff00;
}

.highcharts-grid path {
display: none;
}

Body:
You can specify the width of the chart by adding the chart: {width: WIDTH}, key value pair to the options object as can be seen below.

As for the chart's borders, there is no configuration. You need to add styles to the container div as I did in the snippet below

Highcharts.chart('container', {
    chart: {
        width: 300
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        type: 'column'
    }]

});

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="border-top: thin solid black" ></div>


问:
C# string manipulation, why this doesn't work?
```<code>int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}
</code>```

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

答:
You should try this syntax:</p>

```<code>for (int i = 1; i <= 10; i++) {
    string str = String.Format("test{0}", i);
    Console.WriteLine(str);
}
</code>```

Body:
int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

Body:
You should try this syntax:

for (int i = 1; i <= 10; i++) {
    string str = String.Format("test{0}", i);
    Console.WriteLine(str);
}


问:
How do I make a function out of these sql statements so I dont have to repeat them so many times?
I would like to make these statements into a function instead, as you see its kind of repetitive. How would you make this more efficient using a function? Very grateful for tips!

```<code>if (isset ($_GET["news"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'news'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

if (isset ($_GET["style"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'style'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

if (isset ($_GET["interior"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'interior'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

if (isset ($_GET["featured"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'featured'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}
</code>```

Its based on a category sorting(news, style, interior, featured).

答:
There are a couple of ways to skin this cat, but I use a function from which I can run all queries with PDO. Here is that function, along with the connection:

```<code>function dataQuery($query, $params) {
    // what kind of query is this?
    $queryType = explode(' ', $query);

    // establish database connection
    try {
        $dbh = new PDO(DBL, USER, PASS);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e) {
        echo $e->getMessage();
        $errorCode = $e->getCode();
    }

    // run query
    try {
        $queryResults = $dbh->prepare($query);
        $result = $queryResults->execute($params);
        if($queryResults != null && 'SELECT' == $queryType[0]) {
            // only return results for SELECT queries - the remainder need no output
            $results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
            return $results;
        }

        $queryResults = null; // first of the two steps to properly close
        $dbh = null; // second step to close the connection
        return $result;
    }
    catch(PDOException $e) {
        $errorMsg = $e->getMessage();
        echo $errorMsg;
    }
}
</code>```

NOTE: The try/catch is not necessary but I do capture the error messages for other pruposes, so this is a handy way of doing it.

Then, any time I need to query I can just write the query and send the parameters with the request:

```<code>$role = $_POST['role'];
$getRoleID = "SELECT `id` FROM `roles` WHERE `role` = :role;";
$params = array(':role'=>$role);
$result = dataQuery($getRoleID, $params);
</code>```

However, your's is a little more specific. You want a single function for your blog. Combining yours with mine you could do this:

```<code>function getBlogPosts($type) {

    $getPosts = "SELECT * FROM posts INNER JOIN users ON posts.userID = users.id WHERE category = :category");
    $params = array(':category'=>$type);
    $result = dataQuery($getPosts, $params);
    return $result;
}
</code>```

Now, to call the function you just have to insert the type of posts you want:

```<code>$featured = getBlogPosts('featured');
</code>```

or:

```<code>$interior = getBlogPosts('interior');
</code>```

Parse the returned results and you're well on your way.

Body:
I would like to make these statements into a function instead, as you see its kind of repetitive. How would you make this more efficient using a function? Very grateful for tips!

if (isset ($_GET["news"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'news'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

if (isset ($_GET["style"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'style'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

if (isset ($_GET["interior"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'interior'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

if (isset ($_GET["featured"])){

$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'featured'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);

}

Its based on a category sorting(news, style, interior, featured).

Body:
There are a couple of ways to skin this cat, but I use a function from which I can run all queries with PDO. Here is that function, along with the connection:

function dataQuery($query, $params) {
    // what kind of query is this?
    $queryType = explode(' ', $query);

    // establish database connection
    try {
        $dbh = new PDO(DBL, USER, PASS);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e) {
        echo $e->getMessage();
        $errorCode = $e->getCode();
    }

    // run query
    try {
        $queryResults = $dbh->prepare($query);
        $result = $queryResults->execute($params);
        if($queryResults != null && 'SELECT' == $queryType[0]) {
            // only return results for SELECT queries - the remainder need no output
            $results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
            return $results;
        }

        $queryResults = null; // first of the two steps to properly close
        $dbh = null; // second step to close the connection
        return $result;
    }
    catch(PDOException $e) {
        $errorMsg = $e->getMessage();
        echo $errorMsg;
    }
}

NOTE: The try/catch is not necessary but I do capture the error messages for other pruposes, so this is a handy way of doing it.

Then, any time I need to query I can just write the query and send the parameters with the request:

$role = $_POST['role'];
$getRoleID = "SELECT `id` FROM `roles` WHERE `role` = :role;";
$params = array(':role'=>$role);
$result = dataQuery($getRoleID, $params);

However, your's is a little more specific. You want a single function for your blog. Combining yours with mine you could do this:

function getBlogPosts($type) {

    $getPosts = "SELECT * FROM posts INNER JOIN users ON posts.userID = users.id WHERE category = :category");
    $params = array(':category'=>$type);
    $result = dataQuery($getPosts, $params);
    return $result;
}

Now, to call the function you just have to insert the type of posts you want:

$featured = getBlogPosts('featured');

or:

$interior = getBlogPosts('interior');

Parse the returned results and you're well on your way.


问:
Git push and commiter
when I make a push to GIT (Gitlab) repo in the commits I see that commit has been made by user set in 'user.email' and 'user.name'.

Why does it happen? I think that information about user, should be taken from Gitlab profile.
Now it's possible to spoof our identification.

答:
GitHub uses the email address in the commit header to link the commit to a GitHub user. If your commits are being linked to another user, or not linked to a user at all, you may need to change your local Git configuration settings, add an email address to your account email settings, or do both.
refer-->https://help.github.com/articles/why-are-my-commits-linked-to-the-wrong-user/</p>

Title: Git push and commiter


问:
Do not log my own visits with a tracking pixel (web beacon)
I'm adding a tracking pixel at then end of the emails I send via Gmail:

```

and then I have a script on my server which sends me a notification via email when Apache sees 1pixelimage.png?id=track_* in the logs. It works perfectly.

Problem: I receive a notification each time I open my own email in Gmail's Sent folder.

I've thought about:

filter by IP: not working because I often Gmail on phone, which has a dynamic IP, changing very often.

filter by UserAgent (that I could customize, e.g. I could set user agent = blabla, and send me notifications only if user agent is NOT blabla): this would require that I install a UserAgent modifier extension on all my browsers (not possible on phone), so this is not a solution.

anyway, when opening an email in Gmail, Gmail caches the images, so the request would not be done by my own browser but by Gmail's image caching server

How would you filter out your own visits of the tracking pixel image?

Note: I don't want to use a third-party app that requires "Send, write, manage your emails" permissions on Gmail.

答:
Do it the way you prevent tracking pixels from others, too. Disable HTML-Mail in your mail programs and adblock tracking pixels in your browser for webmail.

If the gmail app does not allow this, get another e-mail app. Loading content linked in a e-mail is a bad idea anyway. If you want an easy example, then think of read receipts for spammers ...

On the other hand: Why do you want to track others? They will be as annoyed as you, because they like their privacy as well.

Body:
I'm adding a tracking pixel at then end of the emails I send via Gmail:

and then I have a script on my server which sends me a notification via email when Apache sees 1pixelimage.png?id=track_* in the logs. It works perfectly.

Problem: I receive a notification each time I open my own email in Gmail's Sent folder.

I've thought about:

filter by IP: not working because I often Gmail on phone, which has a dynamic IP, changing very often.

filter by UserAgent (that I could customize, e.g. I could set user agent = blabla, and send me notifications only if user agent is NOT blabla): this would require that I install a UserAgent modifier extension on all my browsers (not possible on phone), so this is not a solution.

anyway, when opening an email in Gmail, Gmail caches the images, so the request would not be done by my own browser but by Gmail's image caching server

How would you filter out your own visits of the tracking pixel image?

Note: I don't want to use a third-party app that requires "Send, write, manage your emails" permissions on Gmail.


问:
How can I qualify an autowired property with a variable from a config file using annotations?
My specific problem is that I have configured two beans that implement the same interface and I have a third bean that has a property of that interface's type. I inject the property using a config property. So, assuming RemoteDataSource and LocalDataSource implement IDataSource and dao1 has a property of type IDataSource, my XML config might look like this:

```<code><bean id="datasource1" class="com.foo.RemoteDataSource">
  <property name="url">${url}</property>
</bean>
<bean id="datasource2" class="com.foo.LocalDataSource">
  <property name="path">${filepath}</property>
</bean>
<bean id="dao1" class="com.foo.MyDAO">
  <property name="dataSource">${datasource}</property>
</bean>
</code>```

With url, filepath and datasource being defined in an included properties file. We are now making a push for annotation-driven configuration and I'm not sure how to annotate my dao to put the data source configured in the property file. I want to do something like this, but it is evidently not allowed:

```<code>@Autowired
@Qualifier("${datasource}")
public void setDataSource(IDataSource datasource) {...}
</code>```

NB: this is spring 3

答:
My solution was thus:

```<code>@Autowired
public void setDataProviders(Map<String,IDataProvider> dataProviders) {
    this.dataProviders = dataProviders;
}

@Autowired
@Value("${cms}")
public void setDataProviderName(String dataProviderName) {
    this.dataProviderName = dataProviderName;
}

public IDataProvider getDataProvider() {
    return dataProviders.get(dataProviderName);
}
</code>```

NB: I changed that naming to DataProvider to disambiguate from the canonical DataSource which this isn't. It's actually just a homemade REST client.

Body:
My specific problem is that I have configured two beans that implement the same interface and I have a third bean that has a property of that interface's type. I inject the property using a config property. So, assuming RemoteDataSource and LocalDataSource implement IDataSource and dao1 has a property of type IDataSource, my XML config might look like this:

<bean id="datasource1" class="com.foo.RemoteDataSource">
  <property name="url">${url}</property>
</bean>
<bean id="datasource2" class="com.foo.LocalDataSource">
  <property name="path">${filepath}</property>
</bean>
<bean id="dao1" class="com.foo.MyDAO">
  <property name="dataSource">${datasource}</property>
</bean>

With url, filepath and datasource being defined in an included properties file. We are now making a push for annotation-driven configuration and I'm not sure how to annotate my dao to put the data source configured in the property file. I want to do something like this, but it is evidently not allowed:

@Autowired
@Qualifier("${datasource}")
public void setDataSource(IDataSource datasource) {...}

NB: this is spring 3

Body:
My solution was thus:

@Autowired
public void setDataProviders(Map<String,IDataProvider> dataProviders) {
    this.dataProviders = dataProviders;
}

@Autowired
@Value("${cms}")
public void setDataProviderName(String dataProviderName) {
    this.dataProviderName = dataProviderName;
}

public IDataProvider getDataProvider() {
    return dataProviders.get(dataProviderName);
}

NB: I changed that naming to DataProvider to disambiguate from the canonical DataSource which this isn't. It's actually just a homemade REST client.


答:
Read up on joins and you'll find they make this type of problem very easy to solve:</p>

```<code>quant <- left_join(quant, summary_backgrounds, by = c("conc_factor", "serum_factor"))
mutate(quant, avg_flourescence_minus_bg = mean_fluorescence - avg_fluorescence_grouped)
</code>```

Title: dplyr - subtract based on condition from two different data frames

Body:
I have a data frame which looks like the following:

quant <- structure(list(Name = structure(c(158L, 159L, 160L, 161L, 162L,
163L, 164L, 165L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 98L,
99L, 100L, 101L), .Label = c("abc_02_NEHC_025_100_A", "abc_02_NEHC_025_100_B",
"abc_02_NEHC_025_100_C", "abc_02_NEHC_025_100_D", "abc_02_NEHC_025_100_E",
"abc_02_NEHC_025_100_F", "abc_02_NEHC_025_100_G", "abc_02_NEHC_025_100_H",
"abc_02_NEHC_05_100_A", "abc_02_NEHC_05_100_B", "abc_02_NEHC_05_100_C",
"abc_02_NEHC_05_100_D", "abc_02_NEHC_05_100_E", "abc_02_NEHC_05_100_F",
"abc_02_NEHC_05_100_G", "abc_02_NEHC_05_100_H", "abc_02_NEHC_100_1_A",
"abc_02_NEHC_100_1_B", "abc_02_NEHC_100_1_C", "abc_02_NEHC_100_1_D",
"abc_02_NEHC_100_1_E", "abc_02_NEHC_100_1_F", "abc_02_NEHC_100_1_G",
"abc_02_NEHC_100_1_H", "abc_02_VL_025_100_A", "abc_02_VL_025_100_B",
"abc_02_VL_025_100_C", "abc_02_VL_025_100_D", "abc_02_VL_025_100_E",
"abc_02_VL_025_100_F", "abc_02_VL_025_100_G", "abc_02_VL_025_100_H",
"abc_02_VL_05_100_A", "abc_02_VL_05_100_B", "abc_02_VL_05_100_C",
"abc_02_VL_05_100_D", "abc_02_VL_05_100_E", "abc_02_VL_05_100_F",
"abc_02_VL_05_100_G", "abc_02_VL_05_100_H", "abc_02_VL_1_100_A",
"abc_02_VL_1_100_B", "abc_02_VL_1_100_C", "abc_02_VL_1_100_D",
"abc_02_VL_1_100_E", "abc_02_VL_1_100_F", "abc_02_VL_1_100_G",
"abc_02_VL_1_100_H", "BACKGROUND_NEHC_0125_100_A", "BACKGROUND_NEHC_0125_100_B",
"BACKGROUND_NEHC_0125_100_C", "BACKGROUND_NEHC_0125_100_D", "BACKGROUND_NEHC_0125_100_E",
"BACKGROUND_NEHC_0125_100_F", "BACKGROUND_NEHC_0125_100_G", "BACKGROUND_NEHC_025_100_A",
"BACKGROUND_NEHC_025_100_B", "BACKGROUND_NEHC_025_100_C", "BACKGROUND_NEHC_025_100_D",
"BACKGROUND_NEHC_025_100_F", "BACKGROUND_NEHC_025_100_G", "BACKGROUND_NEHC_05_100_A",
"BACKGROUND_NEHC_05_100_B", "BACKGROUND_NEHC_05_100_C", "BACKGROUND_NEHC_05_100_D",
"BACKGROUND_NEHC_05_100_F", "BACKGROUND_NEHC_05_100_G", "BACKGROUND_NEHC_05_100_H",
"BACKGROUND_NEHC_1_100_A", "BACKGROUND_NEHC_1_100_B", "BACKGROUND_NEHC_1_100_C",
"BACKGROUND_NEHC_1_100_D", "BACKGROUND_NEHC_1_100_E", "BACKGROUND_NEHC_1_100_F",
"BACKGROUND_NEHC_1_100_G", "BACKGROUND_VL_0125_100_A", "BACKGROUND_VL_0125_100_B",
"BACKGROUND_VL_0125_100_C", "BACKGROUND_VL_0125_100_D", "BACKGROUND_VL_0125_100_E",
"BACKGROUND_VL_0125_100_F", "BACKGROUND_VL_025_100_A", "BACKGROUND_VL_025_100_B",
"BACKGROUND_VL_025_100_C", "BACKGROUND_VL_025_100_D", "BACKGROUND_VL_025_100_E",
"BACKGROUND_VL_025_100_F", "BACKGROUND_VL_025_100_G", "BACKGROUND_VL_025_100_H",
"BACKGROUND_VL_05_100_A", "BACKGROUND_VL_05_100_B", "BACKGROUND_VL_05_100_C",
"BACKGROUND_VL_05_100_D", "BACKGROUND_VL_05_100_E", "BACKGROUND_VL_05_100_F",
"BACKGROUND_VL_05_100_G", "BACKGROUND_VL_05_100_H", "BACKGROUND_VL_1_100_A",
"BACKGROUND_VL_1_100_B", "BACKGROUND_VL_1_100_C", "BACKGROUND_VL_1_100_D",
"BACKGROUND_VL_1_100_E", "BACKGROUND_VL_1_100_F", "BACKGROUND_VL_1_100_G",
"BACKGROUND_VL_1_100_H", "Epq_11_NEHC_0125_100_a", "Epq_11_NEHC_0125_100_B",
"Epq_11_NEHC_0125_100_C", "Epq_11_NEHC_0125_100_D", "Epq_11_NEHC_0125_100_E",
"Epq_11_NEHC_0125_100_F", "Epq_11_NEHC_0125_100_G", "Epq_11_NEHC_025_100_a",
"Epq_11_NEHC_025_100_B", "Epq_11_NEHC_025_100_C", "Epq_11_NEHC_025_100_D",
"Epq_11_NEHC_025_100_E", "Epq_11_NEHC_05_100_a", "Epq_11_NEHC_05_100_B",
"Epq_11_NEHC_05_100_C", "Epq_11_NEHC_05_100_D", "Epq_11_NEHC_05_100_E",
"Epq_11_NEHC_05_100_F", "Epq_11_NEHC_05_100_G", "Epq_11_NEHC_05_100_H",
"Epq_11_NEHC_1_100_a", "Epq_11_NEHC_1_100_B", "Epq_11_NEHC_1_100_C",
"Epq_11_NEHC_1_100_D", "Epq_11_NEHC_1_100_E", "Epq_11_NEHC_1_100_F",
"Epq_11_NEHC_1_100_G", "Epq_11_NEHC_1_100_H", "Epq_11_VL_0125_100_A",
"Epq_11_VL_0125_100_B", "Epq_11_VL_0125_100_C", "Epq_11_VL_0125_100_D",
"Epq_11_VL_0125_100_E", "Epq_11_VL_0125_100_F", "Epq_11_VL_0125_100_G",
"Epq_11_VL_0125_100_H", "Epq_11_VL_025_100_A", "Epq_11_VL_025_100_B",
"Epq_11_VL_025_100_C", "Epq_11_VL_025_100_D", "Epq_11_VL_025_100_E",
"Epq_11_VL_025_100_F", "Epq_11_VL_025_100_G", "Epq_11_VL_025_100_H",
"Epq_11_VL_05_100_A", "Epq_11_VL_05_100_B", "Epq_11_VL_05_100_C",
"Epq_11_VL_05_100_D", "Epq_11_VL_05_100_E", "Epq_11_VL_05_100_F",
"Epq_11_VL_05_100_G", "Epq_11_VL_05_100_H", "Epq_11_VL_1_100_A",
"Epq_11_VL_1_100_B", "Epq_11_VL_1_100_C", "Epq_11_VL_1_100_D",
"Epq_11_VL_1_100_E", "Epq_11_VL_1_100_F", "Epq_11_VL_1_100_G",
"Epq_11_VL_1_100_H"), class = "factor"), conc_factor = structure(c(4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L), .Label = c("pep_0.125", "pep_0.25", "pep_0.5", "pep_1.0"
), class = "factor"), peptide_factor = structure(c(3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L), .Label = c("ABC", "Background", "EpQ_11"), class = "factor"),
    serum_factor = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("NEHC",
    "VL"), class = "factor"), mean_fluorescence = c(65535, 65535,
    65534.93359, 65535, 65535, 65535, 65535, 65535, 21322.06055,
    22704.08594, 22546.32617, 21801.30664, 21668.2168, 22054.40234,
    21621.54688, 21516.33984, 17760.80273, 17886.12891, 18382.7832,
    17531.80273)), class = "data.frame", row.names = c(NA, -20L
), .Names = c("Name", "conc_factor", "peptide_factor", "serum_factor",
"mean_fluorescence"))

This is actually just a slice (1:20) of my complete data frame. Just to have a better idea of my complete data frame, I am pasting below the levels of the variables conc_factor, peptide_factor and serum_factor:

levels(quant$conc_factor)
[1] "pep_0.125" "pep_0.25"  "pep_0.5"   "pep_1.0"
levels(quant$peptide_factor)
[1] "ABC"        "Background" "EpQ_11"
levels(quant$serum_factor)
[1] "NEHC" "VL"

With the following command:

summary_backgrounds <- quant %>% filter(peptide_factor=="Background") %>% group_by(conc_factor, serum_factor) %>% summarise(avg_fluorescence_grouped = mean(mean_fluorescence))

  conc_factor serum_factor avg_fluorescence_grouped
       <fctr>       <fctr>                    <dbl>
1   pep_0.125         NEHC                 18439.70
2   pep_0.125           VL                 16985.60
3    pep_0.25         NEHC                 18666.52
4    pep_0.25           VL                 17577.98
5     pep_0.5         NEHC                 18300.47
6     pep_0.5           VL                 18010.99
7     pep_1.0         NEHC                 16103.50
8     pep_1.0           VL                 17710.50

I obtained the mean_fluorescence values of the Background, for each conc_factor and serum_factor. What I am trying to do now is the following: I want to add a new variable to the data frame quant (named avg_fluorescence_minus_background) in which I will subtract the background values (summary_backgrounds$avg_fluorescence_grouped, considering conc_factor and serum_factor from each of the individual values on quant$mean_fluorescence.

For example, for quant[1, ], given that I have conc_factor=="pep_1.0" and serum_factor=="VL", my result would be 65535.00 - 17710.50 = 47824.5. and so on.

Body:
Read up on joins and you'll find they make this type of problem very easy to solve:

quant <- left_join(quant, summary_backgrounds, by = c("conc_factor", "serum_factor"))
mutate(quant, avg_flourescence_minus_bg = mean_fluorescence - avg_fluorescence_grouped)


问:
CSS fullscreen box working in firefox but not in Chrome
I'm working on a simple "Dead Pixel Finder" webpage.
I have code that works in Firefox Quantum, but not in Chrome.

In the script section I have code that enables Fullscreen API when page is clicked. And it works fine in Firefox Quantum.

....

```<code>    <style type="text/css">
        div
        {
            height: 100vh;
            width: 100wh;
            background-color: red;
        }
    </style>

</head>
<body>
    <div id="box" onclick="full_screen();"></div>
</body>
</code>```

But in Chrome I get a black page, not the color I set for background color?

答:
I am not sure what kind of API you are using there but check this out:

https://jsfiddle.net/cwoz3qw1/1/

```<code> div {
   height: 100vh;
   width: 100vw;
   background-color: red;
 }

let i = document.querySelector('#box');

i.addEventListener('click', () => {

  if (i.requestFullscreen) {
    i.requestFullscreen();
  } else if (i.webkitRequestFullscreen) {
    i.webkitRequestFullscreen();
  } else if (i.mozRequestFullScreen) {
    i.mozRequestFullScreen();
  } else if (i.msRequestFullscreen) {
    i.msRequestFullscreen();
  }
});
</code>```

More info:

https://www.sitepoint.com/use-html5-full-screen-api/

Body:
I'm working on a simple "Dead Pixel Finder" webpage.
I have code that works in Firefox Quantum, but not in Chrome.

In the script section I have code that enables Fullscreen API when page is clicked. And it works fine in Firefox Quantum.

....

But in Chrome I get a black page, not the color I set for background color?

Body:
I am not sure what kind of API you are using there but check this out:

https://jsfiddle.net/cwoz3qw1/1/

 div {
   height: 100vh;
   width: 100vw;
   background-color: red;
 }

let i = document.querySelector('#box');

i.addEventListener('click', () => {

  if (i.requestFullscreen) {
    i.requestFullscreen();
  } else if (i.webkitRequestFullscreen) {
    i.webkitRequestFullscreen();
  } else if (i.mozRequestFullScreen) {
    i.mozRequestFullScreen();
  } else if (i.msRequestFullscreen) {
    i.msRequestFullscreen();
  }
});

More info:

https://www.sitepoint.com/use-html5-full-screen-api/