问:
Identify start and stop sequences and length of run in R
I am trying to loop over a dataframe and find sequences of events between a start and stop object (an event that occurs at both the beginning and end).

Here is some sample data:

```<code>time = c('8:20', '8:19', '8:15', '8:14', '8:14', '8:10', '8:04', '8:03', '8:00', '7:59', '7:55', '7:44', '7:43','7:42')

action = c('A', 'B', 'C', 'B', 'F', 'T', 'Z', 'U', 'A', 'G', 'B', 'C', 'L', 'Z')

group = c('group1', 'group1', 'group1', 'group2', 'group1', 'group1', 'group2', 'group2','group2', 'group2', 'group2', 'group2', 'group1', 'group1')

test.df = cbind(time, action, group) %>% data.frame()
</code>```

The full data set is longer and wider, but this should suffice.

The rules are, that if one group (either group1 or group2) registers action 'A' and only 'A', it starts the sequence of the run. Any number of events can occur following that, until the opposite group (group2 if group1 initiated 'A', or group 1 if it's the reverse) logs action 'Z'. Action 'Z' by the opposite group signifies the 'end' point of the sequence.

This process iterates hundreds of time over the dataframe.

Each time one of the group starts action 'A', I want every subsequent event to be linked with an ID value that sums for each time the group starts a new sequence over the dataframe, until action 'Z' is taken by the opposite group.

I.E., in the above sample, there would be a new column identifying that it was 'group1' to which the sequence belongs to and this is ID 1, and their next sequence that initiates later in the data set would be ID 2 for group 1, etc.

```<code>time   action   group  group.sequence  id
8:20   A        group1 group1          1
8:19   B        group1 group1          1
8:15   C        group1 group1          1
8:14   B        group2 group1          1
8:14   F        group1 group1          1
[...]
</code>```

That way, summation on time, # of actions in between, types of actions in between can be found. Any actions that occur outside the 'A' to 'Z' actions of a group (example, row 8) can be ignored for now.

Prefer something I can use in my dplyr pipe, but open to any solutions that achieve success.

答:
Here is my attempt using tidyverse. Run the code with a larger dataframe and let me know if your expected answer differs from mine.

```<code>library(tidyverse)

test.df %>%
  mutate_if(is.factor, as.character) %>%
  filter(action != "U") %>%
  mutate(temp = ifelse(paste(group, action) %in%
                         c("group1 A", "group2 A", "group1 Z", "group2 Z"),
                       paste(group, action), NA),
         group.sequence = ifelse(temp %in% c("group1 Z", "group2 Z"), NA, temp),
         group.sequence = ifelse(!is.na(group.sequence), group, NA)) %>%
  group_by(group.sequence) %>%
  mutate(id = 1:n(),
         id = ifelse(is.na(group.sequence), NA, id)) %>%
  ungroup() %>%
  fill(c(group.sequence, id)) %>%
  select(-temp)
#> # A tibble: 13 x 5
#>    time  action group  group.sequence    id
#>    <chr> <chr>  <chr>  <chr>          <int>
#>  1 8:20  A      group1 group1             1
#>  2 8:19  B      group1 group1             1
#>  3 8:15  C      group1 group1             1
#>  4 8:14  B      group2 group1             1
#>  5 8:14  F      group1 group1             1
#>  6 8:10  T      group1 group1             1
#>  7 8:04  Z      group2 group1             1
#>  8 8:00  A      group2 group2             1
#>  9 7:59  G      group2 group2             1
#> 10 7:55  B      group2 group2             1
#> 11 7:44  C      group2 group2             1
#> 12 7:43  L      group1 group2             1
#> 13 7:42  Z      group1 group2             1
</code>```

Body:
I am trying to loop over a dataframe and find sequences of events between a start and stop object (an event that occurs at both the beginning and end).

Here is some sample data:

time = c('8:20', '8:19', '8:15', '8:14', '8:14', '8:10', '8:04', '8:03', '8:00', '7:59', '7:55', '7:44', '7:43','7:42')

action = c('A', 'B', 'C', 'B', 'F', 'T', 'Z', 'U', 'A', 'G', 'B', 'C', 'L', 'Z')

group = c('group1', 'group1', 'group1', 'group2', 'group1', 'group1', 'group2', 'group2','group2', 'group2', 'group2', 'group2', 'group1', 'group1')

test.df = cbind(time, action, group) %>% data.frame()

The full data set is longer and wider, but this should suffice.

The rules are, that if one group (either group1 or group2) registers action 'A' and only 'A', it starts the sequence of the run. Any number of events can occur following that, until the opposite group (group2 if group1 initiated 'A', or group 1 if it's the reverse) logs action 'Z'. Action 'Z' by the opposite group signifies the 'end' point of the sequence.

This process iterates hundreds of time over the dataframe.

Each time one of the group starts action 'A', I want every subsequent event to be linked with an ID value that sums for each time the group starts a new sequence over the dataframe, until action 'Z' is taken by the opposite group.

I.E., in the above sample, there would be a new column identifying that it was 'group1' to which the sequence belongs to and this is ID 1, and their next sequence that initiates later in the data set would be ID 2 for group 1, etc.

time   action   group  group.sequence  id
8:20   A        group1 group1          1
8:19   B        group1 group1          1
8:15   C        group1 group1          1
8:14   B        group2 group1          1
8:14   F        group1 group1          1
[...]

That way, summation on time, # of actions in between, types of actions in between can be found. Any actions that occur outside the 'A' to 'Z' actions of a group (example, row 8) can be ignored for now.

Prefer something I can use in my dplyr pipe, but open to any solutions that achieve success.

Body:
Here is my attempt using tidyverse. Run the code with a larger dataframe and let me know if your expected answer differs from mine.

library(tidyverse)

test.df %>%
  mutate_if(is.factor, as.character) %>%
  filter(action != "U") %>%
  mutate(temp = ifelse(paste(group, action) %in%
                         c("group1 A", "group2 A", "group1 Z", "group2 Z"),
                       paste(group, action), NA),
         group.sequence = ifelse(temp %in% c("group1 Z", "group2 Z"), NA, temp),
         group.sequence = ifelse(!is.na(group.sequence), group, NA)) %>%
  group_by(group.sequence) %>%
  mutate(id = 1:n(),
         id = ifelse(is.na(group.sequence), NA, id)) %>%
  ungroup() %>%
  fill(c(group.sequence, id)) %>%
  select(-temp)
#> # A tibble: 13 x 5
#>    time  action group  group.sequence    id
#>    <chr> <chr>  <chr>  <chr>          <int>
#>  1 8:20  A      group1 group1             1
#>  2 8:19  B      group1 group1             1
#>  3 8:15  C      group1 group1             1
#>  4 8:14  B      group2 group1             1
#>  5 8:14  F      group1 group1             1
#>  6 8:10  T      group1 group1             1
#>  7 8:04  Z      group2 group1             1
#>  8 8:00  A      group2 group2             1
#>  9 7:59  G      group2 group2             1
#> 10 7:55  B      group2 group2             1
#> 11 7:44  C      group2 group2             1
#> 12 7:43  L      group1 group2             1
#> 13 7:42  Z      group1 group2             1


来源: stackexchange

问:
Relate elements in table form from Json file with jq
I'm new to jq and I have the following code to obtain tabulated the values for each element called Abc:

```<code>["Abc"], ( .. | objects | select(has("Abc")) | [.["Abc"]] ) | @tsv
</code>```

This is the current output I get:

```<code>"Abc"
"4"
"2"
"1"
"9"
"3"
"2"
"4"
"9"
</code>```

I would like to add 4 columns to the left to show for each Abc value the corresponding page, row and column. Additionally if possible as first column add a counter from 1 to number of "Abc" elements.

Below I show the current output, compared with the desired output and the structure of the Json file in order to clarify:

The input Json file is below:

```<code>{
  "document": {
    "page": [
      {
        "@index": "0",
        "image": {
          "Abc": "4"
        }
      },
      {
        "@index": "1",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "1"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "3"
                }
              }
            ]
          }
        ]
      },
      {
        "@index": "2",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "4"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}
</code>```

I hope someone could help me. Thanks in advance.

答:
The following solution uses paths and has several advantages, including brevity, simplicity, and that it can easily be adapted to a handle data that is in a different format.

For clarity, we begin by defining a function that adds the row numbers:

```<code># add a sequential id, starting at 1
def tsvRows(s):
  foreach s as $s (0; .+1; [.] + $s)
  | @tsv;

(["counter", "page", "row", "column", "Abc"] | @tsv),
tsvRows(paths as $p
  | select($p[-1] == "Abc")
  | getpath($p) as $v
  | $p
  | .[2] as $page
  | (if .[3] == "row" then .[4] else null end) as $row
  | (if .[5] == "column" then .[6] else null end) as $column
  | [$page, $row, $column, $v] )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to jq and I have the following code to obtain tabulated the values for each element called Abc:

["Abc"], ( .. | objects | select(has("Abc")) | [.["Abc"]] ) | @tsv

This is the current output I get:

"Abc"
"4"
"2"
"1"
"9"
"3"
"2"
"4"
"9"

I would like to add 4 columns to the left to show for each Abc value the corresponding page, row and column. Additionally if possible as first column add a counter from 1 to number of "Abc" elements.

Below I show the current output, compared with the desired output and the structure of the Json file in order to clarify:

The input Json file is below:

{
  "document": {
    "page": [
      {
        "@index": "0",
        "image": {
          "Abc": "4"
        }
      },
      {
        "@index": "1",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "1"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "3"
                }
              }
            ]
          }
        ]
      },
      {
        "@index": "2",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "4"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

I hope someone could help me. Thanks in advance.

Body:
The following solution uses paths and has several advantages, including brevity, simplicity, and that it can easily be adapted to a handle data that is in a different format.

For clarity, we begin by defining a function that adds the row numbers:

# add a sequential id, starting at 1
def tsvRows(s):
  foreach s as $s (0; .+1; [.] + $s)
  | @tsv;

(["counter", "page", "row", "column", "Abc"] | @tsv),
tsvRows(paths as $p
  | select($p[-1] == "Abc")
  | getpath($p) as $v
  | $p
  | .[2] as $page
  | (if .[3] == "row" then .[4] else null end) as $row
  | (if .[5] == "column" then .[6] else null end) as $column
  | [$page, $row, $column, $v] )


问:
How to make where condition always be true with field =?
I have a sql statement follow:

select * from table where id = ?

Now, problem is, l don't know whether front end will send me the value of id, if it did, this sql seem like id = 1, and if not, sql should be like id = true(fake code) to find all data

How could I write my sql?

Or, It is fundamentally wrong?

答:
What you can try doing is in your code, write a function for fetching a specific record, and another function for fetching all the records from your table.

In PHP, it  could be something like:

```<code>// Fetching a specific record
function getCustomerRecord($customerId) {
     // Code to fetch specific record from database
}

// Fetching all records
function getAllCustomerRecords() {
     // Code to fetch all records from database
}
</code>```

In the function where you process requests received, check first if a value for id was passed. If a value for id was passed, call the function to fetch a specific record, making sure to pass along the value you received as an argument. Otherwise, call the function to fetch all the records from your table.

Body:
What you can try doing is in your code, write a function for fetching a specific record, and another function for fetching all the records from your table.

In PHP, it  could be something like:

// Fetching a specific record
function getCustomerRecord($customerId) {
     // Code to fetch specific record from database
}

// Fetching all records
function getAllCustomerRecords() {
     // Code to fetch all records from database
}

In the function where you process requests received, check first if a value for id was passed. If a value for id was passed, call the function to fetch a specific record, making sure to pass along the value you received as an argument. Otherwise, call the function to fetch all the records from your table.


问:
Handling database errors in sinatra
I'm writing a Sinatra http-server with active-record. I'm using pg database to store data.

In this code I want to get all Cars from database with params (name, give them order, limit them) and I need to handle errors which are coming from the database.

For example if I ping '/cars' from curl:

```<code>curl -X GET http://localhost:8080/cars?attribute=error
</code>```

I need the result:
    'Sorry, but there is no attribute with name error'

```<code>get '/cars' do
  @cars = Car.order("#{params[:attribute]} #{params[:order]}").limit(params[:limit]).offset(params[:offset])
  @cars.to_json
 end
</code>```

How can I handle exceptions which are coming from the database and display them to the user?

答:
You need to check incoming attribute parameter</p>

```<code>get '/cars' do
  if Car.columns.map(&:name).include?(params[:attribute])
    @cars = Car.order("#{params[:attribute]} #{params[:order]}")
             .limit(params[:limit]).offset(params[:offset])
    @cars.to_json
  else
    { error: 'Sorry, but there is no attribute with name error' }.to_json
  end
end
</code>```

Title: Handling database errors in sinatra

Body:
I'm writing a Sinatra http-server with active-record. I'm using pg database to store data.

In this code I want to get all Cars from database with params (name, give them order, limit them) and I need to handle errors which are coming from the database.

For example if I ping '/cars' from curl:

curl -X GET http://localhost:8080/cars?attribute=error

I need the result:
    'Sorry, but there is no attribute with name error'

get '/cars' do
  @cars = Car.order("#{params[:attribute]} #{params[:order]}").limit(params[:limit]).offset(params[:offset])
  @cars.to_json
 end

How can I handle exceptions which are coming from the database and display them to the user?

Body:
You need to check incoming attribute parameter

get '/cars' do
  if Car.columns.map(&:name).include?(params[:attribute])
    @cars = Car.order("#{params[:attribute]} #{params[:order]}")
             .limit(params[:limit]).offset(params[:offset])
    @cars.to_json
  else
    { error: 'Sorry, but there is no attribute with name error' }.to_json
  end
end


问:
How to click on lines in a textarea element
I have this textarea element, and i want each line in the box to be clickable and respond to javascript events, is that possible or am i looking for a different type of element?</p>

答: That is not possible. In order for you do produce such behavior, you would need to design your own "textbox". Google Docs has done this for example, where the entire "textarea" is a complex and highly functional set of divs etc.</p>

ContentLicense: CC BY-SA 3.0


问:
Returning Nan while my all values are number type
i'm making the summary function that will show the summary of myToDos, but in console it shows "You have NaN meetings today!" while i'm using all the variables of number type.

let myTodos={
    day: 'Monday',
    meetings: 0,
    meetDone: 0,

    addMeeting: function(num){
        this.meetings = this.meetings + num;
    },
    meetDone: function(meet=0) {
        this.meetDone = this.meetDone + meet;
    },
    resetDay: function(){
        this.meetings = 0;
        this.meetDone = 0;
    },
    summary: function(){
        let leftmeetings = this.meetings - this.meetDone;
        return `You have ${leftmeetings} meetings today!`
    }
}

myTodos.addMeeting(5);
myTodos.meetDone(3);
console.log(myTodos.summary());```
</div>
</div>
</p>

<p>I expect the output as</p>

<blockquote>
  <p>javascript</p>
</blockquote>

```"You have 2 meetings today!"
```

答:
As mentioned in the comments you have duplicate properties.

Renaming meetDone to done will remove the conflict.

```<code>let myTodos = {
  day: "Monday",
  meetings: 0,
  done: 0,

  addMeeting: function(num) {
    this.meetings = this.meetings + num;
  },
  meetDone: function(meet = 0) {
    this.done = this.done + meet;
  },
  resetDay: function() {
    this.meetings = 0;
    this.meetDone = 0;
  },
  summary: function() {
    let leftmeetings = this.meetings - this.done;
    return `You have ${leftmeetings} meetings today!`;
  }
};

myTodos.addMeeting(5);
myTodos.meetDone(3);
console.log(myTodos.summary());
</code>```

Output:

You have 2 meetings today!

Body:
i'm making the summary function that will show the summary of myToDos, but in console it shows "You have NaN meetings today!" while i'm using all the variables of number type.

let myTodos={
    day: 'Monday',
    meetings: 0,
    meetDone: 0,

    addMeeting: function(num){
        this.meetings = this.meetings + num;
    },
    meetDone: function(meet=0) {
        this.meetDone = this.meetDone + meet;
    },
    resetDay: function(){
        this.meetings = 0;
        this.meetDone = 0;
    },
    summary: function(){
        let leftmeetings = this.meetings - this.meetDone;
        return `You have ${leftmeetings} meetings today!`
    }
}

myTodos.addMeeting(5);
myTodos.meetDone(3);
console.log(myTodos.summary());

I expect the output as

javascript

"You have 2 meetings today!"

Body:
As mentioned in the comments you have duplicate properties.

Renaming meetDone to done will remove the conflict.

let myTodos = {
  day: "Monday",
  meetings: 0,
  done: 0,

  addMeeting: function(num) {
    this.meetings = this.meetings + num;
  },
  meetDone: function(meet = 0) {
    this.done = this.done + meet;
  },
  resetDay: function() {
    this.meetings = 0;
    this.meetDone = 0;
  },
  summary: function() {
    let leftmeetings = this.meetings - this.done;
    return `You have ${leftmeetings} meetings today!`;
  }
};

myTodos.addMeeting(5);
myTodos.meetDone(3);
console.log(myTodos.summary());

Output:

You have 2 meetings today!


问:
Java: How to create new child class instance from abstract parent class?
Here is the gist of what I am trying to do:

```<code>abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}
</code>```

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

答:
I want to be able to call Dog.makeFive() to give me a List or
  Cat.makeFive() to give me a List without having to re-define
  makeFive() in Dog, Cat, and every other animal class.

I feel your pain!  It looks so much like it should be possible, but as the other answers and comments say, Java for whatever reason does not allow it.

So IMHO, the best workaround is to have the single makeFive method in Animal, and pass the destination class to it.

So your caller would be :

```<code>List<Dog> dogList = Animal.makeFive(Dog.class);
</code>```

The implementation would be :

```<code>public abstract class Animal {

    public abstract void initialise(String input);

    static <T extends Animal> List<T> makeFive(Class<T> clazz) {
        List<T> animals = new ArrayList<T>();
        animals.add(makeNew(clazz, "Input 1"));
        animals.add(makeNew(clazz, "Input 2"));
        animals.add(makeNew(clazz, "Input 3"));
        animals.add(makeNew(clazz, "Input 4"));
        animals.add(makeNew(clazz, "Input 5"));
        return animals;
    }

    private static <T extends Animal> T makeNew(Class<T> clazz, String input) {
        T newAnimal;
        try {
            newAnimal = clazz.newInstance();
            newAnimal.initialise(input);
        } catch (InstantiationException | IllegalAccessException e) {
            newAnimal = null;  // Change This !!!  Maybe throw exception, or add "throws" to method declaration
        }
        return newAnimal;
    }

}
</code>```

And finally, have each animal type perform it's initialisation :

```<code>class Dog extends Animal {

    @Override
    public void initialise(String input) {
        // do some initial dog stuff with input
    }
}
</code>```

This approach does require that each subclass (Dog, Cat, etc) have a no-argument constructor, but that's a fairly common requirement for various objects in the Java ecosystem.

Alternatively, it could be possible to have the Animal.makeNew method use reflection to find an appropriate constructor, but I personally would advise against that since it becomes difficult to maintain.

Body:
Here is the gist of what I am trying to do:

abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

Body:
I want to be able to call Dog.makeFive() to give me a List or
  Cat.makeFive() to give me a List without having to re-define
  makeFive() in Dog, Cat, and every other animal class.

I feel your pain!  It looks so much like it should be possible, but as the other answers and comments say, Java for whatever reason does not allow it.

So IMHO, the best workaround is to have the single makeFive method in Animal, and pass the destination class to it.

So your caller would be :

List<Dog> dogList = Animal.makeFive(Dog.class);

The implementation would be :

public abstract class Animal {

    public abstract void initialise(String input);

    static <T extends Animal> List<T> makeFive(Class<T> clazz) {
        List<T> animals = new ArrayList<T>();
        animals.add(makeNew(clazz, "Input 1"));
        animals.add(makeNew(clazz, "Input 2"));
        animals.add(makeNew(clazz, "Input 3"));
        animals.add(makeNew(clazz, "Input 4"));
        animals.add(makeNew(clazz, "Input 5"));
        return animals;
    }

    private static <T extends Animal> T makeNew(Class<T> clazz, String input) {
        T newAnimal;
        try {
            newAnimal = clazz.newInstance();
            newAnimal.initialise(input);
        } catch (InstantiationException | IllegalAccessException e) {
            newAnimal = null;  // Change This !!!  Maybe throw exception, or add "throws" to method declaration
        }
        return newAnimal;
    }

}

And finally, have each animal type perform it's initialisation :

class Dog extends Animal {

    @Override
    public void initialise(String input) {
        // do some initial dog stuff with input
    }
}

This approach does require that each subclass (Dog, Cat, etc) have a no-argument constructor, but that's a fairly common requirement for various objects in the Java ecosystem.

Alternatively, it could be possible to have the Animal.makeNew method use reflection to find an appropriate constructor, but I personally would advise against that since it becomes difficult to maintain.


问:
Get the amount of days between two given days of the week
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

```<code>const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)
</code>```

Monday to Thursday is easy enough :

```<code>let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1
</code>```

But Thursday to Monday (for example) needs some logic that I can't figure out.

答:
Something like this would work:

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let getDayDistance = (days, from, to) => {
  let f = days.indexOf(from), t = days.indexOf(to)
  return f < t ? (t - f) : (days.length - f) + t
}

console.log(getDayDistance(days, 'Monday', 'Thursday'))   // 3
console.log(getDayDistance(days, 'Thursday', 'Monday'))   // 4
console.log(getDayDistance(days, 'Sunday', 'Saturday'))   // 6
console.log(getDayDistance(days, 'Saturday', 'Friday'))   // 6
console.log(getDayDistance(days, 'Thursday', 'Tuesday'))  // 5
console.log(getDayDistance(days, 'Wednesday', 'Sunday'))  // 4
console.log(getDayDistance(days, 'Friday', 'Tuesday'))    // 4 ```

Body:
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)

Monday to Thursday is easy enough :

let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1

But Thursday to Monday (for example) needs some logic that I can't figure out.


问:
how to use firebase cloud function pubsub.schedule?
Today, there is new feature of Cloud Functions for Firebase which is running functions on a schedule. So I tried to test the sample code.

index.js file

```<code>exports.scheduledFunction = functions.pubsub.schedule(‘every 5 minutes’).onRun((context) => {
  console.log(‘This will be run every 5 minutes!’);
});
</code>```

But when I tried to deploy this, I got the following error message:

```<code>Error: Error occurred while parsing your function triggers.

TypeError: functions.pubsub.schedule is not a function
</code>```

My firebase tools version is 6.7 (updated today)

What is the solution?

I checked the example git code in here (https://github.com/firebase/functions-samples/blob/master/delete-unused-accounts-cron/functions/index.js)

But it also cause the same error:

functions.pubsub.schedule is not a function

Can anyone help me with this problem?

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
   console.log('This will be run every 5 minutes!');
});
</code>```

答:
Here's the documentation https://firebase.google.com/docs/functions/schedule-functions

```<code>export const scheduledFunction = functions.pubsub.schedule('every 5 minutes')
.timeZone('Asia/Jakarta')
.onRun((context) => {
    console.log('This will be run every 5 minutes!');
});
</code>```

And you can set the timeZone as additional

Body:
Today, there is new feature of Cloud Functions for Firebase which is running functions on a schedule. So I tried to test the sample code.

index.js file

exports.scheduledFunction = functions.pubsub.schedule(‘every 5 minutes’).onRun((context) => {
  console.log(‘This will be run every 5 minutes!’);
});

But when I tried to deploy this, I got the following error message:

Error: Error occurred while parsing your function triggers.

TypeError: functions.pubsub.schedule is not a function

My firebase tools version is 6.7 (updated today)

What is the solution?

I checked the example git code in here (https://github.com/firebase/functions-samples/blob/master/delete-unused-accounts-cron/functions/index.js)

But it also cause the same error:

functions.pubsub.schedule is not a function

Can anyone help me with this problem?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
   console.log('This will be run every 5 minutes!');
});

Body:
Here's the documentation https://firebase.google.com/docs/functions/schedule-functions

export const scheduledFunction = functions.pubsub.schedule('every 5 minutes')
.timeZone('Asia/Jakarta')
.onRun((context) => {
    console.log('This will be run every 5 minutes!');
});

And you can set the timeZone as additional


问:
Formula in Excel to match a value in two columns with an occurence date of 24 hours difference
I am trying to match products in two different tables by their product name and date/time. I'm looking to find a match between column A & K if the date in column C occurred 24 hours BEFORE column L.

I have attached a picture of the matches I'm looking for & highlighted the ones that should result in a match.

thank you in advance for your help - this is far more advance than my knowledge of excel unfortunately, so I really appreciate the assistance.

Body:
This can be accomplished with COUNTIFS.

=IF(COUNTIFS($K$2:$K$8,A2,$L$2:$L$8,">="&C2,$L$2:$L$8,"<="&C2+1)>0,A2,"")


问:
Google Analytics Events - Triggering a user exit
I am looking for a way to simulate with Google Analytics _gaq.push that the user has left the page (so GA stops counting on Average time on site).

This is some code I use to track AJAX pages in Google Analytics (it counts a page view):

```<code>_gaq.push(['_trackPageview', '/ajax/save']);
</code>```

What I am looking for is something such as:

```<code>_gaq.push(['_exitCurrentPage', 'http://example.com/']);
</code>```

Does anything with that functionality exist?

Thanks in advance,

Xavi

答: I don't think that there's any specific functionality in GA for this but you could just set a cookie called something like dont_track then set it to simulate the page exit. You could then check for the cookie's existence before calling your normal tracking code and stop execution if it exists.

Body:
I am looking for a way to simulate with Google Analytics _gaq.push that the user has left the page (so GA stops counting on Average time on site).

This is some code I use to track AJAX pages in Google Analytics (it counts a page view):

_gaq.push(['_trackPageview', '/ajax/save']);

What I am looking for is something such as:

_gaq.push(['_exitCurrentPage', 'http://example.com/']);

Does anything with that functionality exist?

Thanks in advance,

Xavi


问:
How to get a userID from Firebase Database
Today i try to get some child of firebase database, i dont know if my structure is a best of my case so i have a app like a "rappi" and i have child empresa and child if user id like this:

so i want to get child inside pet shop and user Logged is inside farmacia. i want to know is a better method to get id from empresa.

```<code>DatabaseReference produtosRef = firebaseRef
            .child("empresa")
            .child( "How i get this?" )
            .child(UserID);
