问:
Correct commenting for class method return value
What would be the correct PHPDocumentor comment for a class method which returns a Boolean value if it fails and something like an array if it doesn't. Here's my code example:</p>

```<code>public function getServers()
{
    $q = $this->db->query('SELECT * FROM servers');

    if($q->execute())
    {
        return $q;
    } else {
        return false;
    }
}
</code>```

答:
Have a look into the phpDocumentor manual.

Example:

```<code>/**
 * @return array|bool some result or false if none found.
 */
public function getServers()
{
[...]
</code>```

Body:
What would be the correct PHPDocumentor comment for a class method which returns a Boolean value if it fails and something like an array if it doesn't. Here's my code example:

public function getServers()
{
    $q = $this->db->query('SELECT * FROM servers');

    if($q->execute())
    {
        return $q;
    } else {
        return false;
    }
}

Body:
Have a look into the phpDocumentor manual.

Example:

/**
 * @return array|bool some result or false if none found.
 */
public function getServers()
{
[...]


来源: stackexchange

问:
Unable to Call function without being stuck in endless loop
When the following function is called and run, if the initial "if" condition is met, the program runs as intended; repetitively. If the initial "if" condition is not met, the program proceeds to run the else statement, but gets stuck in an endless loop.

Why?

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

int num_func();

int main()
{
    num_func();

   return 0;
}

int num_func()
{
    int num;
    char yn[1];

    printf("Please enter an integer value: ");

    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");
            }
        }

    else {
        printf("You were told to put in a number!");
    }

    num_func();
}
</code>```

I am also interested in finding out how to make num and yn[1] global variables so that num_func() can access them w/o having to allocate memory each run. If you could explain that, I would be grateful.

答:
Problem here was that after entering in else statement and to run scanf which is in if condition can not take input because i/o buffer is not clear and according to ur wish i have made num and yn[] global.</p>

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

int num_func();
int num, c;
char yn[1];
int main()
{
    num_func();

    return 0;
}

int num_func()
{

    printf("Please enter an integer value: ");
    fflush(stdin);
    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");

            }
        }

    else {
        printf("You were told to put in a number!\n");

    }

    num_func();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When the following function is called and run, if the initial "if" condition is met, the program runs as intended; repetitively. If the initial "if" condition is not met, the program proceeds to run the else statement, but gets stuck in an endless loop.

Why?

#include <stdio.h>
#include <string.h>

int num_func();

int main()
{
    num_func();

   return 0;
}

int num_func()
{
    int num;
    char yn[1];

    printf("Please enter an integer value: ");

    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");
            }
        }

    else {
        printf("You were told to put in a number!");
    }

    num_func();
}

I am also interested in finding out how to make num and yn[1] global variables so that num_func() can access them w/o having to allocate memory each run. If you could explain that, I would be grateful.

Body:
Problem here was that after entering in else statement and to run scanf which is in if condition can not take input because i/o buffer is not clear and according to ur wish i have made num and yn[] global.

#include <stdio.h>
#include <string.h>

int num_func();
int num, c;
char yn[1];
int main()
{
    num_func();

    return 0;
}

int num_func()
{

    printf("Please enter an integer value: ");
    fflush(stdin);
    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");

            }
        }

    else {
        printf("You were told to put in a number!\n");

    }

    num_func();
}


问:
Java Process with constant heap size allocates more and more memory in OS
I have a java application which seems to allocate more and more memory from OS(but the heap size isn't growing at all!) It's an application communicating with a PLC so it needs quite some CPU.

for testing porpuse I have written this program, to be sure the problem isn't in some library:

```<code>public static void main(String[] args) {
    Random rand= new Random();
    if (args[0].equals("auto")) {
        for(int i = 0; i< Integer.valueOf(args[2]);i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<byte[]> threaddata = new ArrayList<>();
                    while(true) {
                        byte[] arr = new byte[Integer.valueOf(args[3])];
                        rand.nextBytes(arr);
                        threaddata.add(arr);
                        Thread.sleep(Long.valueOf(args[1]));
                        threaddata.clear();
                        Thread.sleep(Long.valueOf(args[1]));
                    }
                }
            }).start();
        }
    }
</code>```

I have started the application like this

```<code>java -XX:NativeMemoryTracking=detail -Xmx1G -XX:+UseG1GC -XX:G1PeriodicGCInterval=10000 -XX:G1HeapWastePercent=10 -jar gctest.jar auto 100 3 10000000
</code>```

this means the application allocates and releases 10MB every 100ms in 3 Threads.

Now I came across Native Memory Tracking which gives me this output for Internal

```<code>-                  Internal (reserved=367356KB, committed=367356KB)
                        (malloc=367324KB #3131147)
                        (mmap: reserved=32KB, committed=32KB)
</code>```

At start it needed about 15MB now it neds almost 400MB

I just came across this documentation but it doesn't realy help me at all. Any clue how I could prevent java from allocating more and more memory from OS?

EDIT: The faster I allocate and release memory, the faster the memory in OS is growing

答:
I ran your snippet.

This is how it looks in VisualVM (JDK 11, standard settings):

I checked resource usage in Task Manager (Windows).  It's constant.

So, I checked on Linux.  Had to install htop, and upgrade the JDK, but I see no difference there.  Here's the htop output after running the program for 5 minutes orso.  VIRT and RES values stay the same, total memory consumption remained similar.

And here after 5 more minutes.  Res changed to 119M, but I don't think it's anything to worry about.

From native memory tracking, taken 5 minutes apart:

```<code>[root@Ukyo 130 /download]# while sleep 300; do jcmd 16920 VM.native_memory |grep Internal -A 3; done
               Internal (reserved=605KB, committed=605KB)
                        (malloc=565KB #1151)
                        (mmap: reserved=40KB, committed=40KB)

               Internal (reserved=605KB, committed=605KB)
                        (malloc=565KB #1151)
                        (mmap: reserved=40KB, committed=40KB)
</code>```

Body:
I have a java application which seems to allocate more and more memory from OS(but the heap size isn't growing at all!) It's an application communicating with a PLC so it needs quite some CPU.

for testing porpuse I have written this program, to be sure the problem isn't in some library:

public static void main(String[] args) {
    Random rand= new Random();
    if (args[0].equals("auto")) {
        for(int i = 0; i< Integer.valueOf(args[2]);i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<byte[]> threaddata = new ArrayList<>();
                    while(true) {
                        byte[] arr = new byte[Integer.valueOf(args[3])];
                        rand.nextBytes(arr);
                        threaddata.add(arr);
                        Thread.sleep(Long.valueOf(args[1]));
                        threaddata.clear();
                        Thread.sleep(Long.valueOf(args[1]));
                    }
                }
            }).start();
        }
    }

I have started the application like this

java -XX:NativeMemoryTracking=detail -Xmx1G -XX:+UseG1GC -XX:G1PeriodicGCInterval=10000 -XX:G1HeapWastePercent=10 -jar gctest.jar auto 100 3 10000000

this means the application allocates and releases 10MB every 100ms in 3 Threads.

Now I came across Native Memory Tracking which gives me this output for Internal

-                  Internal (reserved=367356KB, committed=367356KB)
                        (malloc=367324KB #3131147)
                        (mmap: reserved=32KB, committed=32KB)

At start it needed about 15MB now it neds almost 400MB

I just came across this documentation but it doesn't realy help me at all. Any clue how I could prevent java from allocating more and more memory from OS?

EDIT: The faster I allocate and release memory, the faster the memory in OS is growing

Body:
I ran your snippet.

This is how it looks in VisualVM (JDK 11, standard settings):

I checked resource usage in Task Manager (Windows).  It's constant.

So, I checked on Linux.  Had to install htop, and upgrade the JDK, but I see no difference there.  Here's the htop output after running the program for 5 minutes orso.  VIRT and RES values stay the same, total memory consumption remained similar.

And here after 5 more minutes.  Res changed to 119M, but I don't think it's anything to worry about.

From native memory tracking, taken 5 minutes apart:

[root@Ukyo 130 /download]# while sleep 300; do jcmd 16920 VM.native_memory |grep Internal -A 3; done
               Internal (reserved=605KB, committed=605KB)
                        (malloc=565KB #1151)
                        (mmap: reserved=40KB, committed=40KB)

               Internal (reserved=605KB, committed=605KB)
                        (malloc=565KB #1151)
                        (mmap: reserved=40KB, committed=40KB)


问:
additional "items" in "navbar-toggler" "button"
Creating a navbar that has many menu items. Navbar will always visible. Some items will be shown right after clicking the navbar button. And others remain steady to navbar.

This is with bootstrap navbar-toggler button. Toggler button is fully functional but adding more and more items make the navbar just lengthier.

Thanks.

```<code>    <div class="container">
        <a class="navbar-brand" href="#"><img src="img/X.png" alt="logo" style="width:40px;"></a>
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a href="#">Home</a>
            </li>
            <li class="nav-item">
                <a href="#">Services</a>

            <li class="nav-item">
                <a href="#">Contact</a>
            </li>
            <li class="nav-item">
                <a href="#">About</a>
            </li>
        </ul>
        </div>
        <button class="btn" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"></button>
        <div>
            <ul>
                <li class="nav-item">
                    <a class="nav-link" href="#">Item 1</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Item 2</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Item 3</a>
                </li>
            </ul>
            <span class="navbar-toggler-icon"></span>
        </div>
        </div>
    </nav>
</code>```

答:
You have some issues in your HTML. You have wrapped everything inside button. I think I got what you wanted to implement. Have a look:

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Services

          Contact

          About

          Dropdown

            Item 1
            Item 2
            Item 3

```

Body:
Creating a navbar that has many menu items. Navbar will always visible. Some items will be shown right after clicking the navbar button. And others remain steady to navbar.

This is with bootstrap navbar-toggler button. Toggler button is fully functional but adding more and more items make the navbar just lengthier.

Thanks.

                Home

                Services

                Contact

                About

        <button class="btn" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"></button>

                    Item 1

                    Item 2

                    Item 3

Body:
You have some issues in your HTML. You have wrapped everything inside button. I think I got what you wanted to implement. Have a look:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#"><img src="img/X.png" alt="logo" style="width:40px;"></a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Services</a>

        <li class="nav-item">
          <a class="nav-link" href="#">Contact</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">About</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="#">Item 1</a>
            <a class="dropdown-item" href="#">Item 2</a>
            <a class="dropdown-item" href="#">Item 3</a>
          </div>
        </li>
    </ul>
  </div>
</nav>


问:
Trying to dynamically compile a list of CIDRs for an AWS S3 policy. Expression works in console but fails in plan
Trying to compile a dynamic list of CIDRs to add to an S3 policy, but even though the expression I use seem to work fine in the terraform console they are not accepted by terraform plan.

I've tried to serve it as JSON or as a list, didn't work. The only thing that did, was either passing the list manually or compiling a string like shown below.
Am I missing something here?

LIST

```<code>jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))

split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))

list(jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))))
</code>```

STRING

```<code>jsonencode(join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))
</code>```

Here is the config I'm using:

```<code>terraform --version
Terraform v0.11.14
+ provider.aws v2.12.0
+ provider.template v2.1.2
</code>```

vars.tf

```<code>variable "web_ips" {
  type = "list"
  default = []
}
variable "allowed_sources" {
  type = "list"
  default = []
}
variable "vpn_ip" {}
variable "vpc_cidr" {}
</code>```

uat.tfvars

```<code>web_ips = [
  "10.10.0.1"
]
allowed_sources = [
  "10.0.0.1/32",
  "10.0.0.2/32"
]
vpc_cidr = "10.0.0.0/16"
vpn_ip = "10.11.0.1"
</code>```

app.tf

```<code>locals {
ips1 = "${jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))}"
ips2 = "${split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))}"
}

resource "aws_s3_bucket_policy" "bucket" {
  bucket = "${aws_s3_bucket.bucket.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "Policy00000000000",
    "Statement": [
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ${local.ips}
              }
            }
        },
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-XXXXXXXXXXX"
                }
            }
        }
    ]
}
POLICY
}
</code>```

In the tf console

```<code>> jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))
["10.10.0.1/32","10.0.0.0/16","10.0.0.1/32","10.0.0.2/32","10.11.0.1"/32"]

> split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))
[
  "10.10.0.1/32",
  "10.0.0.0/16",
  "10.0.0.1/32",
  "10.0.0.2/32",
  "10.11.0.1"/32",
]
</code>```

When passing JSON (${local.ips1}), I get:

```<code>Error: Error running plan: 1 error(s) occurred:

* aws_s3_bucket_policy.bucket: "policy" contains an invalid JSON: invalid character '1' after object key:value pair
</code>```

When pass a list I get:

```<code>Error: aws_s3_bucket_policy.bucket
: 1 error occurred:
    * aws_s3_bucket_policy.bucket: At column 1, line 1: output of an HIL expression must be a string, or a single list (argument 2 is TypeList) in:

{
    "Version": "2012-10-17",
    "Id": "Policy0000000000000",
    "Statement": [
        {
            "Sid": "Stmt0000000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "${local.ips2}"
              }
            }
        },
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-000000000000"
                }
            }
        }
    ]
}
</code>```

答:
Yeah, so after battling with this for a while, the JSON solution would've have worked but I stuffed it up (as my colleague Doug pointed out) with putting double quotes around the variable within the policy like you can see in the last code snippet ("${local.ips2}")
Here's the working config:

```<code>locals {

ips = "${jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))}"
}

resource "aws_s3_bucket_policy" "bucket" {
  bucket = "${aws_s3_bucket.bucket.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "Policy000000000000",
    "Statement": [
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ${local.ips} <<<< NO QUOTES HERE!
              }
            }
        },
        {
            "Sid": "Stmt0000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-00000000000"
                }
            }
        }
    ]
}
POLICY
}
</code>```

Hope this helps anyone out there

Body:
Trying to compile a dynamic list of CIDRs to add to an S3 policy, but even though the expression I use seem to work fine in the terraform console they are not accepted by terraform plan.

I've tried to serve it as JSON or as a list, didn't work. The only thing that did, was either passing the list manually or compiling a string like shown below.
Am I missing something here?

LIST

jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))

split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))

