问:
A few problems with my javascript sample. Please help
Alright, so I'm trying to get a page to load some js at the end of it's loading. I think I got it, but now it's saying I'm not getting a number with this line:

```<code>parseInt(document.getElementById('canvas').style.width);
</code>```

It should be "480px" but it's NaN.

It also said the line document.getElementById('ss') was null.

Here's the full thing:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Cypri Designs</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="/images/favicon1.ico" type="image/x-icon" />
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <script type="text/javascript">
        <!--
            //Variables to handle game parameters
            var gameloopId;
            var screenWidth;
            var screenHeight;
            var gameRunning = false;
            var ctx;

            var playerX = 0;
            var playerY = 0;

            //Create images
            var playerImg = new Image();

            //Wait for DOM to load and init game
            window.onload = function(){
                init();
            };

            function init(){
                initSettings();
                initImages();

                //add event handler to surrounding DIV to monitor mouse move and update mushroom's x position
                /*$("#container").mousemove(function(e){
                    mushroomX = e.pageX;
                });*/

                //add event handler for clicking on start/stop button and toggle the game play
                document.getElementById('ss').onclick = function (){

                    toggleGameplay();
                };
            }

            function initSettings()
            {
                //Get a handle to the 2d context of the canvas
                ctx = document.getElementById('canvas').getContext('2d');

                //Calulate screen height and width
                screenWidth = parseInt(document.getElementById('canvas').style.width);
                screenHeight = parseInt(document.getElementById('canvas').style.height);

                playerX = 100;
                playerY = 100;
            }

            function initImages(){
                playerImg.src = "images/player.png";
            }
            //Main game loop, it all happens here!
            function gameLoop(){

                //Clear the screen (i.e. a draw a clear rectangle the size of the screen)
                ctx.clearRect(0, 0, screenWidth, screenHeight);

                ctx.save();
                ctx.drawImage(playerImg, 0, 0);

                ctx.restore();
            }

            //Start/stop the game loop (and more importantly that annoying boinging!)
            function toggleGameplay()
            {
                gameRunning = !gameRunning;

                if(gameRunning)
                {
                    clearInterval(gameloopId);
                    gameloopId = setInterval(gameLoop, 10);
                }
                else
                {
                    clearInterval(gameloopId);
                }
            }
        //-->
        </script>

    </head>

    <body>
        <input id="ss" type="button" value="start/stop" />
        <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
            <canvas id="canvas" width="480px" height="320px" >
            Canvas not displaying.
            </canvas>
        </div>
    </body>
</html>
</code>```

答:
To get the width you should use the element property instead of the style property:</p>

```<code>document.getElementById('canvas').offsetWidth
</code>```

Body:
Alright, so I'm trying to get a page to load some js at the end of it's loading. I think I got it, but now it's saying I'm not getting a number with this line:

parseInt(document.getElementById('canvas').style.width);

It should be "480px" but it's NaN.

It also said the line document.getElementById('ss') was null.

Here's the full thing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>Cypri Designs</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="/images/favicon1.ico" type="image/x-icon" />
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

        <input id="ss" type="button" value="start/stop" />

            <canvas id="canvas" width="480px" height="320px" >
            Canvas not displaying.
            </canvas>

Body:
To get the width you should use the element property instead of the style property:

document.getElementById('canvas').offsetWidth


来源: stackexchange

问:
How do i get the caller classname from a static method of different class
 Lets say, I have

```<code>public class ClassA {
    public static void main(String[] args) {
        ClassB.methodB();
    }
}
</code>```

and I'm calling a static function of another class

```<code>public class ClassB{
    public static void methodB() {
        System.out.Println("<I want to print the classname of classA>");
    }
}
</code>```

How do I achieve this?

答:
You can't really (you could throw an exception and dig through the stack trace, but that is very slow and unnecessary).

Instead ask yourself the question why you think you need that?
Is it for logging purposes?

What does methodB need to know to perform its job.
If it needs to know something, it should just take a parameter and decide what to do based on that.

ContentLicense: CC BY-SA 3.0

Body:
 Lets say, I have

public class ClassA {
    public static void main(String[] args) {
        ClassB.methodB();
    }
}

and I'm calling a static function of another class

public class ClassB{
    public static void methodB() {
        System.out.Println("");
    }
}

How do I achieve this?


问:
How do we connect our docker app to a locally running postgres?
I'm looking for a way to connect a docker container app so it can access Postgres database via https://postgresapp.com/

Was wondering if there are certain ports to open and what the yml file would look like to enable docker-compose to work with locally running postgres.

Thanks!

答:
There is no difference between accessing a database from inside a container or outside a container.

Let's say the Postgres database is running on localhost. If you want to connect to it from a small Python script, you can do so as follows, as found in the Docs:

```<code>#!/usr/bin/python
import psycopg2
import sys

def main():
    #Define our connection string
    conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"

    # print the connection string we will use to connect
    print "Connecting to database\n ->%s" % (conn_string)

    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)

    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()
    print "Connected!\n"

if __name__ == "__main__":
    main()
</code>```

In order for this script to run you need to install Python and psycopg2 on your local machine, probably in a virtual environment. Alternatively, you could put it in a container. Instead of installing everything manually, you would define a Dockerfile with your installation instructions. It would probably look something like this:

```<code>FROM python:latest
ADD python-script.py /opt/www/python-script.py
RUN pip install psycopg2
CMD ["python", "/opt/www/python-script.py"]
</code>```

And if we build and run...

```<code>dave-mbp:Desktop dave$ ls -la
-rw-r--r--    1 dave  staff   135 Dec  8 19:05 Dockerfile
-rw-r--r--    1 dave  staff    22 Dec  8 19:04 python-script.py

dave-mbp:Desktop dave$ docker build -t python-script .
Sending build context to Docker daemon  17.92kB
Step 1/4 : FROM python:latest
latest: Pulling from library/python
85b1f47fba49: Already exists
ba6bd283713a: Pull complete
817c8cd48a09: Pull complete
47cc0ed96dc3: Pull complete
4a36819a59dc: Pull complete
db9a0221399f: Pull complete
7a511a7689b6: Pull complete
1223757f6914: Pull complete
Digest: sha256:db9d8546f3ff74e96702abe0a78a0e0454df6ea898de8f124feba81deea416d7
Status: Downloaded newer image for python:latest
 ---> 79e1dc9af1c1
Step 2/4 : ADD python-script.py /opt/www/python-script.py
 ---> 21f31c8803f7
Step 3/4 : RUN pip install psycopg2
 ---> Running in f280c82d74e7
Collecting psycopg2
  Downloading psycopg2-2.7.3.2-cp36-cp36m-manylinux1_x86_64.whl (2.7MB)
Installing collected packages: psycopg2
Successfully installed psycopg2-2.7.3.2
 ---> bd38f911bb6a
Removing intermediate container f280c82d74e7
Step 4/4 : CMD python /opt/www/python-script.py
 ---> Running in 159b70861893
 ---> 4aa783be5c90
Removing intermediate container 159b70861893
Successfully built 4aa783be5c90
Successfully tagged python-script:latest

dave-mbp:Desktop dave$ docker run python-script
>> Connected!
</code>```

Containers are largely a packaging solution. We'll be able to connect to an external database or API endpoint as if we were running everything from outside of a container.

There is one thing to keep in mind though...localhost may resolve to the virtual machine if you're using docker toolbox/virtualbox. In which case, you wouldn't connect to localhost unless you were running a bridged network connection in the VM. Otherwise, just specify the host IP instead of localhost.

Body:
There is no difference between accessing a database from inside a container or outside a container.

Let's say the Postgres database is running on localhost. If you want to connect to it from a small Python script, you can do so as follows, as found in the Docs:

#!/usr/bin/python
import psycopg2
import sys

def main():
    #Define our connection string
    conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"

    # print the connection string we will use to connect
    print "Connecting to database\n ->%s" % (conn_string)

    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)

    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()
    print "Connected!\n"

if __name__ == "__main__":
    main()

In order for this script to run you need to install Python and psycopg2 on your local machine, probably in a virtual environment. Alternatively, you could put it in a container. Instead of installing everything manually, you would define a Dockerfile with your installation instructions. It would probably look something like this:

FROM python:latest
ADD python-script.py /opt/www/python-script.py
RUN pip install psycopg2
CMD ["python", "/opt/www/python-script.py"]

And if we build and run...

dave-mbp:Desktop dave$ ls -la
-rw-r--r--    1 dave  staff   135 Dec  8 19:05 Dockerfile
-rw-r--r--    1 dave  staff    22 Dec  8 19:04 python-script.py

dave-mbp:Desktop dave$ docker build -t python-script .
Sending build context to Docker daemon  17.92kB
Step 1/4 : FROM python:latest
latest: Pulling from library/python
85b1f47fba49: Already exists
ba6bd283713a: Pull complete
817c8cd48a09: Pull complete
47cc0ed96dc3: Pull complete
4a36819a59dc: Pull complete
db9a0221399f: Pull complete
7a511a7689b6: Pull complete
1223757f6914: Pull complete
Digest: sha256:db9d8546f3ff74e96702abe0a78a0e0454df6ea898de8f124feba81deea416d7
Status: Downloaded newer image for python:latest
 ---> 79e1dc9af1c1
Step 2/4 : ADD python-script.py /opt/www/python-script.py
 ---> 21f31c8803f7
Step 3/4 : RUN pip install psycopg2
 ---> Running in f280c82d74e7
Collecting psycopg2
  Downloading psycopg2-2.7.3.2-cp36-cp36m-manylinux1_x86_64.whl (2.7MB)
Installing collected packages: psycopg2
Successfully installed psycopg2-2.7.3.2
 ---> bd38f911bb6a
Removing intermediate container f280c82d74e7
Step 4/4 : CMD python /opt/www/python-script.py
 ---> Running in 159b70861893
 ---> 4aa783be5c90
Removing intermediate container 159b70861893
Successfully built 4aa783be5c90
Successfully tagged python-script:latest

dave-mbp:Desktop dave$ docker run python-script
>> Connected!

Containers are largely a packaging solution. We'll be able to connect to an external database or API endpoint as if we were running everything from outside of a container.

There is one thing to keep in mind though...localhost may resolve to the virtual machine if you're using docker toolbox/virtualbox. In which case, you wouldn't connect to localhost unless you were running a bridged network connection in the VM. Otherwise, just specify the host IP instead of localhost.


问:
Decimal to binary in C language
I wrote simple code in C language (without libraries), but the result is good only when you read it from right to left, how to reverse it? I want the most simplified code as it is possible. My code below:</p>

```<code>#include <stdio.h>