</code>```

I don't know how to get a second instance

Edit1: I want to get user id if out pass "petshop" or " farmácia"

答:
I think you have already had a custom class to store objects. If not, create it!

```<code>class YourClass{
    public String categoria;
    public String email;
    public String uid;
    ///....and some attributes as in your pic you posted
}
</code>```

Next, at somewhere in your code. to get all objects from database. you need to add child event listener to your firebase reference.

```<code>ArrayList < YourClass > objects = new ArrayList < > ();
    DatabaseReference dataRef =
     FirebaseDatabase.getInstance().getReference("empresa").child("farmacia");
    dataRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildChanged(DataSnapshot snapshot, String previousChildName) {}

     @Override
     public void onCancelled() {
        System.err.println("Listener was cancelled");
     }

     @Override
     public void onChildAdded(DataSnapshot snapshot, String arg1) {
        YourClass object =
           (YourClass(dataSnapshot.getValue(YourClass.class));
        if (object != null) objects.add(object);
        //from now you have object so you can access and modify or do anything with it
     }

     @Override
     public void onChildMoved(DataSnapshot arg0, String arg1) {
      // TODO Auto-generated method stub

     }

     @Override
     public void onChildRemoved(DataSnapshot arg0) {
      // TODO Auto-generated method stub

     }
 });