list(jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))))

STRING

jsonencode(join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))

Here is the config I'm using:

terraform --version
Terraform v0.11.14
+ provider.aws v2.12.0
+ provider.template v2.1.2

vars.tf

variable "web_ips" {
  type = "list"
  default = []
}
variable "allowed_sources" {
  type = "list"
  default = []
}
variable "vpn_ip" {}
variable "vpc_cidr" {}

uat.tfvars

web_ips = [
  "10.10.0.1"
]
allowed_sources = [
  "10.0.0.1/32",
  "10.0.0.2/32"
]
vpc_cidr = "10.0.0.0/16"
vpn_ip = "10.11.0.1"

app.tf

locals {
ips1 = "${jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))}"
ips2 = "${split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))}"
}

resource "aws_s3_bucket_policy" "bucket" {
  bucket = "${aws_s3_bucket.bucket.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "Policy00000000000",
    "Statement": [
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ${local.ips}
              }
            }
        },
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-XXXXXXXXXXX"
                }
            }
        }
    ]
}
POLICY
}

In the tf console

> jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))
["10.10.0.1/32","10.0.0.0/16","10.0.0.1/32","10.0.0.2/32","10.11.0.1"/32"]

> split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip))))
[
  "10.10.0.1/32",
  "10.0.0.0/16",
  "10.0.0.1/32",
  "10.0.0.2/32",
  "10.11.0.1"/32",
]

When passing JSON (${local.ips1}), I get:

Error: Error running plan: 1 error(s) occurred:

* aws_s3_bucket_policy.bucket: "policy" contains an invalid JSON: invalid character '1' after object key:value pair

When pass a list I get:

Error: aws_s3_bucket_policy.bucket
: 1 error occurred:
    * aws_s3_bucket_policy.bucket: At column 1, line 1: output of an HIL expression must be a string, or a single list (argument 2 is TypeList) in:

{
    "Version": "2012-10-17",
    "Id": "Policy0000000000000",
    "Statement": [
        {
            "Sid": "Stmt0000000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "${local.ips2}"
              }
            }
        },
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-000000000000"
                }
            }
        }
    ]
}

Body:
Yeah, so after battling with this for a while, the JSON solution would've have worked but I stuffed it up (as my colleague Doug pointed out) with putting double quotes around the variable within the policy like you can see in the last code snippet ("${local.ips2}")
Here's the working config:

locals {

ips = "${jsonencode(split(",", join(",", formatlist("%s/32", var.web_ips), list(var.vpc_cidr), var.allowed_sources, formatlist("%s/32", list(var.vpn_ip)))))}"
}

resource "aws_s3_bucket_policy" "bucket" {
  bucket = "${aws_s3_bucket.bucket.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "Policy000000000000",
    "Statement": [
        {
            "Sid": "Stmt00000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": ${local.ips} <<<< NO QUOTES HERE!
              }
            }
        },
        {
            "Sid": "Stmt0000000000",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucket/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceVpc": "vpc-00000000000"
                }
            }
        }
    ]
}
POLICY
}

Hope this helps anyone out there


问:
How can I set session timeout for 2-3 days in PHP?
I would like to set my sessions to last for 2-3 days so that my users will not have to login to get data after days of being idle.

Please help me with the code to achieve this.

答:
You can do by,

```<code>ini_set('session.gc_maxlifetime', 2*60*60*24); //2 days
</code>```

But as session will destroy as soon as your user close the browser alternate you can use cookies.

```<code>setcookie("TestCookie", $value, time() + 2*60*60*24);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can do by,

ini_set('session.gc_maxlifetime', 2*60*60*24); //2 days

But as session will destroy as soon as your user close the browser alternate you can use cookies.

setcookie("TestCookie", $value, time() + 2*60*60*24);


问:
SQLServer differential backup and restore
I have a scenario in which I need to maintain a replica of existing database.
Is there a solution to achieve the below mentioned approach.
1. Take a full back once and restore to a destination database.
2. Scheduled( ex: Every day) differential backup(Only the data which has changed since last backup) of the source database and restore into the destination database

This is to avoid taking full backup and restore each time.

答:
You can consider configuring an availability group and use a secondary SQL server instance with asynchronous data sync. This should be considered only if the primary(original live SQL server) and secondary servers are in the same location\data centre. So you don't need to take backup-restore or do any extra work other than properly configuring it at the first time.

If that is not the case (copy should be available in another location\data center), it would be better to go with configuring log shipping.

First option is a lot better because it would contain the exact copy of the primary database (with a sync delay depending on various factors...probably seconds) and you can directly fail over to the secondary in case of any issues with the primary server.


问:
OpenCL and C++: events not working properly
I'm very lost, but luckily I narrowed the problem to a few lines of code.

I'm defining a class that stores events as pointers in member std::vector<cl::Event*> m_lastaccesses. In call to operator= between class instances A and B, enqueueWriteBuffer is called with blockingWrite set to CL_FALSE and A.m_lastaccesses[0] as its return event. Before exiting operator= this event is copied with *B.m_lastaccesses[1]=*A.m_lastaccesses[0], and operator= is exited.

If I change CL_FALSE to CL_TRUE or call A.m_lastaccesses[0]->wait() before exiting operator= the host effectively waits for the data transfer and everything works fine. If I instead leave CL_FALSE and call A.m_lastaccesses[0]->wait() right after exiting operator= the host doesn't wait, even though I verify that A.m_lastaccesses[0] points to the same memory address as before.

My conjecture is that some reference count works unexpectedly and cl::Event is freed or modified by OpenCL's C++ wrapper

答:
So... you have a vector of pointers:

std::vector<cl::Event*> m_lastaccesses

... and you're copying pointer contents:

*B.m_lastaccesses[1]=*A.m_lastaccesses[0]

... how do you know B.m_lastaccesses[1] is a valid pointer ? If it is a valid pointer, what happens to the instance stored there when that line of code overwrites it ? Is this the actual code, because i'm surprised it works at all...

My conjecture is that some reference count works unexpectedly

Perhaps. My conjecture is that you're messing with pointers and pointer contents, and somewhere it blows up. And i don't really see a good reason to use pointers here; i'd simply store cl::Event objects directly. The classes in cl2.hpp usually only store a single pointer to the underlying CL object, copying/deleting them is cheap (only results in clRetain/clRelease) and you can avoid even those clRetain/clRelease calls with move-assignments. In a way, cl::Event acts as a "smart" pointer.

Oh, and you can always take a look at cl2.hpp source. It's not that complicated.


问:
Expand a column entry and adding values from one or more rows in pandas
I have a data frame with entries that have the same meaning, I'd like to get them in the same row(and column).
My mock df:

```<code>my = pd.DataFrame(
{'fruit': ['Apple', 'Banana', 'Pomme', 'aeble', 'Banan', 'Orange', 'Apelsin'],
'bites': [1, 2, 3, 1, 2, 3, 4]})
</code>```

and what I would like it to be:

The closest I've gotten is

```<code>my.loc['Apple'] +=my.loc['Pomme'] += my.loc['aeble']
</code>```

But I am wondering if there is an easier way.

答:
An alternative could be to create a third column to identify your fruit and then do a groupby :

```<code>my = pd.DataFrame(
{'fruit': ['Apple', 'Banana', 'Pomme', 'aeble', 'Banan', 'Orange', 'Apelsin'],
'bites': [1, 2, 3, 1, 2, 3, 4]})

