问:
Cant sent POST request to server with NodeMCU
I have a NodeMCU programmed in the Arduino language. I'm trying to send some data from my sensors to a PHP script on my server which then writes the data to a MySQL server. When ran through the URL the script runs fine but when I try sending values from my code I get this error

200
  INSERT INTO sensor (temp, light)
      VALUES ('', '')
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'temp' at row 1

Now I understand that this is happening because there is no data being sent to the PHP script and an empty space isn't an integer.

Here's the code on the NodeMCU

```<code>#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("ssid", "password");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://server_public_ip_address/test3.php");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("?temp=20&light=88");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(3000);  //Send a request every 30 seconds

}
</code>```

I suspect that the problem is somewhere in http.addHeader("Content-Type", "text/plain"); or int httpCode = http.POST("?temp=20&light=88"); lines.

Also, this is a just a test program. The final program will take variables in this line int httpCode = http.POST("?temp=20&light=88"); instead of the numbers. So how do I write that as well?

EDIT:

Adding the PHP script as well

```<code><?php
$servername = "localhost";
$username = "root";
$password = "*************";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $temp = $_GET["temp"];
    $light = $_GET["light"];
    $sql = "INSERT INTO sensor (temp, light)
    VALUES ('$temp', '$light')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>
</code>```

答:
You were passing

http.POST("?temp=20&light=88")

Which should be as

http.POST("temp=20&light=88")

and the header

http.addHeader("Content-Type", "text/plain")

is basically used to send plain text, you can refer to the docs of content-type header here. Since, you are sending form data, this should be used

http.addHeader("Content-Type", "application/x-www-form-urlencoded")

The following code should solve your issue.

```<code>#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("ssid", "password");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://server_public_ip_address/test3.php");      //Specify request destination
   http.addHeader("Content-Type", "application/x-www-form-urlencoded");  //Specify content-type header

   int httpCode = http.POST("temp=20&light=88");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(3000);  //Send a request every 30 seconds

}
</code>```

Use this as your PHP file to view the sent values:

```<code><?php
    print_r($_POST);
?>
</code>```

The issue was with your PHP script. You have to use $_POST, instead of $_GET. Also, there was a small error in your PDO syntax. I have tried to fix it. Check this:

```<code><?php
$servername = "localhost";
$username = "root";
$password = "*************";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $temp = $_POST["temp"];
    $light = $_POST["light"];
    $sql = $conn->prepare("INSERT INTO sensor (temp, light) VALUES (?, ?)");
    $sql->bindParam(1, $temp);
    $sql->bindParam(2, $light);
    $sql->execute();
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
?>
</code>```

Body:
I have a NodeMCU programmed in the Arduino language. I'm trying to send some data from my sensors to a PHP script on my server which then writes the data to a MySQL server. When ran through the URL the script runs fine but when I try sending values from my code I get this error

200
  INSERT INTO sensor (temp, light)
      VALUES ('', '')
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'temp' at row 1

Now I understand that this is happening because there is no data being sent to the PHP script and an empty space isn't an integer.

Here's the code on the NodeMCU

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("ssid", "password");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://server_public_ip_address/test3.php");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("?temp=20&light=88");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(3000);  //Send a request every 30 seconds

}

I suspect that the problem is somewhere in http.addHeader("Content-Type", "text/plain"); or int httpCode = http.POST("?temp=20&light=88"); lines.

Also, this is a just a test program. The final program will take variables in this line int httpCode = http.POST("?temp=20&light=88"); instead of the numbers. So how do I write that as well?

EDIT:

Adding the PHP script as well

<?php
$servername = "localhost";
$username = "root";
$password = "*************";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $temp = $_GET["temp"];
    $light = $_GET["light"];
    $sql = "INSERT INTO sensor (temp, light)
    VALUES ('$temp', '$light')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "
" . $e->getMessage();
    }

$conn = null;
?>

Body:
You were passing

http.POST("?temp=20&light=88")

Which should be as

http.POST("temp=20&light=88")

and the header

http.addHeader("Content-Type", "text/plain")

is basically used to send plain text, you can refer to the docs of content-type header here. Since, you are sending form data, this should be used

http.addHeader("Content-Type", "application/x-www-form-urlencoded")

The following code should solve your issue.

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("ssid", "password");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://server_public_ip_address/test3.php");      //Specify request destination
   http.addHeader("Content-Type", "application/x-www-form-urlencoded");  //Specify content-type header

   int httpCode = http.POST("temp=20&light=88");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(3000);  //Send a request every 30 seconds

}

Use this as your PHP file to view the sent values:

<?php
    print_r($_POST);
?>

The issue was with your PHP script. You have to use $_POST, instead of $_GET. Also, there was a small error in your PDO syntax. I have tried to fix it. Check this:

<?php
$servername = "localhost";
$username = "root";
$password = "*************";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $temp = $_POST["temp"];
    $light = $_POST["light"];
    $sql = $conn->prepare("INSERT INTO sensor (temp, light) VALUES (?, ?)");
    $sql->bindParam(1, $temp);
    $sql->bindParam(2, $light);
    $sql->execute();
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
?>


来源: stackexchange

问:
Delete rows older than 14 days in MySQL

Summary

I need to purge the history of a table from rows that are older than 14 days.

Being no MySQL Expert, my searches lead me to this:

```<code>delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );
</code>```

Thrown Exception

But then I'm stuck with this error message:

Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.

What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.

In safe-mode, if I try to delete using only the date field, it doesn't comply.

```<code>delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec
</code>```

Am I missing something?

答:
I don't understand why do you complicate it :</p>

```<code>delete
    from SYS_VERROUS_POLICE
    where date(dateHeureModification)
                           <(curdate() - interval 14 day);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Delete rows older than 14 days in MySQL

Body:
Summary

I need to purge the history of a table from rows that are older than 14 days.

Being no MySQL Expert, my searches lead me to this:

delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );

Thrown Exception

But then I'm stuck with this error message:

Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.

What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.

In safe-mode, if I try to delete using only the date field, it doesn't comply.

delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec

Am I missing something?

Body:
I don't understand why do you complicate it :

delete
    from SYS_VERROUS_POLICE
    where date(dateHeureModification)
                           <(curdate() - interval 14 day);


问:
Why am I getting an error message when trying to "cat" my char device driver?
I've written a simple character device driver for Linux.

It is a simple message storing/retrieving system where the messages are stored in kernel space.

I should be able to do something like this:

```<code>echo "message 1" > /dev/mydevice
</code>```

and then retrieve the message with

```<code>cat /dev/mydevice
</code>```

The messages are stored in a queue.

When I try to retrieve a message that I hard coded in for testing (the message is "hello"), I get the following command line output:

```<code>cat /dev/mydevice
hellocat: /dev/mydevice: Resource temporarily unavailable
</code>```

So I get the hello message as intended, but clearly I'm doing something not quite right.

Here is the function that handles device reads.

```<code>static ssize_t device_read(struct file *filp, char *buffer,
               size_t length, loff_t * offset) {
  unsigned long result;
  int message_size;
  struct message_list* message = pop_message(&global_message_list);

  if (!message) return -EAGAIN;

  message_size = message -> message_length;

  result = copy_to_user(buffer, message -> message, message_size);

  printk(KERN_ALERT "res: %lu, msg_size: %d, len: %d\n", result, message_size, length);
  if (result == 0) return message_size;
  else return message_size - result;
}
</code>```

答:
The cat utility calls read more than once for each file, until it reaches EOF (which is signified by read returning 0).

This is because not all data may be available right away. If the file is bigger than cats internal buffer, it will of course need to call read multiple times to get the full data. Even if the number of bytes returned by read is less that the length of the buffer, it will need to call read again in case more data is available later (as could be the case if the input is a TTY or pipe). Therefore, you need to return 0 in order to get cat to think it’s at the end of the file and stop reading.

(For more detail on how cat works, you can check the source code, and the safe_read function.)

A simple way to handle this would be to put a zero-length message in your queue after each “real” message, so that the next read will return EOF. However, this won’t work correctly if you have multiple readers at the same time; in that case, one reader might read a message, then the other reads the EOF, then the first reads another message, so that one reader gets two messages and the other gets zero. It’s up to you and/or your instructor whether to make your device threadsafe.¹

This also indicates another potential problem with your code, which you only partially handle: if you have a message bigger than the buffer passed in to read, you discard the rest of the message instead of saving it for the next read. Again, this might be an acceptable shortoming, or not.

¹ I’m not sure if it’s possible to make it threadsafe; that depends on how well you can distinguish different readers, and I don’t know enough about kernel code or writing character devices to say if that’s possible.

Body:
I've written a simple character device driver for Linux.

It is a simple message storing/retrieving system where the messages are stored in kernel space.

I should be able to do something like this:

echo "message 1" > /dev/mydevice

and then retrieve the message with

cat /dev/mydevice

The messages are stored in a queue.

When I try to retrieve a message that I hard coded in for testing (the message is "hello"), I get the following command line output:

cat /dev/mydevice
hellocat: /dev/mydevice: Resource temporarily unavailable

So I get the hello message as intended, but clearly I'm doing something not quite right.

Here is the function that handles device reads.

static ssize_t device_read(struct file *filp, char *buffer,
               size_t length, loff_t * offset) {
  unsigned long result;
  int message_size;
  struct message_list* message = pop_message(&global_message_list);

  if (!message) return -EAGAIN;

  message_size = message -> message_length;

  result = copy_to_user(buffer, message -> message, message_size);

  printk(KERN_ALERT "res: %lu, msg_size: %d, len: %d\n", result, message_size, length);
  if (result == 0) return message_size;
  else return message_size - result;
}


问:
How to draw circles around a button if it is selected?
My scene looks like this:

I'm using SpriteKit and I created this scene with four buttons.

If the user taps on one of them there should appear a black circle around the selected button (and stay there). And if the user selects another button the previous circle should disappear and the new button gets a circle.

Does anyone know how to do this?

Here is my code:

```<code>override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let locationUser = touch.location(in: self)
        if atPoint(locationUser) == blueButton {
        }
        if atPoint(locationUser) == purpleButton {
        }
        if atPoint(locationUser) == redButton {
        }
        if atPoint(locationUser) == orangeButton {
        }
    }
}
</code>```

答:
there are several ways that you could achieve this. What I would do (and you should consider doing this any time you have 4 of the same object) is to subclass your buttons. That way you could add a property to your subclass that indicates whether or not the button isSelected and change it accordingly.

```<code>class Button: SKSpriteNode {

    var isSelected = false {
        didSet {
            if isSelected {
                background.isHidden = false
            }
            else {
                background.isHidden = true
            }
        }
   }

    //you can design the init to better suit however you want to differentiate between your buttons
    init(color: String) {

        //create an image of a black circle that you want to use as your border that is slightly larger than your other images
        let texture = SKTexture(imageNamed: "blackCircle")

        super.init(texture: nil, color: .clear, size: texture.size())

        let background = SKSpriteNode(texture: texture)
        background.zPosition = 0
        addChild(background)

        //add your color image here based on passed in parameters
        //but make sure that the zPosition is higher than 0
        let buttonTexture = SKTexture(imageNamed: color)

        let button = SKSpriteNode(texture: buttonTexture)
        button.zPosition = 1
        addChild(button)
    }
}
</code>```

in your gameScene I would store the buttons in an array

```<code>private var blueButton: Button!
private var purpleButton: Button!
private var redButton: Button!
private var orangeButton: Button!
private var buttons = [Button]()

