问:
Unknown resource referenced in variable with Terraform
I am a beginner to Terraform.
I am trying to execute following code from Terraform Getting started guide.

```<code>provider "aws" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region     = "${var.region}"
}

resource "aws_instance" "example" {
  ami           = "${lookup(var.amis, var.region)}"
  instance_type = "t2.micro"

  tags {
    Name = "newprovisionerstest"
  }

  provisioner "local-exec" {
    command = "echo ${aws_instance.example.public_ip} > ip_address.txt"
  }
}

output "ip" {
  value = "${aws_eip.ip.public_ip}"
}
</code>```

When I run

terraform apply

or

terraform refresh

It gives following error:

Error: output 'ip': unknown resource 'aws_eip.ip' referenced in variable aws_eip.ip.public_ip

Why is it so? Is it because "aws_eip" resource is not declared anywhere?

答:
Like you said it yourself, there is no aws_eip resource called ip.
If you use the

aws_instance.example.public_ip

it should work totally fine

Body:
I am a beginner to Terraform.
I am trying to execute following code from Terraform Getting started guide.

provider "aws" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region     = "${var.region}"
}

resource "aws_instance" "example" {
  ami           = "${lookup(var.amis, var.region)}"
  instance_type = "t2.micro"

  tags {
    Name = "newprovisionerstest"
  }

  provisioner "local-exec" {
    command = "echo ${aws_instance.example.public_ip} > ip_address.txt"
  }
}

output "ip" {
  value = "${aws_eip.ip.public_ip}"
}

When I run

terraform apply

or

terraform refresh

It gives following error:

Error: output 'ip': unknown resource 'aws_eip.ip' referenced in variable aws_eip.ip.public_ip

Why is it so? Is it because "aws_eip" resource is not declared anywhere?


来源: stackexchange

问:
How can I create a column that cumulatively adds the sum of two previous rows based on conditions?
I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.

I have a dataset with winners, losers, date, winner_points and loser_points.

For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).

Example data:

```<code>winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)
</code>```

I want the output to be:

```<code>winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)
</code>```

How I've solved it thus far is to do a for loop such as:

```<code>library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0

for(i in row.names(test_data)) {
  test_data[i,]$winner_points_sum_loop <-
    (
    test_data %>%
      dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
  +
    test_data %>%
      dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
    )
}

test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)
</code>```

Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.

答:
The difference to the previous question of the OP is that the OP is now asking for the cumulative sum of points each player has scored so far, i.e., before the actual date. Furthermore, the sample data set now contains a date column which uniquely identifies each row.

So, my previous approach can be used here as well, with some modifications. The solution below reshapes the data from wide to long format whereby two value variables are reshaped simultaneously, computes the cumulative sums for each player id , and finally reshapes from long back to wide format, again. In order to sum only points scored before the actual date, the rows are lagged by one.

It is important to note that the winner and loser columns contain the respective player ids.

```<code>library(data.table)
cols <- c("winner", "loser")
setDT(test_data)[
  # reshape multiple value variables simultaneously from wide to long format
  , melt(.SD, id.vars = "date",
         measure.vars = list(cols, paste0(cols, "_points")),
         value.name = c("id", "points"))][
           # rename variable column
           , variable := forcats::lvls_revalue(variable, cols)][
             # order by date and cumulate the lagged points by id
             order(date), points_sum := cumsum(shift(points, fill = 0)), by = id][
               # reshape multiple value variables simultaneously from long to wide format
               , dcast(.SD, date ~ variable, value.var = c("id", "points", "points_sum"))]
</code>```

```<code>         date id_winner id_loser points_winner points_loser points_sum_winner points_sum_loser
1: 2017-10-01         1        3             2            1                 0                0
2: 2017-10-02         2        1             1            0                 0                2
3: 2017-10-03         3        1             2            1                 1                2
4: 2017-10-04         1        2             1            0                 3                1
5: 2017-10-05         2        1             2            1                 1                4
6: 2017-10-06         3        1             1            0                 3                5
7: 2017-10-07         1        3             2            1                 5                4
8: 2017-10-08         2        1             1            0                 3                7
9: 2017-10-09         3        2             2            1                 5                4
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.

I have a dataset with winners, losers, date, winner_points and loser_points.

For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).

Example data:

winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)

I want the output to be:

winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)

How I've solved it thus far is to do a for loop such as:

library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0

for(i in row.names(test_data)) {
  test_data[i,]$winner_points_sum_loop <-
    (
    test_data %>%
      dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
  +
    test_data %>%
      dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
    )
}

test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)

Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.

Body:
The difference to the previous question of the OP is that the OP is now asking for the cumulative sum of points each player has scored so far, i.e., before the actual date. Furthermore, the sample data set now contains a date column which uniquely identifies each row.

So, my previous approach can be used here as well, with some modifications. The solution below reshapes the data from wide to long format whereby two value variables are reshaped simultaneously, computes the cumulative sums for each player id , and finally reshapes from long back to wide format, again. In order to sum only points scored before the actual date, the rows are lagged by one.

It is important to note that the winner and loser columns contain the respective player ids.

library(data.table)
cols <- c("winner", "loser")
setDT(test_data)[
  # reshape multiple value variables simultaneously from wide to long format
  , melt(.SD, id.vars = "date",
         measure.vars = list(cols, paste0(cols, "_points")),
         value.name = c("id", "points"))][
           # rename variable column
           , variable := forcats::lvls_revalue(variable, cols)][
             # order by date and cumulate the lagged points by id
             order(date), points_sum := cumsum(shift(points, fill = 0)), by = id][
               # reshape multiple value variables simultaneously from long to wide format
               , dcast(.SD, date ~ variable, value.var = c("id", "points", "points_sum"))]

         date id_winner id_loser points_winner points_loser points_sum_winner points_sum_loser
1: 2017-10-01         1        3             2            1                 0                0
2: 2017-10-02         2        1             1            0                 0                2
3: 2017-10-03         3        1             2            1                 1                2
4: 2017-10-04         1        2             1            0                 3                1
5: 2017-10-05         2        1             2            1                 1                4
6: 2017-10-06         3        1             1            0                 3                5
7: 2017-10-07         1        3             2            1                 5                4
8: 2017-10-08         2        1             1            0                 3                7
9: 2017-10-09         3        2             2            1                 5                4


问:
During Webix datatable sub-column edit how to modify the nested JSON data accordingly?
In my Webix datatable, I have multiple columns under one column header by colspan.
I populate the table by a JSON data and that JSON data is having an Array structure to populate those sub-columns.

I observe that when I edit a cell under those columns, it is adding one extra field to the data set and not updating the exact nested object.

Let's say for a specific row, the data set looks like below before editing :

```<code>obj = {"No":"1","Name":"Justine","place":[{"address":"address1","name":"name1"}],"id":1512587573601}
</code>```

Now if I edit the adress field to 'address_new', then it is getting added as a separate key (as place_address) to the data set as below :

```<code>obj = {"No":"1","Name":"Justine","place":[{"address":"address1","name":"name1"}],"id":1512587573601,"place_address":"address_new"}
</code>```

Here is the snippet: https://webix.com/snippet/7882897c

How can this be solved?

Thanks.

答:
I think you are doing lot of work, you can do the same by simple steps:
https://webix.com/snippet/c60a1b45</p>

Body:
In my Webix datatable, I have multiple columns under one column header by colspan.
I populate the table by a JSON data and that JSON data is having an Array structure to populate those sub-columns.

I observe that when I edit a cell under those columns, it is adding one extra field to the data set and not updating the exact nested object.

Let's say for a specific row, the data set looks like below before editing :

obj = {"No":"1","Name":"Justine","place":[{"address":"address1","name":"name1"}],"id":1512587573601}

Now if I edit the adress field to 'address_new', then it is getting added as a separate key (as place_address) to the data set as below :

obj = {"No":"1","Name":"Justine","place":[{"address":"address1","name":"name1"}],"id":1512587573601,"place_address":"address_new"}

Here is the snippet: https://webix.com/snippet/7882897c

How can this be solved?

Thanks.


问:
Win32_NetworkAdapter.Index and Win32_IP4RouteTable.InterfaceIndex do not match
I am writing a script that would update DNS servers list on Windows 7 machines for the interfaces that pass traffic for default routes.

I have selected the route table entries with

```<code>$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable |
    Where-Object {$_.Destination -eq "0.0.0.0"}