#Create new column
my['Type Fruit'] = ['Apple', 'Bannana', 'Apple', 'Apple', 'Bannana', 'Orange', 'Orange']
# Group by fruit type
fruit_type = my.groupby(['Type Fruit'])['bites'].agg('sum')

In [1] : print(fruit_type )
Out[1] : Type Fruit
Apple      5
Bannana    4
Orange     7
</code>```

The idea of @Chris to use google translate could also be used in this method to create the third column :

```<code>from googletrans import Translator
translator = Translator()

my['Type Fruit'] = [x.text for x in translator.translate(my['fruit'].unique().tolist())]

# Group by fruit type
fruit_type = my.groupby(['Type Fruit'])['bites'].agg('sum')
</code>```

Body:
I have a data frame with entries that have the same meaning, I'd like to get them in the same row(and column).
My mock df:

my = pd.DataFrame(
{'fruit': ['Apple', 'Banana', 'Pomme', 'aeble', 'Banan', 'Orange', 'Apelsin'],
'bites': [1, 2, 3, 1, 2, 3, 4]})

and what I would like it to be:

The closest I've gotten is

my.loc['Apple'] +=my.loc['Pomme'] += my.loc['aeble']

But I am wondering if there is an easier way.

Body:
An alternative could be to create a third column to identify your fruit and then do a groupby :

my = pd.DataFrame(
{'fruit': ['Apple', 'Banana', 'Pomme', 'aeble', 'Banan', 'Orange', 'Apelsin'],
'bites': [1, 2, 3, 1, 2, 3, 4]})

#Create new column
my['Type Fruit'] = ['Apple', 'Bannana', 'Apple', 'Apple', 'Bannana', 'Orange', 'Orange']
# Group by fruit type
fruit_type = my.groupby(['Type Fruit'])['bites'].agg('sum')

In [1] : print(fruit_type )
Out[1] : Type Fruit
Apple      5
Bannana    4
Orange     7

The idea of @Chris to use google translate could also be used in this method to create the third column :

from googletrans import Translator
translator = Translator()

my['Type Fruit'] = [x.text for x in translator.translate(my['fruit'].unique().tolist())]

# Group by fruit type
fruit_type = my.groupby(['Type Fruit'])['bites'].agg('sum')


问:
Delegates: Predicate vs. Action vs. Func
Can someone provide a good explanation (hopefully with examples) of these 3 most important delegates:

Predicate

Action

Func

答:
A simple example about the arguments and what retutn each type

This Func take two int arguments and return an int.Func always has return type

```<code> Func<int, int, int> sum = (a, b) => a + b;
 Console.WriteLine(sum(3, 5));//Print 8
</code>```

In this case func doesn't have arguments but return a string

```<code>Func<string> print = () => "Hello world";
Console.WriteLine(print());//Print Hello world
</code>```

This Action take two int arguments and return void

```<code>Action<int, int> displayInput = (x, y) => Console.WriteLine("First number is :" + x + " , Second number is "+ y);
displayInput(4, 6); //Print First number is :4 , Second number is :6
</code>```

This Predicate take one argument and always return bool.Generally Predicates always return bool.

```<code>Predicate<int> isPositive = (x) => x > 0;
Console.WriteLine(isPositive(5));//Print True
</code>```

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

Body:
A simple example about the arguments and what retutn each type

This Func take two int arguments and return an int.Func always has return type

 Func<int, int, int> sum = (a, b) => a + b;
 Console.WriteLine(sum(3, 5));//Print 8

In this case func doesn't have arguments but return a string

Func<string> print = () => "Hello world";
Console.WriteLine(print());//Print Hello world

This Action take two int arguments and return void

Action<int, int> displayInput = (x, y) => Console.WriteLine("First number is :" + x + " , Second number is "+ y);
displayInput(4, 6); //Print First number is :4 , Second number is :6

This Predicate take one argument and always return bool.Generally Predicates always return bool.

Predicate<int> isPositive = (x) => x > 0;
Console.WriteLine(isPositive(5));//Print True


问:
CountA function parameters
I'm debugging an VBA code issue and I have found the following line of code for which I don't understand the meaning.

```<code>=COUNTA(R[-1]C[3]:R[-1]C[31])
</code>```

How can counting the number of empty cells can contain a reference to a negative cell (R[-1]).

答:
General Notes:

R represent the rows

C represent the columns

In order to count Blank cells is better to use =COUNTBLANK()

Negative:

Above the cell that you have selected

Left from the cell that you have selected

Positive:

Below the cell that you have selected

Right from the cell that you have selected

Example:

Image:

Code:

```<code>Option Explicit

Sub test()

    With ThisWorkbook.Worksheets("Sheet1").Range("C1")
        .FormulaR1C1 = "=COUNTBLANK(R[2]C[-2]:R[8]C[-2])"
    End With

End Sub
</code>```

So,

Selected cell: C3

Range: (A3:A9)

R2 & R8 are positive because are below selected cell

C[-2] is negative because are left from the selected cell

Title: CountA function parameters

Body:
I'm debugging an VBA code issue and I have found the following line of code for which I don't understand the meaning.

=COUNTA(R[-1]C[3]:R[-1]C[31])

How can counting the number of empty cells can contain a reference to a negative cell (R[-1]).

Body:
General Notes:

R represent the rows

C represent the columns

In order to count Blank cells is better to use =COUNTBLANK()

Negative:

Above the cell that you have selected

Left from the cell that you have selected

Positive:

Below the cell that you have selected

Right from the cell that you have selected

Example:

Image:

Code:

Option Explicit

Sub test()

    With ThisWorkbook.Worksheets("Sheet1").Range("C1")
        .FormulaR1C1 = "=COUNTBLANK(R[2]C[-2]:R[8]C[-2])"
    End With

End Sub

So,

Selected cell: C3

Range: (A3:A9)

R2 & R8 are positive because are below selected cell

C[-2] is negative because are left from the selected cell


问:
SmartPointer : cast between base and derived classes
Say you have a function like this :

```<code>SmartPtr<A> doSomething(SmartPtr<A> a);
</code>```

And classes like this :

```<code>class A { }
class B : public A { }
</code>```

And now I do this :

```<code>SmartPtr<A> foo = new B();
doSomething(foo);
</code>```

Now, I would like to get back a SmartPtr object from doSomething.

```<code>SmartPtr<B> b = doSomething(foo);
</code>```

Is it possible ? What kind of casting do I have to do ?

Right now, I just found something I believe ugly :

```<code>B* b = (B*)doSomething().get()
</code>```

Important notes :  I do not have any access to SmartPtr and doSomething() code.

答:
You can define your own SmartPtrCast template function which does something like:

```<code>template <typename DestT, typename SrcT>
inline SmartPtr<DestT> SmartPtrCast(const SmartPtr<SrcT> &src)
{
    return SmartPtr<DestT>(static_cast<DestT*>(src.get()));
}
</code>```

Then, all you have to do cast gracefully from A to B is:

```<code>SmartPtr<B> b = SmartPtrCast<B>(doSomething(foo));
</code>```

Caveat Emptor:
This will only work if the smart pointer returned by doSomething() is referenced somewhere else, and is not destroyed when it goes out of scope. Judging by your example, this is the case, but it's still not as graceful, and it should be noted that the two pointers won't share their reference counting (so if one of them gets destroyed, the second will lose its data).

A better solution is either to detach one of the pointers (if SmartPtr has a detach method). An even better solution (if you don't have a detach method or if you want to share the reference count) is to use a wrapper class:

```<code>template <typename SrcT, typename DestT>
class CastedSmartPtr
{
private:
    SmartPtr<SrcT> ptr;
public:
    CastedSmartPtr(const SmartPtr<SrcT>& src)
    {
        ptr = src;
    }

    DestT& operator* () const
    {
        return *(static_cast<DestT*> >(ptr.get()));
    }

    DestT* operator->() const
    {
         return static_cast<DestT*> >(ptr.get());
    }

    DestT* get() const
    {
        return static_cast<DestT*> >(ptr.get());
    }
}

