问:
Dealing with concurrency and complex WCF services interacting with objects of the overall application
I am enjoying creating and hosting WCF services.
Up until now I can create services defining contracts for the service and data (interfaces) and defining hosts and configuration options to reach them (endpoint specifications).

Well, consider this piece of code defining a service and using it (no mention for endpoints that are defined in app.config not shown here):

```<code>[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      using (ServiceHost host = new ServiceHost(typeof(MyService))) {
         host.Open();
         ...
         host.Close();
      }
   }
}
</code>```

Well, this structure is good when creating something that could be called a Standalone service.
What if I needed my service to use objects of a greater application.
For example I need a service that does something basing on a certain collection defined somewhere in my program (which is hosting the service). The service must look into this collection and search and return a particular element.

The list I am talking about is a list managed by the program and edited and modified by it.

I have the following questions:

1) How can I build a service able to handle this list?
I know that a possible option is using the overloaded ServiceHost constructor accepting an Object instead of a Type service.
So I could pass my list there. Is it good?

```<code>[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   private List<> myinternallist;
   public MyService(List<> mylist) {
      // Constructing the service passing the list
   }
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      List<> thelist;
      ...
      MyService S = new MyService(thelist)
      using (ServiceHost host = new ServiceHost(S)) {
         host.Open();
         ...
         host.Close();
         // Here my application creates a functions and other that manages the queue. For this reason my application will edit the list (it can be a thread or callbacks from the user interface)
      }
   }
}
</code>```

This example should clarify.
Is it the good way of doing? Am I doing right?

2) How to handle conflicts on this shared resource between my service and my application?
When my application runs, hosting the service, my application can insert items in the list and delete them, the same can do the service too. Do I need a mutex? how to handle this?
Please note that the concurrency issue concerns two actors: the main application and the service. It is true that the service is singleton but the application acts on the list!!!
I assume that the service is called by an external entity, when this happens the application still runs right? Is there concurrency in this case???

Thankyou

答:
Adding the constructor to MyService for passing the list certainly will work as you'd expect. Like I said in my comment to the question however, the ServiceHost will only ever contain a single instance of the MyService class so the list will not be shared because only one service instance will consume it.

I would look at a dependency injector (DI) container for WCF to do what you are trying do. Let the DI container provide the singleton list instance to your services. Also @Smudge202 is absolutely correct that using the Concurrent Collection functionality is what you need to implement the list.

UPDATE based on the comments thread:

The DI approach would works by getting all of an object's dependencies from the DI container instead of creating them manually in code. You register all the types that will be provided by the container as part of the application start up. When the application (or WCF) needs a new object instance it requests it from the container instead of "newing" it up. The Castle Windsor WCF integration library for example implements all the wiring needed to provide WCF a service instance from the container. This posts explains the details of how to use the Microsoft Unity DI container with WCF if you want to roll your own WCF integration.

The shared list referenced in this question would be registered in the container as an already instantiated object from your application. When a WCF service instance is spun up from the DI container, all the constructor parameters will be provided including a reference to the shared list. There is a lot of information out there on dependency injection and inversion of control but this Martin Fowler article is a good place to start.

Body:
I am enjoying creating and hosting WCF services.
Up until now I can create services defining contracts for the service and data (interfaces) and defining hosts and configuration options to reach them (endpoint specifications).

Well, consider this piece of code defining a service and using it (no mention for endpoints that are defined in app.config not shown here):

[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      using (ServiceHost host = new ServiceHost(typeof(MyService))) {
         host.Open();
         ...
         host.Close();
      }
   }
}

Well, this structure is good when creating something that could be called a Standalone service.
What if I needed my service to use objects of a greater application.
For example I need a service that does something basing on a certain collection defined somewhere in my program (which is hosting the service). The service must look into this collection and search and return a particular element.

The list I am talking about is a list managed by the program and edited and modified by it.

I have the following questions:

1) How can I build a service able to handle this list?
I know that a possible option is using the overloaded ServiceHost constructor accepting an Object instead of a Type service.
So I could pass my list there. Is it good?

[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   private List<> myinternallist;
   public MyService(List<> mylist) {
      // Constructing the service passing the list
   }
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      List<> thelist;
      ...
      MyService S = new MyService(thelist)
      using (ServiceHost host = new ServiceHost(S)) {
         host.Open();
         ...
         host.Close();
         // Here my application creates a functions and other that manages the queue. For this reason my application will edit the list (it can be a thread or callbacks from the user interface)
      }
   }
}

This example should clarify.
Is it the good way of doing? Am I doing right?

2) How to handle conflicts on this shared resource between my service and my application?
When my application runs, hosting the service, my application can insert items in the list and delete them, the same can do the service too. Do I need a mutex? how to handle this?
Please note that the concurrency issue concerns two actors: the main application and the service. It is true that the service is singleton but the application acts on the list!!!
I assume that the service is called by an external entity, when this happens the application still runs right? Is there concurrency in this case???

Thankyou


来源: stackexchange

问:
Python 2 Subprocess: Cannot get output from readline
I have the following C application

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

int main(void)
{
    printf("hello world\n");
    /* Go into an infinite loop here. */
    while(1);

    return 0;
}
</code>```

And I have the following python code.

```<code>import subprocess
import time
import pprint

def run():
    command = ["./myapplication"]
    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    try:
        while process.poll() is None:
            # HELP: This call blocks...
            for i in  process.stdout.readline():
                print(i)

    finally:
        if process.poll() is None:
            process.kill()

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

When I run the python code, the stdout.readline or even stdout.read blocks.

If I run the application using subprocess.call(program) then I can see "hello world" in stdout.

How can I read input from stdout with the example I have provided?

Note: I would not want to modify my C program. I have tried this on both Python 2.7.17 and Python 3.7.5 under Ubuntu 19.10 and I get the same behaviour. Adding bufsize=0 did not help me.

答:
The easiest way is to flush buffers in the C program

```<code>...
printf("hello world\n");
fflush(stdout);
while(1);
...
</code>```

If you don't want to change the C program, you can manipulate the libc buffering behavior from outside. This can be done by using stdbuf to call your program (linux). The syntax is "stdbuf -o0 yourapplication" for zero buffering and "stdbuf -oL yourapplication" for line buffering. Therefore in your python code use