</code>```

and assuming the list of interfaces obtained with Win32_NetworkAdapterConfiguration is in the $interfaces variable defined as

```<code>$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration
</code>```

I expected to join the two lists on condition $route.InterfaceIndex -eq $interface.Index. However I noticed that the indices do not match.

The route table has the following interface definitions:

```<code>C:\Users\user01>route print if 11
===========================================================================
Interface list
  ....
 13...08 00 27 8d 7e 19 ......Intel(R) PRO/1000 MT #2
 11...08 00 27 a4 16 ad ......Intel(R) PRO/1000 MT
 12...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
  ...
</code>```

However the $interface list has

```<code>ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT
Index            : 7

ServiceName      : tunnel
Description      : Tunnel adapter Microsoft Teredo
Index            : 11

ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT #2
Index            : 13
</code>```

That is in both lists Intel(R) PRO/1000 MT #2 has index 13, however Intel(R) PRO/1000 MT is 11 in one list and 7 in the other list. What could be the reason for this "seven-eleven" discrepancy?

From the description of the InterfaceIndex property I would expect that the indices should match.

InterfaceIndex

IP address of the next hop of this route. The value in this property is the same as the value in the InterfaceIndex property in
  the instances of Win32_NetworkAdapter and
  Win32_NetworkAdapterConfiguration that represent the network interface
  of the next hop of the route.

答:
I think you should check this now to understand the difference between them: </p>

```<code>$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration | select InterfaceIndex, Index
$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable |?{$_.Destination -eq "0.0.0.0"} | Select InterfaceIndex,Index

$interfaces
$defaultgw_routes
</code>```

Body:
I am writing a script that would update DNS servers list on Windows 7 machines for the interfaces that pass traffic for default routes.

I have selected the route table entries with

$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable |
    Where-Object {$_.Destination -eq "0.0.0.0"}

and assuming the list of interfaces obtained with Win32_NetworkAdapterConfiguration is in the $interfaces variable defined as

$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration

I expected to join the two lists on condition $route.InterfaceIndex -eq $interface.Index. However I noticed that the indices do not match.

The route table has the following interface definitions:

C:\Users\user01>route print if 11
===========================================================================
Interface list
  ....
 13...08 00 27 8d 7e 19 ......Intel(R) PRO/1000 MT #2
 11...08 00 27 a4 16 ad ......Intel(R) PRO/1000 MT
 12...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
  ...

However the $interface list has

ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT
Index            : 7

ServiceName      : tunnel
Description      : Tunnel adapter Microsoft Teredo
Index            : 11

ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT #2
Index            : 13

That is in both lists Intel(R) PRO/1000 MT #2 has index 13, however Intel(R) PRO/1000 MT is 11 in one list and 7 in the other list. What could be the reason for this "seven-eleven" discrepancy?

From the description of the InterfaceIndex property I would expect that the indices should match.

InterfaceIndex

IP address of the next hop of this route. The value in this property is the same as the value in the InterfaceIndex property in
  the instances of Win32_NetworkAdapter and
  Win32_NetworkAdapterConfiguration that represent the network interface
  of the next hop of the route.

Body:
I think you should check this now to understand the difference between them:

$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration | select InterfaceIndex, Index
$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable |?{$_.Destination -eq "0.0.0.0"} | Select InterfaceIndex,Index

$interfaces
$defaultgw_routes


问:
Date comparison validation in angular
I have 2 dates:  1.start and 2.end
format is like this.

```<code>12/4/2017               console.log(startDate);
12/20/2017              console.log(endDate);
</code>```

I am writing a validation to check if the end date is bigger than start date throw error,but it is not working.
this is what i have tried:

```<code>var startDate = new Date(this.formB['startDateVal']).toLocaleDateString();
var endDate=new Date(this.formB['dueDateVal']).toLocaleDateString();
</code>```

this is my condition:

```<code>if(endDate<startDate){
      this.bucketMsgClass='fielderror';
      this.bucketSuccessMsg = 'End Date is must lower than Start Date.';
 }
</code>```

where am i doing wrong.?

答:
I've always just subtracted one of the dates from the other. If the result is negative, then Date 1 is before Date 2.

```<code>var d1 = new Date("12/12/2017");
var d2 = new Date("12/13/2017");

console.log(d1 - d2) // -86400000 (exactly 1 day in milliseconds)
</code>```

So

```<code>if (d1 - d2 < 0) {
    // d1 is smaller
}
</code>```

Title: Date comparison validation in angular

Body:
I have 2 dates:  1.start and 2.end
format is like this.

12/4/2017               console.log(startDate);
12/20/2017              console.log(endDate);

I am writing a validation to check if the end date is bigger than start date throw error,but it is not working.
this is what i have tried:

var startDate = new Date(this.formB['startDateVal']).toLocaleDateString();
var endDate=new Date(this.formB['dueDateVal']).toLocaleDateString();

this is my condition:

if(endDate<startDate){
      this.bucketMsgClass='fielderror';
      this.bucketSuccessMsg = 'End Date is must lower than Start Date.';
 }

where am i doing wrong.?

Body:
I've always just subtracted one of the dates from the other. If the result is negative, then Date 1 is before Date 2.

var d1 = new Date("12/12/2017");
var d2 = new Date("12/13/2017");

console.log(d1 - d2) // -86400000 (exactly 1 day in milliseconds)

So

if (d1 - d2 < 0) {
    // d1 is smaller
}


问:
Custom GSON parser exclude object instances based on property value
When parsing JSON in Android using the GSON parser, I'd like to implement a rule that will exclude any objects from being created based on property value. For example:

```<code>{"people": [
    {"first_name": "Bob"},
    {"first_name": "Bob", "last_name": "Loblaw"}]}
</code>```

I want to exclude the first person object because it doesn't have a last name property.

Is this possible at parse time?

答:
It is possible with JsonDeserializer.

Suppose you would have POJOs like

```<code>public class Response {
   @Getter
   private List<Person> people = new ArrayList<>();
}
</code>```

and

```<code>public class Person {
   @Getter @Setter
   private String first_name, last_name;
}
</code>```

Creating JsonDeserializer like

```<code>public class PersonResponseDeserializer implements JsonDeserializer<Response> {
   // Create a new gson to make the default parsing for response object
   private final Gson gson = new Gson();

   @Override
   public Response deserialize(JsonElement json, Type typeOfT
         , JsonDeserializationContext context) throws JsonParseException {
      Response r = gson.fromJson(json, typeOfT);
      // Remove all persons from R that have last name null
      r.getPeople().removeAll(
            r.getPeople().stream().filter( p -> p.getLast_name() == null )
             .collect(Collectors.toSet())
      );
      return r;
   }
}
</code>```

could then be used like

```<code>Gson gson = new GsonBuilder()
        .registerTypeAdapter(Response.class, new PersonResponseDeserializer())
        .create();