//example of creating your new button
blueButton = Button(color: "blue")
blueButton.position = CGPoint(x: blah, y: blah)
blueButton.zPosition = 1
addChild(blueButton)
buttons.append(blueButton)

//previously selected Button so that you know which one to unselect
private var prevSelectedButton: Button!

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let locationUser = touch.location(in: self)

        //unhighlight the last selected button
        prevSelectedButton.isSelected = false

        if atPoint(locationUser) == blueButton {
            blueButton.isSelected = true
            prevSelectedButton = blueButton
        }
        else if atPoint(locationUser) == purpleButton {
            purpleButton.isSelected = true
            prevSelectedButton = purpleButton
        }
        else if atPoint(locationUser) == redButton {
            redButton.isSelected = true
            prevSelectedButton = redButton
        }
        else if atPoint(locationUser) == orangeButton {
            orangeButton.isSelected = true
            prevSelectedButton = orangeButton
        }
    }
}
</code>```

Worth noting that I would handle the touches events inside of the Button class to truly encapsulate the functionality, but that is outside of the scope of this question

Also if you are using shapeNodes instead of SpriteNodes you can still use this method just add a black circle behind color circle

Body:
My scene looks like this:

I'm using SpriteKit and I created this scene with four buttons.

If the user taps on one of them there should appear a black circle around the selected button (and stay there). And if the user selects another button the previous circle should disappear and the new button gets a circle.

Does anyone know how to do this?

Here is my code:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let locationUser = touch.location(in: self)
        if atPoint(locationUser) == blueButton {
        }
        if atPoint(locationUser) == purpleButton {
        }
        if atPoint(locationUser) == redButton {
        }
        if atPoint(locationUser) == orangeButton {
        }
    }
}

Body:
there are several ways that you could achieve this. What I would do (and you should consider doing this any time you have 4 of the same object) is to subclass your buttons. That way you could add a property to your subclass that indicates whether or not the button isSelected and change it accordingly.

class Button: SKSpriteNode {

    var isSelected = false {
        didSet {
            if isSelected {
                background.isHidden = false
            }
            else {
                background.isHidden = true
            }
        }
   }

    //you can design the init to better suit however you want to differentiate between your buttons
    init(color: String) {

        //create an image of a black circle that you want to use as your border that is slightly larger than your other images
        let texture = SKTexture(imageNamed: "blackCircle")

        super.init(texture: nil, color: .clear, size: texture.size())

        let background = SKSpriteNode(texture: texture)
        background.zPosition = 0
        addChild(background)

        //add your color image here based on passed in parameters
        //but make sure that the zPosition is higher than 0
        let buttonTexture = SKTexture(imageNamed: color)

        let button = SKSpriteNode(texture: buttonTexture)
        button.zPosition = 1
        addChild(button)
    }
}

in your gameScene I would store the buttons in an array

private var blueButton: Button!
private var purpleButton: Button!
private var redButton: Button!
private var orangeButton: Button!
private var buttons = [Button]()

//example of creating your new button
blueButton = Button(color: "blue")
blueButton.position = CGPoint(x: blah, y: blah)
blueButton.zPosition = 1
addChild(blueButton)
buttons.append(blueButton)

//previously selected Button so that you know which one to unselect
private var prevSelectedButton: Button!

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let locationUser = touch.location(in: self)

        //unhighlight the last selected button
        prevSelectedButton.isSelected = false

        if atPoint(locationUser) == blueButton {
            blueButton.isSelected = true
            prevSelectedButton = blueButton
        }
        else if atPoint(locationUser) == purpleButton {
            purpleButton.isSelected = true
            prevSelectedButton = purpleButton
        }
        else if atPoint(locationUser) == redButton {
            redButton.isSelected = true
            prevSelectedButton = redButton
        }
        else if atPoint(locationUser) == orangeButton {
            orangeButton.isSelected = true
            prevSelectedButton = orangeButton
        }
    }
}

Worth noting that I would handle the touches events inside of the Button class to truly encapsulate the functionality, but that is outside of the scope of this question

Also if you are using shapeNodes instead of SpriteNodes you can still use this method just add a black circle behind color circle


问:
Unexpected token : at window.onload
I'm a beginner in Javascript and I have a little problem with the eval() function. So, first I get some data through an API :

```<code>const xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);
</code>```

So, at that point, I know that xhr.response is for example :

```<code>"{"data":[{"id":41462,"created_at":"2017-11-13 [...]}"
</code>```

Now, I want to make a dictionary with it, so I do :

```<code>var req = eval(xhr.response);
</code>```

But the console shows me "Uncaught SyntaxError: Unexpected token : at window.onload" at the eval() step. And I don't know really why... any tips ?

答:
eval expects to be passed a chunk of JavaScript. A JSON representation of an object is not (by itself) valid JavaScript.

To parse JSON, use JSON.parse and not eval.

Title: Unexpected token : at window.onload

Body:
I'm a beginner in Javascript and I have a little problem with the eval() function. So, first I get some data through an API :

const xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);

So, at that point, I know that xhr.response is for example :

"{"data":[{"id":41462,"created_at":"2017-11-13 [...]}"

Now, I want to make a dictionary with it, so I do :

var req = eval(xhr.response);

But the console shows me "Uncaught SyntaxError: Unexpected token : at window.onload" at the eval() step. And I don't know really why... any tips ?


问:
GLES30.glBufferData crash
When I program a project on Android with GLES 3.0 VBO, sometimes the application crashes when it invoking the method GLES30.glBufferData. There is no crashes happen if I use simple data while it crash when I get data from file.

```<code>int[] vboIDs = new int[1];
GLES30.glGenBuffers(1, vboIDs, 0);
GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, vboIDs[0]);
GLES30.glBufferData(GLES30.GL_ELEMENT_ARRAY_BUFFER, size, buffer, GLES30.GL_STATIC_DRAW);//size=1296 buffer.capacity()=1296
GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0);
</code>```

It just crashed with no exception log. Is the format of buffer wrong? Below is how I get the buffer instance,the parameter byteBuffer is got from a binary file,

```<code> public static ByteBuffer createSlice(
    ByteBuffer byteBuffer, int position, int length)
{
    if (byteBuffer == null)
    {
        return null;
    }
    int oldPosition = byteBuffer.position();
    int oldLimit = byteBuffer.limit();
    try
    {
        int newLimit = position + length;
        if (newLimit > byteBuffer.capacity())
        {
            throw new IllegalArgumentException(
                "The new limit is " + newLimit + ", but the capacity is "
                + byteBuffer.capacity());
        }
        byteBuffer.limit(newLimit);
        byteBuffer.position(position);
        ByteBuffer slice = byteBuffer.slice();
        slice.order(byteBuffer.order());
        return slice;
    }
    finally
    {
        byteBuffer.limit(oldLimit);
        byteBuffer.position(oldPosition);
    }
}
</code>```

答: A crash in buffer data normally means you've run off the end of the buffer and accessed an unmapped page, so check that size is correct for the buffer you are uploading.

Title: GLES30.glBufferData crash

Body:
When I program a project on Android with GLES 3.0 VBO, sometimes the application crashes when it invoking the method GLES30.glBufferData. There is no crashes happen if I use simple data while it crash when I get data from file.

int[] vboIDs = new int[1];
GLES30.glGenBuffers(1, vboIDs, 0);
GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, vboIDs[0]);
GLES30.glBufferData(GLES30.GL_ELEMENT_ARRAY_BUFFER, size, buffer, GLES30.GL_STATIC_DRAW);//size=1296 buffer.capacity()=1296
GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0);

It just crashed with no exception log. Is the format of buffer wrong? Below is how I get the buffer instance,the parameter byteBuffer is got from a binary file,

 public static ByteBuffer createSlice(
    ByteBuffer byteBuffer, int position, int length)
{
    if (byteBuffer == null)
    {
        return null;
    }
    int oldPosition = byteBuffer.position();
    int oldLimit = byteBuffer.limit();
    try
    {
        int newLimit = position + length;
        if (newLimit > byteBuffer.capacity())
        {
            throw new IllegalArgumentException(
                "The new limit is " + newLimit + ", but the capacity is "
                + byteBuffer.capacity());
        }
        byteBuffer.limit(newLimit);
        byteBuffer.position(position);
        ByteBuffer slice = byteBuffer.slice();
        slice.order(byteBuffer.order());
        return slice;
    }
    finally
    {
        byteBuffer.limit(oldLimit);
        byteBuffer.position(oldPosition);
    }
}


问:
UITableViewCells with UICollectionView inside Low performance (Swift)
I have a tableview with nested in each cell a collectionView.

The number of tableViewCell is dynamic and also the number of collectionViewCell for each tableViewCell is dynamic.

I "dequeueReusableCell" both kind of cells.

Every time that I load a tableViewCell I do cell.collectionView.reloadData().

TableView is really jerking when I scroll it. Plus the viewController takes a lot to load.

I tried to move collectionView.reloadData() in prepareforReuse of uitableviewcell, or in willDisplayCell, but nothing.

I found few posts asking this question, but actually I could not solve my problem.

答:
Using reloadData() method is like using an hammer. It costs a lot because you are saying to reload all your data.

The question to ask yourself is : "Do I need to reload all the data every time ? Or only a part of that ? Just a row with func reloadRows(at: [IndexPath], with: UITableViewRowAnimation) ? Just a section maybe with func reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) ?

With those methods you can reduce the cost and speed up a little your program.


问:
What does SCM mean in Jenkins
I have an option (a plugin?) called "Poll SCM" in Jenkins and I know what it does and how to use it. Please tell me what "SCM" stands for. Is it "Source Code Management", "Sync Code [something]"?

Thanks.

答:
SCM = Source Control Management

From jenkin's tutorial

Section: Create your Pipeline project in Jenkins

Step 6: From the Definition field, choose the Pipeline script from SCM option. This option instructs Jenkins to obtain your Pipeline from Source Control Management (SCM), which will be your locally cloned Git repository.

ContentLicense: CC BY-SA 4.0

Title: What does SCM mean in Jenkins


问:
What HTTP response code to use for failed POST request?
What HTTP response code should be returned when a POST request was not successful and a request body was correctly formatted?

For successful POST request i am using 201 - Created, but there is no equivalent not created code.

I am thinking either 400 - bad request but that would actually point user that a request is poorly formatted or 304 - not modified.

答:
What HTTP response code should be returned when a POST request was not successful and a request body was correctly formatted?

If you mean the syntax of the request payload is valid but it cannot be processed due to invalid data, you can use 422:

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415 (Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained
instructions.  For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.

Remember to provide a good description in the response payload explaining what's wrong with the payload. Refer to the RFC 7807 for details on how to report problems in HTTP APIs.

Updates (according to the comments)

The reason why a POST request would fail is more of a business logic error, for example "account balance too low to withdraw 5.00 USD".

For the situation described in your comment, 403 or 409 would be a better fit.

6.5.3.  403 Forbidden

The 403 (Forbidden) status code indicates that the server understood
the request but refuses to authorize it.  A server that wishes to
make public why the request has been forbidden can describe that
reason in the response payload (if any). [...]

6.5.8.  409 Conflict

The 409 (Conflict) status code indicates that the request could not
be completed due to a conflict with the current state of the target
resource.  This code is used in situations where the user might be
able to resolve the conflict and resubmit the request.  The server
SHOULD generate a payload that includes enough information for a user
to recognize the source of the conflict. [...]


问:
How many numbers are there that include a given digit?
Let's have 3 digit number (100-999). How many such numbers with at least one digit "2" exist?

How to make algorithm for that? Or math function?

答:
A quick'n'dirty with python is:

```<code>n  = [x for x in range(100,999) if '2' in str(x)]