```<code>...
command = ["/usr/bin/stdbuf","-oL","pathtomyapplication"]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
...
</code>```

or

```<code>...
command = ["/usr/bin/stdbuf","-o0","pathtomyapplication"]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following C application

#include <stdio.h>

int main(void)
{
    printf("hello world\n");
    /* Go into an infinite loop here. */
    while(1);

    return 0;
}

And I have the following python code.

import subprocess
import time
import pprint

def run():
    command = ["./myapplication"]
    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    try:
        while process.poll() is None:
            # HELP: This call blocks...
            for i in  process.stdout.readline():
                print(i)

    finally:
        if process.poll() is None:
            process.kill()

if __name__ == "__main__":
    run()

When I run the python code, the stdout.readline or even stdout.read blocks.

If I run the application using subprocess.call(program) then I can see "hello world" in stdout.

How can I read input from stdout with the example I have provided?

Note: I would not want to modify my C program. I have tried this on both Python 2.7.17 and Python 3.7.5 under Ubuntu 19.10 and I get the same behaviour. Adding bufsize=0 did not help me.

Body:
The easiest way is to flush buffers in the C program

...
printf("hello world\n");
fflush(stdout);
while(1);
...

If you don't want to change the C program, you can manipulate the libc buffering behavior from outside. This can be done by using stdbuf to call your program (linux). The syntax is "stdbuf -o0 yourapplication" for zero buffering and "stdbuf -oL yourapplication" for line buffering. Therefore in your python code use

...
command = ["/usr/bin/stdbuf","-oL","pathtomyapplication"]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
...

or

...
command = ["/usr/bin/stdbuf","-o0","pathtomyapplication"]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
...


问:
Wildcard ssl certificate (*.blog.mydomain.com) not working on blog.mydomain.com
I have a web app in Azure. I have requested wildcard ssl certificate for *.blog.mydomain.com. I was going to use it on all blog subdomains as well as on blog.mydomain.com. However when I try to bind it on blog.mydomain.com it doesn't accept it. What could be the reason?

答:
Which correct answer?

*.mydomain.com would make a whole lot more sense, because it covers all of these.

It even circumvents the idea of using wildcards, to still add multiple host-names.

If the blog is another server with another IP, this might be the only exception.


问:
How to use a variable to select a function within a package?
I've created a variable and want to use that variable to select my desired function in a package (e.g. package::function), however, the variable name is interpreted literally instead of being evaluated.

Here's the approach:

```<code>library(GSEABase)
library(tidyverse)

### SET ONTOLOGY GROUP (e.g. Biological Process = BP, Molecular Function = MF, Cellular Component = CC)
ontology <- "BP"

### Set GOOFFSPRING database, based on ontology group set above
go_offspring <- paste("GO", ontology, "OFFSPRING", sep = "")

## Need to know the 'offspring' of each term in the ontology, and this is given by the data in:
GO.db::go_offspring

## Create function to parse out GO terms assigned to each GOslim
## Courtesy Bioconductor Support: https://support.bioconductor.org/p/128407/
mappedIds <-
  function(df, collection, OFFSPRING)
  {
    map <- as.list(OFFSPRING[rownames(df)])
    mapped <- lapply(map, intersect, ids(collection))
    df[["go_terms"]] <- vapply(unname(mapped), paste, collapse = ";", character(1L))
    df
  }

## Run the function
slimsdf <- mappedIds(slimsdf, myCollection, go_offspring)
</code>```

This spits out the error:

```<code>Error: 'go_offspring' is not an exported object from 'namespace:GO.db'
</code>```

When playing around in the R Studio console, I also notice that when I type

GO.db::

the autocomplete feature does not list my go_offspring variable as an option; it only lists the available functions within the GO.db package.

Seeing this behavior suggests there's a scope issue, in that the package cannot see variable definitions defined outside of the package.

Is there any way around this?

I've looked at this http://adv-r.had.co.nz/Environments.html, but I'm not entirely sure I follow all of it, nor do I see how to manipulate my environments to allow passing go_offspring to GO.db::.

答:
You can use getFromNamespace to get the function via its character name from the namespace.

```<code>slimsdf <- mappedIds(slimsdf, myCollection, getFromNamespace(go_offspring, "GO.db"))
</code>```

Body:
I've created a variable and want to use that variable to select my desired function in a package (e.g. package::function), however, the variable name is interpreted literally instead of being evaluated.

Here's the approach:

library(GSEABase)
library(tidyverse)

### SET ONTOLOGY GROUP (e.g. Biological Process = BP, Molecular Function = MF, Cellular Component = CC)
ontology <- "BP"

### Set GOOFFSPRING database, based on ontology group set above
go_offspring <- paste("GO", ontology, "OFFSPRING", sep = "")

## Need to know the 'offspring' of each term in the ontology, and this is given by the data in:
GO.db::go_offspring

## Create function to parse out GO terms assigned to each GOslim
## Courtesy Bioconductor Support: https://support.bioconductor.org/p/128407/
mappedIds <-
  function(df, collection, OFFSPRING)
  {
    map <- as.list(OFFSPRING[rownames(df)])
    mapped <- lapply(map, intersect, ids(collection))
    df[["go_terms"]] <- vapply(unname(mapped), paste, collapse = ";", character(1L))
    df
  }

## Run the function
slimsdf <- mappedIds(slimsdf, myCollection, go_offspring)

This spits out the error:

Error: 'go_offspring' is not an exported object from 'namespace:GO.db'

When playing around in the R Studio console, I also notice that when I type

GO.db::

the autocomplete feature does not list my go_offspring variable as an option; it only lists the available functions within the GO.db package.

Seeing this behavior suggests there's a scope issue, in that the package cannot see variable definitions defined outside of the package.

Is there any way around this?

I've looked at this http://adv-r.had.co.nz/Environments.html, but I'm not entirely sure I follow all of it, nor do I see how to manipulate my environments to allow passing go_offspring to GO.db::.

Body:
You can use getFromNamespace to get the function via its character name from the namespace.

slimsdf <- mappedIds(slimsdf, myCollection, getFromNamespace(go_offspring, "GO.db"))


问:
Trying to end a loop Python 3
Hi I have a pretty basic pong game using the turtle module going and I am trying to add a game end and display a winner, but after adding a break to the main loop it seems to keeps the loop going but broken...

#Main game loop
while score_p_1<5 or score_p_2<5:
    window.update()

    #ball movement
    ball.setx(ball.xcor() + ball.vx)
    ball.sety(ball.ycor() + ball.vy)

    #border detection
    if ball.xcor()>300:
        score_p_1 += 1
        ball.setpos(0,0)
        ball.vx *= -1
        score_display.clear()
        score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2),move=False,align="center", font=("Arial", 12, "normal"))

    if ball.xcor()<-300:
        score_p_2 += 1
        ball.setpos(0,0)
        ball.vx *= -1
        #need to add to update
        score_display.clear()
        score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2),move=False,align="center", font=("Arial", 12, "normal"))

    if ball.ycor()>290:
        ball.vy = -0.05

    if ball.ycor()<-290:
        ball.vy = 0.05

    #colision
    if ball.distance(paddle1) < 25:
        ball.vx = 0.05

    if ball.distance(paddle2) < 25:
        ball.vx = -0.05

    if paddle1.ycor()>=270:
        paddle1.setpos(-250,260)

    if paddle1.ycor()<=-270:
        paddle1.setpos(-250,-260)

    if paddle2.ycor()>=270:
        paddle2.setpos(250,260)

    if paddle2.ycor()<=-270:
        paddle2.setpos(250,-260)

    #Game end
    if score_p_1>=5:
        break

    score_display.clear()
    score_display.write("Player 1 is the Winner!", font=("Arial", 20, "normal"))
```