template <typename DestT, typename SrcT>
inline SmartPtr<DestT> SmartPtrCast(const SmartPtr<SrcT>& src)
{
    return CastedSmartPtr<SrcT, DestT>(src);
}
</code>```

This will use a SmartPtr internally (so reference count is properly shared) and static_cast it to internally to DestT (with no performance impact). If you want to use dynamic_cast, you can do it only once, in the constructor, to avoid unnecessary overhead. You may also want to add additional method to the wrapper such as copy constructor, assignment operator, detach method, etc.

Body:
Say you have a function like this :

SmartPtr doSomething(SmartPtr a);

And classes like this :

class A { }
class B : public A { }

And now I do this :

SmartPtr foo = new B();
doSomething(foo);

Now, I would like to get back a SmartPtr object from doSomething.

SmartPtr b = doSomething(foo);

Is it possible ? What kind of casting do I have to do ?

Right now, I just found something I believe ugly :

B* b = (B*)doSomething().get()

Important notes :  I do not have any access to SmartPtr and doSomething() code.

Body:
You can define your own SmartPtrCast template function which does something like:

template <typename DestT, typename SrcT>
inline SmartPtr<DestT> SmartPtrCast(const SmartPtr<SrcT> &src)
{
    return SmartPtr<DestT>(static_cast<DestT*>(src.get()));
}

Then, all you have to do cast gracefully from A to B is:

SmartPtr<B> b = SmartPtrCast<B>(doSomething(foo));

Caveat Emptor:
This will only work if the smart pointer returned by doSomething() is referenced somewhere else, and is not destroyed when it goes out of scope. Judging by your example, this is the case, but it's still not as graceful, and it should be noted that the two pointers won't share their reference counting (so if one of them gets destroyed, the second will lose its data).

A better solution is either to detach one of the pointers (if SmartPtr has a detach method). An even better solution (if you don't have a detach method or if you want to share the reference count) is to use a wrapper class:

template <typename SrcT, typename DestT>
class CastedSmartPtr
{
private:
    SmartPtr<SrcT> ptr;
public:
    CastedSmartPtr(const SmartPtr<SrcT>& src)
    {
        ptr = src;
    }

    DestT& operator* () const
    {
        return *(static_cast<DestT*> >(ptr.get()));
    }

    DestT* operator->() const
    {
         return static_cast<DestT*> >(ptr.get());
    }

    DestT* get() const
    {
        return static_cast<DestT*> >(ptr.get());
    }
}

template <typename DestT, typename SrcT>
inline SmartPtr<DestT> SmartPtrCast(const SmartPtr<SrcT>& src)
{
    return CastedSmartPtr<SrcT, DestT>(src);
}

This will use a SmartPtr internally (so reference count is properly shared) and static_cast it to internally to DestT (with no performance impact). If you want to use dynamic_cast, you can do it only once, in the constructor, to avoid unnecessary overhead. You may also want to add additional method to the wrapper such as copy constructor, assignment operator, detach method, etc.


问:
Sitecore 9.1 Installation errors
Install-SitecoreConfiguration : Cannot remove item C:\solr-7.6.0\server\solr\mhp_xdb\data\index\write.lock: Access to
the path 'write.lock' is denied.

enter image description here

答: remove the core from solr , (first unload it from solr instance and then remove the core folder ) , and then try to run the script again </p>

Title: Sitecore 9.1 Installation errors


答:
First convert column by to_datetime and then DataFrame.resample by MS for starts of months, last change  format of DatetimeIndex to MM/YYY by DatetimeIndex.strftime:

```<code>df['datetime'] = pd.to_datetime(df['datetime'], format='%d/%m/%Y %H:%M')

df = df.resample('MS', on='datetime').mean()
df.index = df.index.strftime('%m/%Y')
print (df)
         val1      val2  val3  val4  val5      val6      val7  val8  val9  \
06/2017   0.0  0.000000   0.0   0.0   0.0  0.000000  0.000000   0.0   0.0
07/2017   NaN       NaN   NaN   NaN   NaN       NaN       NaN   NaN   NaN
08/2017   0.0  0.143333   0.0   0.0   0.0  0.186667  0.183333   0.0   0.0

          val10  val11     val12
06/2017  0.0115    0.0  0.035667
07/2017     NaN    NaN       NaN
08/2017  0.0120    0.0  0.034000
</code>```

Or pass converted column of datetimes by Series.dt.strftime to groupby and aggregate mean:

```<code>df = df.groupby(df['datetime'].dt.strftime('%m/%Y')).mean()
print (df)
          val1      val2  val3  val4  val5      val6      val7  val8  val9  \
datetime
06/2017      0  0.000000     0     0     0  0.000000  0.000000     0     0
08/2017      0  0.143333     0     0     0  0.186667  0.183333     0     0

           val10  val11     val12
datetime
06/2017   0.0115      0  0.035667
08/2017   0.0120      0  0.034000
</code>```

Title: Average a minute-wise time-series dataset monthly with Panda

Body:
I have got a very large minute-wise time series dataset(for 3 months) which is in the following format

datetime,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12
1/06/2017 0:00,0,0,0,0,0,0,0,0,0,0.011,0,0.036
1/06/2017 0:01,0,0,0,0,0,0,0,0,0,0.011,0,0.036
...
1/06/2017 23:59,0,0,0,0,0,0,0,0,0,0.011,0,0.035
2/06/2017 0:00,0,0,0,0,0,0,0,0,0,0.014,0,0.036
2/06/2017 0:01,0,0,0,0,0,0,0,0,0,0.011,0,0.036
...
2/06/2017 23:59,0,0,0,0,0,0,0,0,0,0.011,0,0.035
....
31/08/2017 0:00,0,0.2,0,0,0,0.56,0,0,0,0.014,0,0.036
31/08/2017 0:01,0,0.23,0,0,0,0,0,0,0,0.011,0,0.032
...
31/08/2017 23:59,0,0,0,0,0,0,.55,0,0,0.011,0,0.034

what is the most efficient way of getting the average of each column per each month using panda?
expected output would be

month,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12
06/2017,0,0,0,0,0,0,0,0,0,0.011,0,0.036
07/2017,0,0,0,0,0,0,0,0,0,0.014,0,0.036
08/2017,0,0,0.21,0,0,0,0,0.52,0,0.011,0,0.036

At the moment what I'm doing is read the dataset day by day and then get an accumulated dataset of days and then divide it by the no of days per month. But this very inefficient and take a lot of time.

Body:
First convert column by to_datetime and then DataFrame.resample by MS for starts of months, last change  format of DatetimeIndex to MM/YYY by DatetimeIndex.strftime:

df['datetime'] = pd.to_datetime(df['datetime'], format='%d/%m/%Y %H:%M')

df = df.resample('MS', on='datetime').mean()
df.index = df.index.strftime('%m/%Y')
print (df)
         val1      val2  val3  val4  val5      val6      val7  val8  val9  \
06/2017   0.0  0.000000   0.0   0.0   0.0  0.000000  0.000000   0.0   0.0
07/2017   NaN       NaN   NaN   NaN   NaN       NaN       NaN   NaN   NaN
08/2017   0.0  0.143333   0.0   0.0   0.0  0.186667  0.183333   0.0   0.0

          val10  val11     val12
06/2017  0.0115    0.0  0.035667
07/2017     NaN    NaN       NaN
08/2017  0.0120    0.0  0.034000

Or pass converted column of datetimes by Series.dt.strftime to groupby and aggregate mean:

df = df.groupby(df['datetime'].dt.strftime('%m/%Y')).mean()
print (df)
          val1      val2  val3  val4  val5      val6      val7  val8  val9  \
datetime
06/2017      0  0.000000     0     0     0  0.000000  0.000000     0     0
08/2017      0  0.143333     0     0     0  0.186667  0.183333     0     0

           val10  val11     val12
datetime
06/2017   0.0115      0  0.035667
08/2017   0.0120      0  0.034000


问:
How can I pass the isConnect state to the other class
Now I have App.js is my init page.
I want listen internet status from net_provide.js.
If isConnected is true then APP.js show renderLoadingView()
If not then APP.js show renderDisconnectView() like below code
But I don't know how to pass the isConnected from net_provide.js to APP.js

Can anyone help me? Thank you!

App.js

```<code>renderLoadingView() {
    _aesDecryptWithMode(_aesEncryptWithMode('test'))
    getFcmToken()
    return (
      <View style={ styles.container }>
        <NetworkNotifier
          offlineText="無網路連線"
          onlineText="網路已連線"
          position="top" />
        <Network_provider/>
        <Text>
          Loading Events....
          { '\n' }
        </Text>
      </View>
    )
  }

  renderDisconnectView() {
    return (
      <View style={ styles.container }>
        <Network_provider/>
        <Text>
          diss
          { '\n' }
        </Text>
      </View>
    )

  }
</code>```

The problem is here
this.props.Connected

```<code>  render() {
    return (
   if (this.props.isConnected) {
     return this.renderLoadingView();
   }
   if (!this.props.isConnected) {
     return this.renderDisconnectView();
   }

  }
</code>```

And below is network_provider.js

```<code>export class Network_provider extends React.PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({
        isConnected
      });
    } else {
      this.setState({
        isConnected
      });
    }
  };

  render() {
    return <App Connected={ this.state.isConnected } />;
  }
}
</code>```

答:
You can use Function as Children pattern for that.

network_provider.js

```<code>render() {
  const { children } = this.props;
  const { isConnected } = this.state;

  return children && children({isConnected});
}
</code>```

App.js

```<code><Network_provider>
  {({isConnected}) => {
    if(isConnected) return this.renderDisconnectView();
    return this.renderLoadingView();
    }
  }