print("There are " + str(len(n)) + " numbers between 100 and 999 containing at least one '2'")
print(n)
</code>```

Put that in https://pyfiddle.io/ to test.

Body:
A quick'n'dirty with python is:

n  = [x for x in range(100,999) if '2' in str(x)]

print("There are " + str(len(n)) + " numbers between 100 and 999 containing at least one '2'")
print(n)

Put that in https://pyfiddle.io/ to test.


问:
SQLite count similair items based on first x number of characters
I have a table of errors which look like

```<code>"file not configured [filename1]"
"file not configured [filename2]"
"file not configured [filename3]"
"A bomb went off!!"
</code>```

What i want to do is get a list of occurrences of an error eg.

```<code>text                      occurrences
____________________________________
file not configured..     3
a bomb went off!!         1
</code>```

Is it possible to run queries in sqlite to check for similairity of the first x number of characters?

答:
You could try aggregating on a certain number of first characters of each error message:

```<code>SELECT
    SUBSTR(text, 1, 12) AS text,   -- or however long a substring you want
    COUNT(*) AS occurrences
FROM errors
GROUP BY
    SUBSTR(text, 1, 12);
</code>```

Note that the above query is strictly not ANSI compliant, because the GROUP BY clause contains a function of a column.  To fix that we can just rewrite with a subquery.

Body:
I have a table of errors which look like

"file not configured [filename1]"
"file not configured [filename2]"
"file not configured [filename3]"
"A bomb went off!!"

What i want to do is get a list of occurrences of an error eg.

text                      occurrences
____________________________________
file not configured..     3
a bomb went off!!         1

Is it possible to run queries in sqlite to check for similairity of the first x number of characters?

Body:
You could try aggregating on a certain number of first characters of each error message:

SELECT
    SUBSTR(text, 1, 12) AS text,   -- or however long a substring you want
    COUNT(*) AS occurrences
FROM errors
GROUP BY
    SUBSTR(text, 1, 12);

Note that the above query is strictly not ANSI compliant, because the GROUP BY clause contains a function of a column.  To fix that we can just rewrite with a subquery.


问:
React Transition Group
I have been reading about React Transition Group.  95% of the material talks about CSSTransitionGroup.  My understanding is that CSSTransitionGroup just builds off of TransitionGroup which simply provides callback methods that correspond to various animation events.  </p>

<p>So I've wrapped my component up in a TransitionGroup element and given it an animation event but it is never fired.  </p>

```<code>import React, { Component } from "react";

import { TransitionGroup, Transition } from "react-transition-group";

class Test extends Component {

    componentWillAppear(cb) {
        console.log('componentWillAppear')
        cb()
    }

    render() {
        return <div> test </div>
    }
}

class App extends Component {
    render() {
        return (
        <TransitionGroup>
         <Test />
         </TransitionGroup>
         )
    }
}

export default App;
</code>```

答:
You can use Transition or CSSTransition without TransitionGroup, but you can't use TransitionGroup without one of the others.

From the react-transition-group docs:

The <TransitionGroup> component manages a set of <Transition> components in a list. Like with the <Transition> component, <TransitionGroup>, is a state machine for managing the mounting and unmounting of components over time.

...As items are removed or added to the TodoList the in prop is toggled automatically by the <TransitionGroup>.

Try changing your Test component's render to something like this:

```<code>render() {
    return (
        <Transition timeout={150}>
            {(status) => (
                <div className={`fade fade-${status}`}>
                    test
                <div>
            )}
        </Transition>
    )
}
</code>```

Title: React Transition Group

Body:
I have been reading about React Transition Group.  95% of the material talks about CSSTransitionGroup.  My understanding is that CSSTransitionGroup just builds off of TransitionGroup which simply provides callback methods that correspond to various animation events.

So I've wrapped my component up in a TransitionGroup element and given it an animation event but it is never fired.

import React, { Component } from "react";

import { TransitionGroup, Transition } from "react-transition-group";

class Test extends Component {

    componentWillAppear(cb) {
        console.log('componentWillAppear')
        cb()
    }

    render() {
        return
 test

    }
}

class App extends Component {
    render() {
        return (
        <TransitionGroup>
         <Test />
         </TransitionGroup>
         )
    }
}

export default App;

Body:
You can use Transition or CSSTransition without TransitionGroup, but you can't use TransitionGroup without one of the others.

From the react-transition-group docs:

The <TransitionGroup> component manages a set of <Transition> components in a list. Like with the <Transition> component, <TransitionGroup>, is a state machine for managing the mounting and unmounting of components over time.

...As items are removed or added to the TodoList the in prop is toggled automatically by the <TransitionGroup>.

Try changing your Test component's render to something like this:

render() {
    return (
        <Transition timeout={150}>
            {(status) => (
                <div className={`fade fade-${status}`}>
                    test
                <div>
            )}
        </Transition>
    )
}


问:
What data structure should I use if I want to search an object in different ways according to different attributes?
I'm programming in java, but that's just a detail.
I have  this object person class with attributes like: name, age, weight... And I need to have people stored in my application and being able to search them. Now, I can search them by name, age, weight... all that person's attributes. What's the best data structure/implementation that allows me to do this efficiently?</p>

答:
K-D tree is a good choice for that. It partitions multi-dimensional data (any object with multiple attributes), and enables binary search tree like O(logN) search complexity. However, this will require few modifications to main variant.

If you don't know about it yet, go read about it first. So now you know, K-D tree doesn't exactly allow that "Given name="John Doe",find the guy" kind of queries. Instead, what it allows is "given this entire John Doe guy, find who is *closest* to him".

At every level of the tree, it chooses left or right  sub-tree based on corresponding dimension of that level. But for 1st kind of query, your data for all dimensions except one is null. So, to search, you create an input object anyway with special dummy data for all but that one dimension. In your search function, when you encounter those special data, you carry on search on both sub-trees. Instead of closeness, unlike K-D tree, you can check for exact match.

You are unlikely to see the effect of this data structure if you are dealing with small amount of data. Interestingly though, when you search against more than 1 attribute, like "given age=20 and name = "John", find the guy(s)", the search will be lot faster.


问:
foreach & silencer in a makefile target
I am using a foreach in a makefile for a particular target.

```<code>my_Target:
    $(foreach x,$(MY_TARGET_DIRS), @echo "  BUILD   $(x)";$(Q)$(MAKE) --directory=$(x) LIB_DIR=$(MY_LIB_DIR) $(MY_TARGET_RULES); )
</code>```

This is intended call the makefiles contained every specified directory of MY_TARGET_DIRS, after a string has been printed to tell which build is ongoing.

The Q variable is defined as follows:

```<code># Silent per default, 'make V=1' shows all compiler calls.
ifneq ($(V),1)
    Q := @