</code>```

Body:
Today i try to get some child of firebase database, i dont know if my structure is a best of my case so i have a app like a "rappi" and i have child empresa and child if user id like this:

so i want to get child inside pet shop and user Logged is inside farmacia. i want to know is a better method to get id from empresa.

DatabaseReference produtosRef = firebaseRef
            .child("empresa")
            .child( "How i get this?" )
            .child(UserID);

I don't know how to get a second instance

Edit1: I want to get user id if out pass "petshop" or " farmácia"

Body:
I think you have already had a custom class to store objects. If not, create it!

class YourClass{
    public String categoria;
    public String email;
    public String uid;
    ///....and some attributes as in your pic you posted
}

Next, at somewhere in your code. to get all objects from database. you need to add child event listener to your firebase reference.

ArrayList < YourClass > objects = new ArrayList < > ();
    DatabaseReference dataRef =
     FirebaseDatabase.getInstance().getReference("empresa").child("farmacia");
    dataRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildChanged(DataSnapshot snapshot, String previousChildName) {}

     @Override
     public void onCancelled() {
        System.err.println("Listener was cancelled");
     }

     @Override
     public void onChildAdded(DataSnapshot snapshot, String arg1) {
        YourClass object =
           (YourClass(dataSnapshot.getValue(YourClass.class));
        if (object != null) objects.add(object);
        //from now you have object so you can access and modify or do anything with it
     }

     @Override
     public void onChildMoved(DataSnapshot arg0, String arg1) {
      // TODO Auto-generated method stub

     }

     @Override
     public void onChildRemoved(DataSnapshot arg0) {
      // TODO Auto-generated method stub

     }
 });


问:
How do I make a circle semi-transparent in pygame?
I want to make a partially transparent circle as an area of effect indicator, but I haven't found any way to do this in pygame.

I tried passing in an rgba 4-tuple as an argument (as suggested by this post), but it didn't change the transparency at all. On top of that, according to this other post, the method shouldn't work at all, since draw doesn't accept alpha values. That's conflicting information.

```<code>pygame.draw.circle(screen, (255, 0, 0, 100), (x, y), r)
</code>```

I've also tried creating a new surface, drawing the circle onto that surface, and then blitting the new surface onto my game screen (as suggested by this post). It gives me a semi-transparent circle as requested, but since surfaces in pygame are rectangular, it also gives me a gray rectangle around the circle, which I don't want.

```<code>s = pygame.Surface((1000, 1000))
s.set_alpha(100)
pygame.draw.circle(s, (255, 0, 0), (x, y), r)
screen.blit(s, (0, 0))
</code>```

Is there any way to make this circle semi-transparent without adding any other visible effects to my screen?

答:
Here's a runnable version of the answer to the last question you linked to titled How to draw a semi-transparent circle in Pygame?. It seems to do what you want, as far as I can tell.</p>

```<code>import pygame