答:
Not an answer to your question per se, but a friendly change in style to avoid repetition and clarify what's happening:</p>

```<code># Main game loop.
while score_p_1 < 5 or score_p_2 < 5:
    window.update()

    # Process ball movement.
    ball.setx(ball.xcor() + ball.vx)
    ball.sety(ball.ycor() + ball.vy)

    # Scoring detection.
    if ball.xcor() > 300 or ball.xcor() < -300:

        # Who scored?
        if ball.xcor() > 300:
            score_p_1 += 1
        elif ball.xcor() < -300:
            score_p_2 += 1

        # Reset.
        ball.setpos(0, 0)
        ball.vx *= -1
        score_display.clear()
        score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2), move=False, align="center", font=("Arial", 12, "normal"))

    # Bouncing against walls.
    if abs(ball.ycor()) > 290:
        ball.vy = -0.05 * np.sign(ball.ycor())

    # Ball/paddle collision.
    for paddle in (paddle1, paddle2):
        if ball.distance(paddle) < 25:
            ball.vx = +0.05 if paddle is paddle1 else -0.05

    # Wall/paddle collision.
    for paddle in (paddle1, paddle2):
        x = -250 if paddle is paddle1 else +250
        y = np.clip(paddle.ycor(), -260, +260) # <- Ensures the paddles stay in [-260, +260].
        paddle.setpos(x, y)

    # Game end. No need for a break, it's already in the while condition.
    if score_p_1 >= 5:
        winner = 1
    elif score_p_2 >= 5:
        winner = 2
    score_display.clear()
    score_display.write(f"Player {winner} is the Winner!", font=("Arial", 20, "normal"))
</code>```

Title: Trying to end a loop Python 3

Body:
Not an answer to your question per se, but a friendly change in style to avoid repetition and clarify what's happening:

# Main game loop.
while score_p_1 < 5 or score_p_2 < 5:
    window.update()

    # Process ball movement.
    ball.setx(ball.xcor() + ball.vx)
    ball.sety(ball.ycor() + ball.vy)

    # Scoring detection.
    if ball.xcor() > 300 or ball.xcor() < -300:

        # Who scored?
        if ball.xcor() > 300:
            score_p_1 += 1
        elif ball.xcor() < -300:
            score_p_2 += 1

        # Reset.
        ball.setpos(0, 0)
        ball.vx *= -1
        score_display.clear()
        score_display.write("Player 1: %d    Player 2: %d" %(score_p_1, score_p_2), move=False, align="center", font=("Arial", 12, "normal"))

    # Bouncing against walls.
    if abs(ball.ycor()) > 290:
        ball.vy = -0.05 * np.sign(ball.ycor())

    # Ball/paddle collision.
    for paddle in (paddle1, paddle2):
        if ball.distance(paddle) < 25:
            ball.vx = +0.05 if paddle is paddle1 else -0.05

    # Wall/paddle collision.
    for paddle in (paddle1, paddle2):
        x = -250 if paddle is paddle1 else +250
        y = np.clip(paddle.ycor(), -260, +260) # <- Ensures the paddles stay in [-260, +260].
        paddle.setpos(x, y)

    # Game end. No need for a break, it's already in the while condition.
    if score_p_1 >= 5:
        winner = 1
    elif score_p_2 >= 5:
        winner = 2
    score_display.clear()
    score_display.write(f"Player {winner} is the Winner!", font=("Arial", 20, "normal"))


问:
How can I guarantee that my enums definition doesn't change in JavaScript?
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:

my.namespace.ColorEnum = {
  RED : 0,
  GREEN : 1,
  BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
  // whatever
}

```

Or is there some other way I can do this?

答:
I wasn't satisfied with any of the answers, so I made Yet Another Enum (YEA!).

This implementation:

uses more up-to-date JS

requires just the declaration of this one class to easily create enums

has mapping by name (colors.RED), string (colors["RED"]), and index (colors[0]), but you only need to pass in the strings as an array

binds equivalent toString() and valueOf() functions to each enum object (if this is somehow not desired, one can simply remove it - small overhead for JS though)

has optional global naming/storage by name string

freezes the enum object once created so that it can't be modified

Special thanks to Andre 'Fi''s answer for some inspiration.

The codes:

class Enums {
  static create({ name = undefined, items = [] }) {
    let newEnum = {};
    newEnum.length = items.length;
    newEnum.items = items;
    for (let itemIndex in items) {
      //Map by name.
      newEnum[items[itemIndex]] = parseInt(itemIndex, 10);
      //Map by index.
      newEnum[parseInt(itemIndex, 10)] = items[itemIndex];
    }
    newEnum.toString = Enums.enumToString.bind(newEnum);
    newEnum.valueOf = newEnum.toString;
    //Optional naming and global registration.
    if (name != undefined) {
      newEnum.name = name;
      Enums[name] = newEnum;
    }
    //Prevent modification of the enum object.
    Object.freeze(newEnum);
    return newEnum;
  }
  static enumToString() {
    return "Enum " +
      (this.name != undefined ? this.name + " " : "") +
      "[" + this.items.toString() + "]";
  }
}
```