int main() {
    int number;

    printf("Changes from decimal to binary\n");
    printf("Enter the number: ");

    scanf("%d",&number);

    do{
        if(number % 2 == 1){
            printf("1");
        }else{
            printf("0");
        }
        number = number / 2;
    }
     while(number>0);

  return 0;
}
</code>```

答:
You could use recursion and print the digits as you fall off the stack.  I changed number from int to unsigned int.

```<code>void print_dec_to_bin_hlp(unsigned int number)
{
    if(number > 0)
    {
        print_dec_to_bin_hlp(number/2);
        printf("%d", (number%2));
    }
}

void print_dec_to_bin(unsigned int number)
{
    if (number == 0) printf("%d", number);
    else print_dec_to_bin_hlp(number);
}
</code>```

Title: Decimal to binary in C language

Body:
I wrote simple code in C language (without libraries), but the result is good only when you read it from right to left, how to reverse it? I want the most simplified code as it is possible. My code below:

#include <stdio.h>

int main() {
    int number;

    printf("Changes from decimal to binary\n");
    printf("Enter the number: ");

    scanf("%d",&number);

    do{
        if(number % 2 == 1){
            printf("1");
        }else{
            printf("0");
        }
        number = number / 2;
    }
     while(number>0);

  return 0;
}

Body:
You could use recursion and print the digits as you fall off the stack.  I changed number from int to unsigned int.

void print_dec_to_bin_hlp(unsigned int number)
{
    if(number > 0)
    {
        print_dec_to_bin_hlp(number/2);
        printf("%d", (number%2));
    }
}

void print_dec_to_bin(unsigned int number)
{
    if (number == 0) printf("%d", number);
    else print_dec_to_bin_hlp(number);
}


问:
Check time series incongruencies
Let's say that we have the following matrix:

```<code>x<- as.data.frame(cbind(c("A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D"),
                        c(1,2,3,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                        c(14,28,42,14,46,64,71,85,14,28,51,84,66,22,38,32,40,42)))
colnames(x)<- c("ID","Visit", "Age")
</code>```

The first column represents subject ID, the second a list of observations and the third the age at each of this consecutive observations.

Which would be the easiest way of finding visits where the age is wrong according to the previous visit age. (i.e. in row 13, subject C is 66 years old, when in the previous visit he was already 84 or in row 16, subject D is 32 years old, when in the previous visit he was already 38).

Which would be the way of highlighting the potential errors and removing rows 13 and 16?

I have tried to aggregate by IDs and look for the difference between ages across visits, but it seems hard for me since the error could occur in any visit.

答:
You could do it by filtering out the rows where diff(Age) is negative for each ID.
Using the dplyr package:

```<code>library(dplyr)

x %>% group_by(ID) %>%  filter(c(0,diff(Age))>=0)
# A tibble: 16 x 3
# Groups:   ID [4]
       ID  Visit    Age
   <fctr> <fctr> <fctr>
 1      A      1     14
 2      A      2     28
 3      A      3     42
 4      B      1     14
 5      B      2     46
 6      B      3     64
 7      B      4     71
 8      B      5     85
 9      C      1     14
10      C      2     28
11      C      3     51
12      C      4     84
13      D      1     22
14      D      2     38
15      D      4     40
16      D      5     42
</code>```

Title: Check time series incongruencies

Body:
Let's say that we have the following matrix:

x<- as.data.frame(cbind(c("A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D"),
                        c(1,2,3,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                        c(14,28,42,14,46,64,71,85,14,28,51,84,66,22,38,32,40,42)))
colnames(x)<- c("ID","Visit", "Age")

The first column represents subject ID, the second a list of observations and the third the age at each of this consecutive observations.

Which would be the easiest way of finding visits where the age is wrong according to the previous visit age. (i.e. in row 13, subject C is 66 years old, when in the previous visit he was already 84 or in row 16, subject D is 32 years old, when in the previous visit he was already 38).

Which would be the way of highlighting the potential errors and removing rows 13 and 16?

I have tried to aggregate by IDs and look for the difference between ages across visits, but it seems hard for me since the error could occur in any visit.

Body:
You could do it by filtering out the rows where diff(Age) is negative for each ID.
Using the dplyr package:

library(dplyr)

x %>% group_by(ID) %>%  filter(c(0,diff(Age))>=0)
# A tibble: 16 x 3
# Groups:   ID [4]
       ID  Visit    Age
   <fctr> <fctr> <fctr>
 1      A      1     14
 2      A      2     28
 3      A      3     42
 4      B      1     14
 5      B      2     46
 6      B      3     64
 7      B      4     71
 8      B      5     85
 9      C      1     14
10      C      2     28
11      C      3     51
12      C      4     84
13      D      1     22
14      D      2     38
15      D      4     40
16      D      5     42


答:
A recursive solution using bitwise operations, for unsigned integers:

```<code>void print_binary(unsigned int num) {
    if(num >> 1) print_binary(num >> 1);
    putchar(num & 1 ? '1' : '0');
}
</code>```

The bitwise operators >>, &, etc. access the bits in the value. The bits form a binary representation of the number. >> shifts the bits to the right, where the bits are ordered from MSB (most significant bit) to LSB, like the normal way numbers are written.

num & 1 returns non-zero only if the LSB (rightmost) bit is set. (AND mask with ..0001). So (num >> 1) & 1 does the same on the second-rightmost bit. So this recursive function prints the bits in MSB to LSB order.

The if(num >> 1) check makes sure prefix zeroes are not printed: If after the rightshift, num is all-zeroes, it is not printed any further. The check is made outside the function call, so that print_binary(0) (initial call) will still always print a single 0.

For signed integers:

```<code>void print_signed_binary(int num) {
    if(num < 0) {
        putchar('-');
        print_binary(-num);
    } else {
        print_binary(num);
    }
}
</code>```

Title: Decimal to binary in C language

Body:
A recursive solution using bitwise operations, for unsigned integers:

void print_binary(unsigned int num) {
    if(num >> 1) print_binary(num >> 1);
    putchar(num & 1 ? '1' : '0');
}

The bitwise operators >>, &, etc. access the bits in the value. The bits form a binary representation of the number. >> shifts the bits to the right, where the bits are ordered from MSB (most significant bit) to LSB, like the normal way numbers are written.

num & 1 returns non-zero only if the LSB (rightmost) bit is set. (AND mask with ..0001). So (num >> 1) & 1 does the same on the second-rightmost bit. So this recursive function prints the bits in MSB to LSB order.

The if(num >> 1) check makes sure prefix zeroes are not printed: If after the rightshift, num is all-zeroes, it is not printed any further. The check is made outside the function call, so that print_binary(0) (initial call) will still always print a single 0.

For signed integers:

void print_signed_binary(int num) {
    if(num < 0) {
        putchar('-');
        print_binary(-num);
    } else {
        print_binary(num);
    }
}


问:
Updating a JSON object using Javascript
How can i update the following JSON object dynamically using javascript or Jquery?

```<code>var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}]
</code>```

I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.

How can I achieve this?

答:
I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.

```<code>function setVal(update) {
    /* Included to show an option if you care to use jQuery
    var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
        targetField: null, targetData: null, checkAllRows: false };
    //update = $.extend({}, defaults, update); */

    for (var i = 0; i < update.jsonRS.length; i++) {
        if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
            update.jsonRS[i][update.targetField] = update.targetData;
            if (!update.checkAllRows) { return; }
        }
    }
}

var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
           {'Id':'2','Username':'Steve','FatherName':'Johnson'},
           {'Id':'3','Username':'Albert','FatherName':'Einstein'}]
</code>```

With your data you would use like:

```<code>var update = {
    jsonRS: jsonObj,
    lookupField: "Id",
    lookupKey: 2,
    targetField: "Username",
    targetData: "Thomas",
    checkAllRows: false
    };

setVal(update);
</code>```

And Bob's your Uncle. :) [Works great]

ContentLicense: CC BY-SA 4.0

Title: Updating a JSON object using Javascript

Body:
How can i update the following JSON object dynamically using javascript or Jquery?

var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.

How can I achieve this?

Body:
I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.

function setVal(update) {
    /* Included to show an option if you care to use jQuery
    var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
        targetField: null, targetData: null, checkAllRows: false };
    //update = $.extend({}, defaults, update); */

    for (var i = 0; i < update.jsonRS.length; i++) {
        if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
            update.jsonRS[i][update.targetField] = update.targetData;
            if (!update.checkAllRows) { return; }
        }
    }
}

var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
           {'Id':'2','Username':'Steve','FatherName':'Johnson'},
           {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

With your data you would use like:

var update = {
    jsonRS: jsonObj,
    lookupField: "Id",
    lookupKey: 2,
    targetField: "Username",
    targetData: "Thomas",
    checkAllRows: false
    };

setVal(update);

And Bob's your Uncle. :) [Works great]


问:
Calling class method, when changing tab
I have the following tab navigation structure:

tab1: Sound Player Screen (where you can play sounds),

tab2: Info Screen,

tab3: Settings Screen,

I want that the sound player stops playing (the class has stop() method) , when I switch from Sound Player tab to info or settings tab. I've tried to use tabBarOnPress, but I don't really understand how to call the stop method from there. I've tried stuff like this :

```<code>static navigationOptions = {
    tabBarOnPress: ({previousScene,scene,jumpToIndex}) => {
        previousScene.stop();
        jumpToIndex(scene.index);
    }
}
</code>```

答:
This is surprisingly difficult to achieve using react-navigation, because it turns out to be quite tricky to know which screen currently has focus with the current state of the library (see long issue here).

One solution is to use react-navigation-is-focused-hoc, which wraps your screen component providing a boolean in props which you can check. Given that, you can put something like the following in the componentWillUpdate of your tab1:

```<code>componentWillUpdate (nextProps) {
  if (!nextProps.isFocused) {
    // component is going out of focus, stop the music
    this.stop()
  }
}
</code>```

Note: I recommend using the version of the library I linked, it's Patrick Wozniak's fork which is slightly more up to date.

Title: Calling class method, when changing tab

Body:
I have the following tab navigation structure:

tab1: Sound Player Screen (where you can play sounds),

tab2: Info Screen,

tab3: Settings Screen,

I want that the sound player stops playing (the class has stop() method) , when I switch from Sound Player tab to info or settings tab. I've tried to use tabBarOnPress, but I don't really understand how to call the stop method from there. I've tried stuff like this :

static navigationOptions = {
    tabBarOnPress: ({previousScene,scene,jumpToIndex}) => {
        previousScene.stop();
        jumpToIndex(scene.index);
    }
}

Body:
This is surprisingly difficult to achieve using react-navigation, because it turns out to be quite tricky to know which screen currently has focus with the current state of the library (see long issue here).

One solution is to use react-navigation-is-focused-hoc, which wraps your screen component providing a boolean in props which you can check. Given that, you can put something like the following in the componentWillUpdate of your tab1:

componentWillUpdate (nextProps) {
  if (!nextProps.isFocused) {
    // component is going out of focus, stop the music
    this.stop()
  }
}

Note: I recommend using the version of the library I linked, it's Patrick Wozniak's fork which is slightly more up to date.


问:
StrictMode java.lang.Throwable: Untagged socket detected
With StrictMode enabled I just started getting this exception:

java.lang.Throwable: Untagged socket detected; use TrafficStats.setThreadSocketTag() to track all network usage

答:
My solution has been to call on initialisation the following:</p>

```<code>private static final int THREAD_ID = 10000;
TrafficStats.setThreadStatsTag(THREAD_ID);
</code>```

Body:
My solution has been to call on initialisation the following:

private static final int THREAD_ID = 10000;
TrafficStats.setThreadStatsTag(THREAD_ID);


问:
C++: multidimensional array initialization in constructor
I want to use a two dimensional array of constant size as a class member in C++. I have problems initializing it in the constructor though.

Here are my non-working tries:

1.)

```<code>class A {
 public:
  int a[2][2];
  A();
};