</Network_provider>
</code>```

Body:
Now I have App.js is my init page.
I want listen internet status from net_provide.js.
If isConnected is true then APP.js show renderLoadingView()
If not then APP.js show renderDisconnectView() like below code
But I don't know how to pass the isConnected from net_provide.js to APP.js

Can anyone help me? Thank you!

App.js

renderLoadingView() {
    _aesDecryptWithMode(_aesEncryptWithMode('test'))
    getFcmToken()
    return (
      <View style={ styles.container }>
        <NetworkNotifier
          offlineText="無網路連線"
          onlineText="網路已連線"
          position="top" />
        <Network_provider/>
        <Text>
          Loading Events....
          { '\n' }
        </Text>
      </View>
    )
  }

  renderDisconnectView() {
    return (
      <View style={ styles.container }>
        <Network_provider/>
        <Text>
          diss
          { '\n' }
        </Text>
      </View>
    )

  }

The problem is here
this.props.Connected

  render() {
    return (
   if (this.props.isConnected) {
     return this.renderLoadingView();
   }
   if (!this.props.isConnected) {
     return this.renderDisconnectView();
   }

  }

And below is network_provider.js

export class Network_provider extends React.PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({
        isConnected
      });
    } else {
      this.setState({
        isConnected
      });
    }
  };

  render() {
    return <App Connected={ this.state.isConnected } />;
  }
}

Body:
You can use Function as Children pattern for that.

network_provider.js

render() {
  const { children } = this.props;
  const { isConnected } = this.state;

  return children && children({isConnected});
}

App.js

<Network_provider>
  {({isConnected}) => {
    if(isConnected) return this.renderDisconnectView();
    return this.renderLoadingView();
    }
  }
</Network_provider>


问:
How do I push a field of an object into another array of object
I know how to operate on array of objects but never had the necessity to populate an array data into another. I need to populate firstname + lastname field into name field of birth array

```<code>let birth = [
    {name: '' }
]
</code>```

firstly my array is empty and i want to poplulate it with these datas

```<code>let names = [
   {firstname: "Julien", lastname: "DEHAIS"},
   {firstname: "Cyril", lastname: "GUIGUIAN"},
   {firstname: "Pascal", lastname: "BOUTRIN"},
   {firstname: "Franck", lastname: "BORDERIE"},
   {firstname: "Arnold", lastname: "GIRARD"}
]
</code>```

to get something like this

```<code>let birth = [
    {name: 'Julien DEHAIS' },
    {name: 'Cyril GUIGUIAN' },
    {name: 'Pascal BOUTRIN' },
    {name: 'Franck BORDERIE' },
    {name: 'Arnold GIRARD' }
]
</code>```

Kindly someone help me in this please

答:
You can use map() and return a new object with name property

let names = [ {firstname: "Julien", lastname: "DEHAIS"}, {firstname: "Cyril", lastname: "GUIGUIAN"}, {firstname: "Pascal", lastname: "BOUTRIN"}, {firstname: "Franck", lastname: "BORDERIE"}, {firstname: "Arnold", lastname: "GIRARD"} ]

const res = names.map(x => ({name: `${x.firstname} ${x.lastname}`}))
console.log(res)```

Body:
I know how to operate on array of objects but never had the necessity to populate an array data into another. I need to populate firstname + lastname field into name field of birth array

let birth = [
    {name: '' }
]

firstly my array is empty and i want to poplulate it with these datas

let names = [
   {firstname: "Julien", lastname: "DEHAIS"},
   {firstname: "Cyril", lastname: "GUIGUIAN"},
   {firstname: "Pascal", lastname: "BOUTRIN"},
   {firstname: "Franck", lastname: "BORDERIE"},
   {firstname: "Arnold", lastname: "GIRARD"}
]

to get something like this

let birth = [
    {name: 'Julien DEHAIS' },
    {name: 'Cyril GUIGUIAN' },
    {name: 'Pascal BOUTRIN' },
    {name: 'Franck BORDERIE' },
    {name: 'Arnold GIRARD' }
]

Kindly someone help me in this please


问:
Implementation of String.prototype.startsWith in ClojureScript
I need to convert this Javascript code into ClojureScript. I'm having some trouble with the this keyword.

Here's my JS:

```<code>if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}
</code>```

I'm getting a Object doesn't support property or method 'startsWith' error with the Google Closure compiler in advanced mode so I need to add this code. (IE 11)

答:
ClojureScript already has clojure.string/starts-with?:

```<code>$ clj -Sdeps '{:deps {org.clojure/clojurescript {:mvn/version "RELEASE"}}}' -m cljs.main -re node
ClojureScript 1.10.520
cljs.user=> (require '[clojure.string :as str])
nil
cljs.user=> (str/starts-with? "foobar" "foo")
true
</code>```

re-find can also help you find it.

Body:
I need to convert this Javascript code into ClojureScript. I'm having some trouble with the this keyword.

Here's my JS:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

I'm getting a Object doesn't support property or method 'startsWith' error with the Google Closure compiler in advanced mode so I need to add this code. (IE 11)

Body:
ClojureScript already has clojure.string/starts-with?:

$ clj -Sdeps '{:deps {org.clojure/clojurescript {:mvn/version "RELEASE"}}}' -m cljs.main -re node
ClojureScript 1.10.520
cljs.user=> (require '[clojure.string :as str])
nil
cljs.user=> (str/starts-with? "foobar" "foo")
true

re-find can also help you find it.


问:
How to make a foreach button in vba that saves values for an array of textboxes?
I have an List in a different form , and the values that are located inside the text boxes are retrieved from a list in a different form , my problem is that i cannot delete the values all at once because they come from a view and i'm not allowed to change multiple tables all at once, so my solution is to create an array with all my text boxes and to turn the value to null 1 by 1 and save them individual so that i don't get that error.

I've tried different solutions like saving everything at once.

Private Sub Comando28_Click()
Dim strTextBoxes(1 To 5) As String

tbAplic = Me.TbUAplicacion.Value

tbUsr = Me.tbuUsuario.Value

tbMail = Me.tbuMailUsuario.Value

tbnmbre = Me.tbuNombrePersona.Value

tbAppld = Me.tbuApellidosPersona.Value

tbDni = Me.tbuDNIPersona.Value

Dim ITM As strTextBoxes.ITM

For Each ITM In strTextBoxes.ITM
    If ITM = Not Null Then ITM = Null
    Guardar_Click '<---- this is a macro which I use to save the items new value
Next ITM

End Sub
```

the error it gives me when pressing the button that should make the action is as follows:

the user-defined type has not been defined

答:
Try this:</p>

```<code>Private Sub Comando28_Click()

    Dim strTextBoxes(1 To 5) As String

    tbAplic = Me.TbUAplicacion.Value

    tbUsr = Me.tbuUsuario.Value

    tbMail = Me.tbuMailUsuario.Value

    tbnmbre = Me.tbuNombrePersona.Value

    tbAppld = Me.tbuApellidosPersona.Value

    tbDni = Me.tbuDNIPersona.Value

    Dim ITM As String
    Dim Item As Long

    For Item = LBound(strTextBoxes) To UBound(strTextBoxes)
        ITM = strTextBoxes(Item)
        If ITM <> "" Then ITM = ""
        Guardar_Click '<---- this is a macro which I use to save the items new value
    Next

End Sub
</code>```

Body:
I have an List in a different form , and the values that are located inside the text boxes are retrieved from a list in a different form , my problem is that i cannot delete the values all at once because they come from a view and i'm not allowed to change multiple tables all at once, so my solution is to create an array with all my text boxes and to turn the value to null 1 by 1 and save them individual so that i don't get that error.

I've tried different solutions like saving everything at once.

Private Sub Comando28_Click()
Dim strTextBoxes(1 To 5) As String

tbAplic = Me.TbUAplicacion.Value

tbUsr = Me.tbuUsuario.Value

tbMail = Me.tbuMailUsuario.Value

tbnmbre = Me.tbuNombrePersona.Value

tbAppld = Me.tbuApellidosPersona.Value

tbDni = Me.tbuDNIPersona.Value

Dim ITM As strTextBoxes.ITM

For Each ITM In strTextBoxes.ITM
    If ITM = Not Null Then ITM = Null
    Guardar_Click '<---- this is a macro which I use to save the items new value
Next ITM

End Sub

the error it gives me when pressing the button that should make the action is as follows:

the user-defined type has not been defined

Body:
Try this:

Private Sub Comando28_Click()

    Dim strTextBoxes(1 To 5) As String

    tbAplic = Me.TbUAplicacion.Value

    tbUsr = Me.tbuUsuario.Value

    tbMail = Me.tbuMailUsuario.Value

    tbnmbre = Me.tbuNombrePersona.Value

    tbAppld = Me.tbuApellidosPersona.Value

    tbDni = Me.tbuDNIPersona.Value

    Dim ITM As String
    Dim Item As Long

    For Item = LBound(strTextBoxes) To UBound(strTextBoxes)
        ITM = strTextBoxes(Item)
        If ITM <> "" Then ITM = ""
        Guardar_Click '<---- this is a macro which I use to save the items new value
    Next

End Sub


问:
How to fill a div but maintain aspect ratio for child divs
I have the following page showing the HTML as well as the CSS.  I want the five buttons on the left (div id=button1..5) to always be square at any aspect ratio and resolution of the screen. Also, I want the five buttons to always fill the middle div (id=menu). In fact, I AM ABLE TO DO BOTH, but NOT TOGETHER! The latter is easy with Flex and the former as you can see I have done in the code below.  I have looked at several examples on SO, notably this one, but they don't do what I am talking about.

Any suggestions?
Note: Preferably no Javascript...

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
html, body {
    margin:0;
    padding:0;
}
#container {
    display:flex;
    flex-direction: column;
    background-color: #444;
    height:100vh;
    width:100%;
    margin:0;
    padding:0;
}
#top{
    background-color: #777;
    height:5%;
    width:100%;
    margin:0;
    padding:0;
}
#main{
    background-color: #DDD;
    height:100%;
    width:100%;
    margin:0;
    padding:0;
    align-items: stretch;
}
#menu{
    display:flex;
    flex-direction: column;
    background-color: #FFF;
    height:100%;
    width:10%;
    margin:0;
    padding:0;
}
.buttons{
    display:inline-block;
    position:relative;
    height:0;
    margin:0;
    padding-bottom:100%;
}
#button1{background-color:blue; margin:2px 0 2px 0;}
#button2{background-color:green; margin:2px 0 2px 0;}
#button3{background-color:red; margin:2px 0 2px 0;}
#button4{background-color:black; margin:2px 0 2px 0;}
#button5{background-color:orange; margin:2px 0 2px 0;}
.img-container {
  justify-content: center;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  padding:16px;
}
.img-container .img-to-fit {
  flex: 1;
  height: 100%;
}

.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}

#bottom {
    height:2%;
    display:flex;
}
#bottom1{background-color:blue;}
#bottom2{background-color:green;}
#bottom3{background-color:red;}
#bottom4{background-color:white;}
#bottom5{background-color:orange;}
.bottoms{
    height:100%;
    width:20%;
    margin:0;
    padding:0;
}
</style>
</head>

<body>
    <div id="container">
        <div id="top"/>
        <div id="main">
             <div id="menu">
                <div id="button1" class="buttons">
                     <div class="img-container">
                         <img class="img-to-fit" src="parcel.png" />
                     </div>
                </div>
                <div id="button2" class="buttons"/>
                <div id="button3" class="buttons"/>
                <div id="button4" class="buttons"/>
                <div id="button5" class="buttons"/>
            </div>
        </div>
        <div id="bottom">
                <div id="bottom1" class="bottoms"/>
                <div id="bottom2" class="bottoms"/>
                <div id="bottom3" class="bottoms"/>
                <div id="bottom4" class="bottoms"/>
                <div id="bottom5" class="bottoms"/>
        </div>
    </div>
</body>
</html>
</code>```

答:
You already have squared buttons.
The thing you miss is the width of those buttons but it's something you can calculate easily.

The div #menu has a height of 100vh - 7%, it means that your buttons should have a height of (100vh - 7%) / 5.

Their height ise equal to their width, so if they have width: calc(93vh / 5) they will fill the height of the #menu.

Therefore, you can simply add #menu { width: calc(93vh / 5)}

I would also remove #main { height: 100% }, it's not needed.

html, body {
    margin:0;
    padding:0;
}
#container {
    display:flex;
    flex-direction: column;
    background-color: #444;
    height:100vh;
    width:100%;
    margin:0;
    padding:0;
}
#top{
    background-color: #777;
    height:5%;
    width:100%;
    margin:0;
    padding:0;
}
#main{
    background-color: #DDD;
    /* height:100%; not needed */
    width:100%;
    margin:0;
    padding:0;
    align-items: stretch;
}
#menu{
    display:flex;
    flex-direction: column;
    background-color: #FFF;
    height:100%;
    width: calc((93vh) / 5); // Width of the menu = Height of the menu divided by the number of buttons
    margin:0;
    padding:0;
}
.buttons{
    display:block;
    position:relative;
    height:0;
    margin:0;
    padding-bottom:100%;
}
#button1{background-color:blue; margin:2px 0 2px 0;}
#button2{background-color:green; margin:2px 0 2px 0;}
#button3{background-color:red; margin:2px 0 2px 0;}
#button4{background-color:black; margin:2px 0 2px 0;}
#button5{background-color:orange; margin:2px 0 2px 0;}
.img-container {
  justify-content: center;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  padding:16px;
}
.img-container .img-to-fit {
  flex: 1;
  height: 100%;
}