width, height = 640, 480

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width,height))
surface = pygame.display.set_mode((width,height), pygame.SRCALPHA)

while True:
    msElapsed = clock.tick(100)
    screen.fill((255,255,255))
    pygame.draw.circle(surface,(30,224,33,100),(250,100),10)
    screen.blit(surface, (0,0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
</code>```

Body:
I want to make a partially transparent circle as an area of effect indicator, but I haven't found any way to do this in pygame.

I tried passing in an rgba 4-tuple as an argument (as suggested by this post), but it didn't change the transparency at all. On top of that, according to this other post, the method shouldn't work at all, since draw doesn't accept alpha values. That's conflicting information.

pygame.draw.circle(screen, (255, 0, 0, 100), (x, y), r)

I've also tried creating a new surface, drawing the circle onto that surface, and then blitting the new surface onto my game screen (as suggested by this post). It gives me a semi-transparent circle as requested, but since surfaces in pygame are rectangular, it also gives me a gray rectangle around the circle, which I don't want.

s = pygame.Surface((1000, 1000))
s.set_alpha(100)
pygame.draw.circle(s, (255, 0, 0), (x, y), r)
screen.blit(s, (0, 0))

Is there any way to make this circle semi-transparent without adding any other visible effects to my screen?

Body:
Here's a runnable version of the answer to the last question you linked to titled How to draw a semi-transparent circle in Pygame?. It seems to do what you want, as far as I can tell.

import pygame

width, height = 640, 480

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width,height))
surface = pygame.display.set_mode((width,height), pygame.SRCALPHA)

while True:
    msElapsed = clock.tick(100)
    screen.fill((255,255,255))
    pygame.draw.circle(surface,(30,224,33,100),(250,100),10)
    screen.blit(surface, (0,0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()


问:
Excel Ledger with running Balance using sumif
I want to make a ledger with multiple currency, problem i m getting is in running balance

答:
Use this in your G6 cell.. then drag downwards.

=IF(ISNUMBER(G5),G5,0)+IF([@Currency]=$D$1,[@Debit],0)-IF([@Currency]=$D$1,[@Credit],0)

You may edit the $D$1 & G5 to match the other currency/column.

idea : if top = value, copy. If debit/credit = have value, add/minus from the copied value.

Please share if it solves (or not)..


问:
why not use system timer on linux(timerfd)?
I found that most of the server(for example, RPG web game server) always realize a timer by themselves instead of using system timer, for example on linux,

```<code>int timerfd_create(int clockid, int flags)
</code>```

Could you tell me why ? I think the system api(timerfd_create) can have a higher performance.

答:
There are at least two potential reasons that I can think of to not use timerfds in a program:

1) The program is a server that maintains a large number of open connections. By default, Linux allows a process to have 1024 descriptors per process. This can be changed, however, the fact remains that file descriptors are not a free resource and if you have thousands of open socket connections, you will likely have at least that many timers in order to manage timeouts. All this adds up to a lot of descriptors.

2) There is probably more overhead to using timerfds than there would be to manage a set of timers in user space. Blocking on a call to select() or, more appropriately, epoll_wait(), involves a system call, while one could manage a large set of timers in user space without any such transitions, given that clock_gettime() doesn't require one.

http://linuxmogeb.blogspot.com/2013/10/how-does-clockgettime-work.html

Body:
I found that most of the server(for example, RPG web game server) always realize a timer by themselves instead of using system timer, for example on linux,

int timerfd_create(int clockid, int flags)

Could you tell me why ? I think the system api(timerfd_create) can have a higher performance.


问:
Queries related to utilization, distribution and pricing of IP addresses on Azure
I have queries related to utilization, distribution and pricing of IP addresses on Azure.

Taking an example, 10.0.0.0/27. It says, 10.0.0.0 - 10.0.0.31 (32 addresses).

After expanding I found as..

CIDR Range: 10.0.0.0/27
Netmask: 255.255.255.224
Wildcard Bits: 0.0.0.31
First IP: 10.0.0.0
Last IP: 10.0.0.31
Total Host: 32

I assigned 10.0.0.0/27 for both VNet and Subnet on Azure Portal.
After creating the virtual network, I see available address 27.

1) No virtual machine created yet, then why the available addresses are 27?

2) What is the IP range for 27 available addresses?

While creating Gateway Subnet, I see errors like...

The specified address space overlaps with subnet 'Subnet1' which has a range of '10.0.0.0/27'.

Your subnet is not contained within the address space for this virtual network: 10.0.0.0/27.

3) How to calculate and decide the available gateway subnet address space for a virtual network?

4) For using gateway subnet, is it mandatory or recommended to add another subnet before or after creating gateway subnet?

5) Why address space is required for creating a gateway subnet? Is gateway subnet not a fixed or static IP address for creating connection?

6) In case of virtual network, 10.0.0.0/27, is pricing done on the basis of utilized IP addresses only?

7) In case of virtual network, 10.0.0.0/27, if there are some un-utilized IP addresses, are they blocked to me or  my subscription or un-utilized IP addresses can be used by someone else on his azure portal?

I sincerely request to clarify all seven queries.

答:
Q1-Q3:

Read Azure VNet FAQ, Azure reserves 5 IP addresses within each subnet. These are x.x.x.0-x.x.x.3 and the last address of the subnet. So you have 27 available addresses for the address range 10.0.0.0/27. It's address range 10.0.0.4 - 10.0.0.30

Q4: It's not mandatory for creating Gateway subnet order, you only need to calculate the CIDR Range for each subnet including in your current virtual network address range.

Q5: If you need to configure a virtual network gateway. The gateway subnet contains the IP addresses that the virtual network gateway services use. All gateway subnets must be named GatewaySubnet to work properly. Read here. If you don't need a VPN gateway, you don't need to create Gateway subnet in this VNet.

Q6-Q7: Have a look at Azure VNet pricing and VPN gateway pricing.

Azure Virtual Network is free of charge. Every subscription is allowed
  to create up to 50 virtual networks across all regions.

Public IP addresses, and reserved IP addresses used on services inside
  a virtual network, are charged.

Network appliances such as VPN Gateway and Application Gateway that
  are run inside a virtual network are also charged.

For the un-utilized IP addresses, It looks like unassigned private IP address in your on-premise network. They can continue to be assigned to the resources when you deployed some resources in the VNet or subnet.

For more details, you can read this blog: Understanding CIDR Notation when designing Azure Virtual Networks and Subnets


问:
How to mock resttemplate by mockito
I want to mock a resttemplate request,but it seems not work.
Here is the class that i want test:

public class SomeUtil {
    public static OrderInstanceResponse doGet(String url, otherargs...) {
       //some code...
       ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestHeader, String.class, requestMap);
       //another code...
    }
}
```

<p>Here is the Test Class:</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(MockitoJUnitRunner.class)
public class SomeUtilTest {
    @Mock
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void doGet() {
        OrderInstanceResponse exceptResponse = OrderInstanceResponse.builder().code("123").build();
        OrderInstanceRequest request = OrderInstanceRequest.builder().userId("123").build();

        Map<String, Object> testMap = new HashMap<>(1);
        testMap.put("userId", "123");

        Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.eq(String.class), Mockito.eq(testMap)))
                .thenReturn(new ResponseEntity<>("\"code\":\"123\"", HttpStatus.OK));

        OrderInstanceResponse actualResponse = RestTemplateUtil.doGet("123", request, "123");
        Assert.assertEquals(actualResponse.getCode(), exceptResponse.getCode());
    }
}
</code>```

There are some errors when I run this test:
java.lang.IllegalArgumentException: URI is not absolute.

It seems that mock not work,There was a real request to "123".

How can i fix this bug?thanks

答:
I found a solution.
When we need to mock a object that created by new, like RestTemplate rest = new RestTemplate(), should be written like this：

PowerMockito.whenNew(ObjectToBeMocked.class).withAnyArguments().thenReturn(mockedObject);
```