A::A() {
a = {{1,2},{2,4}};
}
</code>```

yields: error: assigning to an array from an initializer list

2.)

```<code>class A {
 public:
  int a[2][2];
  A();
};

A::A() {
int b[2][2] = {{1,2},{2,4}};
a = b;
}
</code>```

yields: invalid array assignment

3.)

```<code>class A {
 public:
  int **a;
  A();
};

A::A() {
int b[2][2] = {{1,2},{2,4}};
a = b;
}
</code>```

yields: cannot convert ‘int [2][2]’ to ‘int**’ in assignment

I come from C background. I know that I could use std::vector and I am aware of the disadvantages this approach has but since this is an exercise for me I would like to know how to get it working with plain arrays. I should add that I want to work on this array later on. I want to change the stored values but not the size. Maybe that matters as well (I figured a const at the right place could help somehow?).

答:
various multidimensional array in constructor by example:</p>

```<code>// int array1[1];
A() : array1{0} {}

// int array2[2][2];
A() : array2{{0}} {}

// int array3[3][3][3];
A() : array3{{{0}}} {}
</code>```

Body:
I want to use a two dimensional array of constant size as a class member in C++. I have problems initializing it in the constructor though.

Here are my non-working tries:

1.)

class A {
 public:
  int a[2][2];
  A();
};

A::A() {
a = {{1,2},{2,4}};
}

yields: error: assigning to an array from an initializer list

2.)

class A {
 public:
  int a[2][2];
  A();
};

A::A() {
int b[2][2] = {{1,2},{2,4}};
a = b;
}

yields: invalid array assignment

3.)

class A {
 public:
  int **a;
  A();
};

A::A() {
int b[2][2] = {{1,2},{2,4}};
a = b;
}

yields: cannot convert ‘int [2][2]’ to ‘int**’ in assignment

I come from C background. I know that I could use std::vector and I am aware of the disadvantages this approach has but since this is an exercise for me I would like to know how to get it working with plain arrays. I should add that I want to work on this array later on. I want to change the stored values but not the size. Maybe that matters as well (I figured a const at the right place could help somehow?).

Body:
various multidimensional array in constructor by example:

// int array1[1];
A() : array1{0} {}

// int array2[2][2];
A() : array2{{0}} {}

// int array3[3][3][3];
A() : array3{{{0}}} {}


问:
64/32-bit division on a processor with 32/16-bit division
My processor, a small 16-bit microcontroller with no FPU and integer math only has 16/16 division and 32/16 division which both take 18 cycles. At the moment I'm using a very slow software routine (~7,500 cycles) to do 64/32 division. Is there any way to use these division engines to calculate a 64/32 division? Similar to how I'm already using the 16x16 multiplier and adder to calculate 32x32 multiplies? I'm using C but can work with any general explanation on how it can be done... I'm hoping to target <200 cycles (if it's at all possible.)</p>

答:
See "Hacker's Delight", multiword division (pages 140-145).

The basic concept (going back to Knuth) is to think of your problem in base-65536 terms.  Then you have a 4 digit by 2 digit division problem, with 2/1 digit division as a primitive.

The C code is here:  https://github.com/hcs0/Hackers-Delight/blob/master/divmnu.c.txt

ContentLicense: CC BY-SA 2.5


问:
W3CSS: centering input field
Background: Ive done a few small websites using W3CSS, & get my knowledge from this website: https://www.w3schools.com/w3css/w3css_input.asp

Right now, I am starting on a brand new website & having a bit of difficulty centering an input field. (the form doesnt work as yet, i'm just trying to get it to look right).

http://clubs.kwister.com/login

Basically, you can see TWO forms asking for an email address. The first one, is CENTERED, with the input field at 50% width.  However the actual input field where a person enters their email address is flushed to the left.

The second form, I have taken out the width:50%  but now i see an input field taking the whole width of the screen.

Is there something i am missing, to make it look somewhat presentable & have the actual input field centered, but only 40-50% of the width ?

I see from the W3 website that theres no 'width' examples and all the input fields take up 100% of the available width.

i do want white-space on both sides (I may or may not add anything later on to fill the whitespace)

PS I could do the w3-third class (responsive section), and divide the screen into thirds, however i want the form to take up more than a third of the width of the screen.

答:
Well, There's an easy way to center an input field. There's a way you could center it by setting its position: relative; and left: 25%;, or you could set text-align: center; on the parent form. Depends on what you're after. Personally, I'd go with the relative position and left.

Hope that helps

ps. I wouldn't try to use display: inline-block; use display: block; float: left;

Title: W3CSS: centering input field


问:
Stopwatch class in c++
I have to write a stopwatch class in c++. The way I am trying to do this is by defining a variable to save laps (named 'time') and a bool that I use to see if the watch is started or stopped. When entering a char the timer should start and set time1. When another char is entered the bool switches to false and sets time2 and then prints time2-time1. This should be repeatable until 'n' is entered

I also am not quite sure I understand what unit of time time_t is in. In my code i get a return value of ±40 units every time i try to measure the interval of a lap, which I am guessing is the runtime of the program and not actually the time of the interval.

```<code>#ifndef stoppuhr_hpp
#define stoppuhr_hpp

#include <iostream>
#include <time.h>

class Stoppuhr{
private:
    bool running;
    clock_t time;

public:
    void pushButtonStartStop () {
        char t=0;
        running=false;
        time=0;
        std::cout << "to start/stop watch please press a key, to end
clock type 'n' " << std::endl;
        clock_t time1=0;
        clock_t time2=0;
        std::cout << time;

        while (t!='n') {
            std::cin >> t;
            running= !running;
            if (running) {
                time1=clock();
            }
            else {
                time2=clock();
                time+=time2-time1;
                std::cout << time << std::endl;
            }
        }

    }

};

#endif /* stoppuhr_hpp */
</code>```

答:
I also am not quite sure I understand what unit of time time_t is in.

The unit of time represented by time_t is implementation specified. Usually, it represents seconds, as specified by POSIX.

However, you don't use time_t anywhere in your program.

I am guessing is the runtime of the program

I recommend not to guess, but to read documentation instead. clock() returns the processor time used by the program since some point in time. So deducting two timepoints returned by clock() will give you the processor time used between those timepoints.  The unit of clock_t is 1 /  CLOCKS_PER_SEC seconds.

i get a return value of ±40 units every time

Granularity of clock is implementation specified. It might be 40 units on your system. The program consumes hardly any processor time while it waits for input.

I have to write a stopwatch class

Stopwatches typically measure real world time i.e. wall clock time. Measuring processor time would be futile for this task.

I recommend using std::chrono::steady_clock::now instead.

If you insist on using time.h, then you can use time(nullptr) to get the wall clock time but I don't recommend it.

Title: Stopwatch class in c++

Body:
I have to write a stopwatch class in c++. The way I am trying to do this is by defining a variable to save laps (named 'time') and a bool that I use to see if the watch is started or stopped. When entering a char the timer should start and set time1. When another char is entered the bool switches to false and sets time2 and then prints time2-time1. This should be repeatable until 'n' is entered

I also am not quite sure I understand what unit of time time_t is in. In my code i get a return value of ±40 units every time i try to measure the interval of a lap, which I am guessing is the runtime of the program and not actually the time of the interval.

#ifndef stoppuhr_hpp
#define stoppuhr_hpp

#include <iostream>
#include <time.h>

class Stoppuhr{
private:
    bool running;
    clock_t time;

public:
    void pushButtonStartStop () {
        char t=0;
        running=false;
        time=0;
        std::cout << "to start/stop watch please press a key, to end
clock type 'n' " << std::endl;
        clock_t time1=0;
        clock_t time2=0;
        std::cout << time;

        while (t!='n') {
            std::cin >> t;
            running= !running;
            if (running) {
                time1=clock();
            }
            else {
                time2=clock();
                time+=time2-time1;
                std::cout << time << std::endl;
            }
        }

    }

};

#endif /* stoppuhr_hpp */


问:
Modifying the weights and biases of a restored CNN model in TensorFlow
I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following:
how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF?

Here is my code:

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
  LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
  LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

  # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) #

  # Testing the acuracy of the model:
  X = g.get_tensor_by_name('ImageIn:0')
  Y = g.get_tensor_by_name('LabelIn:0')
  KP = g.get_tensor_by_name('KeepProb:0')
  Accuracy = g.get_tensor_by_name('NetAccuracy:0')
  feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
  print( 'Model Accuracy = ' )
  print( sess.run( Accuracy, feed_dict ) )
</code>```

答:
Yes it is possible. Your weights and biases are already loaded after you loaded the meta graph. You need to find their names (see the list_variables  function) and then assign them to a Python variable.

For that, use tf.get_variable with the variable name. You might have to set reuse=True on your variable scope. See this answer for more detail on reusing variables.

Once you have them as a weights variable, you can call sess.run(weights.assign(...)).

Body:
I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following:
how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF?

Here is my code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
  LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
  LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

  # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) #

  # Testing the acuracy of the model:
  X = g.get_tensor_by_name('ImageIn:0')
  Y = g.get_tensor_by_name('LabelIn:0')
  KP = g.get_tensor_by_name('KeepProb:0')
  Accuracy = g.get_tensor_by_name('NetAccuracy:0')
  feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
  print( 'Model Accuracy = ' )
  print( sess.run( Accuracy, feed_dict ) )


问:
2D array Classification using Python
I am trying to build a voice recognition application. Until now, I already extract the mfcc feature from 10 sample voice. Each sample yield different shape like shown below:

(698, 12)

(414, 12)

(610, 12)

(586, 12)

(698, 12)

(282, 12)

(250, 12)

(370, 12)

(694, 12)

(490, 12)

I planned to use kNN (or other classification algorithms) to do this but the shapes are not same for every sample and it 2D array not 1D array so I can feed it directly to the model.

How can I convert this array such a way so I can feed it into machine learning algorithm or how to build a model using 2D array?

Please advise

答: I complete this using GMM. So each observation will have its own model.</p>

Title: 2D array Classification using Python


问:
3 table addition and subtraction
I have three tables:

I want to group all the results according to Table 3 collection operation and year.

Here is an example of what I want:

tablo1