<hr>

<p><strong>Usage:</strong></p>

<pre class="lang-js prettyprint-override"><code>let colors = Enums.create({
  name: "COLORS",
  items: [ "RED", "GREEN", "BLUE", "PORPLE" ]
});

//Global access, if named.
Enums.COLORS;

colors.items; //Array(4) [ "RED", "GREEN", "BLUE", "PORPLE" ]
colors.length; //4

colors.RED; //0
colors.GREEN; //1
colors.BLUE; //2
colors.PORPLE; //3
colors[0]; //"RED"
colors[1]; //"GREEN"
colors[2]; //"BLUE"
colors[3]; //"PORPLE"

colors.toString(); //"Enum COLORS [RED,GREEN,BLUE,PORPLE]"

//Enum frozen, makes it a real enum.
colors.RED = 9001;
colors.RED; //0
</code>```

OwnerDisplayName: David Citron

Body:
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:

my.namespace.ColorEnum = {
  RED : 0,
  GREEN : 1,
  BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
  // whatever
}

Or is there some other way I can do this?

Body:
I wasn't satisfied with any of the answers, so I made Yet Another Enum (YEA!).

This implementation:

uses more up-to-date JS

requires just the declaration of this one class to easily create enums

has mapping by name (colors.RED), string (colors["RED"]), and index (colors[0]), but you only need to pass in the strings as an array

binds equivalent toString() and valueOf() functions to each enum object (if this is somehow not desired, one can simply remove it - small overhead for JS though)

has optional global naming/storage by name string

freezes the enum object once created so that it can't be modified

Special thanks to Andre 'Fi''s answer for some inspiration.

The codes:

class Enums {
  static create({ name = undefined, items = [] }) {
    let newEnum = {};
    newEnum.length = items.length;
    newEnum.items = items;
    for (let itemIndex in items) {
      //Map by name.
      newEnum[items[itemIndex]] = parseInt(itemIndex, 10);
      //Map by index.
      newEnum[parseInt(itemIndex, 10)] = items[itemIndex];
    }
    newEnum.toString = Enums.enumToString.bind(newEnum);
    newEnum.valueOf = newEnum.toString;
    //Optional naming and global registration.
    if (name != undefined) {
      newEnum.name = name;
      Enums[name] = newEnum;
    }
    //Prevent modification of the enum object.
    Object.freeze(newEnum);
    return newEnum;
  }
  static enumToString() {
    return "Enum " +
      (this.name != undefined ? this.name + " " : "") +
      "[" + this.items.toString() + "]";
  }
}

Usage:

let colors = Enums.create({
  name: "COLORS",
  items: [ "RED", "GREEN", "BLUE", "PORPLE" ]
});

//Global access, if named.
Enums.COLORS;

colors.items; //Array(4) [ "RED", "GREEN", "BLUE", "PORPLE" ]
colors.length; //4

colors.RED; //0
colors.GREEN; //1
colors.BLUE; //2
colors.PORPLE; //3
colors[0]; //"RED"
colors[1]; //"GREEN"
colors[2]; //"BLUE"
colors[3]; //"PORPLE"

colors.toString(); //"Enum COLORS [RED,GREEN,BLUE,PORPLE]"

//Enum frozen, makes it a real enum.
colors.RED = 9001;
colors.RED; //0


问:
Trying to remove outliers in R for ggplot with excel file

```<code>ggplot(data = Flint %>% filter(Flint$Lead <=7), aes(y=Flint$Lead, group=Flint$Ward)) + geom_boxplot() + stat_boxplot()
</code>```

I have an excel file which Im trying to ggplot. I have to remove all values above 7 from the ggplot as its considered an outlier. I have tried to use subset and filter but am receiving this error. Error: Aesthetics must be either length 1 or the same as the data (5): y, group Is there a way I can get the data for Flint$First_Draw to be all values below . Sample Output would be multiple box plots based on wards. An example would be Ward 1: Lead 5.0 6.3, Ward 2: Lead 3.6, Ward 3: 2.8. For Ward 1 Lead 7.8 wouldn't appear as it is an outlier and is above 7. Thanks in advance!

答:
If you remove the Flint$ elements from the aes call then it should work.

This works:

```<code>data(mtcars)
ggplot(mtcars %>% filter(mpg <= 20), aes(y = hp, group = cyl)) +
  geom_boxplot()
</code>```

But this fails with a similar error message:

```<code>ggplot(mtcars %>% filter(mtcars$mpg <= 20), aes(y = mtcars$hp, group = mtcars$cyl)) +
  geom_boxplot()