<p>Then add annotation <code>@PrepareForTest({TheClassToBeTested.class})</code>. Please note, the param is the class that containing the object obtained by <code>new</code>.
So, the complete code is as follows:</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({SomeUtil.class})
public class SomeUtilTest {

    @Mock
    private RestTemplate restTemplate;

    @Test
    public void doGet() {
        //......
        PowerMockito.whenNew(RestTemplate.class).withAnyArguments().thenReturn(restTemplate);
        //......
    }
}
</code>```

Thanks all the friends who helped me.

Title: How to mock resttemplate by mockito

Body:
I want to mock a resttemplate request,but it seems not work.
Here is the class that i want test:

public class SomeUtil {
    public static OrderInstanceResponse doGet(String url, otherargs...) {
       //some code...
       ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestHeader, String.class, requestMap);
       //another code...
    }
}

Here is the Test Class:

@RunWith(MockitoJUnitRunner.class)
public class SomeUtilTest {
    @Mock
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void doGet() {
        OrderInstanceResponse exceptResponse = OrderInstanceResponse.builder().code("123").build();
        OrderInstanceRequest request = OrderInstanceRequest.builder().userId("123").build();

        Map<String, Object> testMap = new HashMap<>(1);
        testMap.put("userId", "123");

        Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.eq(String.class), Mockito.eq(testMap)))
                .thenReturn(new ResponseEntity<>("\"code\":\"123\"", HttpStatus.OK));

        OrderInstanceResponse actualResponse = RestTemplateUtil.doGet("123", request, "123");
        Assert.assertEquals(actualResponse.getCode(), exceptResponse.getCode());
    }
}

There are some errors when I run this test:
java.lang.IllegalArgumentException: URI is not absolute.

It seems that mock not work,There was a real request to "123".

How can i fix this bug?thanks

Body:
I found a solution.
When we need to mock a object that created by new, like RestTemplate rest = new RestTemplate(), should be written like this：

PowerMockito.whenNew(ObjectToBeMocked.class).withAnyArguments().thenReturn(mockedObject);

Then add annotation @PrepareForTest({TheClassToBeTested.class}). Please note, the param is the class that containing the object obtained by new.
So, the complete code is as follows:

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({SomeUtil.class})
public class SomeUtilTest {

    @Mock
    private RestTemplate restTemplate;

    @Test
    public void doGet() {
        //......
        PowerMockito.whenNew(RestTemplate.class).withAnyArguments().thenReturn(restTemplate);
        //......
    }
}

Thanks all the friends who helped me.


问:
Insert data to MySQL with Ajax in Laravel
I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. But I don't know how to write it right. This is what I tried in my blade view:

      <button id="saveBtn" type="button">Save To Database</button>

```

But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found).

How I can fix this?

Thank you very much!

答:
First, enter your database details on .env file.

You need to use two routes. One for the blade file to render and another for the api request.

On routes/web.php, define your route,

```<code>Route::get('/', function(){ return view('app');});
</code>```

Create app.blade.php in resources/views/ folder with your HTML code.

On routes/api.php, define your route like this

```<code>Route::post('saveToDatabase','HomeController@saveToDb')
</code>```

Next, you need to create saveToDb method on the HomeController.

Open App\Http\Controller\HomeController.php

Create a new method

```<code>public function saveToDb()
{
  // Database Insertion Code goes here

}
</code>```

Laravel Provide CSRF Protection to the POST request. So add Exception to this route by adding it in the App\Http\Middleware\VerifyCSRFToken.php

```<code>  protected $except = [
        'api/*'
    ];
</code>```

For the insertion operation, we can do this with the help of the model.

So first create Form.php in App\ folder.

Inside that, we specify the fields of the database.

```<code><?php

use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    protected $fillable = [
        "key", "data"
    ];

    protected $hidden = [];

}

</code>```

Next, we can use this model to insert data to the Form table.

In your HomeController.php at the top

```<code>use App\Form;
use Request;
</code>```

Now we can update the saveToDb function that we write before.

```<code>public function saveToDb()
{
  // Request all the post data
  $req = Request::all();
  // From that post data store key and data part to form table
  Form::create($req);
}
</code>```

If you have any issue in route, controller or model. Refer Laravel official docs: https://laravel.com/docs/5.8/routing

And this one is also useful to get started to laravel. https://laracasts.com/series/laravel-from-scratch-2018

Body:
I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. But I don't know how to write it right. This is what I tried in my blade view:

      <button id="saveBtn" type="button">Save To Database</button>

But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found).

How I can fix this?

Thank you very much!

Body:
First, enter your database details on .env file.

You need to use two routes. One for the blade file to render and another for the api request.

On routes/web.php, define your route,

Route::get('/', function(){ return view('app');});

Create app.blade.php in resources/views/ folder with your HTML code.

On routes/api.php, define your route like this

Route::post('saveToDatabase','HomeController@saveToDb')

Next, you need to create saveToDb method on the HomeController.

Open App\Http\Controller\HomeController.php

Create a new method

public function saveToDb()
{
  // Database Insertion Code goes here

}

Laravel Provide CSRF Protection to the POST request. So add Exception to this route by adding it in the App\Http\Middleware\VerifyCSRFToken.php

  protected $except = [
        'api/*'
    ];

For the insertion operation, we can do this with the help of the model.

So first create Form.php in App\ folder.

Inside that, we specify the fields of the database.

<?php

use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    protected $fillable = [
        "key", "data"
    ];

    protected $hidden = [];

}

Next, we can use this model to insert data to the Form table.

In your HomeController.php at the top

use App\Form;
use Request;

Now we can update the saveToDb function that we write before.

public function saveToDb()
{
  // Request all the post data
  $req = Request::all();
  // From that post data store key and data part to form table
  Form::create($req);
}

If you have any issue in route, controller or model. Refer Laravel official docs: https://laravel.com/docs/5.8/routing

And this one is also useful to get started to laravel. https://laracasts.com/series/laravel-from-scratch-2018


答:
This is normally handled by using logic such as this:

```<code>select *
from table
where id = ? or ? is null;
</code>```

If you don't want to pass the parameter twice or use named parameters:

```<code>select t.*
from table t cross join
     (select ? as param) params
where id = params.param or params.param is null;
</code>```

If you want to return all ids if the passed-in value does not exist:

```<code>select t.*
from table t
where id = ? or
      not exists (select 1 from table t2 where t2.id = ?);
</code>```

Title: How to make where condition always be true with field =?

Body:
I have a sql statement follow:

select * from table where id = ?

Now, problem is, l don't know whether front end will send me the value of id, if it did, this sql seem like id = 1, and if not, sql should be like id = true(fake code) to find all data

How could I write my sql?

Or, It is fundamentally wrong?

Body:
This is normally handled by using logic such as this:

select *
from table
where id = ? or ? is null;

If you don't want to pass the parameter twice or use named parameters:

select t.*
from table t cross join
     (select ? as param) params
where id = params.param or params.param is null;

If you want to return all ids if the passed-in value does not exist:

select t.*
from table t
where id = ? or
      not exists (select 1 from table t2 where t2.id = ?);


问:
Stream 'Azure Blob Storage' file URL to Amazon S3 bucket
I am consuming a document-sharing API in my application, which when used, returns a "downloadUrl" for a given file located in Azure Blob Storage.

I want to take that Azure Blob Storage url, and stream the document into an Amazon S3 bucket.

How would I go about doing this? I see similar questions such as Copy from Azure Blob to AWS S3 using C# , but in that example they seem to have access to the stream of the document itself. Is there any way for me to simply provide S3 with the link, and have them do the rest? Or do I need to get the file on the server, and stream it as in the example above?

Thanks in advance for the help.

答:
There is only one case where S3 can be directed to fetch content "into" an object, and that is when the source is also an existing S3 object.  It can be in the same bucket or a different bucket, or even a different AWS region or account, as long as the calling user has permissions on both source and target.

Any other case -- such as what you are contemplating -- requires that you fetch the object from the source, yourself, and then upload it into S3... as in the example.


问:
Not getting expected output in we scraping R
I have written a small program.
Where I scrape Google search website and I want all the URL on the Google search web page. But I'm getting character(0) in the O/P. Plz help me.

CODE -

```<code>library("rvest")
r_h  = read_html("https://www.google.com/search?q=google&oq=google&aqs=chrome.0.69i59j0l2j69i60l2j69i65.1101j0j7&sourceid=chrome&ie=UTF-8")
d  =  r_h %>% html_nodes(".iUh30") %>% html_text() %>% as.character()
</code>```

答:
That class is not present in the returned html. You need a different selector strategy and then extract href</p>

```<code>library(rvest)
library(stringr)
r_h  = read_html("https://www.google.com/search?q=google&oq=google&aqs=chrome.0.69i59j0l2j69i60l2j69i65.1101j0j7&sourceid=chrome&ie=UTF-8")
d  =  r_h %>% html_nodes(".jfp3ef > a") %>% html_attr(., "href")

for(i in d){
  res <- str_match_all(i,'(http.*?)&')
  print(res[[1]][,2])
}
</code>```

Body:
I have written a small program.
Where I scrape Google search website and I want all the URL on the Google search web page. But I'm getting character(0) in the O/P. Plz help me.

CODE -

library("rvest")
r_h  = read_html("https://www.google.com/search?q=google&oq=google&aqs=chrome.0.69i59j0l2j69i60l2j69i65.1101j0j7&sourceid=chrome&ie=UTF-8")
d  =  r_h %>% html_nodes(".iUh30") %>% html_text() %>% as.character()