2017 -> 2100(alacak)

tablo2

2017 -> 600(borc)

2100(alacak) - 600(borc) = 1600(result)

tablo3

2017 -> 600(gider)

1600(result) - 600(gider) = 1000(final)

I tried a code like this:

```<code>SELECT tablo1.year, (SUM(tablo1.alacak)-SUM(tablo2.borc)-SUM(tablo3.gider)) AS result
FROM
    tablo1 JOIN tablo2 ON tablo1.alacak = tablo2.borc
    LEFT JOIN giderler ON tablo1.alacak = tablo3.gider
    GROUP BY tablo1.year DESC;
</code>```

But it doesn't work. Any help will be appreciated.

答:
Is this what you want???</p>

```<code>select year,
 (select sum(alacak) quantity
      from table1
    where table1.year = t3.year)
    -
 (select sum(borc) quantity
    from table2
   where table2.year = t3.year)
   -
 (select sum(gider) quantity
    from table3
   where table3.year = t3.year) as result
   from table3 t3
   group by year;
</code>```

Title: 3 table addition and subtraction

Body:
I have three tables:

I want to group all the results according to Table 3 collection operation and year.

Here is an example of what I want:

tablo1

2017 -> 2100(alacak)

tablo2

2017 -> 600(borc)

2100(alacak) - 600(borc) = 1600(result)

tablo3

2017 -> 600(gider)

1600(result) - 600(gider) = 1000(final)

I tried a code like this:

SELECT tablo1.year, (SUM(tablo1.alacak)-SUM(tablo2.borc)-SUM(tablo3.gider)) AS result
FROM
    tablo1 JOIN tablo2 ON tablo1.alacak = tablo2.borc
    LEFT JOIN giderler ON tablo1.alacak = tablo3.gider
    GROUP BY tablo1.year DESC;

But it doesn't work. Any help will be appreciated.

Body:
Is this what you want???

select year,
 (select sum(alacak) quantity
      from table1
    where table1.year = t3.year)
    -
 (select sum(borc) quantity
    from table2
   where table2.year = t3.year)
   -
 (select sum(gider) quantity
    from table3
   where table3.year = t3.year) as result
   from table3 t3
   group by year;


问:
after_filter in devise
I would like to execute an action after the user has logged in. I need something like:

```<code>after_filter :log_login
</code>```

The method should be called as soon as the user has logged in.

答: You could try inheriting the sessions controller, and add more of your custom login proc.   http://github.com/zmbmartin/devise-roles-user-management.  I use this as an example, it inherit registration controller, not example the same, but the principle is the same.</p>

Title: after_filter in devise

Body:
I would like to execute an action after the user has logged in. I need something like:

after_filter :log_login

The method should be called as soon as the user has logged in.


问:
Filter/subset of data frames
I have this dataset that I call:crime and I want to sort/filter only let's say Rape from the crime category column and show all occurrences. But the closest I get is that it shows True but not showing the actual word "Rape". What am I doing wrong? I have tried to use subset and/or filter but to no avail. It works in Pandas (Jypyter notebook) with slightly different code. This is my line in RStudio. Thanks for any ideas in advance.

Shows True/False:
View(crime["UCR.CRIME.CATEGORY"]=="RAPE")

答:
Make sure it's a factor or a character before you use this command.

rset = subset(data, crime == 'Rape')

Title: Filter/subset of data frames


答:
Postgres default port is 5432.

Docker offers different networking modes to use. I can tell you how to achieve your goal using bridge mode (used by default).

There is always a bridge network that allows you access host machine. It is created by default and called docker0.

Run the following command in terminal ip addr show docker0 to see your host ip available to all the containers you run.

Output on my machine:

```<code>developer@dlbra:~$ ip addr show docker0
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:b4:95:60:89 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 scope global docker0
       valid_lft forever preferred_lft forever
</code>```

Therefore you don't need any additional configuration in docker-compose.yml
You just have to configure your db host to the ip address you saw. In my case it would be 172.17.0.1.

If your locally installed Postgres listens to a different port also specify that port in your application configuration.

Title: How do we connect our docker app to a locally running postgres?

Body:
I'm looking for a way to connect a docker container app so it can access Postgres database via https://postgresapp.com/

Was wondering if there are certain ports to open and what the yml file would look like to enable docker-compose to work with locally running postgres.

Thanks!

Body:
Postgres default port is 5432.

Docker offers different networking modes to use. I can tell you how to achieve your goal using bridge mode (used by default).

There is always a bridge network that allows you access host machine. It is created by default and called docker0.

Run the following command in terminal ip addr show docker0 to see your host ip available to all the containers you run.

Output on my machine:

developer@dlbra:~$ ip addr show docker0
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:b4:95:60:89 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 scope global docker0
       valid_lft forever preferred_lft forever

Therefore you don't need any additional configuration in docker-compose.yml
You just have to configure your db host to the ip address you saw. In my case it would be 172.17.0.1.

If your locally installed Postgres listens to a different port also specify that port in your application configuration.


问:
What is the function of cyclic sleep mode in Router API MODE in XBee XCTU software?
I am using XBee pro series 2.

I have read in many forums that ZigBee routers do not support sleep mode. But I have seen in XCTU software that we can still set the sleep mode (e.g. cyclic sleep mode etc.).

Does XBee pro series 2 support sleep mode ROUTER devices?

答: ZigBee routers are mains powered devices that do not sleep in order to route data in the network.  The XBee Pro modules have a sleep option (with the SM command), but if sleep is enabled, the module joins the network as an end device.  If it was functioning as a router when sleep is enabled, it will leave the network before trying to join as an end device.</p>


问:
Calling a jQuery function with JavaScript
I am using jQuery and JavaScript, I need to call the jQuery function inside my JavaScript code.

My jQuery code:

```<code>function display(id){
    $.ajax({
        type:'POST',
        url: 'ajax.php',
        data:'id='+id  ,
        success: function(data){
            $("#response").html(data);
        }//success
    }); //Ajax

    //Here I need to return the ajax.php salary
    //return ?
}
</code>```

My ajax.php file has:

```<code><?php
   session_start();
    ....

   echo "$salary";
?>
</code>```

My JavaScript function has:

```<code>my.js

function showName(){
    var id = 12;

    var a = display(id); //Here I need to call the jQuery function display().
}
</code>```

How do I call the jQuery function inside JavaScript code and how do I return the PHP values to jQuery?

答:
You call showName from the anonymous function you assigned to the key 'success' in the Ajax request. The anonymous function you assigned to success is your call back function.

Review the documentation on the Ajax class.

OwnerDisplayName: venkatachalam

Body:
I am using jQuery and JavaScript, I need to call the jQuery function inside my JavaScript code.

My jQuery code:

function display(id){
    $.ajax({
        type:'POST',
        url: 'ajax.php',
        data:'id='+id  ,
        success: function(data){
            $("#response").html(data);
        }//success
    }); //Ajax

    //Here I need to return the ajax.php salary
    //return ?
}

My ajax.php file has:

<?php
   session_start();
    ....

   echo "$salary";
?>

My JavaScript function has:

my.js

function showName(){
    var id = 12;

    var a = display(id); //Here I need to call the jQuery function display().
}

How do I call the jQuery function inside JavaScript code and how do I return the PHP values to jQuery?

LastEditorDisplayName: Dreas Grech


问:
Using scipy.optimize.brute
Based on this post I am trying to use brute to do a grid serach on a ARIMA model but I cannot make it run. I am doign this proof of principle, but what am I doing wrong with the arguments?

```<code>y = pd.DataFrame([0,1,4,9,16]) + 3
def objfunc(coeffs, endog):
    exp = coeffs[0]
    const = coeffs[1]
    print(exp, const, endog)
    out = 0
    for i in range(4):
        out += i**exp + const
    return out

from scipy.optimize import brute
grid = (slice(0, 2, 1), slice(3, 4, 1))
brute(objfunc, ranges=grid, args=y)

(0, 3, 0)
(0, 3, 0)
(1, 3, 0)
...
TypeError: objfunc() takes exactly 2 arguments (1 given)
</code>```

Once I solve this my aim is actually to optimize this function on order and seasonal_order being tuples like this ( _ , _  , _ ) and this ( _ , _ , _ ,12), respectively.

```<code>def objfunc(coeffs, endog):
    order = coeffs[0]
    seasonal = coeffs[1]
    fit = sm.tsa.statespace.SARIMAX(endog, trend='n', order=order, seasonal_order=seasonal).fit()
    return fit.aic()
</code>```

EDIT: this code works (thanks to @sasha), variable names are more clear, and makes more sense (I minimize the function on the error).

```<code>import pandas as pd
y = np.array([0,1,4,9,16]) + 3 #polynomial x^2+3 with x=0:4
def objfunc(coeffs, *args):
    arr = args[0]                       # access first element of tuple: y
    exp = coeffs[0]                       #     assuming y should become endog
    const = coeffs[1]
    pol = [i**exp + const for i in range(len(y))]
    print coeffs
    return abs(sum(pol) - sum(arr))

from scipy.optimize import brute
grid = (slice(1, 3, 1), slice(2, 5, 1))
resbrute = brute(objfunc, ranges=grid, args=(y,), full_output=True, finish=None)
print("Best coeffs: {}".format(resbrute[0]))
print("Score with best coeffs: {}".format(resbrute[1]))
print("Grid: {}".format(resbrute[2].tolist()))
print("Scores for grid: {}".format(resbrute[3].tolist()))
</code>```

答:
The code looks a bit strange with all those variable-names. endog, y; y becomes endog?

But the following is probably the approach, which follows exactly the documentation

args : tuple, optional

Any additional fixed parameters needed to completely specify the function.

Code:

```<code>import pandas as pd

y = pd.DataFrame([0,1,4,9,16]) + 3
def objfunc(coeffs, *args):
    endog = args[0]                       # access first element of tuple: y
    exp = coeffs[0]                       #     assuming y should become endog
    const = coeffs[1]
    print(exp, const, endog)
    out = 0
    for i in range(4):
        out += i**exp + const
    return out

from scipy.optimize import brute
grid = (slice(0, 2, 1), slice(3, 4, 1))
brute(objfunc, ranges=grid, args=(y,))    # in general a tuple; first pos: y
</code>```

Title: Using scipy.optimize.brute

Body:
Based on this post I am trying to use brute to do a grid serach on a ARIMA model but I cannot make it run. I am doign this proof of principle, but what am I doing wrong with the arguments?

y = pd.DataFrame([0,1,4,9,16]) + 3
def objfunc(coeffs, endog):
    exp = coeffs[0]
    const = coeffs[1]
    print(exp, const, endog)
    out = 0
    for i in range(4):
        out += i**exp + const
    return out

from scipy.optimize import brute
grid = (slice(0, 2, 1), slice(3, 4, 1))
brute(objfunc, ranges=grid, args=y)