Error: Aesthetics must be either length 1 or the same as the data (18): y, group
</code>```

Body:
ggplot(data = Flint %>% filter(Flint$Lead <=7), aes(y=Flint$Lead, group=Flint$Ward)) + geom_boxplot() + stat_boxplot()

I have an excel file which Im trying to ggplot. I have to remove all values above 7 from the ggplot as its considered an outlier. I have tried to use subset and filter but am receiving this error. Error: Aesthetics must be either length 1 or the same as the data (5): y, group Is there a way I can get the data for Flint$First_Draw to be all values below . Sample Output would be multiple box plots based on wards. An example would be Ward 1: Lead 5.0 6.3, Ward 2: Lead 3.6, Ward 3: 2.8. For Ward 1 Lead 7.8 wouldn't appear as it is an outlier and is above 7. Thanks in advance!

Body:
If you remove the Flint$ elements from the aes call then it should work.

This works:

data(mtcars)
ggplot(mtcars %>% filter(mpg <= 20), aes(y = hp, group = cyl)) +
  geom_boxplot()

But this fails with a similar error message:

ggplot(mtcars %>% filter(mtcars$mpg <= 20), aes(y = mtcars$hp, group = mtcars$cyl)) +
  geom_boxplot()

Error: Aesthetics must be either length 1 or the same as the data (18): y, group


问:
Session vs URI multi language identifier
I am working on a multilingual website (php/mysql) and my question is what would be the best solution for language identification - sessions/cookies or URI identification.  I mean in terms of SEO, what would be more accurate.

Thanks

答:
If you put the language into the URI a webcrawler can index the site in its different languages and users are able to bookmark/link to them. This is not possible, if there is no direct reference (=> URL) to the pages.

You can combine both ways: If no language specific information available within the URI, try to find it out from a cookie/session, and if this one fails, look at the Accept-Language-Header. Now, if one user change the language (by link or whatever) write it into a cookie (for later visits).

ContentLicense: CC BY-SA 3.0


问:
elusive recaptcha bug. Copy code always fails
A very small amount of my users get a captcha that asks them to copy and paste a code, but it always fails for them - while most of the users get the normal one (checkbox) which goes through correctly.
Googling only returned three instances of people getting that captcha none of which had any valuable information

Any ideas as to why they're getting that captcha and most importantly why does it fail?

答:
OK, I've run into the same issue. It's very difficult to find any useful information about this online. I did come across this post, though: https://community.cloudflare.com/t/urgent-problem-with-cloudflare-recaptcha-and-firefox/87307/3

It has the info that I needed to finally repro the problem reliably: Setting your user agent string to Firefox/24.0. (This link tells you how to do that in your browser: https://www.howtogeek.com/113439/how-to-change-your-browsers-user-agent-without-installing-any-extensions/

Now the question is: How to solve the problem? When reCaptcha decides to render the "Copy this code and paste it in the empty box below" UI, it seems to deactivate all of the normal JS callbacks that it would normally invoke. It's almost as if reCaptcha "thinks" it's running in a browser that doesn't support JavaScript.

It will still render the g-recaptcha-response textarea in the DOM. Usually that textarea is hidden, but in this mode it's visible. It's the "box" that the user should paste the code into.

It seems to be intended to be included in whatever form data you send to your server. Since reCaptcha "thinks" that it's running in a browser that doesn't support JavaScript, it expects you to do the reCaptcha validation on the server.

However, if you still want to react to the user pasting the code into the textarea, you can simply register an event handler for the input event on the g-recaptcha-response textarea.

```<code>let captchaTextarea = document.querySelector("textarea[name='g-recaptcha-response']")

if (captchaTextarea) {
    captchaTextarea.addEventListener("input", () => {
        console.log("Received reCaptcha input: ", captchaTextarea.value)
    }, false)
}
</code>```

Something along those lines.

Body:
OK, I've run into the same issue. It's very difficult to find any useful information about this online. I did come across this post, though: https://community.cloudflare.com/t/urgent-problem-with-cloudflare-recaptcha-and-firefox/87307/3

It has the info that I needed to finally repro the problem reliably: Setting your user agent string to Firefox/24.0. (This link tells you how to do that in your browser: https://www.howtogeek.com/113439/how-to-change-your-browsers-user-agent-without-installing-any-extensions/

Now the question is: How to solve the problem? When reCaptcha decides to render the "Copy this code and paste it in the empty box below" UI, it seems to deactivate all of the normal JS callbacks that it would normally invoke. It's almost as if reCaptcha "thinks" it's running in a browser that doesn't support JavaScript.

It will still render the g-recaptcha-response textarea in the DOM. Usually that textarea is hidden, but in this mode it's visible. It's the "box" that the user should paste the code into.

It seems to be intended to be included in whatever form data you send to your server. Since reCaptcha "thinks" that it's running in a browser that doesn't support JavaScript, it expects you to do the reCaptcha validation on the server.

However, if you still want to react to the user pasting the code into the textarea, you can simply register an event handler for the input event on the g-recaptcha-response textarea.

let captchaTextarea = document.querySelector("textarea[name='g-recaptcha-response']")

if (captchaTextarea) {
    captchaTextarea.addEventListener("input", () => {
        console.log("Received reCaptcha input: ", captchaTextarea.value)
    }, false)
}

Something along those lines.


问:
Java 'cannot find symbol' for Scanner object
This is my code

```<code>
import java.util.*;
import java.io.*;

public class LSArrayApp{
    public static void main(String[] args){
        System.out.println(ReadFile());

    }