endif
</code>```

So that the make command is verbose if V=1 is defined.

For V=1 the output log is:

```<code>make my_Target V=1
BUILD   /dir1
make[1]: Entering directory `/dir1'
make[1]: Nothing to be done for `elf'.
make[1]: Nothing to be done for `bin'.
make[1]: Leaving directory `/dir1'
/bin/sh: @echo: command not found
make[1]: Entering directory `/dir2'
make[1]: Nothing to be done for `elf'.
make[1]: Nothing to be done for `bin'.
make[1]: Leaving directory `/dir2'
</code>```

While if I do not define V=1, the output log is:

```<code>make my_Target
BUILD   /dir1
/bin/sh: @make: command not found
/bin/sh: @echo: command not found
/bin/sh: @make: command not found
make: *** [my_Target] Error 127
</code>```

How can I get the behavior I desire correctly?

Bye!

答:
Put the @ ($(Q)) at the beginning of the recipe:

```<code>my_Target:
    $(Q)$(foreach x,$(MY_TARGET_DIRS), echo "  BUILD   $(x)";$(MAKE) --directory=$(x) LIB_DIR=$(MY_LIB_DIR) $(MY_TARGET_RULES); )
</code>```

Notice that the foreach will ouptut a single recipe line, and the @ will apply to all of it.   An alternative, if you want to get more fancy is to create a rule for each of the target dirs:

```<code>MY_TARGET_DIRS_TARGS=$(MY_TARGET_DIRS:%=%/.phony)

my_Target: $(MY_TARGET_DIRS_TARG)

$(MY_TARGET_DIRS_TARGS):
     @echo "  BUILD   $(x)"
     $(Q)(MAKE) --directory=$(x) LIB_DIR=$(MY_LIB_DIR) $(MY_TARGET_RULES);

.PHONY: $(MY_TARGET_DIRS_TARGS)
</code>```

Title: foreach & silencer in a makefile target

Body:
I am using a foreach in a makefile for a particular target.

my_Target:
    $(foreach x,$(MY_TARGET_DIRS), @echo "  BUILD   $(x)";$(Q)$(MAKE) --directory=$(x) LIB_DIR=$(MY_LIB_DIR) $(MY_TARGET_RULES); )

This is intended call the makefiles contained every specified directory of MY_TARGET_DIRS, after a string has been printed to tell which build is ongoing.

The Q variable is defined as follows:

# Silent per default, 'make V=1' shows all compiler calls.
ifneq ($(V),1)
    Q := @
endif

So that the make command is verbose if V=1 is defined.

For V=1 the output log is:

make my_Target V=1
BUILD   /dir1
make[1]: Entering directory `/dir1'
make[1]: Nothing to be done for `elf'.
make[1]: Nothing to be done for `bin'.
make[1]: Leaving directory `/dir1'
/bin/sh: @echo: command not found
make[1]: Entering directory `/dir2'
make[1]: Nothing to be done for `elf'.
make[1]: Nothing to be done for `bin'.
make[1]: Leaving directory `/dir2'

While if I do not define V=1, the output log is:

make my_Target
BUILD   /dir1
/bin/sh: @make: command not found
/bin/sh: @echo: command not found
/bin/sh: @make: command not found
make: *** [my_Target] Error 127

How can I get the behavior I desire correctly?

Bye!

Body:
Put the @ ($(Q)) at the beginning of the recipe:

my_Target:
    $(Q)$(foreach x,$(MY_TARGET_DIRS), echo "  BUILD   $(x)";$(MAKE) --directory=$(x) LIB_DIR=$(MY_LIB_DIR) $(MY_TARGET_RULES); )

Notice that the foreach will ouptut a single recipe line, and the @ will apply to all of it.   An alternative, if you want to get more fancy is to create a rule for each of the target dirs:

MY_TARGET_DIRS_TARGS=$(MY_TARGET_DIRS:%=%/.phony)

my_Target: $(MY_TARGET_DIRS_TARG)

$(MY_TARGET_DIRS_TARGS):
     @echo "  BUILD   $(x)"
     $(Q)(MAKE) --directory=$(x) LIB_DIR=$(MY_LIB_DIR) $(MY_TARGET_RULES);

.PHONY: $(MY_TARGET_DIRS_TARGS)


问:
.NET Dropbox API download large file in chunks
I need to download large files from Dropbox with size more than 100GB each. I'm using Dropbox .NET API for that.

To do that kind-like in chunks I call GetContentAsStream method as below:

```<code>var response = await client.Files.DownloadAsync(filePath);
using (var stream = await response.GetContentAsStreamAsync())
{
    var length = await stream.ReadAsync(buffer, 0, bufferSize, token);

    // Append to local file.
}
</code>```

After 5GB or so I get error: Unable to read data from the transport connection: The connection was closed.

Is there any explicit way to download chunk of a Dropbox file specifying offset and number of bytes? That way I will be able to retry or continue from the position I need to.

答:
The API v2 /2/files/download HTTPS endpoint itself does support "Range Retrieval Requests", but that's unfortunately not currently implemented in the Dropbox .NET SDK. I'll send this along as a feature request for that, but I can't promise if/when that would be implemented there.

That being the case, you could implement the HTTPS call directly, outside of the SDK, so you can set the desired Range header.

Body:
I need to download large files from Dropbox with size more than 100GB each. I'm using Dropbox .NET API for that.

To do that kind-like in chunks I call GetContentAsStream method as below:

var response = await client.Files.DownloadAsync(filePath);
using (var stream = await response.GetContentAsStreamAsync())
{
    var length = await stream.ReadAsync(buffer, 0, bufferSize, token);

    // Append to local file.
}

After 5GB or so I get error: Unable to read data from the transport connection: The connection was closed.

Is there any explicit way to download chunk of a Dropbox file specifying offset and number of bytes? That way I will be able to retry or continue from the position I need to.


问:
JavaScript Regular Expression String Match/Replace
Given the string; "{abc}Lorem ipsum{/abc} {a}dolor{/a}"

I want to be able find occurrences of curly brace "tags", store the tag and the index where it was found and remove it from the original string. I want to repeat this process for each occurrence, but because I'm removing part of the string each time the index must be correct...I can't find all the indices THEN remove them at the end. For the example above, what should happen is;

Search the string...

Find "{abc}" at index 0

Push { tag: "{abc}", index: 0 } into an array

Delete "{abc}" from string

Repeat step 1 until no more matches can be found

Given this logic, "{/abc}" should be found at index 11 - since "{abc}" has already been removed.

I basically need to know where those "tags" start and end without actually having them as part of the string.

I'm almost there using regular expressions but it sometimes skips occurrences.

let BETWEEN_CURLYS = /{.*?}/g;
let text = '{abc}Lorem ipsum{/abc} {a}dolor{/a}';
let match = BETWEEN_CURLYS.exec(text);
let tags = [];

while (match !== null) {
    tags.push(match);
    text = text.replace(match[0], '');
    match = BETWEEN_CURLYS.exec(text);
}

console.log(text); // should be; Lorem ipsum dolor
console.log(tags);

/**
 * almost there...but misses '{a}'
 * [ '{abc}', index: 0, input: '{abc}Lorem ipsum{/abc} {a}dolor{/a}' ]
 * [ '{/abc}', index: 11, input: 'Lorem ipsum{/abc} {a}dolor{/a}' ]
 * [ '{/a}', index: 20, input: 'Lorem ipsum {a}dolor{/a}' ]
 */```

答:
You need to subtract the match length from the regex lastIndex value, otherwise the next iteration starts farther than expected (since the input becomes shorter, and the lastIndex does not get changed after you call replace to remove the {...} substring):

let BETWEEN_CURLYS = /{.*?}/g;
let text = '{abc}Lorem ipsum{/abc} {a}dolor{/a}';
let match = BETWEEN_CURLYS.exec(text);
let tags = [];

while (match !== null) {
    tags.push(match);
    text = text.replace(match[0], '');
    BETWEEN_CURLYS.lastIndex = BETWEEN_CURLYS.lastIndex - match[0].length; // HERE
    match = BETWEEN_CURLYS.exec(text);
}

console.log(text); // should be; Lorem ipsum dolor
console.log(tags);```

Some more RegExp#exec reference to bear in mind:

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property).

Body:
You need to subtract the match length from the regex lastIndex value, otherwise the next iteration starts farther than expected (since the input becomes shorter, and the lastIndex does not get changed after you call replace to remove the {...} substring):

let BETWEEN_CURLYS = /{.*?}/g;
let text = '{abc}Lorem ipsum{/abc} {a}dolor{/a}';
let match = BETWEEN_CURLYS.exec(text);
let tags = [];

while (match !== null) {
    tags.push(match);
    text = text.replace(match[0], '');
    BETWEEN_CURLYS.lastIndex = BETWEEN_CURLYS.lastIndex - match[0].length; // HERE
    match = BETWEEN_CURLYS.exec(text);
}

console.log(text); // should be; Lorem ipsum dolor
console.log(tags);

Some more RegExp#exec reference to bear in mind:

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property).


问:
Access SQL - divide value in each row by total (using self join)
I have a table (tblGoals) which shows how many goals each player has scored, e.g:

```<code>| Player  | Goals  |
--------------------
|  John   |   6    |
|  Chris  |   10   |
|  Ben    |   4    |
</code>```

I am trying to write a query that will output each player along with the percentage of the teams total goals that they have scored:

```<code>| Player  | PercentageGoals  |
------------------------------
|  John   |       0.3        |
|  Chris  |       0.5        |
|  Ben    |       0.2        |
</code>```

I have already figured out how to do this with a sub query as shown

```<code>SELECT
    Player,
    Goals/ (SELECT SUM(Goals)FROM tblGoals) AS PercentageGoals
FROM tblGoals
</code>```

The example table I have shown is just to demonstrate what I am trying to do. The actual table I am using is a much larger dataset and trying to use a subquery to get the percentage in this way is running quite slowly.

I have noticed before in Access that self-joins are usually optimised more efficiently than sub queries, and so I am trying to figure out if the above query can be rewritten using a self join.

I have tried something along the lines of below but obviously this is incorrect as t2 is grouped by Player which means I am not getting the true total, but if I leave the Player name out then I can't join on it?

```<code>SELECT
    t1.Player,
    t1.Goals/t2.sumGoals AS PercentageGoals
FROM
    tbl1 t1
INNER JOIN
    (SELECT Player, SUM(Goals) as sumGoals
     FROM tbl1
     GROUP BY Player) t2