(0, 3, 0)
(0, 3, 0)
(1, 3, 0)
...
TypeError: objfunc() takes exactly 2 arguments (1 given)

Once I solve this my aim is actually to optimize this function on order and seasonal_order being tuples like this ( _ , _  , _ ) and this ( _ , _ , _ ,12), respectively.

def objfunc(coeffs, endog):
    order = coeffs[0]
    seasonal = coeffs[1]
    fit = sm.tsa.statespace.SARIMAX(endog, trend='n', order=order, seasonal_order=seasonal).fit()
    return fit.aic()

EDIT: this code works (thanks to @sasha), variable names are more clear, and makes more sense (I minimize the function on the error).

import pandas as pd
y = np.array([0,1,4,9,16]) + 3 #polynomial x^2+3 with x=0:4
def objfunc(coeffs, *args):
    arr = args[0]                       # access first element of tuple: y
    exp = coeffs[0]                       #     assuming y should become endog
    const = coeffs[1]
    pol = [i**exp + const for i in range(len(y))]
    print coeffs
    return abs(sum(pol) - sum(arr))

from scipy.optimize import brute
grid = (slice(1, 3, 1), slice(2, 5, 1))
resbrute = brute(objfunc, ranges=grid, args=(y,), full_output=True, finish=None)
print("Best coeffs: {}".format(resbrute[0]))
print("Score with best coeffs: {}".format(resbrute[1]))
print("Grid: {}".format(resbrute[2].tolist()))
print("Scores for grid: {}".format(resbrute[3].tolist()))

Body:
The code looks a bit strange with all those variable-names. endog, y; y becomes endog?

But the following is probably the approach, which follows exactly the documentation

args : tuple, optional

Any additional fixed parameters needed to completely specify the function.

Code:

import pandas as pd

y = pd.DataFrame([0,1,4,9,16]) + 3
def objfunc(coeffs, *args):
    endog = args[0]                       # access first element of tuple: y
    exp = coeffs[0]                       #     assuming y should become endog
    const = coeffs[1]
    print(exp, const, endog)
    out = 0
    for i in range(4):
        out += i**exp + const
    return out

from scipy.optimize import brute
grid = (slice(0, 2, 1), slice(3, 4, 1))
brute(objfunc, ranges=grid, args=(y,))    # in general a tuple; first pos: y


问:
R trying to predict future population
There may be a a pretty easy solution but I'm new at R so I'm having a hard time trying to understand getting this solution for this exercise im figuring out.

I basically have the following data and want to predict a linear regression of the following data for 2020.

data
     Geographic.Area   Census Estimates.Base    X2010    X2011    X2012    X2013
  15         Florida 18801310       18804592 18849098 19096952 19344156 19582022
        X2014    X2015    X2016 X2020
  15 19888741 20244914 20612439     0

Each year is its own column with 2020 having a value of 0. Trying to predict its value.

I know I have to start out with something in the following path:

linear = lm(X2020 ~ years, data=data)

But am getting errors and the returned numbers arent correct. How should I continue with this? The answer might be pretty simple but im still trying to understand how this works so I can predict the 2020 value.

Edit:
As for code I have done the following which I can see is wrong. But unsure as to what steps to take to correct it.

linear = lm(X2020 ~ X2010 + X2011 + X2012 + X2013 + X2014 + X2015 + X2016, data=florida)
  linear

Call:
lm(formula = X2020 ~ X2010 + X2011 + X2012 + X2013 + X2014 +
    X2015 + X2016, data = florida)

Coefficients:
(Intercept)        X2010        X2011        X2012        X2013        X2014

          0           NA           NA           NA           NA           NA

      X2015        X2016

         NA           NA

答:
Here is a way to conduct this analysis with lm(). Since the OP data source didn't match years to population values, I used data from the American Fact Finder.

```<code> # data from https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=CF

rawData <- "state year population
FL 2010 18511620
FL 2011 18688767
FL 2012 18885152
FL 2013 19091156
FL 2014 19361792
FL 2015 19645772
FL 2016 19934451"

flPopulation <- read.table(textConnection(rawData),header=TRUE)
theModel <- lm(population ~ year,data = flPopulation)
year <- 2017:2020
predictions <- (year * theModel$coef[2]) + theModel$coef[1]
summary(theModel)
data.frame(year,predictions)
</code>```

...and the output:

```<code>> summary(theModel)

Call:
lm(formula = population ~ year, data = flPopulation)

Residuals:
     1      2      3      4      5      6      7
 65284   4604 -36837 -68660 -35850  10303  61156

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -459585001   21171220  -21.71 3.85e-06 ***
year            237826      10517   22.61 3.14e-06 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 55650 on 5 degrees of freedom
Multiple R-squared:  0.9903,    Adjusted R-squared:  0.9884
F-statistic: 511.3 on 1 and 5 DF,  p-value: 3.144e-06

> data.frame(year,predictions)
  year predictions
1 2017    20111122
2 2018    20348948
3 2019    20586775
4 2020    20824601
>
</code>```

Title: R trying to predict future population

Body:
Here is a way to conduct this analysis with lm(). Since the OP data source didn't match years to population values, I used data from the American Fact Finder.

 # data from https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=CF

rawData <- "state year population
FL 2010 18511620
FL 2011 18688767
FL 2012 18885152
FL 2013 19091156
FL 2014 19361792
FL 2015 19645772
FL 2016 19934451"

flPopulation <- read.table(textConnection(rawData),header=TRUE)
theModel <- lm(population ~ year,data = flPopulation)
year <- 2017:2020
predictions <- (year * theModel$coef[2]) + theModel$coef[1]
summary(theModel)
data.frame(year,predictions)

...and the output:

> summary(theModel)

Call:
lm(formula = population ~ year, data = flPopulation)

Residuals:
     1      2      3      4      5      6      7
 65284   4604 -36837 -68660 -35850  10303  61156

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -459585001   21171220  -21.71 3.85e-06 ***
year            237826      10517   22.61 3.14e-06 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 55650 on 5 degrees of freedom
Multiple R-squared:  0.9903,    Adjusted R-squared:  0.9884
F-statistic: 511.3 on 1 and 5 DF,  p-value: 3.144e-06

> data.frame(year,predictions)
  year predictions
1 2017    20111122
2 2018    20348948
3 2019    20586775
4 2020    20824601
>


问:
Check time series incongruencies
Let's say that we have the following matrix:

```<code>x<- as.data.frame(cbind(c("A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D"),
                        c(1,2,3,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                        c(14,28,42,14,46,64,71,85,14,28,51,84,66,22,38,32,40,42)))
colnames(x)<- c("ID","Visit", "Age")
</code>```

The first column represents subject ID, the second a list of observations and the third the age at each of this consecutive observations.

Which would be the easiest way of finding visits where the age is wrong according to the previous visit age. (i.e. in row 13, subject C is 66 years old, when in the previous visit he was already 84 or in row 16, subject D is 32 years old, when in the previous visit he was already 38).

Which would be the way of highlighting the potential errors and removing rows 13 and 16?

I have tried to aggregate by IDs and look for the difference between ages across visits, but it seems hard for me since the error could occur in any visit.

答:
How about this in base R?

```<code>df <- do.call(rbind.data.frame, lapply(split(x, x$ID), function(w)
    w[c(1, which(diff(w[order(w$Visit), "Age"]) > 0) + 1), ]));
df;
#    ID Visit Age
#A.1   A     1  14
#A.2   A     2  28
#A.3   A     3  42
#B.4   B     1  14
#B.5   B     2  46
#B.6   B     3  64
#B.7   B     4  71
#B.8   B     5  85
#C.9   C     1  14
#C.10  C     2  28
#C.11  C     3  51
#C.12  C     4  84
#D.14  D     1  22
#D.15  D     2  38
#D.17  D     4  40
#D.18  D     5  42
</code>```

Explanation: We split the dataframe on column ID, then order every dataframe subset by Visit, calculate differences between successive Age values, and only keep those rows where the difference is > 0 (i.e. Age is increasing); rbinding gives the final dataframe.

Title: Check time series incongruencies

Body:
Let's say that we have the following matrix:

x<- as.data.frame(cbind(c("A","A","A","B","B","B","B","B","C","C","C","C","C","D","D","D","D","D"),
                        c(1,2,3,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                        c(14,28,42,14,46,64,71,85,14,28,51,84,66,22,38,32,40,42)))
colnames(x)<- c("ID","Visit", "Age")

The first column represents subject ID, the second a list of observations and the third the age at each of this consecutive observations.

Which would be the easiest way of finding visits where the age is wrong according to the previous visit age. (i.e. in row 13, subject C is 66 years old, when in the previous visit he was already 84 or in row 16, subject D is 32 years old, when in the previous visit he was already 38).

Which would be the way of highlighting the potential errors and removing rows 13 and 16?

I have tried to aggregate by IDs and look for the difference between ages across visits, but it seems hard for me since the error could occur in any visit.

Body:
How about this in base R?

df <- do.call(rbind.data.frame, lapply(split(x, x$ID), function(w)
    w[c(1, which(diff(w[order(w$Visit), "Age"]) > 0) + 1), ]));
df;
#    ID Visit Age
#A.1   A     1  14
#A.2   A     2  28
#A.3   A     3  42
#B.4   B     1  14
#B.5   B     2  46
#B.6   B     3  64
#B.7   B     4  71
#B.8   B     5  85
#C.9   C     1  14
#C.10  C     2  28
#C.11  C     3  51
#C.12  C     4  84
#D.14  D     1  22
#D.15  D     2  38
#D.17  D     4  40
#D.18  D     5  42

Explanation: We split the dataframe on column ID, then order every dataframe subset by Visit, calculate differences between successive Age values, and only keep those rows where the difference is > 0 (i.e. Age is increasing); rbinding gives the final dataframe.


问:
MUTEX LOCK and MUTEX UNLOCK
what happen in the extremely unlucky case that two processes arrive at exactly & precisely the same moment.  This is not likely, but probabilistically can happen from time to time.  Even more coincidentally, let’s assume the lock is OPEN so that both processes would find the lock available. What happens? </p>

答:
Locking a mutex is an atomic process, so even if two threads manage to request the mutex at exactly the same time, one of them will succeed and the other will fail--that is to say, one will lock the mutex, and the other won't.

Any other result means the mutex is utterly and irrevocably broken--i.e., it's not really a mutex at all.

Title: MUTEX LOCK and MUTEX UNLOCK


问:
is there a simple way to update a single record property in firebase?
Is there a simple way to update a single record property in Firebase?  For example, let's say I wanted to simply update the Name property of Product id 1.  I tried the following code but this eliminated all of the other properties for Product id 1:

```<code>//update a product
var ciRef = dbRef.child("Product");
ciRef.update({
  1: {
    Name: "my-prod-2"
  }
});
</code>```

Is there a simple way to configure my update command to update a single property for a record without eliminating all of the other properties?

答:
Update more deeply into the location that needs to be changed.  Try this instead:</p>

```<code>//update a product
var ciRef = dbRef.child("Product/1");
ciRef.update({
  Name: "my-prod-2"
});
</code>```

Body:
Is there a simple way to update a single record property in Firebase?  For example, let's say I wanted to simply update the Name property of Product id 1.  I tried the following code but this eliminated all of the other properties for Product id 1:

//update a product
var ciRef = dbRef.child("Product");
ciRef.update({
  1: {
    Name: "my-prod-2"
  }
});

Is there a simple way to configure my update command to update a single property for a record without eliminating all of the other properties?

Body:
Update more deeply into the location that needs to be changed.  Try this instead:

//update a product
var ciRef = dbRef.child("Product/1");
ciRef.update({
  Name: "my-prod-2"
});


问:
Django Queryset for concat query fullname of first_name and last_name
I would like to do a fullname (first_name concat last_name) search/query in Django.

The following is my model:

```<code>class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

For example we have an entry like this.
first_name:"Michael", last_name:"Jackson"

I want to be able to query full name "michael jackson". If can show without case sensitive would be great as well.

This other stackoverflow question is similar but the answers is not fulfilling this particular requirement in proper Querying full name in Django. We want to be able to do a concat search.

I tried with annotate but it doesnt work

```<code>queryset = Employee.objects.annotate(fullname=Concat('first_name', 'last_name'))
search_result = queryset.filter(fullname__icontains='michael jackson')
</code>```

答:
this worked.</p>

```<code>from django.db.models.functions import Concat
from django.db.models import Value

queryset = Employee.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name'))
c = queryset.filter(fullname__icontains='michael jackson')
</code>```

Body:
I would like to do a fullname (first_name concat last_name) search/query in Django.

The following is my model:

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)

For example we have an entry like this.
first_name:"Michael", last_name:"Jackson"

I want to be able to query full name "michael jackson". If can show without case sensitive would be great as well.

This other stackoverflow question is similar but the answers is not fulfilling this particular requirement in proper Querying full name in Django. We want to be able to do a concat search.

I tried with annotate but it doesnt work

queryset = Employee.objects.annotate(fullname=Concat('first_name', 'last_name'))
search_result = queryset.filter(fullname__icontains='michael jackson')

Body:
this worked.

from django.db.models.functions import Concat
from django.db.models import Value

queryset = Employee.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name'))
c = queryset.filter(fullname__icontains='michael jackson')


问:
Rare JSON issue: Well parsed but I cant get values. Why?
Here is a JSON string, tested in some lints at https://jsonlint.com/
and they all say it's ok, I guess you will feel this as a redundant question and I understand. But I got stuck and I'm becoming crazy with this issue, unable to fix it by my own.

So I parse the JSON string this way (data var contents on the bottom):

```<code>data = JSON.parse(data);
</code>```

And I have tried to get the data as usual:

```<code>console.log(data.result); or console.log(data['result']);
</code>```

But it always is undefined. Can somebody help me?

Here the contents of var data:

```<code>var data = '{"result":"true","id":"31","content":"{"project":{"title":"New","description":"A new file","template":"cve"},"elements":[{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"EXPERIENCE"},{"eleTarget":"page-2","eleType":"TEXT"},{"eleTarget":"page-2","eleType":"EDUCATION"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"CREDENTIALS"}],"pages":[{"titleName":"page-0-title","titleValue":"About","fields":[{"fieName":"page-0-ele-0","fieValue":"Mark"},{"fieName":"page-0-ele-1","fieValue":"Hilton"},{"fieName":"page-0-ele-2","fieValue":"A creative"},{"fieName":"page-0-ele-3","fieValue":"developer"},{"fieName":"page-0-ele-4","fieValue":"Grown in the forest educated by robots."},{"fieName":"page-0-ele-5","fieValue":"Some Icon links"}]},{"titleName":"page-1-title","titleValue":"Experience","fields":[{"fieName":"page-1-ele-6","fieValue":"Experience"},{"fieName":"page-1-ele-0-0","fieValue":"Magic developer"},{"fieName":"page-1-ele-0-1","fieValue":"Wizards Ltd."},{"fieName":"page-1-ele-0-2","fieValue":"Providence"},{"fieName":"page-1-ele-0-3","fieValue":"2011"},{"fieName":"page-1-ele-0-4","fieValue":"Create essential magic texts and script code."}]},{"titleName":"page-2-title","titleValue":"Education","fields":[{"fieName":"page-2-ele-7","fieValue":"Education"},{"fieName":"page-2-ele-0-0","fieValue":"Junior Wizard"},{"fieName":"page-2-ele-0-1","fieValue":"Advanced spell management"},{"fieName":"page-2-ele-0-2","fieValue":"Howards"},{"fieName":"page-2-ele-0-3","fieValue":"2001"},{"fieName":"page-2-ele-0-4","fieValue":"Denver"},{"fieName":"page-2-ele-0-5","fieValue":"Texas"}]},{"titleName":"page-3-title","titleValue":"Skills","fields":[{"fieName":"page-3-ele-8","fieValue":"Skills"},{"fieName":"page-3-ele-9","fieValue":"Mobile-First  Responsive DesignCross Browser Testing & Debugging Agile Development & Scrum"}]},{"titleName":"page-4-title","titleValue":"Interests","fields":[{"fieName":"page-4-ele-10","fieValue":"Interests"},{"fieName":"page-4-ele-11","fieValue":"Apart from being a web developer, I enjoy most of my time being outdoors."}]},{"titleName":"page-5-title","titleValue":"Awards","fields":[{"fieName":"page-5-ele-12","fieValue":"Awards"},{"fieName":"page-5-ele-13","fieValue":"No awards yet"}]},{"titleName":"page-6-title","titleValue":"Personal details","fields":[{"fieName":"page-6-ele-14","fieValue":"Personal details"},{"fieName":"page-6-ele-0-0","fieValue":"Mark"},{"fieName":"page-6-ele-0-1","fieValue":"Hilton"},{"fieName":"page-6-ele-0-2","fieValue":"Dakota"},{"fieName":"page-6-ele-0-3","fieValue":" 214 987 548 415"},{"fieName":"page-6-ele-0-4","fieValue":"hilton43@email.com"},{"fieName":"page-6-ele-0-5","fieValue":"04-11-78"},{"fieName":"page-6-ele-0-6","fieValue":"Denver TX"},{"fieName":"page-6-ele-0-7","fieValue":"USA"},{"fieName":"page-6-ele-0-8","fieValue":"32,Elm street, Providence NY"},{"fieName":"page-6-ele-0-9","fieValue":"picture"}]}]}","status":"0","edited":"2017-12-08 23:02:28","views":"0"}';
</code>```

Body:
Here is a JSON string, tested in some lints at https://jsonlint.com/
and they all say it's ok, I guess you will feel this as a redundant question and I understand. But I got stuck and I'm becoming crazy with this issue, unable to fix it by my own.

So I parse the JSON string this way (data var contents on the bottom):

data = JSON.parse(data);

And I have tried to get the data as usual:

console.log(data.result); or console.log(data['result']);

But it always is undefined. Can somebody help me?

Here the contents of var data:

var data = '{"result":"true","id":"31","content":"{"project":{"title":"New","description":"A new file","template":"cve"},"elements":[{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"EXPERIENCE"},{"eleTarget":"page-2","eleType":"TEXT"},{"eleTarget":"page-2","eleType":"EDUCATION"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"CREDENTIALS"}],"pages":[{"titleName":"page-0-title","titleValue":"About","fields":[{"fieName":"page-0-ele-0","fieValue":"Mark"},{"fieName":"page-0-ele-1","fieValue":"Hilton"},{"fieName":"page-0-ele-2","fieValue":"A creative"},{"fieName":"page-0-ele-3","fieValue":"developer"},{"fieName":"page-0-ele-4","fieValue":"Grown in the forest educated by robots."},{"fieName":"page-0-ele-5","fieValue":"Some Icon links"}]},{"titleName":"page-1-title","titleValue":"Experience","fields":[{"fieName":"page-1-ele-6","fieValue":"Experience"},{"fieName":"page-1-ele-0-0","fieValue":"Magic developer"},{"fieName":"page-1-ele-0-1","fieValue":"Wizards Ltd."},{"fieName":"page-1-ele-0-2","fieValue":"Providence"},{"fieName":"page-1-ele-0-3","fieValue":"2011"},{"fieName":"page-1-ele-0-4","fieValue":"Create essential magic texts and script code."}]},{"titleName":"page-2-title","titleValue":"Education","fields":[{"fieName":"page-2-ele-7","fieValue":"Education"},{"fieName":"page-2-ele-0-0","fieValue":"Junior Wizard"},{"fieName":"page-2-ele-0-1","fieValue":"Advanced spell management"},{"fieName":"page-2-ele-0-2","fieValue":"Howards"},{"fieName":"page-2-ele-0-3","fieValue":"2001"},{"fieName":"page-2-ele-0-4","fieValue":"Denver"},{"fieName":"page-2-ele-0-5","fieValue":"Texas"}]},{"titleName":"page-3-title","titleValue":"Skills","fields":[{"fieName":"page-3-ele-8","fieValue":"Skills"},{"fieName":"page-3-ele-9","fieValue":"Mobile-First  Responsive DesignCross Browser Testing & Debugging Agile Development & Scrum"}]},{"titleName":"page-4-title","titleValue":"Interests","fields":[{"fieName":"page-4-ele-10","fieValue":"Interests"},{"fieName":"page-4-ele-11","fieValue":"Apart from being a web developer, I enjoy most of my time being outdoors."}]},{"titleName":"page-5-title","titleValue":"Awards","fields":[{"fieName":"page-5-ele-12","fieValue":"Awards"},{"fieName":"page-5-ele-13","fieValue":"No awards yet"}]},{"titleName":"page-6-title","titleValue":"Personal details","fields":[{"fieName":"page-6-ele-14","fieValue":"Personal details"},{"fieName":"page-6-ele-0-0","fieValue":"Mark"},{"fieName":"page-6-ele-0-1","fieValue":"Hilton"},{"fieName":"page-6-ele-0-2","fieValue":"Dakota"},{"fieName":"page-6-ele-0-3","fieValue":" 214 987 548 415"},{"fieName":"page-6-ele-0-4","fieValue":"hilton43@email.com"},{"fieName":"page-6-ele-0-5","fieValue":"04-11-78"},{"fieName":"page-6-ele-0-6","fieValue":"Denver TX"},{"fieName":"page-6-ele-0-7","fieValue":"USA"},{"fieName":"page-6-ele-0-8","fieValue":"32,Elm street, Providence NY"},{"fieName":"page-6-ele-0-9","fieValue":"picture"}]}]}","status":"0","edited":"2017-12-08 23:02:28","views":"0"}';


答:
The problem comes from accessing the data with $ inside the formula rather than just taking it from the data argument as intended. This is generally discouraged because it confuses subsequent functions such as predict() or glht() in your case. Simply use:

```<code>stress.lm <- lm(lnrate ~ group, data = stress.data)
glht(stress.lm, linfct = mcp(group=c("C-P=0", "F-P=0")))
##   General Linear Hypotheses
##
## Multiple Comparisons of Means: User-defined Contrasts
##
## Linear Hypotheses:
##            Estimate
## C - P == 0   0.1180
## F - P == 0   0.2215
</code>```

Body:
My question has been asked on a previous forum but for some reason the answer is not working for me. I am doing a planned comparison on log transformed data using R and I continue to get the error:
Error in mcp2matrix(model, linfct = linfct) :
  Variable(s) ‘group’ have been specified in ‘linfct’ but cannot be found in ‘model’!
Any help would be appreciated. Thank you!

Here's my data:

stress.data = read.table(textConnection(" group    rate   lnrate
1      P  69.169 4.236553
2      P  68.862 4.232105
3      C  84.738 4.439564
4      F  99.692 4.602085
5      C  87.231 4.468560
6      C  84.877 4.441203
7      P  70.169 4.250907
8      P  64.169 4.161520
9      P  58.692 4.072303
10     C  80.369 4.386629
11     C  91.754 4.519111
12     P  79.662 4.377793
13     C  87.446 4.471021
14     C  87.785 4.474891
15     P  69.231 4.237449
16     P  75.985 4.330536
17     F  91.354 4.514742
18     C  73.277 4.294247
19     F  83.400 4.423648
20     F 100.877 4.613902
21     C  84.523 4.437024
22     F 102.154 4.626481
23     C  77.800 4.354141
24     C  70.877 4.260946
25     P  86.446 4.459520
26     P  97.538 4.580242
27     F  89.815 4.497752
28     F  80.277 4.385483
29     P  85.000 4.442651
30     F  98.200 4.587006
31     C  90.015 4.499976
32     F 101.062 4.615734
33     F  76.908 4.342610
34     C  99.046 4.595584
35     F  97.046 4.575185
36     P  69.538 4.241873
37     C  75.477 4.323828
38     C  62.646 4.137500
39     P  70.077 4.249595
40     F  88.015 4.477507
41     F  81.600 4.401829
42     F  86.985 4.465736
43     F  92.492 4.527122
44     P  72.262 4.280298
45     P  65.446 4.181225"), header = TRUE)

library("multcomp")
stress.lm= lm(stress.data$lnrate ~ stress.data$group, data = stress.data)
stressPlanned= glht(stress.lm, linfct=mcp(group=c("C-P=0", "F-P=0")))

Error in mcp2matrix(model, linfct = linfct) :
  Variable(s) ‘group’ have been specified in ‘linfct’ but cannot be found in ‘model’!

Body:
The problem comes from accessing the data with $ inside the formula rather than just taking it from the data argument as intended. This is generally discouraged because it confuses subsequent functions such as predict() or glht() in your case. Simply use:

stress.lm <- lm(lnrate ~ group, data = stress.data)
glht(stress.lm, linfct = mcp(group=c("C-P=0", "F-P=0")))
##   General Linear Hypotheses
##
## Multiple Comparisons of Means: User-defined Contrasts
##
## Linear Hypotheses:
##            Estimate
## C - P == 0   0.1180
## F - P == 0   0.2215


问:
A few problems with my javascript sample. Please help
Alright, so I'm trying to get a page to load some js at the end of it's loading. I think I got it, but now it's saying I'm not getting a number with this line:

```<code>parseInt(document.getElementById('canvas').style.width);
</code>```

It should be "480px" but it's NaN.

It also said the line document.getElementById('ss') was null.

Here's the full thing:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Cypri Designs</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="/images/favicon1.ico" type="image/x-icon" />
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <script type="text/javascript">
        <!--
            //Variables to handle game parameters
            var gameloopId;
            var screenWidth;
            var screenHeight;
            var gameRunning = false;
            var ctx;

            var playerX = 0;
            var playerY = 0;

            //Create images
            var playerImg = new Image();

            //Wait for DOM to load and init game
            window.onload = function(){
                init();
            };

            function init(){
                initSettings();
                initImages();

                //add event handler to surrounding DIV to monitor mouse move and update mushroom's x position
                /*$("#container").mousemove(function(e){
                    mushroomX = e.pageX;
                });*/

                //add event handler for clicking on start/stop button and toggle the game play
                document.getElementById('ss').onclick = function (){

                    toggleGameplay();
                };
            }

            function initSettings()
            {
                //Get a handle to the 2d context of the canvas
                ctx = document.getElementById('canvas').getContext('2d');

                //Calulate screen height and width
                screenWidth = parseInt(document.getElementById('canvas').style.width);
                screenHeight = parseInt(document.getElementById('canvas').style.height);

                playerX = 100;
                playerY = 100;
            }

            function initImages(){
                playerImg.src = "images/player.png";
            }
            //Main game loop, it all happens here!
            function gameLoop(){

                //Clear the screen (i.e. a draw a clear rectangle the size of the screen)
                ctx.clearRect(0, 0, screenWidth, screenHeight);

                ctx.save();
                ctx.drawImage(playerImg, 0, 0);

                ctx.restore();
            }

            //Start/stop the game loop (and more importantly that annoying boinging!)
            function toggleGameplay()
            {
                gameRunning = !gameRunning;

                if(gameRunning)
                {
                    clearInterval(gameloopId);
                    gameloopId = setInterval(gameLoop, 10);
                }
                else
                {
                    clearInterval(gameloopId);
                }
            }
        //-->
        </script>

    </head>

    <body>
        <input id="ss" type="button" value="start/stop" />
        <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
            <canvas id="canvas" width="480px" height="320px" >
            Canvas not displaying.
            </canvas>
        </div>
    </body>
</html>
</code>```

答:
The "width" and "height" properties you defined with the canvas are not style properties; they are attributes of the canvas object.  They define the width and height of the canvas's coordinate system, not the display height and width.

The canvas will fill its parent container, which is 480px and 320px.  As mVChr mentioned, you could get this through "offsetWidth" (with cross-browser caveats), or by using a library like jQuery that will compute it for you in a cross-browser way:

```<code>$("#canvas").width();
</code>```

Body:
Alright, so I'm trying to get a page to load some js at the end of it's loading. I think I got it, but now it's saying I'm not getting a number with this line:

parseInt(document.getElementById('canvas').style.width);

It should be "480px" but it's NaN.

It also said the line document.getElementById('ss') was null.

Here's the full thing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>Cypri Designs</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="/images/favicon1.ico" type="image/x-icon" />
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

        <input id="ss" type="button" value="start/stop" />

            <canvas id="canvas" width="480px" height="320px" >
            Canvas not displaying.
            </canvas>

Body:
The "width" and "height" properties you defined with the canvas are not style properties; they are attributes of the canvas object.  They define the width and height of the canvas's coordinate system, not the display height and width.

The canvas will fill its parent container, which is 480px and 320px.  As mVChr mentioned, you could get this through "offsetWidth" (with cross-browser caveats), or by using a library like jQuery that will compute it for you in a cross-browser way:

$("#canvas").width();


问:
Load testing Bot builder bot

Update

Using emulator as channelId and updating to SDK 3.13.1 works for me.

App ID: 8c082f92-fb38-4841-a29f-339eb315f7aa

SDK Platform: Node.js

SDK Version: 3.13.1

Active Channels: Facebook

Deployment Environment: ngrok

Issue Description

I tried following steps mentioned in this link. This has two parts. One is creating the token and second is to send a message to the bot. POSTMAN request leads to 500 Internal Server Error and ERROR: ChatConnector: receive - invalid signing key or OpenId metadata document in the code.

Code Example

Create token

```<code> curl -X POST  https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token   -H 'cache-control: no-cache' -H 'content-type: application/x-www-form-urlencoded'  -H 'postman-token: 792660ab-b1aa-0cbd-edab-9b3847c170d5'  -d 'grant_type=client_credentials&client_id=8c082f92-fb38-4841-a29f-339eb315f7aa&client_secret=vxcihBT2679%7C(%23puEXBPT1!&scope=8c082f92-fb38-4841-a29f-339eb315f7aa%2F.default'
</code>```

Send a message

```<code> curl -X POST https://1c36f336.ngrok.io/api/messages -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ing0Nzh4eU9wbHNNMUg3TlhrN1N4MTd4MXVwYyJ9.eyJhdWQiOiI4YzA4MmY5Mi1mYjM4LTQ4NDEtYTI5Zi0zMzllYjMxNWY3YWEiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiL3YyLjAiLCJpYXQiOjE1MTIxOTg2NjcsIm5iZiI6MTUxMjE5ODY2NywiZXhwIjoxNTEyMjAyNTY3LCJhaW8iOiJZMk5nWUZEOHRySzgvZk9XcDF2L1BMM2JibnRGRGdBPSIsImF6cCI6IjhjMDgyZjkyLWZiMzgtNDg0MS1hMjlmLTMzOWViMzE1ZjdhYSIsImF6cGFjciI6IjEiLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJXLWdYbXpPSkxVYWdzSFZUbXBJd0FBIiwidmVyIjoiMi4wIn0.G705tzQIU5Mh6IROtXkIwm8Q9AKZ_q-VOtJuuozqP-ekhWoKc0HpcdhgBlnaMsMHKoM0RWhUlXn27xCfK46vEE9IZlkjcAh7huhvlWNtW8IP5w7QiL3JCSTYKCtBXZq-VKeWctNWR9M8Y9Ry4dyiEdcDMcHWrbOUqR6nXvlwG76GSR4YilqzMWdSW6t5Pep3hwOw07DSargYP0pDAnWAg3pWHnhcJ185533I1VVXEIuc_CK-RmP9qhUAScEbYkpp_7l75bVWzxKv-3E1UOG4SBj6UzfH47X5kwz_njn1kAJcrqBvP3s_CjS4qUdDSNARtxGZ3UQWj49UBKosqar0dg' -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'postman-token: 3a74ce00-2da7-d674-5e4c-083f54ed30ff' -d '{ "type": "message", "id": "mid.$cAAGEkG8MNm1mOEBe-lgBvsWZbQUc", "channelId" : "test",  "conversation": { "id": "100023023852067-526013297749070"}, "from": { "id": "100023023852067" }, "recipient": { "id": "526013297749070" },  "serviceUrl": "https://1c36f336.ngrok.io", "text": "Hi message from postman !!!" }'
</code>```

Reproduction Steps

Using the two curl requests mentioned above. This should lead to the mentioned issue.

Expected Behavior

POSTMAN request should lead to 202 Accepted and bot receiving the message. Am I missing something or is there something wrong in the process? I saw some  issues  on load testing but none of them helped.

Actual Results

POSTMAN request leads to 500 Internal Server Error and ERROR: ChatConnector: receive - invalid signing key or OpenId metadata document in the code.

答:
I was able to get this to work after:

1) adding a custom state client to the bot using botbuilder-azure