    public static String[] ReadFile(){

        try{
            File myFile =new File("fileName.txt");
            Scanner scan = new Scanner(myFile);
            System.out.println("Scanner creation succesful");
            }

        catch(FileNotFoundException e){
            System.out.println("File not found");
            }

        String[] data =  new String[2976];
        int lineNumber = 0;
        while (scan.hasNextLine()){
            data[lineNumber] = scan.nextLine();
            lineNumber++;

        return data;
        }

</code>```

Everytime I run the code I get this error:

java: cannot find symbol
  symbol:   variable scan
  location: class LSArrayApp

It seems that the scanner object is not instantiating and I can't figure out why.

答:
The code does not compile, so it cannot be true that you run the program.

The variable "scan" is unknown outside the try block. You need to declare it  before try.

```<code>Scanner scan;
try
{
    File myFile =new File("fileName.txt");
    scan = new Scanner(myFile);
    System.out.println("Scanner creation succesful");
}
catch(FileNotFoundException e)
{
    System.out.println("File not found");
    System.exit(1);
}

</code>```

2) Arrays have a fixed size. To read a file with unknown size you may use the ArrayList class instead.

3) After the exception you should exit the program, otherwise the code below will fail because the scanner is not initialized.

Body:
This is my code

import java.util.*;
import java.io.*;

public class LSArrayApp{
    public static void main(String[] args){
        System.out.println(ReadFile());

    }

    public static String[] ReadFile(){

        try{
            File myFile =new File("fileName.txt");
            Scanner scan = new Scanner(myFile);
            System.out.println("Scanner creation succesful");
            }

        catch(FileNotFoundException e){
            System.out.println("File not found");
            }

        String[] data =  new String[2976];
        int lineNumber = 0;
        while (scan.hasNextLine()){
            data[lineNumber] = scan.nextLine();
            lineNumber++;

        return data;
        }

Everytime I run the code I get this error:

java: cannot find symbol
  symbol:   variable scan
  location: class LSArrayApp

It seems that the scanner object is not instantiating and I can't figure out why.

Body:
The code does not compile, so it cannot be true that you run the program.

The variable "scan" is unknown outside the try block. You need to declare it  before try.

Scanner scan;
try
{
    File myFile =new File("fileName.txt");
    scan = new Scanner(myFile);
    System.out.println("Scanner creation succesful");
}
catch(FileNotFoundException e)
{
    System.out.println("File not found");
    System.exit(1);
}

2) Arrays have a fixed size. To read a file with unknown size you may use the ArrayList class instead.

3) After the exception you should exit the program, otherwise the code below will fail because the scanner is not initialized.


问:
Why does 'if statement' ignores conditions or reads them as if they are not true when they actually are?
I stumbled upon something that is causing me real hard time and I can't figure it out so, please take a look at my situation and help me out...

I am writing a code that is supposed to prevent some of the website users from accessing a specific part of the website called orders.php

Each user has a previously assigned role and I am trying to achieve this restriction by allowing only a few of the roles to access it so if you don't have some of the specific roles that are allowed to visit the website assigned to you, you get redirected to the homepage.

These is one of the ways that I've tried

```<code>    if( $userrole !== 'Administrator' OR
        $userrole !== 'Manager' OR
        $userrole !== 'Product Hunter' OR
        $userrole !== 'Product Selector' OR
        $userrole !== 'Analytic' OR
        $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    else{
     //code here
    }
</code>```

I tried using || instead of OR but it is not working either

I also tried using elseif statement for each role like this:

```<code>if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Hunter'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Selector'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Analytic'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
   else{
    //code goes here
   }
</code>```

As far as I understand, the code shall continue to execute the else statement the moment it reads your role name, for an example if you are an Administrator, then it shall execute the else statement because it is said that if you are not some of the specified roles then you will be redirected and since you are one of the specified roles then the code shall execute for you but for some odd reason it is redirecting you to the homepage no matter if you are an Administrator, Manager or a Visitor...

The only way the code allows you to visit the website instead of redirecting you to the homepage is when you have only one role specified, for an example:

```<code>    if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }else{
     //code goes here
    }
</code>```

This way, if you are an Administrator, then you are allowed to visit the page, and if you have any different role then you get redirected.

The reason I use !== is because I want the code to define if this user can visit this part of the website at the beginning instead of telling it to show the code to the users with these few specific roles and redirect everyone else.

$userrole is previously set to equal a $_SESSION variable which contains the value of the actual role of the user and is defined at login, if I echo it, it prints the name of the role so that is not causing the problem for sure.

I've found some posts suggesting using switch statements but I haven't tried them yet since I prefer doing it this way if possible.

Thanks in advance!

答:
$userrole is one thing, so it can only be equal to one thing, which means it will be not equal to everything else.

So when you compare it to a set of things using !==, only one of those comparisons can possibly be false. When you construct a boolean expression by connecting a set of expressions using OR or || then only one of the inner expressions has to be true for the entire expression to be true.

Take a specific example where $userrole = 'Administrator'.

$userrole !== 'Administrator' will be false, but $userrole !== 'Manager' and all of the other comparisons will be true. So the expression becomes

```<code>if( false OR
    true OR
    true OR
    true OR
    true OR
    true){
    header('Location: ../dashboard.php');
    die;
}
</code>```

Which simplifies to

```<code>if (true){
    header('Location: ../dashboard.php');
    die;
}
</code>```

Same deal with your elseif approach. Only one of the elseifs can possibly be false.

Other answers have already offered some good ideas for other ways to do this. I just wanted to add a bit more explanation. (I would go with one of the in_array methods, personally.)

Body:
I stumbled upon something that is causing me real hard time and I can't figure it out so, please take a look at my situation and help me out...

I am writing a code that is supposed to prevent some of the website users from accessing a specific part of the website called orders.php

Each user has a previously assigned role and I am trying to achieve this restriction by allowing only a few of the roles to access it so if you don't have some of the specific roles that are allowed to visit the website assigned to you, you get redirected to the homepage.

These is one of the ways that I've tried

    if( $userrole !== 'Administrator' OR
        $userrole !== 'Manager' OR
        $userrole !== 'Product Hunter' OR
        $userrole !== 'Product Selector' OR
        $userrole !== 'Analytic' OR
        $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    else{
     //code here
    }

I tried using || instead of OR but it is not working either

I also tried using elseif statement for each role like this:

if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Hunter'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Selector'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Analytic'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
   else{
    //code goes here
   }

As far as I understand, the code shall continue to execute the else statement the moment it reads your role name, for an example if you are an Administrator, then it shall execute the else statement because it is said that if you are not some of the specified roles then you will be redirected and since you are one of the specified roles then the code shall execute for you but for some odd reason it is redirecting you to the homepage no matter if you are an Administrator, Manager or a Visitor...

The only way the code allows you to visit the website instead of redirecting you to the homepage is when you have only one role specified, for an example:

    if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }else{
     //code goes here
    }

This way, if you are an Administrator, then you are allowed to visit the page, and if you have any different role then you get redirected.

The reason I use !== is because I want the code to define if this user can visit this part of the website at the beginning instead of telling it to show the code to the users with these few specific roles and redirect everyone else.

$userrole is previously set to equal a $_SESSION variable which contains the value of the actual role of the user and is defined at login, if I echo it, it prints the name of the role so that is not causing the problem for sure.

I've found some posts suggesting using switch statements but I haven't tried them yet since I prefer doing it this way if possible.

Thanks in advance!

Body:
$userrole is one thing, so it can only be equal to one thing, which means it will be not equal to everything else.

So when you compare it to a set of things using !==, only one of those comparisons can possibly be false. When you construct a boolean expression by connecting a set of expressions using OR or || then only one of the inner expressions has to be true for the entire expression to be true.

Take a specific example where $userrole = 'Administrator'.

$userrole !== 'Administrator' will be false, but $userrole !== 'Manager' and all of the other comparisons will be true. So the expression becomes

if( false OR
    true OR
    true OR
    true OR
    true OR
    true){
    header('Location: ../dashboard.php');
    die;
}

Which simplifies to

if (true){
    header('Location: ../dashboard.php');
    die;
}

Same deal with your elseif approach. Only one of the elseifs can possibly be false.

Other answers have already offered some good ideas for other ways to do this. I just wanted to add a bit more explanation. (I would go with one of the in_array methods, personally.)


问:
Linux wget utility and it's option -O-
I am trying to install software on my Ubuntu, and during following the steps I am trying to get knowledge on what the script actually does. So i have this pice of code:

```<code>wget -q http://some.key.asc -O- | sudo apt-key add -
</code>```

And my question is about -O-. I used man to check options, but only one thing i found there is -O, which seems to be something that can lead me to this reasoning:

It looks like it is actually using - as the argument for storing downloaded data (GPG key), then through pipe it adds it to apt keys. It does not download FILE.

Am I correct, or is there something more behind this construct?

Thanks in advance!

答:
From the wget man pages:
"If - is used as file, documents will be printed to standard output, disabling link conversion."

You are correct in that nothing is written to a file when -O- is used. Instead, the downloaded contents are written to stdout. So for your script; the key is downloaded, printed to stdout, and then that data is piped into apt keys.

Title: Linux wget utility and it's option -O-

Body:
I am trying to install software on my Ubuntu, and during following the steps I am trying to get knowledge on what the script actually does. So i have this pice of code:

wget -q http://some.key.asc -O- | sudo apt-key add -

And my question is about -O-. I used man to check options, but only one thing i found there is -O, which seems to be something that can lead me to this reasoning:

It looks like it is actually using - as the argument for storing downloaded data (GPG key), then through pipe it adds it to apt keys. It does not download FILE.

Am I correct, or is there something more behind this construct?

Thanks in advance!


问:
How to see what monitor is a thread waiting for via API?
We have a junit test runner which timeout if one test is hanging. Now I want create a thread dump via API.

I know I can request the stacktraces via Thread.getAllStackTraces(). But the thread dump on the console include many more information like the monitor which a thread is waiting.

Are there an API to request the monitor on which a thread is waiting?

答:
You could use JMX to create a thread dump.

See How do I create a thread dump via JMX? for an example. The ThreadInfo class supports getting the locked monitors.


问:
How to write multiple excel sheets from a particular column in a pandas dataframe?
This is how df3(pandas dataframe) looks like:

```<code>        Key        Media_type                                    cleaned_text                                     keyword            subtopic       topic
0    910040          facebook                   will wait outside post office                                 post office               Brand     service
1    910040          facebook                   will wait outside post office                                   will wait              random  irrelevant
2    218658          facebook  there no section post office alabama ups fedex                                 post office               Brand     service
3    218658          facebook  there no section post office alabama ups fedex                                   ups fedex               Brand     service
4    763587           twitter               crazy package delivery rammed car                            package delivery            Shipping     company
5    827572           twitter                  formatting idead delivery done                               delivery done            Shipping     country
6  2404106          facebook           supoused mexico united states america                       united states america            location    marathon
7  1077739           twitter                                          rt ups                                      rt ups             retweet     service
8   786786  extraterristrial                                put one toostamp  (put[a-za-z]{,5}|made|leave)(.{,8})(stamp)  put one's stamp on     outlier
9    36283            unkown                                pute horse stamp  (put[a-za-z]{,5}|made|leave)(.{,8})(stamp)  put one's stamp on     outlier
</code>```

I want to put a filter for each value in df3['subtopic'] and return the resulting values to excel.
For eg. the manual way of doing it is:

```<code>df4 = df3.loc[df3['Subtopic'] == 'Brand']
df4.to_excel('subtopic_FedexDriver.xlsx')
</code>```

This is how the output for this piece of code looks like:

```<code>Key        Media_type                                    cleaned_text                                     keyword            subtopic       topic
0    910040          facebook                   will wait outside post office                                 post office               Brand     service
1    218658          facebook  there no section post office alabama ups fedex                                 post office               Brand     service
2    218658          facebook  there no section post office alabama ups fedex                                   ups fedex               Brand     service
</code>```

I would have to do this for each subtopic individually.
Is there a way I can automate this? Even if the values are added to different excel sheets within 1 excel file, that's fine.

答:
IIUC,

```<code>writer = pd.ExcelWriter('a.xlsx', engine = 'xlsxwriter')
for n, g in df.groupby('subtopic'):
    g.to_excel(writer, sheet_name=n)
writer.save()
writer.close()
</code>```

Output:

Body:
This is how df3(pandas dataframe) looks like:

        Key        Media_type                                    cleaned_text                                     keyword            subtopic       topic
0    910040          facebook                   will wait outside post office                                 post office               Brand     service
1    910040          facebook                   will wait outside post office                                   will wait              random  irrelevant
2    218658          facebook  there no section post office alabama ups fedex                                 post office               Brand     service
3    218658          facebook  there no section post office alabama ups fedex                                   ups fedex               Brand     service
4    763587           twitter               crazy package delivery rammed car                            package delivery            Shipping     company
5    827572           twitter                  formatting idead delivery done                               delivery done            Shipping     country
6  2404106          facebook           supoused mexico united states america                       united states america            location    marathon
7  1077739           twitter                                          rt ups                                      rt ups             retweet     service
8   786786  extraterristrial                                put one toostamp  (put[a-za-z]{,5}|made|leave)(.{,8})(stamp)  put one's stamp on     outlier
9    36283            unkown                                pute horse stamp  (put[a-za-z]{,5}|made|leave)(.{,8})(stamp)  put one's stamp on     outlier

I want to put a filter for each value in df3['subtopic'] and return the resulting values to excel.
For eg. the manual way of doing it is:

df4 = df3.loc[df3['Subtopic'] == 'Brand']
df4.to_excel('subtopic_FedexDriver.xlsx')

This is how the output for this piece of code looks like:

Key        Media_type                                    cleaned_text                                     keyword            subtopic       topic
0    910040          facebook                   will wait outside post office                                 post office               Brand     service
1    218658          facebook  there no section post office alabama ups fedex                                 post office               Brand     service
2    218658          facebook  there no section post office alabama ups fedex                                   ups fedex               Brand     service

I would have to do this for each subtopic individually.
Is there a way I can automate this? Even if the values are added to different excel sheets within 1 excel file, that's fine.

Body:
IIUC,

writer = pd.ExcelWriter('a.xlsx', engine = 'xlsxwriter')
for n, g in df.groupby('subtopic'):
    g.to_excel(writer, sheet_name=n)
writer.save()
writer.close()

Output:


问:
Add double quotation mark to first word of each line
I have an R file of results, such as below:

```<code>filename totalvar result runtime
file1  100 0 20.45
file2  400 4 4.50
...
filen  200 1 2.00
</code>```

Some of the filename contains weird characters so I have to add quotations to it. What is the easiest way to use VIM for adding quotation marks to first word of each line?
Something like

```<code>filename totalvar result runtime
"file1"  100 0 20.45
"file2"  400 4 4.50
...
"filen"  200 1 2.00
</code>```

答:
Using a :substitute command and matching the first word by a sequence of non-blank characters:

```<code>:2,$s/\S\+/"&"/
</code>```

The 2,$ performs the substitution starting on line 2 and going through the end of the file.

The \S\+ matches a sequence of non-whitespace characters. It will match the leftmost one and the longest one possible, which corresponds to the first word in each line.

The & on the replacement side is substituted for the match itself, so "&" will surround it in double quotes.

UPDATE: You can generalize this to quote the kth word on a line by matching k-1 words before it.

For example, to quote the 4th word:

```<code>:%s/\(\S\+\s\+\)\{3}\zs\S\+/"&"/
</code>```

Here the \(...\) defines a group of non-whitespace followed by whitespace, the \{3} matches 3 of those and the \zs marks the beginning of the actual match, so only that part will be replaced.

The net effect is that you're quoting the 4th word of lines that have 4 or more words.

Body:
I have an R file of results, such as below:

filename totalvar result runtime
file1  100 0 20.45
file2  400 4 4.50
...
filen  200 1 2.00

Some of the filename contains weird characters so I have to add quotations to it. What is the easiest way to use VIM for adding quotation marks to first word of each line?
Something like

filename totalvar result runtime
"file1"  100 0 20.45
"file2"  400 4 4.50
...
"filen"  200 1 2.00

Body:
Using a :substitute command and matching the first word by a sequence of non-blank characters:

:2,$s/\S\+/"&"/

The 2,$ performs the substitution starting on line 2 and going through the end of the file.

The \S\+ matches a sequence of non-whitespace characters. It will match the leftmost one and the longest one possible, which corresponds to the first word in each line.

The & on the replacement side is substituted for the match itself, so "&" will surround it in double quotes.

UPDATE: You can generalize this to quote the kth word on a line by matching k-1 words before it.

For example, to quote the 4th word:

:%s/\(\S\+\s\+\)\{3}\zs\S\+/"&"/

Here the \(...\) defines a group of non-whitespace followed by whitespace, the \{3} matches 3 of those and the \zs marks the beginning of the actual match, so only that part will be replaced.

The net effect is that you're quoting the 4th word of lines that have 4 or more words.


问:
PDO Insert 300.000 Rows
I have a json file and i want to insert all data to my database.

First i am trying to get contents from json file and store in array. It takes 20 seconds.

```<code>$strJsonFileContents = file_get_contents('C:\books.json');
$array = json_decode($strJsonFileContents);
</code>```

After that i prepare the insert query

```<code>$query = $db->prepare("INSERT INTO product SET
webID = ?,
name = ?,
subtitle = ?,
title = ?,
description = ?,
ISBN = ?
.
.
.
");
</code>```

I create a foreach loop and execute insert query.

```<code>foreach($array->Books as $book){
    $insert = $query->execute(array(
    $book->p2,
    $book->p3,
    $book->p4
    .
    .
    .
));
</code>```

This foreach loops has 300.000 loop. It takes huge time to insert. - I didn't see finish, it made 40,000 additions in about 10 minutes.

What should I do to reduce this time to seconds? It is not a big problem for me to have 20 seconds to read from the file but inserting time it is a huge problem.

答:
One way to reduce this is to create one query using the following syntax:

```<code>INSERT INTO `product` (`webID`, `name`, `subtitle`, `title`, `description`, `ISBN`)
VALUES (?,?,?,?,?,?),(?,?,?,?,?,?) .... // and so on
</code>```

Using the PHP to assemble the VALUES portion of the query as you can have multiple sets of these. Then run the query ONE time.

Regardless of how you do this, it will take some time to prepare the query and then execute it. Inserting that many rows at once is not trivial.

Title: PDO Insert 300.000 Rows

Body:
I have a json file and i want to insert all data to my database.

First i am trying to get contents from json file and store in array. It takes 20 seconds.

$strJsonFileContents = file_get_contents('C:\books.json');
$array = json_decode($strJsonFileContents);

After that i prepare the insert query

$query = $db->prepare("INSERT INTO product SET
webID = ?,
name = ?,
subtitle = ?,
title = ?,
description = ?,
ISBN = ?
.
.
.
");

I create a foreach loop and execute insert query.

foreach($array->Books as $book){
    $insert = $query->execute(array(
    $book->p2,
    $book->p3,
    $book->p4
    .
    .
    .
));

This foreach loops has 300.000 loop. It takes huge time to insert. - I didn't see finish, it made 40,000 additions in about 10 minutes.

What should I do to reduce this time to seconds? It is not a big problem for me to have 20 seconds to read from the file but inserting time it is a huge problem.

Body:
One way to reduce this is to create one query using the following syntax:

INSERT INTO `product` (`webID`, `name`, `subtitle`, `title`, `description`, `ISBN`)
VALUES (?,?,?,?,?,?),(?,?,?,?,?,?) .... // and so on

Using the PHP to assemble the VALUES portion of the query as you can have multiple sets of these. Then run the query ONE time.

Regardless of how you do this, it will take some time to prepare the query and then execute it. Inserting that many rows at once is not trivial.


问:
"object 'i' not found" the for loop
I am trying to make a simple for loop, that would add a new column to the existing data frame, by assigning a time class to each observation. I am getting 'object 'i' not found' and not sure where is a mistake. I am not that experienced with R, so thank you for any help!

for (i in 1:nrow(my.data)) {
    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }ifelse (my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }esle {
        my.data$RTimeHour[i] <- 3
    }
}
```

答:
Vectorized with tidyverse we can just do:

```<code>library(tidyverse)

my.data %>% mutate(RTimeHour = case_when(
    RTime <= 3600 ~ 1,
    RTime < 7200 ~ 2,
    TRUE ~ 3)
)
</code>```

Title: "object 'i' not found" the for loop

Body:
Vectorized with tidyverse we can just do:

library(tidyverse)

my.data %>% mutate(RTimeHour = case_when(
    RTime <= 3600 ~ 1,
    RTime < 7200 ~ 2,
    TRUE ~ 3)
)