Response r = gson.fromJson(s, Response.class);
</code>```

So this is if it is required to be done at the parse time. Maybe it is otherwise better to loop the People after parsing and exclude Persons without last name then.

Body:
When parsing JSON in Android using the GSON parser, I'd like to implement a rule that will exclude any objects from being created based on property value. For example:

{"people": [
    {"first_name": "Bob"},
    {"first_name": "Bob", "last_name": "Loblaw"}]}

I want to exclude the first person object because it doesn't have a last name property.

Is this possible at parse time?

Body:
It is possible with JsonDeserializer.

Suppose you would have POJOs like

public class Response {
   @Getter
   private List<Person> people = new ArrayList<>();
}

and

public class Person {
   @Getter @Setter
   private String first_name, last_name;
}

Creating JsonDeserializer like

public class PersonResponseDeserializer implements JsonDeserializer<Response> {
   // Create a new gson to make the default parsing for response object
   private final Gson gson = new Gson();

   @Override
   public Response deserialize(JsonElement json, Type typeOfT
         , JsonDeserializationContext context) throws JsonParseException {
      Response r = gson.fromJson(json, typeOfT);
      // Remove all persons from R that have last name null
      r.getPeople().removeAll(
            r.getPeople().stream().filter( p -> p.getLast_name() == null )
             .collect(Collectors.toSet())
      );
      return r;
   }
}

could then be used like

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Response.class, new PersonResponseDeserializer())
        .create();
Response r = gson.fromJson(s, Response.class);

So this is if it is required to be done at the parse time. Maybe it is otherwise better to loop the People after parsing and exclude Persons without last name then.


问:
Multithreading/Async download from single FTP server
I need to download many files from a single folder in a single server and so I'm looking for a way to do it quicker. After a little bit of reading it seems that either a multi-threading or asynchronous approach would work, but I can't seem to get either approach to work.

The async approach I'm using is below. This works, i.e. no errors, but it only downloads one file at a time, and so doesn't improve speed. Is there away to modify it so that I do improve speed?

```<code>async def get_file(self):
    async with aioftp.ClientSession(self.host, self.port, self.login, self.password) as client:
        async for path, info in client.list(recursive=True):
            if info["type"] == "file":
                await client.download(path, destination=self.dest_dir,write_into=True, block_size=self.block_size)

def async_update(self):
  loop = asyncio.get_event_loop()
  loop.run_until_complete(self.get_file())
  loop.close()
</code>```

Then I tried using the simple Pool() func in multiprocessing as below:

```<code>def simple_fetch(self,file)
    file = open(self.dest_dir+filename, 'wb')
    ftp.retrbinary('RETR ' + filename, file.write, 8192*(2^3)) #, 8192)
    file.close()

def multi_fetch(self):
    pool = Pool()
    pool.map(self.simple_fetch,self.update_files)
    pool.close()
    pool.join()
</code>```

But this fails with an error. I'll update with that error as soon as I'm back at the server.

答: For the async approach, you will want to build a list of files to download and call them concurrently. You are only calling simple_get once so there is only 1 instance of the download running. See this example as @Klas-d mentioned.</p>

Body:
I need to download many files from a single folder in a single server and so I'm looking for a way to do it quicker. After a little bit of reading it seems that either a multi-threading or asynchronous approach would work, but I can't seem to get either approach to work.

The async approach I'm using is below. This works, i.e. no errors, but it only downloads one file at a time, and so doesn't improve speed. Is there away to modify it so that I do improve speed?

async def get_file(self):
    async with aioftp.ClientSession(self.host, self.port, self.login, self.password) as client:
        async for path, info in client.list(recursive=True):
            if info["type"] == "file":
                await client.download(path, destination=self.dest_dir,write_into=True, block_size=self.block_size)

def async_update(self):
  loop = asyncio.get_event_loop()
  loop.run_until_complete(self.get_file())
  loop.close()

Then I tried using the simple Pool() func in multiprocessing as below:

def simple_fetch(self,file)
    file = open(self.dest_dir+filename, 'wb')
    ftp.retrbinary('RETR ' + filename, file.write, 8192*(2^3)) #, 8192)
    file.close()

def multi_fetch(self):
    pool = Pool()
    pool.map(self.simple_fetch,self.update_files)
    pool.close()
    pool.join()

But this fails with an error. I'll update with that error as soon as I'm back at the server.


问:
Google combo chart issue
I am trying to create a combo chart using google charts,
in HTML added below CDN and div

```<code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: auto; height: 500px;"></div>
</code>```

the result of

```<code>var examname = <?php echo json_encode($examnames); ?>;
var highestScore = <?php echo json_encode($heighestScores); ?>;
var userScore = <?php echo json_encode($userScores); ?>;
</code>```

is

```<code>var examname = ["Test Name 1", "Full Test", "Knowledge"];
var highestScore = ["8", "11", "10"];
var userScore = ["6", "11"];

google.charts.load('current', {
        'packages': ['corechart']
      });
      google.charts.setOnLoadCallback(drawVisualization);

      function drawVisualization() {
        // Some raw data (not necessarily accurate)
        var graphData = new google.visualization.DataTable();
        graphData.addColumn('string', 'TestName');
        graphData.addColumn('number', 'Height');
        graphData.addColumn('number', 'YourScore');

        for (var i = 0; i < examname.length; i++) {
          if (userScore[i] === undefined) {
            userScore[i] = 0;
          }
          console.log(userScore[i]);
          graphData.addRow(examname[i], {
            v: highestScore[i],
            f: userScore[i]
          });
        }
        //graphData = graphData.replace(/'/g, '"');
        //var data = google.visualization.arrayToDataTable(graphData);
        console.log(data);
        var options = {
          title: 'Score Dashboard',
          vAxis: {
            title: 'Score'
          },
          hAxis: {
            title: 'Exam Name'
          },
          seriesType: 'bars',
          series: {
            5: {
              type: 'line'
            }
          }
        };

        var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(graphData, options);
      }
</code>```

JSFIDDLE

I am getting an error:

Error: If argument is given to addRow, it must be an array, or null

even I searched in google but I didn't understand. Please could any one help me to resolve the issue.

答:
Your passing (string, object). When it's expecting just (array).

Change

```<code>graphData.addRow(examname[i], {
    v: highestScore[i],
    f: userScore[i]
});
</code>```

To

```<code>graphData.addRow([
    examname[i],
    Number(highestScore[i]),
    Number(userScore[i])
]);
</code>```

Working example: https://jsfiddle.net/g4vjvam9/

Note: If you want the last column filled, you need to add the value :/

```<code>var userScore = ["6", "11", "2"];
</code>```

Also avoid strings else your need to use Number() like above.

Title: Google combo chart issue

Body:
I am trying to create a combo chart using google charts,
in HTML added below CDN and div

the result of

var examname = <?php echo json_encode($examnames); ?>;
var highestScore = <?php echo json_encode($heighestScores); ?>;
var userScore = <?php echo json_encode($userScores); ?>;

is

var examname = ["Test Name 1", "Full Test", "Knowledge"];
var highestScore = ["8", "11", "10"];
var userScore = ["6", "11"];

google.charts.load('current', {
        'packages': ['corechart']
      });
      google.charts.setOnLoadCallback(drawVisualization);

      function drawVisualization() {
        // Some raw data (not necessarily accurate)
        var graphData = new google.visualization.DataTable();
        graphData.addColumn('string', 'TestName');
        graphData.addColumn('number', 'Height');
        graphData.addColumn('number', 'YourScore');

        for (var i = 0; i < examname.length; i++) {
          if (userScore[i] === undefined) {
            userScore[i] = 0;
          }
          console.log(userScore[i]);
          graphData.addRow(examname[i], {
            v: highestScore[i],
            f: userScore[i]
          });
        }
        //graphData = graphData.replace(/'/g, '"');
        //var data = google.visualization.arrayToDataTable(graphData);
        console.log(data);
        var options = {
          title: 'Score Dashboard',
          vAxis: {
            title: 'Score'
          },
          hAxis: {
            title: 'Exam Name'
          },
          seriesType: 'bars',
          series: {
            5: {
              type: 'line'
            }
          }
        };

        var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(graphData, options);
      }

JSFIDDLE

I am getting an error:

Error: If argument is given to addRow, it must be an array, or null

even I searched in google but I didn't understand. Please could any one help me to resolve the issue.

Body:
Your passing (string, object). When it's expecting just (array).

Change

graphData.addRow(examname[i], {
    v: highestScore[i],
    f: userScore[i]
});

To

graphData.addRow([
    examname[i],
    Number(highestScore[i]),
    Number(userScore[i])
]);

Working example: https://jsfiddle.net/g4vjvam9/

Note: If you want the last column filled, you need to add the value :/

var userScore = ["6", "11", "2"];

Also avoid strings else your need to use Number() like above.


问:
How to clear cookies of web browser from a button
I created a web browser in C# and use this code to clear cookies.

But I'm getting errors..

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (Request.Cookies["UserSettings"] != null)
    {
        HttpCookie myCookie = new HttpCookie("UserSettings");
        myCookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies.Add(myCookie);
    }
}
</code>```