2) exposing the message sink, for receiving the bot response

3) changing the channelId to "emulator" (apparently node sdk doesn't handle 'test' channel)

```<code>curl -X POST  https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token -H "content-type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id=MyMicrosoftAppId&client_secret=MyMicrosoftAppPassword&scope=MyMicrosoftAppId%2F.default"

curl -X POST https://e84a2f49.ngrok.io/api/messages -H "authorization: Bearer TokenFromPreviousCall" -d "{ \"type\": \"message\", \"id\": \"mid.$cAAGEkG8MNm1mOEBe-lgBvsWZbQUc\", \"channelId\" : \"emulator\",  \"conversation\": { \"id\": \"100023023852067-526013297749070\"}, \"from\": { \"id\": \"100023023852067\" }, \"recipient\": { \"id\": \"526013297749070\" },  \"serviceUrl\": \"https://e84a2f49.ngrok.io\", \"text\": \"Hi message from postman !!!\" }"
</code>```

Here is the app, for reference:

```<code>var restify = require('restify');
var builder = require('botbuilder');
var azure = require('botbuilder-azure');

var sqlConfig = {
    userName: 'SqlServerUserId',
    password: 'SqlServerPassword',
    server: 'mySqlServer.net',
    enforceTable: true,
    options: {
        database: 'BotDatabaseName',
        table: 'BotDataTableName',
        encrypt: true,
        rowCollectionOnRequestCompletion: true
    }
}

var sqlClient = new azure.AzureSqlClient(sqlConfig);
var sqlStorage = new azure.AzureBotStorage({ gzipData: false }, sqlClient);

var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3980, function () {
    console.log('%s listening to %s', server.name, server.url);
});

var connector = new builder.ChatConnector({
    appId: "MyAppId",
    appPassword: "MyAppPassword"
});

server.post('/api/messages', connector.listen());

var bot = new builder.UniversalBot(connector, function (session) {
    session.send("You said: %s", session.message.text);
}).set('storage', sqlStorage);;

//message sink
server.post("/v3/conversations/:conversationId/activities/:activityId", function(Request, Response, next) {
    next();
});
</code>```

Title: Load testing Bot builder bot

Body:
Update

Using emulator as channelId and updating to SDK 3.13.1 works for me.

App ID: 8c082f92-fb38-4841-a29f-339eb315f7aa

SDK Platform: Node.js

SDK Version: 3.13.1

Active Channels: Facebook

Deployment Environment: ngrok

Issue Description

I tried following steps mentioned in this link. This has two parts. One is creating the token and second is to send a message to the bot. POSTMAN request leads to 500 Internal Server Error and ERROR: ChatConnector: receive - invalid signing key or OpenId metadata document in the code.

Code Example

Create token

 curl -X POST  https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token   -H 'cache-control: no-cache' -H 'content-type: application/x-www-form-urlencoded'  -H 'postman-token: 792660ab-b1aa-0cbd-edab-9b3847c170d5'  -d 'grant_type=client_credentials&client_id=8c082f92-fb38-4841-a29f-339eb315f7aa&client_secret=vxcihBT2679%7C(%23puEXBPT1!&scope=8c082f92-fb38-4841-a29f-339eb315f7aa%2F.default'

Send a message

 curl -X POST https://1c36f336.ngrok.io/api/messages -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ing0Nzh4eU9wbHNNMUg3TlhrN1N4MTd4MXVwYyJ9.eyJhdWQiOiI4YzA4MmY5Mi1mYjM4LTQ4NDEtYTI5Zi0zMzllYjMxNWY3YWEiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiL3YyLjAiLCJpYXQiOjE1MTIxOTg2NjcsIm5iZiI6MTUxMjE5ODY2NywiZXhwIjoxNTEyMjAyNTY3LCJhaW8iOiJZMk5nWUZEOHRySzgvZk9XcDF2L1BMM2JibnRGRGdBPSIsImF6cCI6IjhjMDgyZjkyLWZiMzgtNDg0MS1hMjlmLTMzOWViMzE1ZjdhYSIsImF6cGFjciI6IjEiLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJXLWdYbXpPSkxVYWdzSFZUbXBJd0FBIiwidmVyIjoiMi4wIn0.G705tzQIU5Mh6IROtXkIwm8Q9AKZ_q-VOtJuuozqP-ekhWoKc0HpcdhgBlnaMsMHKoM0RWhUlXn27xCfK46vEE9IZlkjcAh7huhvlWNtW8IP5w7QiL3JCSTYKCtBXZq-VKeWctNWR9M8Y9Ry4dyiEdcDMcHWrbOUqR6nXvlwG76GSR4YilqzMWdSW6t5Pep3hwOw07DSargYP0pDAnWAg3pWHnhcJ185533I1VVXEIuc_CK-RmP9qhUAScEbYkpp_7l75bVWzxKv-3E1UOG4SBj6UzfH47X5kwz_njn1kAJcrqBvP3s_CjS4qUdDSNARtxGZ3UQWj49UBKosqar0dg' -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'postman-token: 3a74ce00-2da7-d674-5e4c-083f54ed30ff' -d '{ "type": "message", "id": "mid.$cAAGEkG8MNm1mOEBe-lgBvsWZbQUc", "channelId" : "test",  "conversation": { "id": "100023023852067-526013297749070"}, "from": { "id": "100023023852067" }, "recipient": { "id": "526013297749070" },  "serviceUrl": "https://1c36f336.ngrok.io", "text": "Hi message from postman !!!" }'

Reproduction Steps

Using the two curl requests mentioned above. This should lead to the mentioned issue.

Expected Behavior

POSTMAN request should lead to 202 Accepted and bot receiving the message. Am I missing something or is there something wrong in the process? I saw some  issues  on load testing but none of them helped.

Actual Results

POSTMAN request leads to 500 Internal Server Error and ERROR: ChatConnector: receive - invalid signing key or OpenId metadata document in the code.

Body:
I was able to get this to work after:

1) adding a custom state client to the bot using botbuilder-azure