Body:
That class is not present in the returned html. You need a different selector strategy and then extract href

library(rvest)
library(stringr)
r_h  = read_html("https://www.google.com/search?q=google&oq=google&aqs=chrome.0.69i59j0l2j69i60l2j69i65.1101j0j7&sourceid=chrome&ie=UTF-8")
d  =  r_h %>% html_nodes(".jfp3ef > a") %>% html_attr(., "href")

for(i in d){
  res <- str_match_all(i,'(http.*?)&')
  print(res[[1]][,2])
}


问:
Case-Insensitive array search
I am trying to search an NSMutableArray for a string.  I am using containsObject: currently but it looks like this is case sensitive.  I need to search for all combinations of the given string (trip).  Any ideas would be greatly appreciated.

```<code>if ([self.theArray containsObject:trip]) {
</code>```

}

答:
How about a block:</p>

```<code>__block trip = @"blah";
if (NSNotFound!=[self.theArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop)
         {
             if (NSOrderedSame==[(NSString *)obj caseInsensitiveCompare:trip])
             {
                    stop=YES;
                    return YES;
             }
             return NO;
          }])
 {
       NSLog(@"It's a MATCH!");
 }
</code>```

Title: Case-Insensitive array search

Body:
I am trying to search an NSMutableArray for a string.  I am using containsObject: currently but it looks like this is case sensitive.  I need to search for all combinations of the given string (trip).  Any ideas would be greatly appreciated.

if ([self.theArray containsObject:trip]) {

}

Body:
How about a block:

__block trip = @"blah";
if (NSNotFound!=[self.theArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop)
         {
             if (NSOrderedSame==[(NSString *)obj caseInsensitiveCompare:trip])
             {
                    stop=YES;
                    return YES;
             }
             return NO;
          }])
 {
       NSLog(@"It's a MATCH!");
 }


问:
How to I resolve this error? Field never assigned and will always have null value
I have created 4 c# scripts. When I run my 2d unity game I see this warning in my console.

"Assets\Scripts\GameHandler.cs(7,34): warning CS0649: Field
  'GameHandler.car' is never assigned to, and will always have its
  default value null"

I am creating a game similar to snake, using c# scripts in unity 2d. Never used unity before or c#, this is my first project. So far its going well, However, i keep getting this warning which is causing my game to crash.
I've attached 2 of my scripts the first gamehandler is where this issue is and I think its referring to the class Car which i attached below. It's a lot of code so I do apologise, I just have no clue.

```<code>public class GameHandler : MonoBehaviour
{
    [SerializeField] private Car car;

    private LevelGrid levelGrid;

    // Start is called before the first frame update
    private void Start()
    {
        Debug.Log("GameHandler.Start");

        //GameObject carHeadGameObject = new GameObject();
        //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
        //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

        levelGrid = new LevelGrid(20,20); //width,height of grid

        car.Setup(levelGrid);
        levelGrid.Setup(car);
    }

    }
--------------------------------------
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Car : MonoBehaviour
{
    private enum Direction
    {
        Left,
        Right,
        Up,
        Down
    }

    private enum State
    {
        Alive,
        Dead
    }

    private State state;
    private Vector2Int gridPosition; //uses ints instead of floats useful for grid positiioning
    private float gridMoveTimer; //time remaining until next movement
    private float gridMoveTimerMax; // time between moves

    private Direction gridMoveDirection;

    private LevelGrid levelGrid;
    private int carsize;
    private List<CarMovePosition> carMovePositionList;
    private List<Carsize> carSizeList;

    public void Setup(LevelGrid levelGrid) {
        this.levelGrid = levelGrid;
    }

    private void Awake() {
        gridPosition = new Vector2Int(10,10); //initalise grid position into middle of grid
        gridMoveTimerMax = .2f; //car to move along grid every 1/2 second
        gridMoveTimer = gridMoveTimerMax; //0f
        gridMoveDirection = Direction.Right; // default move right

        carMovePositionList = new List<CarMovePosition>();
        carsize = 0;
        carSizeList = new List<Carsize>();

        state = State.Alive;
    }

    private void Update()
    {
        switch (state)
        {
            case State.Alive:
            HandleInput(); // checks for keyboard input
            HandleGridMovement();
                break;
            case State.Dead:
                break;
        }

    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (gridMoveDirection != Direction.Down)
            { // can only go up if not going down
                gridMoveDirection = Direction.Up;
            }
        }
        //return true on up arrow press

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (gridMoveDirection != Direction.Up)
            {
                gridMoveDirection = Direction.Down;

            }
        }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            if (gridMoveDirection != Direction.Right)
            {
                gridMoveDirection = Direction.Left;
            }
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (gridMoveDirection != Direction.Left)
            {
                gridMoveDirection = Direction.Right;
            }
        }
    }

    private void HandleGridMovement()
    {
        gridMoveTimer += Time.deltaTime; // amount of time left since last update
        if (gridMoveTimer >= gridMoveTimerMax)//if true then 1 sec since last move
        {
            gridMoveTimer -= gridMoveTimerMax;

            CarMovePosition previousCarMovePosition = null;

            if (carMovePositionList.Count > 0){
                previousCarMovePosition = carMovePositionList[0];
            }

            CarMovePosition carMovePosition = new CarMovePosition(previousCarMovePosition, gridPosition, gridMoveDirection);
            carMovePositionList.Insert(0, carMovePosition);

            Vector2Int gridMoveDirectionVector;
            switch (gridMoveDirection) {
                default:
                case Direction.Right: gridMoveDirectionVector = new Vector2Int(+1, 0);break;
                case Direction.Left: gridMoveDirectionVector = new Vector2Int(-1, 0); break;
                case Direction.Up: gridMoveDirectionVector = new Vector2Int(0, +1); break;
                case Direction.Down: gridMoveDirectionVector = new Vector2Int(0, -1); break;
            }
            gridPosition += gridMoveDirectionVector;

            bool cargotfuel = levelGrid.Trycarfuel(gridPosition);
            if (cargotfuel)
            {
                carsize++;
                CreateCarSize();
            }

            if (carMovePositionList.Count >= carsize + 1)
            {
                carMovePositionList.RemoveAt(carMovePositionList.Count - 1);
            }

            foreach (Carsize carsize in carSizeList)
            {
                Vector2Int carSizeGridPosition = carsize.GetGridPosition();
                if (gridPosition == carSizeGridPosition)
                {

                    //print("Gameover");
                    state = State.Dead;
                }
            }

            transform.position = new Vector3(gridPosition.x, gridPosition.y);
            //move transform based on location of gridPosition

            transform.eulerAngles = new Vector3(0, 0, GetAngleFromVector(gridMoveDirectionVector) - 90);
            //modify transform to face the correct way

            UpdateCarSize();

        }
    }

    private void CreateCarSize()
    {
        carSizeList.Add(new Carsize(carSizeList.Count));
    }

    private void UpdateCarSize(){
        for (int i = 0; i < carSizeList.Count; i++) {
            carSizeList[i].SetCarMovePosition(carMovePositionList[i]);
            //carSizeList[i].SetGridPosition(carMovePositionList[i].GetGridPosition());
        }
    }

    private float GetAngleFromVector(Vector2Int dir)
    {
        float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        if (n < 0) n += 360;
        return n;
    }

    public Vector2Int GetGridPosition()
    {
        return gridPosition;
    }

    //returns car list of positions full with body
    public List<Vector2Int> Getcargridpositionlist(){
        List<Vector2Int> gridPositionList = new List<Vector2Int>() { gridPosition };
        foreach (CarMovePosition carMovePosition in carMovePositionList)
        {
            gridPositionList.Add(carMovePosition.GetGridPosition());
        }
        return gridPositionList;
    }

    private class Carsize{

        private CarMovePosition carMovePosition;
        private Transform transform;

        public Carsize(int sizeIndex){
            GameObject carsGameObject = new GameObject("carBody", typeof(SpriteRenderer));
            carsGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.instance.carsSprite;
            carsGameObject.GetComponent<SpriteRenderer>().sortingOrder = -sizeIndex;
            transform = carsGameObject.transform;
        }

        public void SetCarMovePosition(CarMovePosition carMovePosition){
            this.carMovePosition = carMovePosition;

            transform.position = new Vector3(carMovePosition.GetGridPosition().x, carMovePosition.GetGridPosition().y);

            float angle;
            switch (carMovePosition.GetDirection()){
            default:
                case Direction.Up:// going up
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 0; break;
                        case Direction.Left: // was going left
                            angle = 0 + 45; break;
                        case Direction.Right:// was going right
                            angle = 0 - 45; break;
                    }
                    break;
                case Direction.Down:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 180; break;
                        case Direction.Left:
                            angle = 180 + 45; break;
                        case Direction.Right:
                            angle = 180 - 45; break;
                    }
                    break;
                case Direction.Left:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = -90; break;
                        case Direction.Down:
                            angle = -45; break;
                        case Direction.Up:
                            angle = 45; break;
                    }
                    break;
                case Direction.Right: // going right
                    switch (carMovePosition.GetPreviousDirection()){
                    default:
                        angle = 90; break;
                    case Direction.Down: // previously going down
                        angle = 45; break;
                    }
                    break;
            }
            transform.eulerAngles = new Vector3(0, 0, angle);
        }

        public Vector2Int GetGridPosition()
        {
            return carMovePosition.GetGridPosition();
        }
    }

    private class CarMovePosition{

        private CarMovePosition previousCarMovePosition;
        private Vector2Int gridPosition;
        private Direction direction;

        public CarMovePosition(CarMovePosition previousCarMovePosition, Vector2Int gridPosition, Direction direction){
            this.previousCarMovePosition = previousCarMovePosition;
            this.gridPosition = gridPosition;
            this.direction = direction;
        }

        public Vector2Int GetGridPosition(){
            return gridPosition;
        }

        public Direction GetDirection(){
            return direction;
        }

        public Direction GetPreviousDirection(){
            if (previousCarMovePosition == null){
                return Direction.Right;
            } else {
                return previousCarMovePosition.direction;
            }
        }

    }
    }
</code>```