Error

Error  2   The type or namespace name 'HttpCookie' could not be found (are you missing a using directive or an assembly reference?)    c:\users\supun\documents\visual studio 2013\Projects\FACEBOOK GROUP POSTER\FACEBOOK GROUP POSTER\Form1.cs   35  17  FACEBOOK GROUP POSTER

Error  4   The name 'Response' does not exist in the current context   c:\users\supun\documents\visual studio 2013\Projects\FACEBOOK GROUP POSTER\FACEBOOK GROUP POSTER\Form1.cs   37  17  FACEBOOK GROUP POSTER

Do you have any idea to fix this issue?

答:
Deleting cookies is not so straight forward. Have a look at this post:

You need to import:

```<code>[System.Runtime.InteropServices.DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
</code>```

Then, call InternetSetOption using:

```<code>int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;

bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
    MessageBox.Show("Encountered an error");
}
</code>```

You may have to mark your assembly unsafe under Properties -> Build Tab.

Body:
I created a web browser in C# and use this code to clear cookies.

But I'm getting errors..

private void button1_Click(object sender, EventArgs e)
{
    if (Request.Cookies["UserSettings"] != null)
    {
        HttpCookie myCookie = new HttpCookie("UserSettings");
        myCookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies.Add(myCookie);
    }
}

Error

Error  2   The type or namespace name 'HttpCookie' could not be found (are you missing a using directive or an assembly reference?)    c:\users\supun\documents\visual studio 2013\Projects\FACEBOOK GROUP POSTER\FACEBOOK GROUP POSTER\Form1.cs   35  17  FACEBOOK GROUP POSTER

Error  4   The name 'Response' does not exist in the current context   c:\users\supun\documents\visual studio 2013\Projects\FACEBOOK GROUP POSTER\FACEBOOK GROUP POSTER\Form1.cs   37  17  FACEBOOK GROUP POSTER

Do you have any idea to fix this issue?

Body:
Deleting cookies is not so straight forward. Have a look at this post:

You need to import:

[System.Runtime.InteropServices.DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);

Then, call InternetSetOption using:

int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;

bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
    MessageBox.Show("Encountered an error");
}

You may have to mark your assembly unsafe under Properties -> Build Tab.


问:
Using AWS SNS to push notifications to React Native Mobile [ANDROID] (optional use of FCM)
I developed a simple pipeline by chaining restful HTTP call from AWS API Gateway to lambda and finally to SNS. My next objective is to trigger push notification to mobile (Android) for every SNS topic triggered. The mobile client specifically developed using React Native. I know that there are several approaches
a) Using aws-sdk to get pushed SNS data
b) Using FCM to get pushed SNS data, but requires SNS to link with FCM.

I did many research on the above, but there seem no clear guidance on how to set it up, because many of them touch on native solution ie Android native or IOS native.

Questions:
1. Which one would be better approach, OR is there any other better approach?
2. Based on the chosen approach, could you kindly provide simple and clear steps on how to set up (step by step with good samples/examples are appreciated)?

Thanks for kind helpers!

答: I am currently working on something similar. I think you can accomplish what you are looking for by using the library 'react-native-push-notification'. There is a tutorial for it-https://medium.com/@xap5xap/show-push-notifications-on-react-native-app-a613a5a2c159. I hope it helps.</p>


问:
How can I tackle this OOP design problem?
I have a system that has 3 components:

Report - Contains logic for defining what a report actually contains in its output. Examples include TopMerchantsReport and LowestTransactionsReport.

ReportRunner - As the reports only do data gathering and generating, this class is responsible for running all of the reports and dispatching the results (via email, for example). Each Report has its own ReportRunner.

ReportProfile - Object mirror of a database table that contains a user's settings for a specific report.

A Report can have multiple pluggable behaviors, such as being Digestable and/or being Schedulable. Since PHP has no mixins, this is best represented by the decorator pattern.

My actual problem is that each of these 3 objects needs its behavior modified when the associated Report is decorated with something like Schedulable. For example, the ReportRunner now needs to only gather scheduled reports, and ReportProfile would benefit from a isScheduled() method.

I don't want to force a user to have to decorate all 3 classes. Not only is that error prone, but then I'd have to create 3 decorators for each behavior (one for each class). What other solution is there?

答: If you want to have for a concrete class of e.g. Report different behaviour in other two components, you have to eventually decorate them, so you cannot avoid that. The only problem migth be managing creation of those three components to be decorated according to choosen behaviour e.g. Digestable. This can be done using a factory method pattern, which allows you to create appropriate kind of all those three components.</p>

ContentLicense: CC BY-SA 2.5


问:
Storing JsonWebToken in frontend
So, I'm right now learning Node.js and I have few newbies doubts. I tried to search here and also in Google and I couldn't find my answer. I'm doing a Jwt Authentication and sending the token through header to my frontend which I'm rendering using handlebars as a view engine, my question is, how can I store that token and sending back through headers in every request? and What's the best way to do it?</p>

答:
Depending on chosen token expiration policy, you can choose different options. As previously said, token may be of course stored in localStorage.

The more secure option is keeping the token in memory. I would strongly suggest using short-lived JWTs and require them to be re-issued regularly (e.g. via an OAuth2 refresh token flow).

Title: Storing JsonWebToken in frontend


问:
UnexpectedJavaScriptError when opening IE using selenium
```<code>An exception of type 'System.InvalidOperationException' occurred in WebDriver.dll
but was not handled in user code
Additional information: JavaScript error (UnexpectedJavaScriptError)
</code>```

I'm trying to browse a url using IE.
I get this error only for Internet explorer. For chrome & firefox it works fine.

Using IE 11, IEDriverServer_Win32_2.47.0, Windows 7 64-bit

C#:

```<code>[TestMethod]
public void GeneratePageSnaps()
{
 IWebDriver NewDriver;
 NewDriver = new InternetExplorerDriver("D:\IeDriver");
 NewDriver.Navigate().GoToUrl("http://www.google.com");
 NewDriver.Manage().Window.Maximize();
 IWait<IWebDriver> wait = new WebDriverWait(NewDriver, TimeSpan.FromSeconds(10.00));
 wait.Until(driver1 => ((IJavaScriptExecutor)NewDriver).ExecuteScript(
                        "return document.readyState").Equals("complete")); //error here
}
</code>```

答:
Try resetting your IE browser settings.
It worked for me, just go to the

settings>Internet Options>Advanced>Reset

Just reset and restart the system.
NOTE:

For Selenium web driver to work with IE the following should also need to be done :
 Internet Options>Security, Select "Enable protected mode" for all the 4 options then Apply these changes and then restart the systems..then only it works.

Body:
An exception of type 'System.InvalidOperationException' occurred in WebDriver.dll
but was not handled in user code
Additional information: JavaScript error (UnexpectedJavaScriptError)

I'm trying to browse a url using IE.
I get this error only for Internet explorer. For chrome & firefox it works fine.

Using IE 11, IEDriverServer_Win32_2.47.0, Windows 7 64-bit