.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}

#bottom {
    height:2%;
    display:flex;
}
#bottom1{background-color:blue;}
#bottom2{background-color:green;}
#bottom3{background-color:red;}
#bottom4{background-color:white;}
#bottom5{background-color:orange;}
.bottoms{
    height:100%;
    width:20%;
    margin:0;
    padding:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
    <div id="top">
    </div>
    <div id="main">
        <div id="menu">
            <div id="button1" class="buttons">
                <div class="img-container">
                  <img class="img-to-fit" src="parcel.png" />
                </div>
            </div>
            <div id="button2" class="buttons">

            </div>
            <div id="button3" class="buttons">

            </div>
            <div id="button4" class="buttons">

            </div>
            <div id="button5" class="buttons">

            </div>
        </div>
    </div>
    <div id="bottom">
            <div id="bottom1" class="bottoms">

            </div>
            <div id="bottom2" class="bottoms">

            </div>
            <div id="bottom3" class="bottoms">

            </div>
            <div id="bottom4" class="bottoms">

            </div>
            <div id="bottom5" class="bottoms">

            </div>
    </div>
</div></code>```

Body:
I have the following page showing the HTML as well as the CSS.  I want the five buttons on the left (div id=button1..5) to always be square at any aspect ratio and resolution of the screen. Also, I want the five buttons to always fill the middle div (id=menu). In fact, I AM ABLE TO DO BOTH, but NOT TOGETHER! The latter is easy with Flex and the former as you can see I have done in the code below.  I have looked at several examples on SO, notably this one, but they don't do what I am talking about.

Any suggestions?
Note: Preferably no Javascript...

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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

Body:
You already have squared buttons.
The thing you miss is the width of those buttons but it's something you can calculate easily.

The div #menu has a height of 100vh - 7%, it means that your buttons should have a height of (100vh - 7%) / 5.

Their height ise equal to their width, so if they have width: calc(93vh / 5) they will fill the height of the #menu.

Therefore, you can simply add #menu { width: calc(93vh / 5)}

I would also remove #main { height: 100% }, it's not needed.

html, body {
    margin:0;
    padding:0;
}
#container {
    display:flex;
    flex-direction: column;
    background-color: #444;
    height:100vh;
    width:100%;
    margin:0;
    padding:0;
}
#top{
    background-color: #777;
    height:5%;
    width:100%;
    margin:0;
    padding:0;
}
#main{
    background-color: #DDD;
    /* height:100%; not needed */
    width:100%;
    margin:0;
    padding:0;
    align-items: stretch;
}
#menu{
    display:flex;
    flex-direction: column;
    background-color: #FFF;
    height:100%;
    width: calc((93vh) / 5); // Width of the menu = Height of the menu divided by the number of buttons
    margin:0;
    padding:0;
}
.buttons{
    display:block;
    position:relative;
    height:0;
    margin:0;
    padding-bottom:100%;
}
#button1{background-color:blue; margin:2px 0 2px 0;}
#button2{background-color:green; margin:2px 0 2px 0;}
#button3{background-color:red; margin:2px 0 2px 0;}
#button4{background-color:black; margin:2px 0 2px 0;}
#button5{background-color:orange; margin:2px 0 2px 0;}
.img-container {
  justify-content: center;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  padding:16px;
}
.img-container .img-to-fit {
  flex: 1;
  height: 100%;
}

.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}

#bottom {
    height:2%;
    display:flex;
}
#bottom1{background-color:blue;}
#bottom2{background-color:green;}
#bottom3{background-color:red;}
#bottom4{background-color:white;}
#bottom5{background-color:orange;}
.bottoms{
    height:100%;
    width:20%;
    margin:0;
    padding:0;
}

<div id="container">
    <div id="top">
    </div>
    <div id="main">
        <div id="menu">
            <div id="button1" class="buttons">
                <div class="img-container">
                  <img class="img-to-fit" src="parcel.png" />
                </div>
            </div>
            <div id="button2" class="buttons">

            </div>
            <div id="button3" class="buttons">

            </div>
            <div id="button4" class="buttons">

            </div>
            <div id="button5" class="buttons">

            </div>
        </div>
    </div>
    <div id="bottom">
            <div id="bottom1" class="bottoms">

            </div>
            <div id="bottom2" class="bottoms">

            </div>
            <div id="bottom3" class="bottoms">

            </div>
            <div id="bottom4" class="bottoms">

            </div>
            <div id="bottom5" class="bottoms">

            </div>
    </div>
</div>


问:
Change Double format - dot to comma
I must change Double format from dot to comma. I try this:

```<code>DecimalFormat df = new DecimalFormat("#,00",
                   DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
                                 selectedCellRow,
                                 Double.valueOf(df.format(value)));
</code>```

but it`s not working. Have you got any ideas how you can change a dot to a comma?

答:
For (i guess) ApachePOI library to set a different CellUnitStyle use this:

CellStyle unitStyle = workbook.createCellStyle();
unitStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("#,##0.00"));
cell.setCellValue(value);
cell.setCellStyle(unit);
```

Following Formats are builtin available:
ApachePOI builtin Formats

Title: Change Double format - dot to comma

Body:
I must change Double format from dot to comma. I try this:

DecimalFormat df = new DecimalFormat("#,00",
                   DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
                                 selectedCellRow,
                                 Double.valueOf(df.format(value)));

but it`s not working. Have you got any ideas how you can change a dot to a comma?

Body:
For (i guess) ApachePOI library to set a different CellUnitStyle use this:

CellStyle unitStyle = workbook.createCellStyle();
unitStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("#,##0.00"));
cell.setCellValue(value);
cell.setCellStyle(unit);

Following Formats are builtin available:
ApachePOI builtin Formats


问:
how to convert list of json object into a single pyspark dataframe?
I'm new to pyspark, I have a list of jsons coming from an api, each json object has same schema(key-value pair). Like this

```<code>[ {'count': 308,
  'next': 'some_url',
  'previous': None,
  'results': [{'assigned_to': 43,
    'category': 'Unused',
    'comments': None,
    'completed_ts': None,
    'created': '2019-05-27T05:14:22.306843Z',
    'description': 'Pollution',
    'display_name': {'admin': False,
     'business_name': 'Test Business',
     'contact_number': 'some_number',
     'dob': None,
     'email': 'some_mail',
     'emp_id': None,
     'first_name': 'Alisha'}}]},
  {'count': 309,
  'next': 'some_url',
  'previous': None,
  'results': [{'assigned_to': 44,
    'category': 'Unused',
    'comments': None,
    'completed_ts': None,
    'created': '2019-05-27T05:14:22.306843Z',
    'description': 'Pollution',
    'display_name': {'admin': False,
     'business_name': 'Test Business',
     'contact_number': 'some_number',
     'dob': None,
     'email': 'some_mail',
     'emp_id': None,
     'first_name': 'Ali'}}]},......}]
</code>```

if it would have been separate json files. I would have created dataframe using

df =spark.read.json('myfile.json')
and then would have merged all dataframes into one. I'm facing issue in converting the datframe directly from list itself. I have used this

```<code>from pyspark.sql import SparkSession
spark= SparkSession.builder.appName("Basics").getOrCreate()
sc= spark.sparkContext
df = pyspark.sql.SQLContext(sc.parallelize(data_list))`
</code>```

It gives me
AttributeError: 'RDD' object has no attribute '_jsc'

答:
I couldn't find a straight forward answer to your problem. But this solution works,

import json
import ast

df = sc.wholeTextFiles(path).map(lambda x:ast.literal_eval(x[1]))\
                            .map(lambda x: json.dumps(x))

df = spark.read.json(df)
```

<p>This will give you output as,</p>