ON t1.Player= t2.Player
</code>```

Is there any way to do this?

答:
I'll try this as an answer - although I'm not sure if it will be faster as only using a three records.

Your second table in the join should just have a total of all the goals to join to each record in the first table - a cartesian product.

You can then divide one by the other:

```<code>SELECT    Player
        , Goals / TotalGoals AS Total
FROM    tblGoals, (SELECT SUM(Goals) AS TotalGoals FROM tblGoals)
</code>```

Is it any faster on a big table?  The idea being that in your SQL it was calculating the total for each record, while this creates the total as a table and joins to it so should only be calculated once.

Body:
I have a table (tblGoals) which shows how many goals each player has scored, e.g:

| Player  | Goals  |
--------------------
|  John   |   6    |
|  Chris  |   10   |
|  Ben    |   4    |

I am trying to write a query that will output each player along with the percentage of the teams total goals that they have scored:

| Player  | PercentageGoals  |
------------------------------
|  John   |       0.3        |
|  Chris  |       0.5        |
|  Ben    |       0.2        |

I have already figured out how to do this with a sub query as shown

SELECT
    Player,
    Goals/ (SELECT SUM(Goals)FROM tblGoals) AS PercentageGoals
FROM tblGoals

The example table I have shown is just to demonstrate what I am trying to do. The actual table I am using is a much larger dataset and trying to use a subquery to get the percentage in this way is running quite slowly.

I have noticed before in Access that self-joins are usually optimised more efficiently than sub queries, and so I am trying to figure out if the above query can be rewritten using a self join.

I have tried something along the lines of below but obviously this is incorrect as t2 is grouped by Player which means I am not getting the true total, but if I leave the Player name out then I can't join on it?

SELECT
    t1.Player,
    t1.Goals/t2.sumGoals AS PercentageGoals
FROM
    tbl1 t1
INNER JOIN
    (SELECT Player, SUM(Goals) as sumGoals
     FROM tbl1
     GROUP BY Player) t2
ON t1.Player= t2.Player

Is there any way to do this?

Body:
I'll try this as an answer - although I'm not sure if it will be faster as only using a three records.

Your second table in the join should just have a total of all the goals to join to each record in the first table - a cartesian product.

You can then divide one by the other:

SELECT    Player
        , Goals / TotalGoals AS Total
FROM    tblGoals, (SELECT SUM(Goals) AS TotalGoals FROM tblGoals)

Is it any faster on a big table?  The idea being that in your SQL it was calculating the total for each record, while this creates the total as a table and joins to it so should only be calculated once.


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答:
I would keep a separate HashMap from queue objects to Integers, and a running count of the total number of objects you've ever added to the queue (so when you insert object X, the counter means that object X is the Nth object inserted). Every time you add an object to the queue, add it to the HashMap as the key; the value is the current value of the counter.

When you need to ask which of two objects is first, look them up in the HashMap and compare the ordinals. Whichever one has a lower value came first.

ContentLicense: CC BY-SA 2.5


问:
Winsorize dataframe
I want to perform winsorization in a dataframe like this:

```<code>event_date  beta_before     beta_after
2000-05-05  1.2911707054    1.3215648954
1999-03-30  0.5089734305    0.4269575657
2000-05-05  0.5414700258    0.5326762272
2000-02-09  1.5491034852    1.2839988507
1999-03-30  1.9380674599    1.6169735009
1999-03-30  1.3109909155    1.4468207148
2000-05-05  1.2576420753    1.3659492507
1999-03-30  1.4393018341    0.7417777965
2000-05-05  0.2624037804    0.3860641307
2000-05-05  0.5532216441    0.2618245169
2000-02-08  2.6642931822    2.3815576738
2000-02-09  2.3007578964    2.2626960407
2001-08-14  3.2681270302    2.1611010935
2000-02-08  2.2509121123    2.9481325199
2000-09-20  0.6624503316    0.947935581
2006-09-26  0.6431111805    0.8745333151
</code>```

By winsorization I mean to find the max and min for beta_before for example. That value should be replaced by the second highest or second lowest value in the same column, without loosing the rest of the details in the observation. For example. In this case, in beta_before the max value is 3.2681270302 and should be replaced by 3.2681270302. The same process will be followed for the min and then for the beta_after variable. Therefore, only 2 values per column will be changes, the highest and the minimum, the rest will remain the same.

Any advice? I tried different approaches in plyr, but I ended up replacing the whole observation, which I don’t want to do. I would like to create 2 new variables, for example beta_before_winsorized and beta _after_winsorized

答:
The statar package works very well for this. Copying the relevant snippet from the readme file:

```<code># winsorize (default based on 5 x interquartile range)
v <- c(1:4, 99)
winsorize(v)
winsorize(v, replace = NA)
winsorize(v, probs = c(0.01, 0.99))
winsorize(v, cutpoints = c(1, 50))
</code>```

https://github.com/matthieugomez/statar

Title: Winsorize dataframe

Body:
I want to perform winsorization in a dataframe like this:

event_date  beta_before     beta_after
2000-05-05  1.2911707054    1.3215648954
1999-03-30  0.5089734305    0.4269575657
2000-05-05  0.5414700258    0.5326762272
2000-02-09  1.5491034852    1.2839988507
1999-03-30  1.9380674599    1.6169735009
1999-03-30  1.3109909155    1.4468207148
2000-05-05  1.2576420753    1.3659492507
1999-03-30  1.4393018341    0.7417777965
2000-05-05  0.2624037804    0.3860641307
2000-05-05  0.5532216441    0.2618245169
2000-02-08  2.6642931822    2.3815576738
2000-02-09  2.3007578964    2.2626960407
2001-08-14  3.2681270302    2.1611010935
2000-02-08  2.2509121123    2.9481325199
2000-09-20  0.6624503316    0.947935581
2006-09-26  0.6431111805    0.8745333151

By winsorization I mean to find the max and min for beta_before for example. That value should be replaced by the second highest or second lowest value in the same column, without loosing the rest of the details in the observation. For example. In this case, in beta_before the max value is 3.2681270302 and should be replaced by 3.2681270302. The same process will be followed for the min and then for the beta_after variable. Therefore, only 2 values per column will be changes, the highest and the minimum, the rest will remain the same.

Any advice? I tried different approaches in plyr, but I ended up replacing the whole observation, which I don’t want to do. I would like to create 2 new variables, for example beta_before_winsorized and beta _after_winsorized

Body:
The statar package works very well for this. Copying the relevant snippet from the readme file:

# winsorize (default based on 5 x interquartile range)
v <- c(1:4, 99)
winsorize(v)
winsorize(v, replace = NA)
winsorize(v, probs = c(0.01, 0.99))
winsorize(v, cutpoints = c(1, 50))

https://github.com/matthieugomez/statar


问:
Angular2: How to enable save button if any model value changed on edit page
I am new for angular 2. I have a page where we can edit details of customer profile. How to enable save button if any property of has been changed. I know it is possible in angular1 by using $watch.</p>

答:
You can use disabled option like below :

```<code>  <button [disabled]="isInvalid()" type="button" (click) = "searchClick()" class="button is-info">
          <span class="icon is-small">
            <i class="fa fa-search" aria-hidden="true"></i>
          </span>
          <span>Search</span>
     </button>
</code>```

you can create isInvalid() in your ts file and check if that property is empty or not and return that boolean value

Body:
You can use disabled option like below :

  <button [disabled]="isInvalid()" type="button" (click) = "searchClick()" class="button is-info">
          <span class="icon is-small">
            <i class="fa fa-search" aria-hidden="true"></i>
          </span>
          <span>Search</span>
     </button>

you can create isInvalid() in your ts file and check if that property is empty or not and return that boolean value


问:
how to stop the process take table offline in sql server managment studio
i am at work and accidentally i click on take offline to the database and i want to stop this process, what can i do?</p>

答:
the solution was this:

check the process running with

```<code>EXEC sp_who2
</code>```

search for the one that was an alter table in my case the 78, i get info about the spid command with:

```<code>DBCC INPUTBUFFER(78)
</code>```

once i was sure that was the process i kill it with:

```<code>KILL 78
</code>```

Body:
the solution was this:

check the process running with

EXEC sp_who2

search for the one that was an alter table in my case the 78, i get info about the spid command with:

DBCC INPUTBUFFER(78)

once i was sure that was the process i kill it with:

KILL 78


问:
Finding all PHP short tags
I need to find all short PHP tags.

The regex for it <\?(?!php) but I can not use it in vim.

How to "convert" it to vim?

答:
Find

```<code><\?(\t|\n|\s)
</code>```

Replace

```<code><?php$1
</code>```

Explanation

Match only short tags <\?, followed by white-space, tab or newline (\t|\n|\s) and store it in $1

All of the solutions provided here match what the line doesn't contain, instead of what we know it will be guaranteed to contain. This allows your code formatting to remain identical, only adding the text php where needed.

We only ever want to match the short tag, and shouldn't care what comes after (php/xml/= etc). This find/replace will match both inline short tags and short tags on a separate line.

Note: If you're using Windows line-breaks, <\?(\t|\r\n|\s) will match the same.

Title: Finding all PHP short tags

Body:
Find

<\?(\t|\n|\s)

Replace

<?php$1

Explanation

Match only short tags <\?, followed by white-space, tab or newline (\t|\n|\s) and store it in $1

All of the solutions provided here match what the line doesn't contain, instead of what we know it will be guaranteed to contain. This allows your code formatting to remain identical, only adding the text php where needed.

We only ever want to match the short tag, and shouldn't care what comes after (php/xml/= etc). This find/replace will match both inline short tags and short tags on a separate line.

Note: If you're using Windows line-breaks, <\?(\t|\r\n|\s) will match the same.


问:
Auto add-to-cart script for Selenium
I’m trying to build my first script with Selenium and I could need some help.

On my website you can buy event tickets. So as soon as one becomes available I would need my script to check for a specific price and then add it to my shopping cart.

For example let’s say I want a 15,00 € ticket added to my shopping cart:

Check the first line of the list to find element that contains “15,00 €”

This is the element:

```<code>id="ctl00_ContentMiddle_TicketList1_GridView1_ctl01_Label4”
</code>```

How do I check this element for the text “15,00 €” ?

If the button contains the correct price I want the script to click the add-to-cart button next to it:

This is the add-to-cart element:

```<code>id="ctl00_ContentMiddle_TicketList1_GridView1_ctl01_LinkButton1”
</code>```

If the price couldn’t be found it should check line two in the list, so

```<code>id="ctl00_ContentMiddle_TicketList1_GridView1_ctl02_Label4”
</code>```

and if correct, click on

```<code>id="ctl00_ContentMiddle_TicketList1_GridView1_ctl02_LinkButton1”
</code>```

How would you write this in Code? This is the first thing I wrote down but I guess it's pretty far off from the right track:

```<code>browser = webdriver.Chrome()
browser.get((‘URL’))