C#:

[TestMethod]
public void GeneratePageSnaps()
{
 IWebDriver NewDriver;
 NewDriver = new InternetExplorerDriver("D:\IeDriver");
 NewDriver.Navigate().GoToUrl("http://www.google.com");
 NewDriver.Manage().Window.Maximize();
 IWait<IWebDriver> wait = new WebDriverWait(NewDriver, TimeSpan.FromSeconds(10.00));
 wait.Until(driver1 => ((IJavaScriptExecutor)NewDriver).ExecuteScript(
                        "return document.readyState").Equals("complete")); //error here
}


问:
Webpack config node_modules outside dist
I'm trying to find the best solution for my project setup:

At the moment my folder structure look like this:

dist

node_modules

src

|- components

|- styles

|-- app.scss

My Webpack config works and compiles everything from 'src' to 'dist'.

I'm going to deploy content of 'dist' to the server so should I move node_modules inside 'dist' with webpack when I run build?

My app.scss reference dependencies from node_modules so if I move node_ modules inside 'dist' I will have to change paths in scss? How to do it?

The same issue with index.html and dynamic paths...

Is this the best practice?

Thanks

答:
When you compile everything with Webpack, it imports the parts needed from the node_modules inside your compiled code. So the files outputted in your dist folder are "standalone". You don't need your node_modules anywhere except when you develop.
Regarding your app.scss, it will be transformed into CSS and node_modules @imports will be integrated inside your app.css.


问:
DSpace 6.2 Mirage 2 Footer Modification
I am having trouble with modification of the footer on the DSpace 6 Mirage 2 theme. I have managed to find where to customize the text content i.e the page_structure file but I can't seem to find the file in which to customize the styling or I could be doing it wrong.</p>

答:
Modifying the page-structure.xsl file found in

```<code>/home/dspace-6.2-src-release/dspace-xmlui-mirage2/src/main/webapp/xsl/core
</code>```

worked great.

Title: DSpace 6.2 Mirage 2 Footer Modification

Body:
Modifying the page-structure.xsl file found in

/home/dspace-6.2-src-release/dspace-xmlui-mirage2/src/main/webapp/xsl/core

worked great.


问:
Creating a simple unit of work with Entity Framework and no repository
I've been trying to implement a .net MVC Unit of Work API (rather than creating a separate repository), but it doesn't feel right. Am I going about this the correct way?

BaseController

```<code>public class BaseController : ApiController
    {
        protected DBEntities _dbEntities;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _dbEntities = new DBEntities();
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            _dbEntities.SaveChanges();
        }
    }
</code>```

MyController

```<code>public class MyController : BaseController
{
    public HttpResponseMessage PutMyObject(int id, int id2)
    {
        if (id != 0)
        {
            var myObject = _dbEntities.MyObjects.Where(x => x.id == id);
            if (myObject.Count() > 0)
            {
                MyObject temp = myObject.SingleOrDefault();
                temp.Processed = true;
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound);
            }
        }
        else
        {
            /* do some other stuff */
        }
    }

}
</code>```

My thinking around this is that the controller action is a single Unit of Work. The database connection is opened when the controller action starts, and SaveChanges is called once the response is returned.

Am I going about this in the correct manner? do i need to dispose of _dbentities after savechanges is called within the BaseController? (or is this a better question for code review exchange)

答:
I think, It would be a bad design for OOP architecture and flexibility. Because, you have to provide database actions in your main MVC project and you couldn't provide them in other layers. So, you should provide repository pattern and you should access the repositories from main MVC project and other required projects. So, I suggest you to handle _dbEntities object in a singleton class for per thread.

Sample singleton class would be like this;

```<code>public class UnitOfWorkSampleContextBase : IDisposable
{
    [ThreadStatic]
    private static UnitOfWorkSampleContextBase _instance;

    public static UnitOfWorkSampleContextBase Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new UnitOfWorkSampleContextBase();
            }
            return _instance;
        }
    }

    public SampleDbContext Context { get; private set; }

    private UnitOfWorkSampleContextBase()
    {

    }

    public void Commit()
    {
        Context.SaveChanges();
    }

    public void ResolveContext()
    {
        Context = new SampleDbContext(ConfigurationManager.ConnectionStrings["MainDatabase"].ConnectionString);
    }

    public void Dispose()
    {
        Context.Dispose();
        Context = null;
    }
}
</code>```

And you can create the DbContext like this;

```<code>UnitOfWorkSampleContextBase.Instance.ResolveContext();
</code>```

Then, you can perform actions in context like this;

```<code>var context = UnitOfWorkSampleContextBase.Instance.Context;
var records = context.sampleEntities.ToList();
</code>```

Finally, you can commit and dispose the context like this;

```<code>UnitOfWorkSampleContextBase.Instance.Commit();
UnitOfWorkSampleContextBase.Instance.Dispose();
</code>```

The singleton class should be in repository or base layer to be accessed desired repository classes.

Note : If you are using CastleWindsor or something like that, creating
  and commiting the context would be better in an interceptor. Also, it is very important that the singleton context class should be initialized for per thread.

Body:
I've been trying to implement a .net MVC Unit of Work API (rather than creating a separate repository), but it doesn't feel right. Am I going about this the correct way?

BaseController

public class BaseController : ApiController
    {
        protected DBEntities _dbEntities;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _dbEntities = new DBEntities();
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            _dbEntities.SaveChanges();
        }
    }

MyController

public class MyController : BaseController
{
    public HttpResponseMessage PutMyObject(int id, int id2)
    {
        if (id != 0)
        {
            var myObject = _dbEntities.MyObjects.Where(x => x.id == id);
            if (myObject.Count() > 0)
            {
                MyObject temp = myObject.SingleOrDefault();
                temp.Processed = true;
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound);
            }
        }
        else
        {
            /* do some other stuff */
        }
    }

}

My thinking around this is that the controller action is a single Unit of Work. The database connection is opened when the controller action starts, and SaveChanges is called once the response is returned.

Am I going about this in the correct manner? do i need to dispose of _dbentities after savechanges is called within the BaseController? (or is this a better question for code review exchange)

Body:
I think, It would be a bad design for OOP architecture and flexibility. Because, you have to provide database actions in your main MVC project and you couldn't provide them in other layers. So, you should provide repository pattern and you should access the repositories from main MVC project and other required projects. So, I suggest you to handle _dbEntities object in a singleton class for per thread.

Sample singleton class would be like this;

public class UnitOfWorkSampleContextBase : IDisposable
{
    [ThreadStatic]
    private static UnitOfWorkSampleContextBase _instance;

    public static UnitOfWorkSampleContextBase Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new UnitOfWorkSampleContextBase();
            }
            return _instance;
        }
    }

    public SampleDbContext Context { get; private set; }

    private UnitOfWorkSampleContextBase()
    {

    }

    public void Commit()
    {
        Context.SaveChanges();
    }

    public void ResolveContext()
    {
        Context = new SampleDbContext(ConfigurationManager.ConnectionStrings["MainDatabase"].ConnectionString);
    }

    public void Dispose()
    {
        Context.Dispose();
        Context = null;
    }
}

And you can create the DbContext like this;

UnitOfWorkSampleContextBase.Instance.ResolveContext();

Then, you can perform actions in context like this;

var context = UnitOfWorkSampleContextBase.Instance.Context;
var records = context.sampleEntities.ToList();

Finally, you can commit and dispose the context like this;

UnitOfWorkSampleContextBase.Instance.Commit();
UnitOfWorkSampleContextBase.Instance.Dispose();

The singleton class should be in repository or base layer to be accessed desired repository classes.

Note : If you are using CastleWindsor or something like that, creating
  and commiting the context would be better in an interceptor. Also, it is very important that the singleton context class should be initialized for per thread.


问:
Google Maps api
I have to provide such functionality:

User checks 2-10 cities at Google Maps, I count the way between those cities using roads and show the way. The additional information is length of the full way.

Is it possible with google maps?

答:
If you already know the order you want to be travelling to the cities in, then you just have to make a DirectionsRequest using the in between cities as waypoints. If you don't know the order, as long as you know the start and end, you can have Google Maps optimize the order of the waypoints for you.

http://code.google.com/apis/maps/documentation/javascript/services.html#Waypoints

Title: Google Maps api

LastEditorDisplayName: delete


问:
What is the MySQL JDBC driver connection string?
I am new to JDBC and I am trying to make a connection to a MySQL database.
I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.

答:
```<code>String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);
</code>```

3306 is the default port for mysql.

If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

```<code>jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
</code>```

OwnerDisplayName: ravi kumar

Body:
String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);

3306 is the default port for mysql.

If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]


问:
How Do I Make somthing a Character in JS
I know how to move a character using arrow keys, but how do I signal which image I want the character to be

Here is my code on making it move on arrow keys, but how do I mark that an image is the character?

///// store key codes and currently pressed ones
var keys = {};
    keys.LEFT = 37;
    keys.RIGHT = 39;

///// store reference to character's position and element
var character = {
  x: 100,
  y: 100,
  element: document.getElementById("character")
};

///// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
  var kc = e.keyCode || e.which;
  keys[kc] = e.type == 'keydown';
};

///// character movement update
var moveCharacter = function(dx, dy){
  character.x += dx||0;
  character.y += dy||0;
  character.element.style.left = character.x + 'px';
  character.element.style.top = character.y + 'px';
};

///// character control
var detectCharacterMovement = function(){
  if ( keys[keys.LEFT] ) {
    moveCharacter(-1);
  }
  if ( keys[keys.RIGHT] ) {
    moveCharacter(1);
  }
};

///// game loop
setInterval(function(){
  detectCharacterMovement();
}, 1000/24);```

If you can help thanks! (: I am new to Javascript.

答:
You probably want something like this. Add a image of your character in the body of your page and give it id="character" . Also use initial CSS like in the below snippet

///// store key codes and currently pressed ones
var keys = {};
    keys.LEFT = 37;
    keys.RIGHT = 39;

///// store reference to character's position and element
var character = {
  x: 100,
  y: 10,
  element: document.getElementById("character")
};

///// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){

  var kc = e.keyCode || e.which;
  keys[kc] = e.type == 'keydown';
};

///// character movement update
var moveCharacter = function(dx, dy){
  character.x += dx||0;
  character.y += dy||0;
  character.element.style.left = character.x + 'px';
  character.element.style.top = character.y + 'px';
};

///// character control
var detectCharacterMovement = function(){
  if ( keys[keys.LEFT] ) {
    moveCharacter(-1);
  }
  if ( keys[keys.RIGHT] ) {
    moveCharacter(1);
  }
};

///// game loop
setInterval(function(){
  detectCharacterMovement();
}, 1000/24);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#character{
  position:absolute;
  width: 50px;
  height: 50px;
  left: 100px;
  top: 10px;
}
.wrap{
  position:relative
}</code>```

Click on Mario and use LEFT/RIGHT arrows to move it

```

Body:
I know how to move a character using arrow keys, but how do I signal which image I want the character to be

Here is my code on making it move on arrow keys, but how do I mark that an image is the character?

///// store key codes and currently pressed ones
var keys = {};
    keys.LEFT = 37;
    keys.RIGHT = 39;

///// store reference to character's position and element
var character = {
  x: 100,
  y: 100,
  element: document.getElementById("character")
};

///// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
  var kc = e.keyCode || e.which;
  keys[kc] = e.type == 'keydown';
};

///// character movement update
var moveCharacter = function(dx, dy){
  character.x += dx||0;
  character.y += dy||0;
  character.element.style.left = character.x + 'px';
  character.element.style.top = character.y + 'px';
};

///// character control
var detectCharacterMovement = function(){
  if ( keys[keys.LEFT] ) {
    moveCharacter(-1);
  }
  if ( keys[keys.RIGHT] ) {
    moveCharacter(1);
  }
};

///// game loop
setInterval(function(){
  detectCharacterMovement();
}, 1000/24);

If you can help thanks! (: I am new to Javascript.

Body:
You probably want something like this. Add a image of your character in the body of your page and give it id="character" . Also use initial CSS like in the below snippet

///// store key codes and currently pressed ones
var keys = {};
    keys.LEFT = 37;
    keys.RIGHT = 39;

///// store reference to character's position and element
var character = {
  x: 100,
  y: 10,
  element: document.getElementById("character")
};

///// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){

  var kc = e.keyCode || e.which;
  keys[kc] = e.type == 'keydown';
};

///// character movement update
var moveCharacter = function(dx, dy){
  character.x += dx||0;
  character.y += dy||0;
  character.element.style.left = character.x + 'px';
  character.element.style.top = character.y + 'px';
};

///// character control
var detectCharacterMovement = function(){
  if ( keys[keys.LEFT] ) {
    moveCharacter(-1);
  }
  if ( keys[keys.RIGHT] ) {
    moveCharacter(1);
  }
};

///// game loop
setInterval(function(){
  detectCharacterMovement();
}, 1000/24);

#character{
  position:absolute;
  width: 50px;
  height: 50px;
  left: 100px;
  top: 10px;
}
.wrap{
  position:relative
}

<body>
<span>Click on Mario and use LEFT/RIGHT arrows to move it</span>
<div class="wrap">
<img src="https://rocketdock.com/images/screenshots/Mario-Icon.jpg" id="character"/>
</div>
</body>


问:
How to create an attribute for a custom component in JavaFx?
After a few hours work I have managed to understand how to create a custom component using javafx and Gluons Scene Builder.
How does one add a new property for that component which will appear in the scene builder properties menu so that the property value can be entered at design time.</p>

答:
You need to subclass something, most likely an implementation of Parent, Region or Pane. From there you can load the FXML which was generated by whatever you have done in Scene Builder.

Example:

```<code>public class MyComponent extends VBox {
    private final StringProperty foo = new SimpleStringProperty();

    public MyComponent {
        final Parent root = (Parent) FXMLLoader.load(getClass().getResource(fxmlPath));

        getChildren().add(root);
    }

    public final StringProperty fooProperty() { return foo; }
    public final String getFoo() { return foo.get(); }
    public final void setFoo(String foo) { this.foo.set(foo); }
}
</code>```

This may produce an extra container, one being MyComponent, the other being the root node of the FXML. To prevent this, use FXMLLoader.setRoot().

Update

It seems like you have an extra obstacle - the controller which has the main logic is decoupled with MyComponent.

There are many ways to do this:

By Reference Passing

You can pass in the reference of MyComponent into the controller.

```<code>public class MyController {
    /* Your controller stuff */

    private MyComponent component;

    public final void setComponent(MyComponent component) {
        // You can bind your controller properties to fooProperty here
    }
}
</code>```

Then when loading the FXML in MyComponent, you get the reference of the controller and manually call setComponent().

By exposing controller property

This method directly exposes the properties of the controller in MyComponent

```<code>public class MyComponent extends VBox {
    // Other stuff

    private MyController controller;

    public MyComponent {
        // Original stuff

        this.controller = loader.getController();
    }

    public final StringProperty fooProperty() {
        assert controller != null; // If you loaded correctly this assertion should be valid

        return controller.fooProperty();
    }

    public final String getFoo() { return fooProperty().get(); }
    public final void setFoo(String foo) { fooProperty().set(foo); }
}
</code>```

Integrating controller into the component

This method simply combines MyComponent and MyController into a single class. You would need FXMLLoader.setController(this).

The advantage is you have direct access to everything. The bad thing is, some people would say this violates MVC.

Body:
You need to subclass something, most likely an implementation of Parent, Region or Pane. From there you can load the FXML which was generated by whatever you have done in Scene Builder.

Example:

public class MyComponent extends VBox {
    private final StringProperty foo = new SimpleStringProperty();

    public MyComponent {
        final Parent root = (Parent) FXMLLoader.load(getClass().getResource(fxmlPath));

        getChildren().add(root);
    }

    public final StringProperty fooProperty() { return foo; }
    public final String getFoo() { return foo.get(); }
    public final void setFoo(String foo) { this.foo.set(foo); }
}

This may produce an extra container, one being MyComponent, the other being the root node of the FXML. To prevent this, use FXMLLoader.setRoot().

Update

It seems like you have an extra obstacle - the controller which has the main logic is decoupled with MyComponent.

There are many ways to do this:

By Reference Passing

You can pass in the reference of MyComponent into the controller.

public class MyController {
    /* Your controller stuff */

    private MyComponent component;

    public final void setComponent(MyComponent component) {
        // You can bind your controller properties to fooProperty here
    }
}

Then when loading the FXML in MyComponent, you get the reference of the controller and manually call setComponent().

By exposing controller property

This method directly exposes the properties of the controller in MyComponent

public class MyComponent extends VBox {
    // Other stuff

    private MyController controller;

    public MyComponent {
        // Original stuff

        this.controller = loader.getController();
    }

    public final StringProperty fooProperty() {
        assert controller != null; // If you loaded correctly this assertion should be valid

        return controller.fooProperty();
    }

    public final String getFoo() { return fooProperty().get(); }
    public final void setFoo(String foo) { fooProperty().set(foo); }
}

Integrating controller into the component

This method simply combines MyComponent and MyController into a single class. You would need FXMLLoader.setController(this).

The advantage is you have direct access to everything. The bad thing is, some people would say this violates MVC.


问:
Extract Column(s) from text file having Multi Character Delimiter i.e. "%$%"
I have tried different solution for the problem given on the forum but doesn't work for the specified Delimiter %$%, I need to extract one specific column from the file containing 200+ columns.

I tried the following:

```<code>awk -F"%$%" '{print $1}' sample.txt > outfile.txt
awk 'gsub("%$%",":")' sample.txt > outfile.txt
</code>```

答:
The symbol $ is a special character in a regex, so you need to escape it with a \, which is also a special character for the string literal, so it needs to be escaped again.

So, finally we have:

```<code>$ cat sample
ghkjlj;lk%$%23e;k32poek%$%eqdje2oijd%$%xrgtdy5h