It may be the case of clicking/dragging something in unity2d itself which I had to do before. But I am so lost now.

答:
The warning occurs because you are not initializing the object "car" and your game crashes when it tries to use this object, which has no value assigned to.

You must initialize the any object before using it in order to avoid crashes.

So, your Start() method must be like this:

```<code>private void Start()
{
    Debug.Log("GameHandler.Start");

    car = new Car(); // you must initialize objects before using them!

    //GameObject carHeadGameObject = new GameObject();
    //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
    //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

    levelGrid = new LevelGrid(20,20); //width,height of grid

    car.Setup(levelGrid);
    levelGrid.Setup(car);
}
</code>```

Hope this help you!

Body:
I have created 4 c# scripts. When I run my 2d unity game I see this warning in my console.

"Assets\Scripts\GameHandler.cs(7,34): warning CS0649: Field
  'GameHandler.car' is never assigned to, and will always have its
  default value null"

I am creating a game similar to snake, using c# scripts in unity 2d. Never used unity before or c#, this is my first project. So far its going well, However, i keep getting this warning which is causing my game to crash.
I've attached 2 of my scripts the first gamehandler is where this issue is and I think its referring to the class Car which i attached below. It's a lot of code so I do apologise, I just have no clue.

public class GameHandler : MonoBehaviour
{
    [SerializeField] private Car car;

    private LevelGrid levelGrid;

    // Start is called before the first frame update
    private void Start()
    {
        Debug.Log("GameHandler.Start");

        //GameObject carHeadGameObject = new GameObject();
        //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
        //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

        levelGrid = new LevelGrid(20,20); //width,height of grid

        car.Setup(levelGrid);
        levelGrid.Setup(car);
    }

    }
--------------------------------------
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Car : MonoBehaviour
{
    private enum Direction
    {
        Left,
        Right,
        Up,
        Down
    }

    private enum State
    {
        Alive,
        Dead
    }

    private State state;
    private Vector2Int gridPosition; //uses ints instead of floats useful for grid positiioning
    private float gridMoveTimer; //time remaining until next movement
    private float gridMoveTimerMax; // time between moves

    private Direction gridMoveDirection;

    private LevelGrid levelGrid;
    private int carsize;
    private List<CarMovePosition> carMovePositionList;
    private List<Carsize> carSizeList;

    public void Setup(LevelGrid levelGrid) {
        this.levelGrid = levelGrid;
    }

    private void Awake() {
        gridPosition = new Vector2Int(10,10); //initalise grid position into middle of grid
        gridMoveTimerMax = .2f; //car to move along grid every 1/2 second
        gridMoveTimer = gridMoveTimerMax; //0f
        gridMoveDirection = Direction.Right; // default move right

        carMovePositionList = new List<CarMovePosition>();
        carsize = 0;
        carSizeList = new List<Carsize>();

        state = State.Alive;
    }

    private void Update()
    {
        switch (state)
        {
            case State.Alive:
            HandleInput(); // checks for keyboard input
            HandleGridMovement();
                break;
            case State.Dead:
                break;
        }

    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (gridMoveDirection != Direction.Down)
            { // can only go up if not going down
                gridMoveDirection = Direction.Up;
            }
        }
        //return true on up arrow press

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (gridMoveDirection != Direction.Up)
            {
                gridMoveDirection = Direction.Down;

            }
        }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            if (gridMoveDirection != Direction.Right)
            {
                gridMoveDirection = Direction.Left;
            }
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (gridMoveDirection != Direction.Left)
            {
                gridMoveDirection = Direction.Right;
            }
        }
    }

    private void HandleGridMovement()
    {
        gridMoveTimer += Time.deltaTime; // amount of time left since last update
        if (gridMoveTimer >= gridMoveTimerMax)//if true then 1 sec since last move
        {
            gridMoveTimer -= gridMoveTimerMax;

            CarMovePosition previousCarMovePosition = null;

            if (carMovePositionList.Count > 0){
                previousCarMovePosition = carMovePositionList[0];
            }

            CarMovePosition carMovePosition = new CarMovePosition(previousCarMovePosition, gridPosition, gridMoveDirection);
            carMovePositionList.Insert(0, carMovePosition);

            Vector2Int gridMoveDirectionVector;
            switch (gridMoveDirection) {
                default:
                case Direction.Right: gridMoveDirectionVector = new Vector2Int(+1, 0);break;
                case Direction.Left: gridMoveDirectionVector = new Vector2Int(-1, 0); break;
                case Direction.Up: gridMoveDirectionVector = new Vector2Int(0, +1); break;
                case Direction.Down: gridMoveDirectionVector = new Vector2Int(0, -1); break;
            }
            gridPosition += gridMoveDirectionVector;

            bool cargotfuel = levelGrid.Trycarfuel(gridPosition);
            if (cargotfuel)
            {
                carsize++;
                CreateCarSize();
            }

            if (carMovePositionList.Count >= carsize + 1)
            {
                carMovePositionList.RemoveAt(carMovePositionList.Count - 1);
            }

            foreach (Carsize carsize in carSizeList)
            {
                Vector2Int carSizeGridPosition = carsize.GetGridPosition();
                if (gridPosition == carSizeGridPosition)
                {

                    //print("Gameover");
                    state = State.Dead;
                }
            }

            transform.position = new Vector3(gridPosition.x, gridPosition.y);
            //move transform based on location of gridPosition

            transform.eulerAngles = new Vector3(0, 0, GetAngleFromVector(gridMoveDirectionVector) - 90);
            //modify transform to face the correct way

            UpdateCarSize();

        }
    }

    private void CreateCarSize()
    {
        carSizeList.Add(new Carsize(carSizeList.Count));
    }

    private void UpdateCarSize(){
        for (int i = 0; i < carSizeList.Count; i++) {
            carSizeList[i].SetCarMovePosition(carMovePositionList[i]);
            //carSizeList[i].SetGridPosition(carMovePositionList[i].GetGridPosition());
        }
    }

    private float GetAngleFromVector(Vector2Int dir)
    {
        float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        if (n < 0) n += 360;
        return n;
    }

    public Vector2Int GetGridPosition()
    {
        return gridPosition;
    }

    //returns car list of positions full with body
    public List<Vector2Int> Getcargridpositionlist(){
        List<Vector2Int> gridPositionList = new List<Vector2Int>() { gridPosition };
        foreach (CarMovePosition carMovePosition in carMovePositionList)
        {
            gridPositionList.Add(carMovePosition.GetGridPosition());
        }
        return gridPositionList;
    }

    private class Carsize{

        private CarMovePosition carMovePosition;
        private Transform transform;

        public Carsize(int sizeIndex){
            GameObject carsGameObject = new GameObject("carBody", typeof(SpriteRenderer));
            carsGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.instance.carsSprite;
            carsGameObject.GetComponent<SpriteRenderer>().sortingOrder = -sizeIndex;
            transform = carsGameObject.transform;
        }

        public void SetCarMovePosition(CarMovePosition carMovePosition){
            this.carMovePosition = carMovePosition;

            transform.position = new Vector3(carMovePosition.GetGridPosition().x, carMovePosition.GetGridPosition().y);

            float angle;
            switch (carMovePosition.GetDirection()){
            default:
                case Direction.Up:// going up
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 0; break;
                        case Direction.Left: // was going left
                            angle = 0 + 45; break;
                        case Direction.Right:// was going right
                            angle = 0 - 45; break;
                    }
                    break;
                case Direction.Down:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 180; break;
                        case Direction.Left:
                            angle = 180 + 45; break;
                        case Direction.Right:
                            angle = 180 - 45; break;
                    }
                    break;
                case Direction.Left:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = -90; break;
                        case Direction.Down:
                            angle = -45; break;
                        case Direction.Up:
                            angle = 45; break;
                    }
                    break;
                case Direction.Right: // going right
                    switch (carMovePosition.GetPreviousDirection()){
                    default:
                        angle = 90; break;
                    case Direction.Down: // previously going down
                        angle = 45; break;
                    }
                    break;
            }
            transform.eulerAngles = new Vector3(0, 0, angle);
        }

        public Vector2Int GetGridPosition()
        {
            return carMovePosition.GetGridPosition();
        }
    }

    private class CarMovePosition{

        private CarMovePosition previousCarMovePosition;
        private Vector2Int gridPosition;
        private Direction direction;

        public CarMovePosition(CarMovePosition previousCarMovePosition, Vector2Int gridPosition, Direction direction){
            this.previousCarMovePosition = previousCarMovePosition;
            this.gridPosition = gridPosition;
            this.direction = direction;
        }

        public Vector2Int GetGridPosition(){
            return gridPosition;
        }

        public Direction GetDirection(){
            return direction;
        }

        public Direction GetPreviousDirection(){
            if (previousCarMovePosition == null){
                return Direction.Right;
            } else {
                return previousCarMovePosition.direction;
            }
        }

    }
    }

It may be the case of clicking/dragging something in unity2d itself which I had to do before. But I am so lost now.

Body:
The warning occurs because you are not initializing the object "car" and your game crashes when it tries to use this object, which has no value assigned to.

You must initialize the any object before using it in order to avoid crashes.