Price = browser.find_element_by_id(‘ctl00_ContentMiddle_TicketList1_GridView1_ctl01_Label4”>15,00 €’)

if elem.is_displayed():

Add = browser.find_element_by_id(‘ctl00_ContentMiddle_TicketList1_GridView1_ctl01_LinkButton1’)
Add.click()
</code>```

Hope someone can guide me in the right direction :)

Best regards
Marc

答:
Checking for a WebElement's text is as simple as it sounds. In your case:

```<code>Price.text;
</code>```

After that, you probably need an IF to determine if your text has value or not:

```<code>if Price.text != "15"
{
    //Click add to cart
}

else
{
    //Search for the other element and get text, then check if its "15" etc.
{
</code>```

The only catch here is if the first element's text is, e.g. 13, do you want to search for the next item or not. Adjust the IF above to your needs. Maybe you want to search for the next element only if the first one does not contain text at all.

Title: Auto add-to-cart script for Selenium

Body:
I’m trying to build my first script with Selenium and I could need some help.

On my website you can buy event tickets. So as soon as one becomes available I would need my script to check for a specific price and then add it to my shopping cart.

For example let’s say I want a 15,00 € ticket added to my shopping cart:

Check the first line of the list to find element that contains “15,00 €”

This is the element:

id="ctl00_ContentMiddle_TicketList1_GridView1_ctl01_Label4”

How do I check this element for the text “15,00 €” ?

If the button contains the correct price I want the script to click the add-to-cart button next to it:

This is the add-to-cart element:

id="ctl00_ContentMiddle_TicketList1_GridView1_ctl01_LinkButton1”

If the price couldn’t be found it should check line two in the list, so

id="ctl00_ContentMiddle_TicketList1_GridView1_ctl02_Label4”

and if correct, click on

id="ctl00_ContentMiddle_TicketList1_GridView1_ctl02_LinkButton1”

How would you write this in Code? This is the first thing I wrote down but I guess it's pretty far off from the right track:

browser = webdriver.Chrome()
browser.get((‘URL’))

Price = browser.find_element_by_id(‘ctl00_ContentMiddle_TicketList1_GridView1_ctl01_Label4”>15,00 €’)

if elem.is_displayed():

Add = browser.find_element_by_id(‘ctl00_ContentMiddle_TicketList1_GridView1_ctl01_LinkButton1’)
Add.click()

Hope someone can guide me in the right direction :)

Best regards
Marc

Body:
Checking for a WebElement's text is as simple as it sounds. In your case:

Price.text;

After that, you probably need an IF to determine if your text has value or not:

if Price.text != "15"
{
    //Click add to cart
}

else
{
    //Search for the other element and get text, then check if its "15" etc.
{

The only catch here is if the first element's text is, e.g. 13, do you want to search for the next item or not. Adjust the IF above to your needs. Maybe you want to search for the next element only if the first one does not contain text at all.


问:
How can i make my each database field into a public variable in php?
I got my all database field by doing this query

```<code>"SHOW  COLUMNS FROM admin"
</code>```

but i am wondering how could i make each of them into a public variable!
and yes these variables will be in a class as i am doing OO PHP.

First, i need to take all field name from my database. Then I need to put them into a variable of a class.

答:
This is how you use PDO to connect to database and execute queries:

```<code>try{
            $db_host = '...';  //  hostname
            $db_name = '...';  //  databasename
            $db_user = '...';  //  username
            $user_pw = '...';  //  password
            $pdo = new PDO("mysql:host=".$db_host.";dbname=".$db_name, $db_user, $user_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            //---------------------- QUERY -----------------------
            $sql = "insert your query here";
            //----------------------END QUERY -----------------------

            $data = $pdo->query($sql);
            //the next lines will convert the query results to an array
            //containing the contents as single variables
            $return = array();
            foreach($data as $row){
                $data = $row[0];
                array_push($return, $row);
            }
            return $return;
        }catch(PDOException $erro){
            echo $erro->getMessage();
        }
    }
</code>```

The $return variable will be an array of every row the query returned, and then you can access it as single variables.

Body:
I got my all database field by doing this query

"SHOW  COLUMNS FROM admin"

but i am wondering how could i make each of them into a public variable!
and yes these variables will be in a class as i am doing OO PHP.

First, i need to take all field name from my database. Then I need to put them into a variable of a class.

Body:
This is how you use PDO to connect to database and execute queries:

try{
            $db_host = '...';  //  hostname
            $db_name = '...';  //  databasename
            $db_user = '...';  //  username
            $user_pw = '...';  //  password
            $pdo = new PDO("mysql:host=".$db_host.";dbname=".$db_name, $db_user, $user_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            //---------------------- QUERY -----------------------
            $sql = "insert your query here";
            //----------------------END QUERY -----------------------

            $data = $pdo->query($sql);
            //the next lines will convert the query results to an array
            //containing the contents as single variables
            $return = array();
            foreach($data as $row){
                $data = $row[0];
                array_push($return, $row);
            }
            return $return;
        }catch(PDOException $erro){
            echo $erro->getMessage();
        }
    }

The $return variable will be an array of every row the query returned, and then you can access it as single variables.


问:
href in scrollable div-container - link not working jumps to top of container
I got a draggable div container with some dynamically generated content inside.

I call it with this code:

```<code>$( function() {
$( "#dialog-message" ).dialog({
    modal: true,
    height: 400,
    buttons: {
    Fertig: function() {
      $( this ).dialog( "close" );
    }
  }
});
</code>```

CSS:

```<code>div#dialog-message {
background-color:#e8ebf3;
overflow:auto;
</code>```

Inside the div I have other divs with href-links inside.
The links that are shown without scrolling do work fine, but when I scroll down in this container the hrefs does not work and the container scrolls automaticaly to the top when clicking.

The problem is that I use the href with an ID input from my database to toggle visibility of other div-containers like so:

```<code><div href="651">This does not scroll</div>
</code>```

Any ideas, how to combine the answers with this?

The href’s do work in Firefox, when I scroll down and click a link for the first time. But when I click it a second time without refreshing the page, it will scroll to the top.

In Chrome it doesn’t work a single time.

```<code><div id="dialog"  href="651">First time clicking works, second time not.</div>
</code>```

Problem solved:

The problem was that the page was not fully load when I tried to href to an div-Container witch did not exists at this point.

Thanks for all the answers!

答: I would suggest This does not scroll.

Body:
I got a draggable div container with some dynamically generated content inside.

I call it with this code:

$( function() {
$( "#dialog-message" ).dialog({
    modal: true,
    height: 400,
    buttons: {
    Fertig: function() {
      $( this ).dialog( "close" );
    }
  }
});

CSS:

div#dialog-message {
background-color:#e8ebf3;
overflow:auto;

Inside the div I have other divs with href-links inside.
The links that are shown without scrolling do work fine, but when I scroll down in this container the hrefs does not work and the container scrolls automaticaly to the top when clicking.

The problem is that I use the href with an ID input from my database to toggle visibility of other div-containers like so:

This does not scroll

Any ideas, how to combine the answers with this?

The href’s do work in Firefox, when I scroll down and click a link for the first time. But when I click it a second time without refreshing the page, it will scroll to the top.

In Chrome it doesn’t work a single time.

First time clicking works, second time not.

Problem solved:

The problem was that the page was not fully load when I tried to href to an div-Container witch did not exists at this point.

Thanks for all the answers!

Body: I would suggest <a href="javascript:void(0)">This does not scroll</a>.


问:
Can i install VSTS on my own server firm?
I know Azure Websites has released a version of its cloud manager to install it on its own server firm.

Likewise, I would like to install VSTS on my own server firm.

Is there also a setup version available for Visual Studio Team Services ?

答:
Team Foundation Server is the on-prem version of Visual Studio Team Services.

Or, more accurately, VSTS is the cloud-hosted version of TFS.


问:
How to read appseting key in xml service declaration at app.config
I am developing a WCF Service in VS 2010 and .NET 4.0.

I am creating the app.config file and I want to specify once the base address for the server.

I've declared it into the appConfig section as:

```<code><appSettings>
  <add key="base_address" value="net.tcp://localhost:5050/Service1/"/>
</appSettings>
</code>```

I would like to know how can I reference that key into the service/host/baseaAddressses like:

```<code><service
    name="WcfService_callbacks_tcp_auth_username.Service1"
    behaviorConfiguration="beh_auth">
    <host>
      <baseAddresses>
        <add baseAddress="!!!here_the_key!!!"/>
      </baseAddresses>
    </host>
</service>
</code>```

And in the client/endpoint section like:

```<code><client>
  <endpoint address="!!!here_the_key!!!" binding="netTcpBinding"
            bindingConfiguration="NetTcpBinding_IService1" contract="Service1.IService1"
            name="NetTcpBinding_IService1">
            <identity>
                <certificate encodedValue="..." />
            </identity>
   </endpoint>
</client>
</code>```

Is there anyway to do this?

Thanks.

答:
You cannot do that out of the box.

Either you specify the base address explicitly in your WCF config

```<code><service
    name="WcfService_callbacks_tcp_auth_username.Service1"
    behaviorConfiguration="beh_auth">
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://localhost:5050/Service1"/>
      </baseAddresses>
    </host>
</service>
</code>```

or you read it from the app.config in code and set it in WCF code (sample for client side - on the service side, you need to call .AddServiceEndpoint() on your ServiceHost):

```<code>string customBaseAddress = ConfigurationManager.AppSettings["base_address"];

YourServiceClient proxy =
     new YourServiceClient("NetTcpBinding_IService1",  // endpoint name in config
                           customBaseAddress);         // custom URL
</code>```

You cannot reference another config settings inside app.config - the .NET config system just doesn't support that.

Body:
I am developing a WCF Service in VS 2010 and .NET 4.0.

I am creating the app.config file and I want to specify once the base address for the server.

I've declared it into the appConfig section as:

<appSettings>
  <add key="base_address" value="net.tcp://localhost:5050/Service1/"/>
</appSettings>

I would like to know how can I reference that key into the service/host/baseaAddressses like:

<service
    name="WcfService_callbacks_tcp_auth_username.Service1"
    behaviorConfiguration="beh_auth">
    <host>
      <baseAddresses>
        <add baseAddress="!!!here_the_key!!!"/>
      </baseAddresses>
    </host>
</service>

And in the client/endpoint section like:

<client>
  <endpoint address="!!!here_the_key!!!" binding="netTcpBinding"
            bindingConfiguration="NetTcpBinding_IService1" contract="Service1.IService1"
            name="NetTcpBinding_IService1">
            <identity>
                <certificate encodedValue="..." />
            </identity>
   </endpoint>
</client>

Is there anyway to do this?

Thanks.

Body:
You cannot do that out of the box.

Either you specify the base address explicitly in your WCF config

<service
    name="WcfService_callbacks_tcp_auth_username.Service1"
    behaviorConfiguration="beh_auth">
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://localhost:5050/Service1"/>
      </baseAddresses>
    </host>
</service>

or you read it from the app.config in code and set it in WCF code (sample for client side - on the service side, you need to call .AddServiceEndpoint() on your ServiceHost):

string customBaseAddress = ConfigurationManager.AppSettings["base_address"];

YourServiceClient proxy =
     new YourServiceClient("NetTcpBinding_IService1",  // endpoint name in config
                           customBaseAddress);         // custom URL

You cannot reference another config settings inside app.config - the .NET config system just doesn't support that.


问:
one key with multiple values Python
```<code>bag =('IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__')
</code>```

What should I do to make this input as below?

```<code>dic1 = {1: {'Q', 'Z', 'X', 'K', 'J'}, 2: {'F', '_', 'P', 'C', 'M', 'W', 'Y', 'B',   'V', 'H'}, 3: {'G'}, 4: {'U', 'D', 'L', 'S'}, 6: {'N', 'R', 'T'}, 8: {'O'}, 9: {'I', 'A'}, 12: {'E'}}
</code>```

(occurrences as a key and correspond letters as a value)

What i have done so far is this

```<code>freq = {i:bag.count(i) for i in set(bag)}
 {'U': 4, '_': 2, 'C': 2, 'K': 1, 'D': 4, 'T': 6, 'Q': 1, 'V': 2, 'A': 9, 'F': 2, 'O': 8, 'J': 1, 'I': 9, 'N': 6, 'P': 2, 'S': 4, 'M': 2, 'W': 2, 'E': 12, 'Z': 1, 'G': 3, 'Y': 2, 'B': 2, 'L': 4, 'R': 6, 'X': 1, 'H': 2}
</code>```

I'm not sure about the next step

Thanks

答:
You can count the frequencies, then group by the similar ones:

```<code>    from collections import Counter

    bag =('IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__')
    frequencies = Counter(bag)

    dict1 = {}

    for k, v in frequencies.items():
        dict1[v] = dict1.get(v,[])+[k,]

    print(dict1)
</code>```

output:

```<code>{1: ['Q', 'J', 'Z', 'K', 'X'], 2: ['M', 'C', 'Y', 'F', 'V', 'H', 'B', 'W', 'P', '_'], 3: ['G'], 4: ['D', 'U', 'L', 'S'], 6: ['T', 'N', 'R'], 8: ['O'], 9: ['I', 'A'], 12: ['E']}
</code>```

Title: one key with multiple values Python

Body:
bag =('IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__')

What should I do to make this input as below?

dic1 = {1: {'Q', 'Z', 'X', 'K', 'J'}, 2: {'F', '_', 'P', 'C', 'M', 'W', 'Y', 'B',   'V', 'H'}, 3: {'G'}, 4: {'U', 'D', 'L', 'S'}, 6: {'N', 'R', 'T'}, 8: {'O'}, 9: {'I', 'A'}, 12: {'E'}}

(occurrences as a key and correspond letters as a value)

What i have done so far is this

freq = {i:bag.count(i) for i in set(bag)}
 {'U': 4, '_': 2, 'C': 2, 'K': 1, 'D': 4, 'T': 6, 'Q': 1, 'V': 2, 'A': 9, 'F': 2, 'O': 8, 'J': 1, 'I': 9, 'N': 6, 'P': 2, 'S': 4, 'M': 2, 'W': 2, 'E': 12, 'Z': 1, 'G': 3, 'Y': 2, 'B': 2, 'L': 4, 'R': 6, 'X': 1, 'H': 2}

I'm not sure about the next step

Thanks

Body:
You can count the frequencies, then group by the similar ones:

    from collections import Counter

    bag =('IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__')
    frequencies = Counter(bag)

    dict1 = {}

    for k, v in frequencies.items():
        dict1[v] = dict1.get(v,[])+[k,]

    print(dict1)

output:

{1: ['Q', 'J', 'Z', 'K', 'X'], 2: ['M', 'C', 'Y', 'F', 'V', 'H', 'B', 'W', 'P', '_'], 3: ['G'], 4: ['D', 'U', 'L', 'S'], 6: ['T', 'N', 'R'], 8: ['O'], 9: ['I', 'A'], 12: ['E']}


问:
JavaScript Chart.js - Custom data formatting to display on tooltip
I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have repeated this question!

As a bit of background info, I have implemented 4 graphs using the Chart.js plugin and passed in the required data using PHP from a database. This is all working correctly and is fine.

My problem is I need to display the data in the tooltips as formatted data aka. as numeric with %. As an example, one of my data from database is -0.17222. I have formatted it as a percentage to display in my table and all is well. However, when setting the data for the chart.js bar graph, the data is obviously missing this formatting and displaying as the -0.17222 which I do not want.

Sorry, I wanted to post a picture, but my reputation is too rubbish!

I grab data from database, then set into my table:

```<code>var kpiRex = new Handsontable(example1, {
    data: getRexData(),
</code>```

Then I feed this data like so in the chart section:

```<code>data: kpiRex.getDataAtRow(3)
</code>```

Any help would be great! I've been stuck on this for hours and it's probably something really simple I am overlooking.

答:
```<code>tooltips: {
            enabled: true,
                  mode: 'single',
                  callbacks: {
                    label: function(tooltipItems, data) {
                      return data.datasets[tooltipItems.datasetIndex].label+": "+tooltipItems.yLabel;
                    }
                  }
                }
</code>```

Body:
I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have repeated this question!

As a bit of background info, I have implemented 4 graphs using the Chart.js plugin and passed in the required data using PHP from a database. This is all working correctly and is fine.

My problem is I need to display the data in the tooltips as formatted data aka. as numeric with %. As an example, one of my data from database is -0.17222. I have formatted it as a percentage to display in my table and all is well. However, when setting the data for the chart.js bar graph, the data is obviously missing this formatting and displaying as the -0.17222 which I do not want.

Sorry, I wanted to post a picture, but my reputation is too rubbish!

I grab data from database, then set into my table:

var kpiRex = new Handsontable(example1, {
    data: getRexData(),

Then I feed this data like so in the chart section:

data: kpiRex.getDataAtRow(3)

Any help would be great! I've been stuck on this for hours and it's probably something really simple I am overlooking.


问:
Is it problematic to use a caching mechanism for throttling?
I implemented a throttling mechanism on our Azure web job. The "job" of our web job is to download separate .wav files from a 3rd party api constantly throughout the day. And it does this around 5,000 times a day (right now). However, the 3rd party api has usage restrictions, and only allows us to download a maximum of 10 wav files every 60 seconds. If we go over that, we get a 429 error for every request for the next 60 seconds.

So I implemented a little code to throttle our requests to this api. This is the block of code that now gets executed before every request:

```<code>        var maxPerPeriod = 10;
        var keyPrefix = RingCentralId;
        var intervalPeriod = 60000;
        var sleepInterval = 5000;
        var recentTransactions = MemoryCache.Default.Count(x => x.Key.StartsWith(keyPrefix));
        while (recentTransactions >= maxPerPeriod)
        {
            System.Threading.Thread.Sleep(sleepInterval);
            recentTransactions = MemoryCache.Default.Count(x => x.Key.StartsWith(keyPrefix));
        }
        var key = keyPrefix + "_" + DateTime.Now.ToUniversalTime().ToString("yyyyMMddHHmmss");
        var existing = MemoryCache.Default.Where(x => x.Key.StartsWith(key));
        if (existing != null && existing.Any())
        {
            var counter = 2;
            var last = existing.OrderBy(x => x.Key).Last();
            var pieces = last.Key.Split('_');
            if (pieces.Count() > 2)
            {
                var lastCount = 0;
                if (int.TryParse(pieces[2], out lastCount))
                {
                    counter = lastCount + 1;
                }
            }
            key = key + "_" + counter;
        }
        var policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMilliseconds(intervalPeriod)
        };
        MemoryCache.Default.Set(key, 1, policy);
</code>```

And this actually works beautifully (at least for now). As you can see, I am using the cache with unique keys that last for 60 seconds each. This mechanism searches the cache, and if there are 10 or more currently in the cache, then that means that we need to wait until they expire. And I do this by implementing a while loop. And that's the part that has me the most concerned. I don't have a lot of experience using the MemoryCache. Am I possibly introducing an infinite loop at some point in time? Is there anything else that I could be overlooking that might cause issues, especially if we scale up to, say 1,000,000 requests per day?

答:
If you're not going to have more than one instance of the WebJob doing the work, why not use a TimerTrigger and space your calls out evenly?

Here's the link to the documentation.

Body:
I implemented a throttling mechanism on our Azure web job. The "job" of our web job is to download separate .wav files from a 3rd party api constantly throughout the day. And it does this around 5,000 times a day (right now). However, the 3rd party api has usage restrictions, and only allows us to download a maximum of 10 wav files every 60 seconds. If we go over that, we get a 429 error for every request for the next 60 seconds.

So I implemented a little code to throttle our requests to this api. This is the block of code that now gets executed before every request:

        var maxPerPeriod = 10;
        var keyPrefix = RingCentralId;
        var intervalPeriod = 60000;
        var sleepInterval = 5000;
        var recentTransactions = MemoryCache.Default.Count(x => x.Key.StartsWith(keyPrefix));
        while (recentTransactions >= maxPerPeriod)
        {
            System.Threading.Thread.Sleep(sleepInterval);
            recentTransactions = MemoryCache.Default.Count(x => x.Key.StartsWith(keyPrefix));
        }
        var key = keyPrefix + "_" + DateTime.Now.ToUniversalTime().ToString("yyyyMMddHHmmss");
        var existing = MemoryCache.Default.Where(x => x.Key.StartsWith(key));
        if (existing != null && existing.Any())
        {
            var counter = 2;
            var last = existing.OrderBy(x => x.Key).Last();
            var pieces = last.Key.Split('_');
            if (pieces.Count() > 2)
            {
                var lastCount = 0;
                if (int.TryParse(pieces[2], out lastCount))
                {
                    counter = lastCount + 1;
                }
            }
            key = key + "_" + counter;
        }
        var policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMilliseconds(intervalPeriod)
        };
        MemoryCache.Default.Set(key, 1, policy);

And this actually works beautifully (at least for now). As you can see, I am using the cache with unique keys that last for 60 seconds each. This mechanism searches the cache, and if there are 10 or more currently in the cache, then that means that we need to wait until they expire. And I do this by implementing a while loop. And that's the part that has me the most concerned. I don't have a lot of experience using the MemoryCache. Am I possibly introducing an infinite loop at some point in time? Is there anything else that I could be overlooking that might cause issues, especially if we scale up to, say 1,000,000 requests per day?


问:
Pandas dataframe get index and header when in multiple columns
I have a dataframe which looks like this:

```<code>d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None
</code>```

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

答:
Late to the party, but I was curious to know if it was possible with more native Pandas features. I know it's already accepted but feel free to upvote if it adds another perspective :)

Got it down to two statements:

```<code># Use dropna to limit the DataFrame to remove names with more than 2 `None` values
In[1]: basic_dict = df.dropna(thresh=2, axis=0).to_dict(orient="index")
Out[1]:
{'G': {'Person1': 'x', 'Person2': 'x', 'Person3': None},
 'Mc': {'Person1': 'x', 'Person2': 'x', 'Person3': 'x'}}

# Strip the dictionary to remove any remaining `None` values
In[2]:  { k:[i for i in v if v[i] == "x"] for k,v in basic_dict.items()}
Out[2]: {'G': ['Person1', 'Person2'], 'Mc': ['Person3', 'Person1', 'Person2']}
</code>```

The returning list isn't sorted in the same order, but I was guessing that wasn't critical.

Body:
I have a dataframe which looks like this:

d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

Body:
Late to the party, but I was curious to know if it was possible with more native Pandas features. I know it's already accepted but feel free to upvote if it adds another perspective :)

Got it down to two statements:

# Use dropna to limit the DataFrame to remove names with more than 2 `None` values
In[1]: basic_dict = df.dropna(thresh=2, axis=0).to_dict(orient="index")
Out[1]:
{'G': {'Person1': 'x', 'Person2': 'x', 'Person3': None},
 'Mc': {'Person1': 'x', 'Person2': 'x', 'Person3': 'x'}}

# Strip the dictionary to remove any remaining `None` values
In[2]:  { k:[i for i in v if v[i] == "x"] for k,v in basic_dict.items()}
Out[2]: {'G': ['Person1', 'Person2'], 'Mc': ['Person3', 'Person1', 'Person2']}

The returning list isn't sorted in the same order, but I was guessing that wasn't critical.


问:
Download current html as .html document page using javascript/jQuery
I am needing to export a current html page as a .html file. However, part of it is modified using jQuery. When I use the following code, it exports, but only exports the html that was originally loaded, not the modifications from jQuery.

I am new to javascript & jQuery, so bear with me please!

$('#modify').keyup(function() {
         var val = $(this).val();
         $('#text_to_mofify').html(val);
        });
        var a = $("#test");
        a.download = "export.html";
        a.href = "data:text/html," + $('#main').html();
        a.innerHTML = "Export content";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
        <p id="text_to_modify">Hello World</p>
    </div>

    <input type="text" id="modify" />
    </code>```

The above snippet will export the html with a P tag containing Hello World, not what I have in the #modify input box.

答:
Answer from Rômulo Gabriel Rodrigues worked for me...

"JS being async it will prepare the data before you modify anything in the #main so to export correctly you will need to update the contents exported in the moment you execute the modification, so update your a.href in the keyup function."

Body:
I am needing to export a current html page as a .html file. However, part of it is modified using jQuery. When I use the following code, it exports, but only exports the html that was originally loaded, not the modifications from jQuery.

I am new to javascript & jQuery, so bear with me please!

$('#modify').keyup(function() {
         var val = $(this).val();
         $('#text_to_mofify').html(val);
        });
        var a = $("#test");
        a.download = "export.html";
        a.href = "data:text/html," + $('#main').html();
        a.innerHTML = "Export content";

Hello World

    <input type="text" id="modify" />

The above snippet will export the html with a P tag containing Hello World, not what I have in the #modify input box.


问:
Java get the hostname and other env var through jenkins
I'm using jenkins to build my projects and i can't get the hostname with java

According to this java doc I wrote the follow lines

```<code>            System.out.println(System.getenv("MACHINE"));
            System.out.println(System.getenv("HOSTNAME"));
</code>```

These are environment variables. BUt the output on build is:

```<code> null
 null
</code>```

What I'm doing wrong?

答:
I solve the problem using the Jenkins Enviromenment Script Plugin

Wiht this plugin I can just run a shell script code and save the values as var to use in the build.

```<code>host=$(hostname)
flavor=$(cat /etc/os-release |grep ^'NAME=' |cut -d'=' -f2)
</code>```

Body:
I'm using jenkins to build my projects and i can't get the hostname with java

According to this java doc I wrote the follow lines

            System.out.println(System.getenv("MACHINE"));
            System.out.println(System.getenv("HOSTNAME"));

These are environment variables. BUt the output on build is:

 null
 null

What I'm doing wrong?

Body:
I solve the problem using the Jenkins Enviromenment Script Plugin

Wiht this plugin I can just run a shell script code and save the values as var to use in the build.

host=$(hostname)
flavor=$(cat /etc/os-release |grep ^'NAME=' |cut -d'=' -f2)


问:
How can I animate using SPPLOT?
I have a shapefile with 5000+ polygons.

I have a netCDF file with timeseries data for several variables with one common key with the shapefile.

Static Map

For any particular time, I plot a static map by

Merging netCDF data for one timestep into the shapefile

Plot the shapefile using spplot

Animation

Now, I want to create an animation for a small time period.

For ggplot2, there are packages such as gganimate etc.

But, how can I do this using spplot?

P.S. GGPLOT2 is too slow for this purpose.

答:
Try the animation package?

Remember that spplot is a lattice based function, so if you're doing this in a function you'll need to print() inside the function.

Title: How can I animate using SPPLOT?


问:
How many numbers are there that include a given digit?
Let's have 3 digit number (100-999). How many such numbers with at least one digit "2" exist?

How to make algorithm for that? Or math function?

答:
Inclusion-exclusion principle

How many 3-digit numbers have 2 as the first digit (2xx)? That's right - 100. And as the second digit (x2x)? 100! And as the third (xx2) - the same number. Ok, now we have 300 numbers, but we forgot about numbers in the form 22x, we count them twice. Now we need to subtract the amount of 22x, 2x2 and x22 numbers. Now we have 270 of them, but we forgot about number 222, we added it three times, and subtracted three times, we need to add it again: 271. This explanation is an example of inclusion-exclusion principle.

But that's not the end, we need to subtract all 0xx numbers having 2 as a digit. Similar approach: 271 - 10 - 10 + 1 = 252.

Dynamic programming

Ok, if you don't like the previous method, there is another one. Let's count the function F(i, has2), where i - is the digit length of the number, has2 boolean value that is equal to true if digits contain 2, otherwise it equals to false. The recurrence relation is the following:

```<code> F(1, false) = 8, F(1, true) = 1
 F(i, true) = F(i-1, true) * 10 + F(i-1, false)
 F(i, false) = F(i-1, false) * 9
</code>```

The answer is F(3, true).

```<code> F(2, true) = 10 + 8 = 18
 F(2, false) = 8 * 9 = 72
 F(3, true) = 18 * 10 + 72 = 252
</code>```

Body:
Inclusion-exclusion principle

How many 3-digit numbers have 2 as the first digit (2xx)? That's right - 100. And as the second digit (x2x)? 100! And as the third (xx2) - the same number. Ok, now we have 300 numbers, but we forgot about numbers in the form 22x, we count them twice. Now we need to subtract the amount of 22x, 2x2 and x22 numbers. Now we have 270 of them, but we forgot about number 222, we added it three times, and subtracted three times, we need to add it again: 271. This explanation is an example of inclusion-exclusion principle.

But that's not the end, we need to subtract all 0xx numbers having 2 as a digit. Similar approach: 271 - 10 - 10 + 1 = 252.

Dynamic programming

Ok, if you don't like the previous method, there is another one. Let's count the function F(i, has2), where i - is the digit length of the number, has2 boolean value that is equal to true if digits contain 2, otherwise it equals to false. The recurrence relation is the following:

 F(1, false) = 8, F(1, true) = 1
 F(i, true) = F(i-1, true) * 10 + F(i-1, false)
 F(i, false) = F(i-1, false) * 9

The answer is F(3, true).

 F(2, true) = 10 + 8 = 18
 F(2, false) = 8 * 9 = 72
 F(3, true) = 18 * 10 + 72 = 252