$ awk -F'%\\$%' '{print $1}' sample
ghkjlj;lk
</code>```

Body:
I have tried different solution for the problem given on the forum but doesn't work for the specified Delimiter %$%, I need to extract one specific column from the file containing 200+ columns.

I tried the following:

awk -F"%$%" '{print $1}' sample.txt > outfile.txt
awk 'gsub("%$%",":")' sample.txt > outfile.txt

Body:
The symbol $ is a special character in a regex, so you need to escape it with a \, which is also a special character for the string literal, so it needs to be escaped again.

So, finally we have:

$ cat sample
ghkjlj;lk%$%23e;k32poek%$%eqdje2oijd%$%xrgtdy5h

$ awk -F'%\\$%' '{print $1}' sample
ghkjlj;lk


问:
filtering in an ng-repeat from JSON response
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

```<code>$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});
</code>```

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow" ng-repeat="customer in customers | orderBy: customer.id">
        <div class="col-lg-8">
            <p class="customer" ng-bind="customer.id + ' ' + customer.firstname + ' ' + customer.lastname">
      </p>
        </div>
</div></code>```

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

```<code>{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}
</code>```

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <ng-form name="stock">
                <div ng-repeat="stock_available in stock_availables">
                    <div class="row full-width padding-tb-15" ng-if="stock_available.id_product == product.id  && stock_available.id_product_attribute == 0" ng-repeat="product in products">
                        <div class="col-lg-12 form-stock-group hidden">
                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">
                        </div>
                        <div class="col-lg-4">
                            <h5 ng-bind="product.name.language"></h5>
                        </div>
                        <div class="col-lg-3">
                            <h5 ng-bind="product.ean13"></h5>
                        </div>
                        <div class="col-lg-2">
                            <h5 ng-bind="product.reference"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">
                            <h5 title="quantity" name="stockQuantity" aria-describedby="" ng-model="stock_available.quantity" ng-bind="stock_available.quantity"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">
                        </div>
                        <div class="col-lg-1 text-center">

                                <i class="fa fa-print" aria-hidden="true"></i>

                        </div>
                    </div>
                </div>
            </ng-form>
        </div>
    </div></code>```

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

答:
By reading your question, I would suggest instead of having the ng-if n times, you can have the logic for filtering inside your controller like

```<code>  $scope.getFilteredList = function() {
     return $scope.stock_availables.filter(function(stock) {
       return stock.id_product === $scope.selectedID;   // $scope.selectedID will be the id to be filter, in your example '0'
     });
  }
</code>```

And your ng-repeat will be changed as

```<code><div ng-repeat="stock_available in getFilteredList">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});

            <ng-form name="stock">

                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">

                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">

                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">

            </ng-form>

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

Body:
By reading your question, I would suggest instead of having the ng-if n times, you can have the logic for filtering inside your controller like

  $scope.getFilteredList = function() {
     return $scope.stock_availables.filter(function(stock) {
       return stock.id_product === $scope.selectedID;   // $scope.selectedID will be the id to be filter, in your example '0'
     });
  }

And your ng-repeat will be changed as

<div ng-repeat="stock_available in getFilteredList">


问:
Independent VueJS components with webpack?
I made some SPA using vuejs-templates/webpack and that's ok. But now I am developing a website, almost everything is static, so there's no need to be a SPA. I already made the pure html/css layout.

Now I will make some pages with forms and dynamic content, I would like to use vue components inside these pages.

Tell me which of this ideas is the best or give me a better option:

Multiple entries in webpack: I don't know very well how to do it, but I guess I can create a webpack project by scratch and render multiple entries that I include in the pages I want.

Use browserify: I didn't want to do this, but sounds like a good option... I could use vueify to render *.vue components

Use Nuxt: I never tried, but seems a good option too, I could make a "SPA" with SSR.

Tell me if you have another idea.

Thank you

答: Don't rule out just referencing Vue as a script file. No bundle, no compilation step. You lose single file components, but you can get something very like them by using js template literals. If your needs are simple and you don't want to impact on the rest of the site, this could be a fine solution.</p>


问:
How can I make this css animation smooth
In the below example you can see the boxes jumping a little bit, How can I make that transition smooth?

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