<pre class="lang-py prettyprint-override"><code>+-----+--------+--------+--------------------+
|count|    next|previous|             results|
+-----+--------+--------+--------------------+
|  308|some_url|    null|[[43,Unused,null,...|
|  309|some_url|    null|[[44,Unused,null,...|
+-----+--------+--------+--------------------+
</code>```

EDIT:
If it is in a variable, all you have to do is,

import json

df = sc.parallelize(data).map(lambda x: json.dumps(x))
df = spark.read.json(df)
```

Body:
I'm new to pyspark, I have a list of jsons coming from an api, each json object has same schema(key-value pair). Like this

[ {'count': 308,
  'next': 'some_url',
  'previous': None,
  'results': [{'assigned_to': 43,
    'category': 'Unused',
    'comments': None,
    'completed_ts': None,
    'created': '2019-05-27T05:14:22.306843Z',
    'description': 'Pollution',
    'display_name': {'admin': False,
     'business_name': 'Test Business',
     'contact_number': 'some_number',
     'dob': None,
     'email': 'some_mail',
     'emp_id': None,
     'first_name': 'Alisha'}}]},
  {'count': 309,
  'next': 'some_url',
  'previous': None,
  'results': [{'assigned_to': 44,
    'category': 'Unused',
    'comments': None,
    'completed_ts': None,
    'created': '2019-05-27T05:14:22.306843Z',
    'description': 'Pollution',
    'display_name': {'admin': False,
     'business_name': 'Test Business',
     'contact_number': 'some_number',
     'dob': None,
     'email': 'some_mail',
     'emp_id': None,
     'first_name': 'Ali'}}]},......}]

if it would have been separate json files. I would have created dataframe using

df =spark.read.json('myfile.json')
and then would have merged all dataframes into one. I'm facing issue in converting the datframe directly from list itself. I have used this

from pyspark.sql import SparkSession
spark= SparkSession.builder.appName("Basics").getOrCreate()
sc= spark.sparkContext
df = pyspark.sql.SQLContext(sc.parallelize(data_list))`

It gives me
AttributeError: 'RDD' object has no attribute '_jsc'

Body:
I couldn't find a straight forward answer to your problem. But this solution works,

import json
import ast

df = sc.wholeTextFiles(path).map(lambda x:ast.literal_eval(x[1]))\
                            .map(lambda x: json.dumps(x))

df = spark.read.json(df)

This will give you output as,

+-----+--------+--------+--------------------+
|count|    next|previous|             results|
+-----+--------+--------+--------------------+
|  308|some_url|    null|[[43,Unused,null,...|
|  309|some_url|    null|[[44,Unused,null,...|
+-----+--------+--------+--------------------+

EDIT:
If it is in a variable, all you have to do is,

import json

df = sc.parallelize(data).map(lambda x: json.dumps(x))
df = spark.read.json(df)


答:
You have a symbol table in the java doc of DecimalFormat:

Symbol   Location    Localized?    Meaning
------------------------------------------
0        Number      Yes           Digit
#        Number      Yes           Digit, zero shows as absent
.        Number      Yes           Decimal separator or monetary decimal separator
-        Number      Yes           Minus sign
,        Number      Yes           Grouping separator
etc...
```

<p>You were using the grouping separator <code>,</code> but you wanted to use the decimal separator <code>.</code>, so change your string from <code>#,00</code> to <code>#.00</code>:</p>

```DecimalFormat df = new DecimalFormat("#.00", DecimalFormatSymbols.getInstance(Locale.GERMANY));
String format = df.format(3.23456);
System.out.println(format); // prints 3,23
```

Title: Change Double format - dot to comma

Body:
You have a symbol table in the java doc of DecimalFormat:

Symbol   Location    Localized?    Meaning
------------------------------------------
0        Number      Yes           Digit
#        Number      Yes           Digit, zero shows as absent
.        Number      Yes           Decimal separator or monetary decimal separator
-        Number      Yes           Minus sign
,        Number      Yes           Grouping separator
etc...

You were using the grouping separator , but you wanted to use the decimal separator ., so change your string from #,00 to #.00:

DecimalFormat df = new DecimalFormat("#.00", DecimalFormatSymbols.getInstance(Locale.GERMANY));
String format = df.format(3.23456);
System.out.println(format); // prints 3,23


问:
Saving DrawingVisual to an image file with a given DPI
I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it's 2362x1181.

I draw images and shapes with DrawingVisual, then I create a RenderTargetBitmap. The size of the rtb is the size of the Canvas. The dpiX and dpiY are 96. I got correct image resolution only with 96 DPI. When I set it to 300, the canvas become upscale, and cropped to 2362x1181. So, it's not good. I tried to modify the canvas width and height value by dpi factor, but didn't work either.

After the RenderTargetBitmap, I use BitmapEncoder, BitmapFrame, and BinaryWriter. See code below. Working great, but the image DPI value will be 96. I've read a tons of topics about reading DPI, resaving image, using SetResolution, but I don't want to loose quality, I don't want to read file and resave it, I don't want to change pixel width/height, etc.

I just really want to save a DrawingVisual with a given DPI. I could write EXIF data for "X Resolution" (uint=282) and "Y Resoulution" (uint=283), but that didn't affect the Image DPI settings, so eg. Photoshop will read 96, not 300.

```<code>BitmapEncoder encoder = new JpegBitmapEncoder();
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
encoder.Save(stream);
byte[] imageData = stream.ToArray();
using (FileStream fs = new FileStream(path, ...)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(imageData);
bw.Close();
}
}
</code>```

答: I tried to apply DPI scaling to the DrawingVisual, but it produced less image quality. :( Also I tried to set the canvas to 756x378 (the 96 DPI size), then set the RenderTargetBitmap to 2362x1181 and 300 DPI, but that produced less image quality too. So, it seems any downscale then upscale or upscale then downscale are not the best solution. The DrawingVisual must be in the final render size.</p>

Body:
I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it's 2362x1181.

I draw images and shapes with DrawingVisual, then I create a RenderTargetBitmap. The size of the rtb is the size of the Canvas. The dpiX and dpiY are 96. I got correct image resolution only with 96 DPI. When I set it to 300, the canvas become upscale, and cropped to 2362x1181. So, it's not good. I tried to modify the canvas width and height value by dpi factor, but didn't work either.

After the RenderTargetBitmap, I use BitmapEncoder, BitmapFrame, and BinaryWriter. See code below. Working great, but the image DPI value will be 96. I've read a tons of topics about reading DPI, resaving image, using SetResolution, but I don't want to loose quality, I don't want to read file and resave it, I don't want to change pixel width/height, etc.

I just really want to save a DrawingVisual with a given DPI. I could write EXIF data for "X Resolution" (uint=282) and "Y Resoulution" (uint=283), but that didn't affect the Image DPI settings, so eg. Photoshop will read 96, not 300.

BitmapEncoder encoder = new JpegBitmapEncoder();
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
encoder.Save(stream);
byte[] imageData = stream.ToArray();
using (FileStream fs = new FileStream(path, ...)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(imageData);
bw.Close();
}
}


问:
How to change the font colour used inside the chunks when building a tufte book using bookdown?
I am trying to build a book, with 9 chapters. I am using the bookdown::bookdown_site package for that, which I have included in the YAML header in index.Rmd. But when I knit the book, using bookdown::tufte_book2, the pdf file generate the text inside the chunks with different font colors.

When I try to run each chapter individually, using "tufte_handout", the outcome is as expected. Main text and inside chunk text is monochrome and TimesNewRoman.
In rStudio, before build the book, I have tried in Sweave/Program defaults to use both Latex Engines, "xeLaTex" and "pdfLaTex"

YAML header in index.Rmd

```<code>---
title: "Operations Research Using R<br />"
author: "Timothy R. Anderson"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
monofont: Times New Roman
highlight: monochrome
documentclass: book
bibliography: ["Master4Bookdowns.bib"]
---
</code>```

YAML header in each individual ChapterX.Rmd file:

```<code>---
title: 'Chapter 3: More LP Models'
header-includes:
- \usepackage{longtable}
- \usepackage{caption}
monofont: Times New Roman
output:
  tufte::tufte_handout:
    citation_package: natbib
    latex_engine: xelatex
    toc: TRUE
    number_sections: true
    highlight: monochrome
  tufte::tufte_html: default
  tufte::tufte_book:
    citation_package: natbib
    latex_engine: xelatex
    highlight: monochrome
---
</code>```

I expect all document with the same font type and monochrome.

答:
Since bookdown::tufte_book2 is not specified in your main YAML header, I assume you have an _output.yml file that defines the output format. In that case, you have to add highlicht: monochrome there, i.e.:

```<code>bookdown::tufte_book2:
  highlight: monochrome
  [other options]
</code>```

Body:
I am trying to build a book, with 9 chapters. I am using the bookdown::bookdown_site package for that, which I have included in the YAML header in index.Rmd. But when I knit the book, using bookdown::tufte_book2, the pdf file generate the text inside the chunks with different font colors.

When I try to run each chapter individually, using "tufte_handout", the outcome is as expected. Main text and inside chunk text is monochrome and TimesNewRoman.
In rStudio, before build the book, I have tried in Sweave/Program defaults to use both Latex Engines, "xeLaTex" and "pdfLaTex"

YAML header in index.Rmd

---
title: "Operations Research Using R
"
author: "Timothy R. Anderson"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
monofont: Times New Roman
highlight: monochrome
documentclass: book
bibliography: ["Master4Bookdowns.bib"]
---

YAML header in each individual ChapterX.Rmd file:

---
title: 'Chapter 3: More LP Models'
header-includes:
- \usepackage{longtable}
- \usepackage{caption}
monofont: Times New Roman
output:
  tufte::tufte_handout:
    citation_package: natbib
    latex_engine: xelatex
    toc: TRUE
    number_sections: true
    highlight: monochrome
  tufte::tufte_html: default
  tufte::tufte_book:
    citation_package: natbib
    latex_engine: xelatex
    highlight: monochrome
---

I expect all document with the same font type and monochrome.

Body:
Since bookdown::tufte_book2 is not specified in your main YAML header, I assume you have an _output.yml file that defines the output format. In that case, you have to add highlicht: monochrome there, i.e.:

bookdown::tufte_book2:
  highlight: monochrome
  [other options]


问:
unable to use accordion in foundation 5
I am trying to use accordion in foundation 5 but still, it's not working. Can anyone guide me where I am doing wrong

```<code><!DOCTYPE html>
<html>
  <head>
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.4.7/css/foundation.min.css">
     <script src = "https://cdnjs.cloudflare.com/ajax/libs/foundation/5.4.7/js/vendor/jquery.js">
     </script>
     <script src = "https://cdnjs.cloudflare.com/ajax/libs/foundation/5.4.7/js/foundation.min.js">
     </script>
     <script src = "https://cdnjs.cloudflare.com/ajax/libs/foundation/5.4.7/js/foundation/foundation.accordion.js">
     </script>

     <script>
    $(document).foundation({
      accordion: {
        callback : function (accordion) {
          console.log(accordion);
        }
      }
    });
  </script>
</head>

<body>

<ul class="small-block-grid-1 medium-block-grid-3">
        <li>
          <ul class="accordion" data-accordion="myAccordionGroup">
            <li class="accordion-navigation">
              <a href="#panel1c">Accordion 1</a>
              <div id="panel1c" class="content">
                Panel 1. Lorem ipsum dolor
              </div>
            </li>
            <li class="accordion-navigation">
              <a href="#panel2c">Accordion 2</a>
              <div id="panel2c" class="content">
                Panel 2. Lorem ipsum dolor
              </div>
            </li>
            <li class="accordion-navigation">
              <a href="#panel3c">Accordion 3</a>
              <div id="panel3c" class="content">
                Panel 3. Lorem ipsum dolor
              </div>
            </li>
          </ul>
        </li>
</ul>

</body>

</html>
</code>```

Versions

Foundation.js - 5.4.7

Foundation.css - 5.4.7

foundation.accordion.js - 5.4.7

jquery - 2.1.1

答:
I found the solution that is foundation 5.4.7 doesn't support accordion with ul & li tags. It provides support for 5.5 and above

https://foundation.zurb.com/sites/docs/v/5.5.3/components/accordion.html

In order to use an accordion, I need to make use of dl & dd tags

Title: unable to use accordion in foundation 5

Body:
I am trying to use accordion in foundation 5 but still, it's not working. Can anyone guide me where I am doing wrong

<!DOCTYPE html>

     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.4.7/css/foundation.min.css">

              Accordion 1

                Panel 1. Lorem ipsum dolor

              Accordion 2

                Panel 2. Lorem ipsum dolor

              Accordion 3

                Panel 3. Lorem ipsum dolor

Versions

Foundation.js - 5.4.7

Foundation.css - 5.4.7

foundation.accordion.js - 5.4.7

jquery - 2.1.1


问:
How to write in the same file C++
I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.

I've tried to close the file and wit ofstream to write in it but it didn't work.

```<code>#include <iostream>
#include <fstream>
#include <string>

int main () {
    std::string file_contents = "";
    std::ifstream myfile ("text.txt");

    char ch;

    if (myfile.is_open())
    {
        // READ FILE CONTENTS AS STRING
        while ( myfile >> std::noskipws >> ch)
        {
            file_contents += ch;
        }

        // DISPLAY STRING
        std::cout << file_contents << '\n';

        // GET WORD TO BE DELETED
        std::string word;
        std::cout << "Please enter word to be deleted: ";
        std::cin >> word;

        std::string::size_type found;

        std::string new_text;
        //DELETE WORD FROM STRING
        bool ok=0;
        do{
        found = file_contents.find(word);
        ok=1;
        if (found!=std::string::npos)
        {
            std::cout << word << " found at: " << found << '\n';
            file_contents.erase(found, word.length());
            std::cout << file_contents << '\n';

        }
        else
            ok==0;
            new_text=file_contents;
        }while(ok==1);

        myfile.close();
    }

    else std::cout << "Unable to open file";

    return 0;
}

</code>```

答:
The simpliest way is first to open as input stream. When finish open as output stream to write. It is not the only way you can do that.</p>

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    std::string file_contents = "";
    {
        std::ifstream myfile ("text.txt");

        if (! myfile.is_open())
        {
            else std::cout << "Unable to open file";
            return 1;
        }

        // READ FILE CONTENTS AS STRING
        char ch;
        while ( myfile >> std::noskipws >> ch) file_contents += ch;
        myfile.close();
    }

    {
        std::string word;
        std::cin >> word; // GET WORD TO BE DELETED
        std::string::size_type found;
        while((found = file_contents.find(word))!=std::string::npos)
            file_contents.erase(found, word.length());

        std::ofstream myfile ("text.txt");
        myfile << file_contents<< std::flush;
        myfile.close();
    }

    return 0;
}
</code>```

Title: How to write in the same file C++

Body:
I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.

I've tried to close the file and wit ofstream to write in it but it didn't work.

#include <iostream>
#include <fstream>
#include <string>

int main () {
    std::string file_contents = "";
    std::ifstream myfile ("text.txt");

    char ch;

    if (myfile.is_open())
    {
        // READ FILE CONTENTS AS STRING
        while ( myfile >> std::noskipws >> ch)
        {
            file_contents += ch;
        }

        // DISPLAY STRING
        std::cout << file_contents << '\n';

        // GET WORD TO BE DELETED
        std::string word;
        std::cout << "Please enter word to be deleted: ";
        std::cin >> word;

        std::string::size_type found;

        std::string new_text;
        //DELETE WORD FROM STRING
        bool ok=0;
        do{
        found = file_contents.find(word);
        ok=1;
        if (found!=std::string::npos)
        {
            std::cout << word << " found at: " << found << '\n';
            file_contents.erase(found, word.length());
            std::cout << file_contents << '\n';

        }
        else
            ok==0;
            new_text=file_contents;
        }while(ok==1);

        myfile.close();
    }

    else std::cout << "Unable to open file";

    return 0;
}

Body:
The simpliest way is first to open as input stream. When finish open as output stream to write. It is not the only way you can do that.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    std::string file_contents = "";
    {
        std::ifstream myfile ("text.txt");

        if (! myfile.is_open())
        {
            else std::cout << "Unable to open file";
            return 1;
        }

        // READ FILE CONTENTS AS STRING
        char ch;
        while ( myfile >> std::noskipws >> ch) file_contents += ch;
        myfile.close();
    }

    {
        std::string word;
        std::cin >> word; // GET WORD TO BE DELETED
        std::string::size_type found;
        while((found = file_contents.find(word))!=std::string::npos)
            file_contents.erase(found, word.length());

        std::ofstream myfile ("text.txt");
        myfile << file_contents<< std::flush;
        myfile.close();
    }

    return 0;
}


问:
Why 'static lifetime needed for owned variable by cloning
I struggle a little with rust lifetimes:
why is 'static lifetime needed for run_trait_test?.

I want it to behave like run_concrete_test

I read the documentation, searched stackoverflow and the rust-book but I'm obviously missing something.

use std::thread;

#[derive(Debug, Clone)]
struct Test {
    test_string: String,
}

trait Example {
    fn tst(&self) -> ();
}

impl Example for Test {
    fn tst(&self) {
        println!("{:?}", self);
    }
}

// compiles, no 'static here
fn run_concrete_test(tester: &Test) {
    let t = tester.clone();
    thread::spawn(move || {
        t.tst();
    });
}

// compiles with 'static
// but F shouldn't be only static
fn run_trait_test<F>(tester: &'static F)
where
    F: Example + Sync + Send + 'static,
{
    let t = tester.clone();
    let store_t = thread::spawn(move || {
        t.tst();
    });
}

fn main() {
    //does run, no static
    let x = Test {
        test_string: "test string".to_string(),
    };
    run_concrete_test(&x);

    // doe sn't compile because of static
    // run_trait_test(&x);
    println!("{:?}", x);
}
```

答:
From reference :

The following traits are implemented for all &T, regardless of the
  type of its referent:

...

Clone (Note that this will not defer to T's Clone implementation if it exists!)

...

Since F has 'static lifetime boundary, &F is a type of shared variable:

Without Clone boundary compiler will use clone from borrowed
version of F (Simply it would just clone the reference)

With  Clone boundary, compiler will use the implementation of F's Clone

With all of these the code below will work as same with run_concrete_test :

trait Example {
    fn test(&self);
}

fn _run_trait_test<F>(tester: &F)
where
    F: Example + Sync + Send + Clone + 'static,
{
    let t = tester.clone();

    ::std::thread::spawn(move || {
        t.test();
    });
}
```

Note: Without 'static lifetime boundary it is possible that F could be considered as some T's borrowed type like F = &T

Playground

Body:
From reference :

The following traits are implemented for all &T, regardless of the
  type of its referent:

...

Clone (Note that this will not defer to T's Clone implementation if it exists!)

...

Since F has 'static lifetime boundary, &F is a type of shared variable:

Without Clone boundary compiler will use clone from borrowed
version of F (Simply it would just clone the reference)

With  Clone boundary, compiler will use the implementation of F's Clone

With all of these the code below will work as same with run_concrete_test :

trait Example {
    fn test(&self);
}

fn _run_trait_test<F>(tester: &F)
where
    F: Example + Sync + Send + Clone + 'static,
{
    let t = tester.clone();

    ::std::thread::spawn(move || {
        t.test();
    });
}

Note: Without 'static lifetime boundary it is possible that F could be considered as some T's borrowed type like F = &T

Playground


问:
nodejs chat example does not work
I've come across a node chat example on github, When I try to run it, I see the following error:

Error connecting to mongo perhaps it isn't running ?

I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io

I can not determine whether if the example not really works or I didn't run it right. Please help.

答:
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.

Check out the follwing code excerpts from chat.io.

main.js:

```<code>/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
</code>```

Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).

UserProvider.js:

```<code>UserProvider = function(host, port) {
    this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
    this.db.addListener('error', function(error) {
      console.log('Error connecting to mongo -- perhaps it isn\'t running?');
    });
    this.db.open(function() {
    });
};
</code>```

Opening the connection to the server, printing out an error on failure (the error you mentioned above).

Consider reading up on the mongo-db docs concerning installation and setup here

Title: nodejs chat example does not work

Body:
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.

Check out the follwing code excerpts from chat.io.

main.js:

/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);

Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).

UserProvider.js:

UserProvider = function(host, port) {
    this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
    this.db.addListener('error', function(error) {
      console.log('Error connecting to mongo -- perhaps it isn\'t running?');
    });
    this.db.open(function() {
    });
};

Opening the connection to the server, printing out an error on failure (the error you mentioned above).

Consider reading up on the mongo-db docs concerning installation and setup here