2) exposing the message sink, for receiving the bot response

3) changing the channelId to "emulator" (apparently node sdk doesn't handle 'test' channel)

curl -X POST  https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token -H "content-type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id=MyMicrosoftAppId&client_secret=MyMicrosoftAppPassword&scope=MyMicrosoftAppId%2F.default"

curl -X POST https://e84a2f49.ngrok.io/api/messages -H "authorization: Bearer TokenFromPreviousCall" -d "{ \"type\": \"message\", \"id\": \"mid.$cAAGEkG8MNm1mOEBe-lgBvsWZbQUc\", \"channelId\" : \"emulator\",  \"conversation\": { \"id\": \"100023023852067-526013297749070\"}, \"from\": { \"id\": \"100023023852067\" }, \"recipient\": { \"id\": \"526013297749070\" },  \"serviceUrl\": \"https://e84a2f49.ngrok.io\", \"text\": \"Hi message from postman !!!\" }"

Here is the app, for reference:

var restify = require('restify');
var builder = require('botbuilder');
var azure = require('botbuilder-azure');

var sqlConfig = {
    userName: 'SqlServerUserId',
    password: 'SqlServerPassword',
    server: 'mySqlServer.net',
    enforceTable: true,
    options: {
        database: 'BotDatabaseName',
        table: 'BotDataTableName',
        encrypt: true,
        rowCollectionOnRequestCompletion: true
    }
}

var sqlClient = new azure.AzureSqlClient(sqlConfig);
var sqlStorage = new azure.AzureBotStorage({ gzipData: false }, sqlClient);

var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3980, function () {
    console.log('%s listening to %s', server.name, server.url);
});

var connector = new builder.ChatConnector({
    appId: "MyAppId",
    appPassword: "MyAppPassword"
});

server.post('/api/messages', connector.listen());

var bot = new builder.UniversalBot(connector, function (session) {
    session.send("You said: %s", session.message.text);
}).set('storage', sqlStorage);;

//message sink
server.post("/v3/conversations/:conversationId/activities/:activityId", function(Request, Response, next) {
    next();
});


问:
Update table (col1 through col4) where exists throws single-row returns more than one row error
The sql statement below is throwing an error:

ORA-01427: single-row subquery returns more than one row

```<code>UPDATE TABLE_1 T1
   SET (  COL1, COL2, COL3, COL4) = (
       SELECT   col1
             ,  col2
             ,  col3
             ,  col4
         FROM   TEMP_TABLE_2 tt2
        WHERE   tt2.COL_XYZ = t1.COL_XYZ)
 WHERE EXISTS ( select null
                  FROM TEMP_TABLE_2 tt2
                 WHERE tt2.COL_XYZ = t.COL_XYZ);
</code>```

I believe the issue is on the "Where exists" because I know the inner select query returns only one row for a given COL_XYZ record.

Any ideas?

答:
Using Inline View (If it is considered updateable by Oracle)

Note: If you face a non key preserved row error add an index to resolve the same to make it update-able

```<code>UPDATE (SELECT t1.col1  AS o_col1,
               t1.col2  AS o_col2,
               t1.col3  AS o_col3,
               t1.col4  AS o_col4,
               tt2.col1 AS n_col1,
               tt2.col2 AS n_col2,
               tt2.col3 AS n_col3,
               tt2.col4 AS n_col4
        FROM   table_1 T1
               inner join temp_table_2 tt2
                       ON tt2.col_xyz = t1.col_xyz) T
SET    o_col1 = o_col1,
       o_col2 = n_col2,
       o_col3 = n_col3,
       o_col4 = n_col4;
</code>```

Body:
The sql statement below is throwing an error:

ORA-01427: single-row subquery returns more than one row

UPDATE TABLE_1 T1
   SET (  COL1, COL2, COL3, COL4) = (
       SELECT   col1
             ,  col2
             ,  col3
             ,  col4
         FROM   TEMP_TABLE_2 tt2
        WHERE   tt2.COL_XYZ = t1.COL_XYZ)
 WHERE EXISTS ( select null
                  FROM TEMP_TABLE_2 tt2
                 WHERE tt2.COL_XYZ = t.COL_XYZ);

I believe the issue is on the "Where exists" because I know the inner select query returns only one row for a given COL_XYZ record.

Any ideas?

Body:
Using Inline View (If it is considered updateable by Oracle)

Note: If you face a non key preserved row error add an index to resolve the same to make it update-able

UPDATE (SELECT t1.col1  AS o_col1,
               t1.col2  AS o_col2,
               t1.col3  AS o_col3,
               t1.col4  AS o_col4,
               tt2.col1 AS n_col1,
               tt2.col2 AS n_col2,
               tt2.col3 AS n_col3,
               tt2.col4 AS n_col4
        FROM   table_1 T1
               inner join temp_table_2 tt2
                       ON tt2.col_xyz = t1.col_xyz) T
SET    o_col1 = o_col1,
       o_col2 = n_col2,
       o_col3 = n_col3,
       o_col4 = n_col4;