答:
If you ask me, your starting point at 0% should begin with 0px, but that's just me:

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px) translateX(0px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

Body:
If you ask me, your starting point at 0% should begin with 0px, but that's just me:

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px) translateX(0px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


问:
jquery simple modal help on window load
I'm trying to something like this  if in the html there is a div called "#super" load it in the simple modal if not do nothing.  I managed to do this with the my skill :D which is none:  to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not.  PLease help  I'm absolute noob on jquery.

```<code>    if( $('super') ){    $("#super").modal({onOpen: function (dialog) {

    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
}});
</code>```

I'm using this jquery plugin link text

答:
If #super does not exist, nothing will happen. So, the following should fit your needs:</p>

```<code>$("#super").modal({onOpen: function (dialog) {
    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
});
</code>```

Title: jquery simple modal help on window load

Body:
I'm trying to something like this  if in the html there is a div called "#super" load it in the simple modal if not do nothing.  I managed to do this with the my skill :D which is none:  to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not.  PLease help  I'm absolute noob on jquery.

    if( $('super') ){    $("#super").modal({onOpen: function (dialog) {

    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
}});

I'm using this jquery plugin link text

Body:
If #super does not exist, nothing will happen. So, the following should fit your needs:

$("#super").modal({onOpen: function (dialog) {
    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
});


问:
Runtime Controller in Jmeter
Can you help me to explain relationship between time in Runtime Controller and Ramp_up period value of Thread group?
I tested

Number of Thread: 1

Ramp_Up Period: 1

Loop count: 1

Runtime Controller: 5s

->Elapsed time of current running test: 5s

But with case

Number of Thread: 5

Ramp_Up Period: 5

Loop count: 1

Runtime Controller: 5s

->Elapsed time of current running test: 10s

I don't understand why it become 10s.

Could you help me to explain more?

答:
Runtime Controller acts according to JMeter Scoping Rules so it defines how long its children are allowed to run.

Normally you should be using it in conjunction with Loop Count = Forever or -1 on either Thread Group or Loop Controller level.

So

if you want the whole test to run for 5 seconds - use "Scheduler" section of the Thread Group

if you want only certain sampler(s) to run for 5 seconds - put them under the Runtime Controller, however the whole test duration will depend on when the last sampler enters the Runtime Controller

Also be aware that JMeter "asks" threads to stop so it might take some extra time to let them gracefully shut down.

Title: Runtime Controller in Jmeter


问:
Wordpress theme reverted back automatically
I have theme Sydney by ATHEMES activated on my Wordpress site http://www.hamrolagi.com, and edited the theme files without making a child theme. I had edited the header.php, template-tags.php and other templates files according to the customization requirement. It was working fine until yesterday, but today I see that the edits I had made to the files were reverted, and though the site is still functioning, the customizations are lost, except that to the template-tags.php, which is the only file I had edited which was not in the main theme directory. I had backed up the edited files. So, I was able to re-edit them, but I wanted to know what caused it and how to prevent it in future?</p>

答: I'm pretty sure it was a theme update. Always use child themes - that is by far the only sure way to prevent it from happening in the future.</p>


问:
Connecting to imap.google with SSL
I`m trying to make an email client but it doesn't work :/ Im trying to connect to google imap with SSL (without SSL i can make it) Code:

```<code>#include "StdAfx.h"
#include "openssl/ssl.h"
#include "iostream"
#include <cstdio>
#include <iostream>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <windows.h>
using namespace std;
#pragma comment(lib, "Ws2_32.lib")

#define BUFSIZE 1024
char buf[BUFSIZE];
char *msg;
WSADATA wsda;
int     sock;
struct hostent *host;
struct sockaddr_in server_addr;
short int       s_port = 993;
const char      *s_ipaddr = "74.125.77.109";
 int SSL_library_init();
 SSL_METHOD *meth;
 int main () {
SSL_load_error_strings();
    SSL_library_init();
    //RAND_seed(buf, BUFSIZE);

    SSL_CTX *sslContext = SSL_CTX_new(SSLv23_client_method());
    if (sslContext == NULL)
    {
        cout << "err\n";
    }

    SSL *sslConnection = SSL_new(sslContext);
    if(sslConnection == NULL)
    {
        cout << "err\n";
    }

    WSAStartup(MAKEWORD(2,2), &wsda);

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(s_port);
    server_addr.sin_addr.s_addr = inet_addr(s_ipaddr);

    if(server_addr.sin_addr.s_addr == INADDR_NONE)
    {
        host = NULL;
        host = gethostbyname(s_ipaddr);
        if(host == NULL)
        {
            return false;
        }
        memcpy(&server_addr.sin_addr, host->h_addr_list[0], host->h_length);
    }

    connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr));

    SSL_set_fd(sslConnection, sock);

    SSL_connect(sslConnection);
    cout << "Connecting:\n";

    SSL_read(sslConnection, buf, sizeof(buf)-1);
    cout << buf << "\n";

    cout << "Logging-in:\n";
    msg = "a1 login emailapp123@gmail.com PASS\n";
    SSL_write(sslConnection, msg, strlen(msg));

    SSL_read(sslConnection, buf, sizeof(buf)-1);
    cout << buf << "\n";

    cout << "INBOX\n";

    msg = "a2 SELECT INBOX\n";
    SSL_write(sslConnection, msg, strlen(msg));
    SSL_read(sslConnection, buf, sizeof(buf)-1);
    cout << buf << "\n";
    system("pause");
 }
</code>```

And thats what i receive:

Connecting:
  * OK Gimap ready for requests from 195.150.156.162 y48if37710eei.45

Logging-in:
  * CAPABILITY IMAP4rev1 UNSELECT LITERAL+ IDLE NAMESPACE QUOTA ID XLIST CHILDREN
  X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE
  a1 OK emailapp123@gmail.com authenticated (Success)

INBOX

What should I do to make the connection right?
Thanks for every advice :-)
Chris

答: You need to terminate all commands sent to an imap server with both a carriage return and a line feed. Send a2 SELECT INBOX\r\n and it should work.

Title: Connecting to imap.google with SSL

Body:
I`m trying to make an email client but it doesn't work :/ Im trying to connect to google imap with SSL (without SSL i can make it) Code:

#include "StdAfx.h"
#include "openssl/ssl.h"
#include "iostream"
#include <cstdio>
#include <iostream>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <windows.h>
using namespace std;
#pragma comment(lib, "Ws2_32.lib")

#define BUFSIZE 1024
char buf[BUFSIZE];
char *msg;
WSADATA wsda;
int     sock;
struct hostent *host;
struct sockaddr_in server_addr;
short int       s_port = 993;
const char      *s_ipaddr = "74.125.77.109";
 int SSL_library_init();
 SSL_METHOD *meth;
 int main () {
SSL_load_error_strings();
    SSL_library_init();
    //RAND_seed(buf, BUFSIZE);

    SSL_CTX *sslContext = SSL_CTX_new(SSLv23_client_method());
    if (sslContext == NULL)
    {
        cout << "err\n";
    }

    SSL *sslConnection = SSL_new(sslContext);
    if(sslConnection == NULL)
    {
        cout << "err\n";
    }

    WSAStartup(MAKEWORD(2,2), &wsda);

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(s_port);
    server_addr.sin_addr.s_addr = inet_addr(s_ipaddr);

    if(server_addr.sin_addr.s_addr == INADDR_NONE)
    {
        host = NULL;
        host = gethostbyname(s_ipaddr);
        if(host == NULL)
        {
            return false;
        }
        memcpy(&server_addr.sin_addr, host->h_addr_list[0], host->h_length);
    }

    connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr));

    SSL_set_fd(sslConnection, sock);

    SSL_connect(sslConnection);
    cout << "Connecting:\n";

    SSL_read(sslConnection, buf, sizeof(buf)-1);
    cout << buf << "\n";

    cout << "Logging-in:\n";
    msg = "a1 login emailapp123@gmail.com PASS\n";
    SSL_write(sslConnection, msg, strlen(msg));

    SSL_read(sslConnection, buf, sizeof(buf)-1);
    cout << buf << "\n";

    cout << "INBOX\n";

    msg = "a2 SELECT INBOX\n";
    SSL_write(sslConnection, msg, strlen(msg));
    SSL_read(sslConnection, buf, sizeof(buf)-1);
    cout << buf << "\n";
    system("pause");
 }

And thats what i receive:

Connecting:
  * OK Gimap ready for requests from 195.150.156.162 y48if37710eei.45

Logging-in:
  * CAPABILITY IMAP4rev1 UNSELECT LITERAL+ IDLE NAMESPACE QUOTA ID XLIST CHILDREN
  X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE
  a1 OK emailapp123@gmail.com authenticated (Success)

INBOX

What should I do to make the connection right?
Thanks for every advice :-)
Chris


问:
java program is not able to read a string
```<code>import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}
</code>```

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

答:
Change this line

```<code>s1 = scan.nextLine();
</code>```

to

```<code>s1 = scan.next();
</code>```

Body:
import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

Body:
Change this line

s1 = scan.nextLine();

to

s1 = scan.next();