So, your Start() method must be like this:

private void Start()
{
    Debug.Log("GameHandler.Start");

    car = new Car(); // you must initialize objects before using them!

    //GameObject carHeadGameObject = new GameObject();
    //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
    //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

    levelGrid = new LevelGrid(20,20); //width,height of grid

    car.Setup(levelGrid);
    levelGrid.Setup(car);
}

Hope this help you!


问:
FirebaseAuth UI Google SignIn Enable cookies on iOS
Using the FirebaseAuthUI when signing in with Google on an iOS app, it redirected to a page saying:

"You've reached this page because we have detected that cookies are
  disabled in your browser. The page you attempted to load cannot
  display properly if cookies are disabled. Please enable cookies and
  retry the operations or go back in your browser"

Is that normal behavior? How can I prevent this?

答: Settings, Safari, Block all cookies Turn Off and wait like an hour. </p>


问:
Get list of values, then all post titles with that value
I have a working wordpress loop which displays all posts of a certain meta_query value. The only issue is that the values are repeated. For example, if I have two posts with the value "Blue" then both posts appear in the loop, which makes "Blue" appear twice.

What I would like is for "Blue" to appear once, and underneath it, a list of all post titles with that value.

Here's my current query:

```<code><?php
$the_query = new WP_Query(array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'meta_key'      => 'colors',
));

while ( $the_query->have_posts() ) : $the_query->the_post();

$colors = get_field('colors');

if( $colors ): foreach( $colors as $color ):
    endforeach;
    endif;
    echo' <div><h2>'.$color.'</h2><div>'.get_the_title( $post_id ).'</div></div>';

    endwhile; wp_reset_postdata();?>
</code>```

I tried using an array for the titles, but it just returned "Array"

```<code>$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}
</code>```

echo $title_names

I'm thinking I need another if statement somewhere with an array? Or maybe I'm approaching this from the wrong direction.

答:
You would want to try something like this:</p>

```<code>$results = [];
while ( $the_query->have_posts() ) {

    $the_query->the_post();
    $colors = get_field('colors');
    if( !empty($colors) ) {

        foreach( $colors as $color ) {
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }

    }

}

foreach ($results as $color => $posts) {

    echo "<div><h2>{$color}<h2>";

    foreach($posts as $post) {
        echo "<div><a href=\"{$post['link']}">{$post['title']}</a></div>";
    }

    echo '</div>';
}
</code>```

Body:
I have a working wordpress loop which displays all posts of a certain meta_query value. The only issue is that the values are repeated. For example, if I have two posts with the value "Blue" then both posts appear in the loop, which makes "Blue" appear twice.

What I would like is for "Blue" to appear once, and underneath it, a list of all post titles with that value.

Here's my current query:

<?php
$the_query = new WP_Query(array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'meta_key'      => 'colors',
));

while ( $the_query->have_posts() ) : $the_query->the_post();

$colors = get_field('colors');

if( $colors ): foreach( $colors as $color ):
    endforeach;
    endif;
    echo'

'.$color.'

'.get_the_title( $post_id ).'

';

    endwhile; wp_reset_postdata();?>

I tried using an array for the titles, but it just returned "Array"

$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}

echo $title_names

I'm thinking I need another if statement somewhere with an array? Or maybe I'm approaching this from the wrong direction.

Body:
You would want to try something like this:

$results = [];
while ( $the_query->have_posts() ) {

    $the_query->the_post();
    $colors = get_field('colors');
    if( !empty($colors) ) {

        foreach( $colors as $color ) {
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }

    }

}

foreach ($results as $color => $posts) {

    echo "<div><h2>{$color}<h2>";

    foreach($posts as $post) {
        echo "<div><a href=\"{$post['link']}">{$post['title']}</a></div>";
    }

    echo '</div>';
}


问:
Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {$$typeof, render})

Error handling and alerts in React

When I bring the <Alert /> to the main app component just below the  tag, as soon as the component mounts it throws this error.

While I remove the <Alert /> from the main app component, it works fine.
This is how the browser renders properly before I brought the <Alert /> to the main app component,
 click here.

Here is the snippet of code that works earlier:

```<code>class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header />
                    <div className="container">
                        <Dashboard />
                    </div>
                </Fragment>
            </AlertProvider>
        </Provider>
    )
}
</code>```

}

I expect to get the proper alert message snippets in the browser. However, nothing gets rendered in the browser after I tried to use the third party package called react-alert from this Github repository.

Below is the snippet of the code that failed with an error in the console.

```<code>class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header />
                    <Alerts />
                    <div className="container">
                        <Dashboard />
                    </div>
                </Fragment>
            </AlertProvider>
        </Provider>
    )
}
</code>```

Here is my Alerts.js component:

```<code>import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';
export class Alerts extends Component {
    componentDidMount() {
        this.props.alert.show('It Works');
    }
    render() {
        return <Fragment />;
    }
}
export default withAlert(Alerts);
</code>```

The given error has seen in the console: Error in the console

答:
Try changing your code at Alert.js

From:
 export default withAlert(Alerts);

To:
export default withAlert()(Alerts);

Body:
Error handling and alerts in React

When I bring the <Alert /> to the main app component just below the  tag, as soon as the component mounts it throws this error.

While I remove the <Alert /> from the main app component, it works fine.
This is how the browser renders properly before I brought the <Alert /> to the main app component,
 click here.

Here is the snippet of code that works earlier:

class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>

                        <Dashboard />

                </Fragment>
            </AlertProvider>
        </Provider>
    )
}

}

I expect to get the proper alert message snippets in the browser. However, nothing gets rendered in the browser after I tried to use the third party package called react-alert from this Github repository.

Below is the snippet of the code that failed with an error in the console.

class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>

                    <Alerts />

                        <Dashboard />

                </Fragment>
            </AlertProvider>
        </Provider>
    )
}

Here is my Alerts.js component:

import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';
export class Alerts extends Component {
    componentDidMount() {
        this.props.alert.show('It Works');
    }
    render() {
        return <Fragment />;
    }
}
export default withAlert(Alerts);

The given error has seen in the console: Error in the console


问:
Check if two rows in pandas DataFrame has same set of values regard & regardless of column order
I have two dataframe with same index but different column names. Number of columns are the same. I want to check, index by index, 1) whether they have same set of values regardless of column order, and 2) whether they have same set of values regarding column order.

ind = ['aaa', 'bbb', 'ccc']
df1 = pd.DataFrame({'old1': ['A','A','A'], 'old2': ['B','B','B'], 'old3': ['C','C','C']}, index=ind)
df2 = pd.DataFrame({'new1': ['A','A','A'], 'new2': ['B','C','B'], 'new3': ['C','B','D']}, index=ind)
```

<p>This is the output I need.</p>

```     OpX   OpY
-------------
aaa  True  True
bbb  False True
ccc  False False
```

Could anyone help me with OpX and OpY?

答:
Using tuple and set: keep the order or tuple , and reorder with set

```<code>s1=df1.apply(tuple,1)==df2.apply(tuple,1)
s2=df1.apply(set,1)==df2.apply(set,1)
pd.concat([s1,s2],1)
Out[746]:
         0      1
aaa   True   True
bbb  False   True
ccc  False  False
</code>```

Since cs95 mentioned apply have problem here

```<code>s=np.equal(df1.values,df2.values).all(1)
t=np.equal(np.sort(df1.values,1),np.sort(df2.values,1)).all(1)
pd.DataFrame(np.column_stack([s,t]),index=df1.index)
Out[754]:
         0      1
aaa   True   True
bbb  False   True
ccc  False  False
</code>```

Body:
I have two dataframe with same index but different column names. Number of columns are the same. I want to check, index by index, 1) whether they have same set of values regardless of column order, and 2) whether they have same set of values regarding column order.

ind = ['aaa', 'bbb', 'ccc']
df1 = pd.DataFrame({'old1': ['A','A','A'], 'old2': ['B','B','B'], 'old3': ['C','C','C']}, index=ind)
df2 = pd.DataFrame({'new1': ['A','A','A'], 'new2': ['B','C','B'], 'new3': ['C','B','D']}, index=ind)

This is the output I need.

     OpX   OpY
-------------
aaa  True  True
bbb  False True
ccc  False False

Could anyone help me with OpX and OpY?

Body:
Using tuple and set: keep the order or tuple , and reorder with set

s1=df1.apply(tuple,1)==df2.apply(tuple,1)
s2=df1.apply(set,1)==df2.apply(set,1)
pd.concat([s1,s2],1)
Out[746]:
         0      1
aaa   True   True
bbb  False   True
ccc  False  False

Since cs95 mentioned apply have problem here

s=np.equal(df1.values,df2.values).all(1)
t=np.equal(np.sort(df1.values,1),np.sort(df2.values,1)).all(1)
pd.DataFrame(np.column_stack([s,t]),index=df1.index)
Out[754]:
         0      1
aaa   True   True
bbb  False   True
ccc  False  False


问:
Maven: hibernate-entitymanager together with javaee-api break my unit tests
I'm having the two dependencies javaee-api and hibernate-entitymanager in my pom. But they don't work very well together: as soon as I add javaee-api, all my unit tests break due to java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/validation/Validation. Without javaee-api, everything works fine. Why is that?

(this question has been edited in order to fit the problem ;))

答:
As far as I know, in Maven2 the order of the dependency is not kept and there is no guarantee on the order of how those dependencies appear in the final class path when you execute your code. In your case, I would "exclude" overlapping libraries in your dependency structure.

Look here for the Maven exclusion docs.

Given the complexity of library version matching I would suggest you start off with one of the Hibernate Maven examples, and morph it into your project.

I hope this helps.