问:
VHDL - how to detect and output correct priority
Currently, I am working on a parking lot system in VHDL.

The goal is simple. When a car parks, it will take a look at all the available spots and output the next empty spot. Seem simple enough, but I am having some problems getting it to work properly.

I am using switches on a board and detecting when the switches are up. That signifies weather there is a car parked there or not.

The goal is that I can hit for example, switch 1, switch 2 and switch 4 and till output 3 as the available spot. Then, if I switch on 3, it'll recalculate and say 5 is the next available spot.

To accomplish this, I am using a bunch of if else statements, but whats happening is that the for example, if I hit the #4 switch, it'll properly display 5, but then once i hit the #5 switch, it will continue to show 5 as the next available spot rather than 6.

I think my problem is that I don't have enough conditions to cover all scenarios. Is there a way for me to write this in a shorter way?

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity Priority is
port(
    SWITCH: in std_logic_vector (8 downto 0);
    H1: out std_logic_vector (3 downto 0);
    H2: out std_logic_vector (3 downto 0);
    H3: out std_logic_vector (3 downto 0);
    H4: out std_logic_vector (3 downto 0)
);
end Priority;

architecture Behavioral of Priority is

begin
process (SWITCH)
begin

if (SWITCH(0) = '1' AND SWITCH(1) = '1' AND SWITCH(2) = '1' AND SWITCH(3) = '1' AND SWITCH(4) = '1' AND SWITCH(5) = '1' AND SWITCH(6) = '1' AND SWITCH(7) = '1')   then  --if all switches are on, display "FULL"

H1 <= "1100";
H2 <= "1100";
H3 <= "1011";
H4 <= "1010";

elsif SWITCH(0) = '1' then  --if switch 0 is turned on, show "PS-1"

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0010";

elsif SWITCH(1) = '1' then  --if switch 1 is turned on, show "PS-2"

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0011";

elsif SWITCH(2) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0100";

elsif SWITCH(3) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0101";

elsif SWITCH(4) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0110";

elsif SWITCH(5) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0111";

elsif SWITCH(6) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "1000";

elsif SWITCH(7) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0001";

end if;
--end if;

end process;

end Behavioral;
</code>```

答:
Okay, so if there is anyone who has the same problem as me in the future, this is how I solved it.

I said I had a parking lot with 8 spots and needed to know when a spot was avaiable. What I was doing wrong was that I was detecting when a car came and trying to find the next avaibale spot. Bad Idea. What happenes is that there is so many possibilities for combinations (8 X 8 so total of 64 combinations) per parking spots that unless you write them out, its totally not worth it.

The better way to go about doing this is detecting when there ISN't a car. That way, the highest priority will always be active so that regarless of where they park, as long as they don't park in the priority spot, it'll continue to be the priority. If they do park at the priority spot, then it'll look for the next spot without a car rather than a spot where there is a car and trying to find the right prioty. Am I making any sense here? I hope I am.

Here is what I mean in code form.

```<code>LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;
USE ieee.std_logic_unsigned.all;

ENTITY Priority IS     PORT
(  switch:     IN    STD_LOGIC_VECTOR(8 DOWNTO 0);
   H1:     out std_logic_vector (3 downto 0);
   H2:     out std_logic_vector (3 downto 0);
   H3:     out std_logic_vector (3 downto 0);
   H4:     out std_logic_vector (3 downto 0)
    );
END Priority;

ARCHITECTURE behavioral OF Priority IS
BEGIN
--SIGNAL Sel : STD_LOGIC;
Process(switch)

BEGIN

    if switch(7 downto 0) = "11111111" then

     H4<= "1010";
     H3<= "1011";
     H2<= "1100";
     H1<= "1100";

    elsif switch(0) = '0' then
     H4<= "0001";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(1) = '0' then
     H4<= "0010" ;
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(2) = '0' then
     H4<= "0011" ;
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(3) = '0' then
     H4<= "0100" ;
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(4) = '0' then
     H4<= "0101";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(5) = '0' then
     H4<= "0110";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(6) = '0' then
     H4<= "0111";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(7) = '0' then
     H4<= "1000";
     H3<= "1111";
         H2<= "1110";
     H1<= "1101";

    else
     H4<= "0000";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";
    end if;

    end process;

END Behavioral;
</code>```

If the binary doesn't make sense to you, don't worry. Just take a look at the binary for h4. When all switches are 1, then it displays FULL. If switch 1 is down, it'll display 1. So, as long as switch 1 is down, it'll continue to display 1 regardless. if it goes up, it moves on to the next one and checks to see if its available. Thats it.

Body:
Currently, I am working on a parking lot system in VHDL.

The goal is simple. When a car parks, it will take a look at all the available spots and output the next empty spot. Seem simple enough, but I am having some problems getting it to work properly.

I am using switches on a board and detecting when the switches are up. That signifies weather there is a car parked there or not.

The goal is that I can hit for example, switch 1, switch 2 and switch 4 and till output 3 as the available spot. Then, if I switch on 3, it'll recalculate and say 5 is the next available spot.

To accomplish this, I am using a bunch of if else statements, but whats happening is that the for example, if I hit the #4 switch, it'll properly display 5, but then once i hit the #5 switch, it will continue to show 5 as the next available spot rather than 6.

I think my problem is that I don't have enough conditions to cover all scenarios. Is there a way for me to write this in a shorter way?

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity Priority is
port(
    SWITCH: in std_logic_vector (8 downto 0);
    H1: out std_logic_vector (3 downto 0);
    H2: out std_logic_vector (3 downto 0);
    H3: out std_logic_vector (3 downto 0);
    H4: out std_logic_vector (3 downto 0)
);
end Priority;

architecture Behavioral of Priority is

begin
process (SWITCH)
begin

if (SWITCH(0) = '1' AND SWITCH(1) = '1' AND SWITCH(2) = '1' AND SWITCH(3) = '1' AND SWITCH(4) = '1' AND SWITCH(5) = '1' AND SWITCH(6) = '1' AND SWITCH(7) = '1')   then  --if all switches are on, display "FULL"

H1 <= "1100";
H2 <= "1100";
H3 <= "1011";
H4 <= "1010";

elsif SWITCH(0) = '1' then  --if switch 0 is turned on, show "PS-1"

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0010";

elsif SWITCH(1) = '1' then  --if switch 1 is turned on, show "PS-2"

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0011";

elsif SWITCH(2) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0100";

elsif SWITCH(3) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0101";

elsif SWITCH(4) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0110";

elsif SWITCH(5) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0111";

elsif SWITCH(6) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "1000";

elsif SWITCH(7) = '1' then

H1 <= "1101";
H2 <= "1110";
H3 <= "1111";
H4 <= "0001";

end if;
--end if;

end process;

end Behavioral;

Body:
Okay, so if there is anyone who has the same problem as me in the future, this is how I solved it.

I said I had a parking lot with 8 spots and needed to know when a spot was avaiable. What I was doing wrong was that I was detecting when a car came and trying to find the next avaibale spot. Bad Idea. What happenes is that there is so many possibilities for combinations (8 X 8 so total of 64 combinations) per parking spots that unless you write them out, its totally not worth it.

The better way to go about doing this is detecting when there ISN't a car. That way, the highest priority will always be active so that regarless of where they park, as long as they don't park in the priority spot, it'll continue to be the priority. If they do park at the priority spot, then it'll look for the next spot without a car rather than a spot where there is a car and trying to find the right prioty. Am I making any sense here? I hope I am.

Here is what I mean in code form.

LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;
USE ieee.std_logic_unsigned.all;

ENTITY Priority IS     PORT
(  switch:     IN    STD_LOGIC_VECTOR(8 DOWNTO 0);
   H1:     out std_logic_vector (3 downto 0);
   H2:     out std_logic_vector (3 downto 0);
   H3:     out std_logic_vector (3 downto 0);
   H4:     out std_logic_vector (3 downto 0)
    );
END Priority;

ARCHITECTURE behavioral OF Priority IS
BEGIN
--SIGNAL Sel : STD_LOGIC;
Process(switch)

BEGIN

    if switch(7 downto 0) = "11111111" then

     H4<= "1010";
     H3<= "1011";
     H2<= "1100";
     H1<= "1100";

    elsif switch(0) = '0' then
     H4<= "0001";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(1) = '0' then
     H4<= "0010" ;
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(2) = '0' then
     H4<= "0011" ;
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(3) = '0' then
     H4<= "0100" ;
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(4) = '0' then
     H4<= "0101";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(5) = '0' then
     H4<= "0110";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(6) = '0' then
     H4<= "0111";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";

    elsif switch(7) = '0' then
     H4<= "1000";
     H3<= "1111";
         H2<= "1110";
     H1<= "1101";

    else
     H4<= "0000";
     H3<= "1111";
     H2<= "1110";
     H1<= "1101";
    end if;

    end process;

END Behavioral;

If the binary doesn't make sense to you, don't worry. Just take a look at the binary for h4. When all switches are 1, then it displays FULL. If switch 1 is down, it'll display 1. So, as long as switch 1 is down, it'll continue to display 1 regardless. if it goes up, it moves on to the next one and checks to see if its available. Thats it.


来源: stackexchange

问:
How do you make a blurry background and in focus div
Im trying to make this effect.

Blurry background : in focus login div form

I manage to make everything blurry with filter: blur() . But I don't know how to remove the blur effect from my login form with id = newlogin .

```<code> <style>
    body{
      filter: blur(4px);
    }

    #newlogin{
      filter: blur(-4px);
    }
    </style>
</code>```

答: You can't "unblur" parts of a blurred area like that, every child of the blurred element is also going to appear blurred. You need to either blur every element individually (may look ugly depending on design) or put everything you want to blur in a container and leave everything you don't want blurred outside of it.</p>

ContentLicense: CC BY-SA 3.0


问:
Calculate total experimental time for each sample
I am trying to calculate cumulative time between experiment initiation and each temperature measurement I made during an experiment. My experiment has 50+ samples (i.e. A1,A2,B1,B2 ect) and each sample was initiated at a different time/day.

I want to treat time as a continuous variable so I need to calculate the total (cumulative time in hours) for each temp measurement, as indicated by a total time variable (below).

Is there a way to do this without telling R the start and end time for each sample? How can I get cumulative time for each temperature measurement?

An example of how the data looks is shown below:

```<code>Date    Time    Sample  Temp    **Total Time**
2017-06-28  13:58   A1  13.67870139 0
2017-06-29  16:08   A1  13.34256319 (time between 06-28 13:58 and 06-29 16:08)
2017-06-30  07:32   A1  12.84005139 (time between 06-28 13:58 and 06-30 07:32)
2017-06-30  19:14   A1  12.84005139 ect
2017-07-01  07:40   A1  11.83983472
2017-07-01  19:20   A1  11.83983472
2017-07-02  07:53   A1  11.75332292
2017-07-02  19:06   A1  11.75332292
2017-07-03  07:45   A1  11.74469167
2017-07-03  19:04   A1  11.74469167
2017-07-04  08:15   A1  11.45409583
</code>```

Thanks!

PS- I haven't tried anything because I can only find example where there is a "start time" and "end time" col. I guess I could create a start time col for each sample and ask r to calculate the time diff between start time and the time of each measurement.... I don't know how to make R make a start time col for the earliest measurement for each sample. I could spend a whole day doing it in excel but there must bet a better solution!

答:
Here's one way. First, unite the Date and Time column. Then, convert it to a timestamp via lubridate::ymd_hm. Next, pluck the first timestamp. Finally, create two new columns that show the difference from that start date.

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

df <- df %>%
  unite("datetime", c("Date", "Time"), sep = " ") %>%
  mutate(datetime = ymd_hm(datetime))

start_date <- df$datetime[1]

df %>%
  mutate(time_from_start_secs = datetime - start_date,
         time_from_start_period = seconds_to_period(time_from_start_secs))

#               datetime Sample     Temp time_from_start_secs time_from_start_period
# 1  2017-06-28 13:58:00     A1 13.67870               0 secs                     0S
# 2  2017-06-29 16:08:00     A1 13.34256           94200 secs           1d 2H 10M 0S
# 3  2017-06-30 07:32:00     A1 12.84005          149640 secs          1d 17H 34M 0S
# 4  2017-06-30 19:14:00     A1 12.84005          191760 secs           2d 5H 16M 0S
# 5  2017-07-01 07:40:00     A1 11.83983          236520 secs          2d 17H 42M 0S
# 6  2017-07-01 19:20:00     A1 11.83983          278520 secs           3d 5H 22M 0S
# 7  2017-07-02 07:53:00     A1 11.75332          323700 secs          3d 17H 55M 0S
# 8  2017-07-02 19:06:00     A1 11.75332          364080 secs            4d 5H 8M 0S
# 9  2017-07-03 07:45:00     A1 11.74469          409620 secs          4d 17H 47M 0S
# 10 2017-07-03 19:04:00     A1 11.74469          450360 secs            5d 5H 6M 0S
# 11 2017-07-04 08:15:00     A1 11.45410          497820 secs          5d 18H 17M 0S
</code>```

Alternatively, you could use min(datetime). In addition, if you need to have the calculation "reset" with each sample, you will want to use group_by -- all in one big swoop we would have:

```<code>df %>%
  unite("datetime", c("Date", "Time"), sep = " ") %>%
  group_by(Sample) %>%
  mutate(datetime = ymd_hm(datetime),
         time_secs = datetime - min(start_date))
</code>```

Body:
I am trying to calculate cumulative time between experiment initiation and each temperature measurement I made during an experiment. My experiment has 50+ samples (i.e. A1,A2,B1,B2 ect) and each sample was initiated at a different time/day.

I want to treat time as a continuous variable so I need to calculate the total (cumulative time in hours) for each temp measurement, as indicated by a total time variable (below).

Is there a way to do this without telling R the start and end time for each sample? How can I get cumulative time for each temperature measurement?

An example of how the data looks is shown below:

Date    Time    Sample  Temp    **Total Time**
2017-06-28  13:58   A1  13.67870139 0
2017-06-29  16:08   A1  13.34256319 (time between 06-28 13:58 and 06-29 16:08)
2017-06-30  07:32   A1  12.84005139 (time between 06-28 13:58 and 06-30 07:32)
2017-06-30  19:14   A1  12.84005139 ect
2017-07-01  07:40   A1  11.83983472
2017-07-01  19:20   A1  11.83983472
2017-07-02  07:53   A1  11.75332292
2017-07-02  19:06   A1  11.75332292
2017-07-03  07:45   A1  11.74469167
2017-07-03  19:04   A1  11.74469167
2017-07-04  08:15   A1  11.45409583

Thanks!

PS- I haven't tried anything because I can only find example where there is a "start time" and "end time" col. I guess I could create a start time col for each sample and ask r to calculate the time diff between start time and the time of each measurement.... I don't know how to make R make a start time col for the earliest measurement for each sample. I could spend a whole day doing it in excel but there must bet a better solution!

Body:
Here's one way. First, unite the Date and Time column. Then, convert it to a timestamp via lubridate::ymd_hm. Next, pluck the first timestamp. Finally, create two new columns that show the difference from that start date.

library(tidyverse)
library(lubridate)

df <- df %>%
  unite("datetime", c("Date", "Time"), sep = " ") %>%
  mutate(datetime = ymd_hm(datetime))

start_date <- df$datetime[1]

df %>%
  mutate(time_from_start_secs = datetime - start_date,
         time_from_start_period = seconds_to_period(time_from_start_secs))

#               datetime Sample     Temp time_from_start_secs time_from_start_period
# 1  2017-06-28 13:58:00     A1 13.67870               0 secs                     0S
# 2  2017-06-29 16:08:00     A1 13.34256           94200 secs           1d 2H 10M 0S
# 3  2017-06-30 07:32:00     A1 12.84005          149640 secs          1d 17H 34M 0S
# 4  2017-06-30 19:14:00     A1 12.84005          191760 secs           2d 5H 16M 0S
# 5  2017-07-01 07:40:00     A1 11.83983          236520 secs          2d 17H 42M 0S
# 6  2017-07-01 19:20:00     A1 11.83983          278520 secs           3d 5H 22M 0S
# 7  2017-07-02 07:53:00     A1 11.75332          323700 secs          3d 17H 55M 0S
# 8  2017-07-02 19:06:00     A1 11.75332          364080 secs            4d 5H 8M 0S
# 9  2017-07-03 07:45:00     A1 11.74469          409620 secs          4d 17H 47M 0S
# 10 2017-07-03 19:04:00     A1 11.74469          450360 secs            5d 5H 6M 0S
# 11 2017-07-04 08:15:00     A1 11.45410          497820 secs          5d 18H 17M 0S

Alternatively, you could use min(datetime). In addition, if you need to have the calculation "reset" with each sample, you will want to use group_by -- all in one big swoop we would have:

df %>%
  unite("datetime", c("Date", "Time"), sep = " ") %>%
  group_by(Sample) %>%
  mutate(datetime = ymd_hm(datetime),
         time_secs = datetime - min(start_date))


问:
NPPExec scanf Notepad++ Console
im new to NPPExec and c coding.
Is there a way to compile and run a c code like

```<code>int number;
scanf("enter a number: %d" ,&number);
printf("\nyour number is: %d\n", number);
</code>```

when i try

NPP_SAVE
cd $(CURRENT_DIRECTORY)
cmd /c g++ -utf-8 -pedantic -Wall -W -Wconversion -Wshadow -Wcast-qual -Wwrite-strings $(FILE_NAME) -o $(NAME_PART).exe& IF ERRORLEVEL 1 (echo. && echo Syntax errors were found during compiling.) ELSE ( cmd /c "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" -run)

the scanf() is ignored

Please help :/

答:
in

```<code>int number;
scanf("enter a number: %d" ,&number);
printf("\nyour number is: %d\n", number);
</code>```

It looks as though you are attempting to print out a user prompt in the call to scanf. Unfortunately that's not what scanf does.

You need to print out the prompt separately. Give

```<code>int number;
prinf("enter a number: ");
int rval = scanf("%d", &number);
if (rval == 1) // test that read got something
{
    printf("\nyour number is: %d\n", number);
}
else
{
    printf("\nyour input is USELESS!\n", number); // though a less mocking tone
                                                  // is usually appreciated by users.
}
</code>```

or something similar a shot.

Title: NPPExec scanf Notepad++ Console

Body:
im new to NPPExec and c coding.
Is there a way to compile and run a c code like

int number;
scanf("enter a number: %d" ,&number);
printf("\nyour number is: %d\n", number);

when i try

NPP_SAVE
cd $(CURRENT_DIRECTORY)
cmd /c g++ -utf-8 -pedantic -Wall -W -Wconversion -Wshadow -Wcast-qual -Wwrite-strings $(FILE_NAME) -o $(NAME_PART).exe& IF ERRORLEVEL 1 (echo. && echo Syntax errors were found during compiling.) ELSE ( cmd /c "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" -run)

the scanf() is ignored

Please help :/

Body:
in

int number;
scanf("enter a number: %d" ,&number);
printf("\nyour number is: %d\n", number);

It looks as though you are attempting to print out a user prompt in the call to scanf. Unfortunately that's not what scanf does.

You need to print out the prompt separately. Give

int number;
prinf("enter a number: ");
int rval = scanf("%d", &number);
if (rval == 1) // test that read got something
{
    printf("\nyour number is: %d\n", number);
}
else
{
    printf("\nyour input is USELESS!\n", number); // though a less mocking tone
                                                  // is usually appreciated by users.
}

or something similar a shot.


问:
Compute a value using multiple preceding rows
I have a DataFrame, that contains events ordered by timestamp.
Certain events mark the beginning of a new epoch:

```<code>+------+-----------+
| Time | Type      |
+------+-----------+
| 0    | New Epoch |
| 2    | Foo       |
| 3    | Bar       |
| 11   | New Epoch |
| 12   | Baz       |
+------+-----------+
</code>```

I would like to add a column with epoch number, that, for simplicity, can be equal to the timestamp of its beginning:

```<code>+------+-----------+–------+
| Time | Type      | Epoch |
+------+-----------+-------+
| 0    | New Epoch | 0     |
| 2    | Foo       | 0     |
| 3    | Bar       | 0     |
| 11   | New Epoch | 11    |
| 12   | Baz       | 11    |
+------+-----------+-------+
</code>```

How can I achieve this?

The naive algorithm would be to write a function that goes backwards until it finds a row with $"Type" === "New Epoch" and takes its $"Time". In case I know the maximum number of events within an epoch, I can probably implement it by calling lag() that many times. But for the general case I don't have any ideas.

答:
Below is my solution. Briefly, I create a dataframe that represents epoch intervals then join it with original dataframe.</p>

```<code>import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val ds = List((0, "New Epoch"), (2, "Fo"), (3, "Bar"), (11, "New Epoch"), (12, "Baz")).toDF("Time", "Type")
val epoch = ds.filter($"Type" === "New Epoch")
val spec = Window.orderBy("Time")
val epochInterval = epoch.withColumn("next_epoch", lead($"Time", 1).over(spec))//.show(false)
val result = ds.as("left").join(epochInterval.as("right"), $"left.Time" >= $"right.Time" && ($"left.Time" < $"right.next_epoch" || $"right.next_epoch".isNull))
      .select($"left.Time", $"left.Type", $"right.Time".as("Epoch"))
result.show(false)

+----+---------+-----+
|Time|Type     |Epoch|
+----+---------+-----+
|0   |New Epoch|0    |
|2   |Fo       |0    |
|3   |Bar      |0    |
|11  |New Epoch|11   |
|12  |Baz      |11   |
+----+---------+-----+
</code>```

Body:
I have a DataFrame, that contains events ordered by timestamp.
Certain events mark the beginning of a new epoch:

+------+-----------+
| Time | Type      |
+------+-----------+
| 0    | New Epoch |
| 2    | Foo       |
| 3    | Bar       |
| 11   | New Epoch |
| 12   | Baz       |
+------+-----------+

I would like to add a column with epoch number, that, for simplicity, can be equal to the timestamp of its beginning:

+------+-----------+–------+
| Time | Type      | Epoch |
+------+-----------+-------+
| 0    | New Epoch | 0     |
| 2    | Foo       | 0     |
| 3    | Bar       | 0     |
| 11   | New Epoch | 11    |
| 12   | Baz       | 11    |
+------+-----------+-------+

How can I achieve this?

The naive algorithm would be to write a function that goes backwards until it finds a row with $"Type" === "New Epoch" and takes its $"Time". In case I know the maximum number of events within an epoch, I can probably implement it by calling lag() that many times. But for the general case I don't have any ideas.

Body:
Below is my solution. Briefly, I create a dataframe that represents epoch intervals then join it with original dataframe.

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val ds = List((0, "New Epoch"), (2, "Fo"), (3, "Bar"), (11, "New Epoch"), (12, "Baz")).toDF("Time", "Type")
val epoch = ds.filter($"Type" === "New Epoch")
val spec = Window.orderBy("Time")
val epochInterval = epoch.withColumn("next_epoch", lead($"Time", 1).over(spec))//.show(false)
val result = ds.as("left").join(epochInterval.as("right"), $"left.Time" >= $"right.Time" && ($"left.Time" < $"right.next_epoch" || $"right.next_epoch".isNull))
      .select($"left.Time", $"left.Type", $"right.Time".as("Epoch"))
result.show(false)

+----+---------+-----+
|Time|Type     |Epoch|
+----+---------+-----+
|0   |New Epoch|0    |
|2   |Fo       |0    |
|3   |Bar      |0    |
|11  |New Epoch|11   |
|12  |Baz      |11   |
+----+---------+-----+


问:
Reverse A Binary Tree (Left to Right)
I was looking at interview questions and I recently came upon one that asked you how to reverse a general binary tree, like flip it from right to left.

So for example if we had the binary tree

```<code>     6
   /   \
  3     4
 / \   / \
7   3 8   1
</code>```

Reversing it would create

```<code>     6
   /   \
  4     3
 / \   / \
1   8 3   7
</code>```

You can see that the new tree is the mirror image of the original tree.

I haven't been able to think of a good implementation on how to solve this problem. Can anyone offer any good ideas?

答:
The recursion function can be very simple as shown below:</p>

```<code>public Node flipTree(Node node) {
    if(node == null) return null;

    Node left = flipTree(node.left);
    Node right = flipTree(node.right);

    node.left = right;
    node.right = left;

    return node;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reverse A Binary Tree (Left to Right)

Body:
I was looking at interview questions and I recently came upon one that asked you how to reverse a general binary tree, like flip it from right to left.

So for example if we had the binary tree

     6
   /   \
  3     4
 / \   / \
7   3 8   1

Reversing it would create

     6
   /   \
  4     3
 / \   / \
1   8 3   7

You can see that the new tree is the mirror image of the original tree.

I haven't been able to think of a good implementation on how to solve this problem. Can anyone offer any good ideas?

Body:
The recursion function can be very simple as shown below:

public Node flipTree(Node node) {
    if(node == null) return null;

    Node left = flipTree(node.left);
    Node right = flipTree(node.right);

    node.left = right;
    node.right = left;

    return node;
}


问:
Why the DataFrame does not update?
I have this portfolio class and i want to create a function AddStockShares that checks if a stock exists and if so it adds the number of shares to the existing ones or else it throw an excemption. I wrote a query with iloc in order to get the value of shares that i want based on the given stock_ticker but when i add the new shares the stocks dataFrame does not update even though when i print the result in the function it is correct. Any suggestions?    </p>

```<code>import numpy as np
import pandas as pd

class Portfolio(object):
"""description of class"""

array_of_stock_prices = []
array_of_stock_names = []
array_of_shares=[]
stocks = pd.DataFrame(np.column_stack([array_of_stock_prices, array_of_stock_names,array_of_shares]))

def __init__(self):
    print()

def AddStock(self, stock_ticker, stock_price,num_shares):
    if stock_ticker in self.array_of_stock_names:
        raise ValueError('Ticker already exists')
    else:
        self.array_of_stock_names.append(stock_ticker)

    self.array_of_stock_prices.append(stock_price)

    if(num_shares<0):
        raise ValueError('Number of shares cannot be negative,Check again')
    else:
        self.array_of_shares.append(num_shares)

    self.stocks = pd.DataFrame(np.column_stack([self.array_of_stock_names, self.array_of_stock_prices,self.array_of_shares]),
                          columns=['Ticker', 'Price','Shares'])

def BuyStockShares(self, stock_ticker, num_shares):
    if stock_ticker in self.array_of_stock_names:
        x=int(self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares'])+num_shares
        print(x)
     else:
        raise ValueError('Stock does not exist.Add stock first')

por=Portfolio()
por.AddStock('AAPLE',100,200)
por.AddStock('SASA',500,10)
por.AddStock('xv',500,50)
por.BuyStockShares('xv',1000)
print(por.stocks)
</code>```

答:
You need to update that row.</p>

```<code>def BuyStockShares(self, stock_ticker, num_shares):
  if stock_ticker in self.array_of_stock_names:
    self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares']=int(self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares'])+num_shares
  else:
    raise ValueError('Stock does not exist.Add stock first')
</code>```

Title: Why the DataFrame does not update?

Body:
I have this portfolio class and i want to create a function AddStockShares that checks if a stock exists and if so it adds the number of shares to the existing ones or else it throw an excemption. I wrote a query with iloc in order to get the value of shares that i want based on the given stock_ticker but when i add the new shares the stocks dataFrame does not update even though when i print the result in the function it is correct. Any suggestions?

import numpy as np
import pandas as pd

class Portfolio(object):
"""description of class"""

array_of_stock_prices = []
array_of_stock_names = []
array_of_shares=[]
stocks = pd.DataFrame(np.column_stack([array_of_stock_prices, array_of_stock_names,array_of_shares]))

def __init__(self):
    print()

def AddStock(self, stock_ticker, stock_price,num_shares):
    if stock_ticker in self.array_of_stock_names:
        raise ValueError('Ticker already exists')
    else:
        self.array_of_stock_names.append(stock_ticker)

    self.array_of_stock_prices.append(stock_price)

    if(num_shares<0):
        raise ValueError('Number of shares cannot be negative,Check again')
    else:
        self.array_of_shares.append(num_shares)

    self.stocks = pd.DataFrame(np.column_stack([self.array_of_stock_names, self.array_of_stock_prices,self.array_of_shares]),
                          columns=['Ticker', 'Price','Shares'])

def BuyStockShares(self, stock_ticker, num_shares):
    if stock_ticker in self.array_of_stock_names:
        x=int(self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares'])+num_shares
        print(x)
     else:
        raise ValueError('Stock does not exist.Add stock first')

por=Portfolio()
por.AddStock('AAPLE',100,200)
por.AddStock('SASA',500,10)
por.AddStock('xv',500,50)
por.BuyStockShares('xv',1000)
print(por.stocks)

Body:
You need to update that row.

def BuyStockShares(self, stock_ticker, num_shares):
  if stock_ticker in self.array_of_stock_names:
    self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares']=int(self.stocks.loc[self.stocks['Ticker']==stock_ticker,'Shares'])+num_shares
  else:
    raise ValueError('Stock does not exist.Add stock first')


问:
Python sin and cosine giving incorrect values
I have code that draws a line from 2 points; One on the middle bottom of the screen, and the other to the mouse pointer. I am trying to constrain the point by not exceeding a length parameter that I set. Heres the code:

```<code>import pygame
import Resources as r
import math as m

pygame.init()

class Segment():

    def __init__(self, _screen, _id, _start_pos, _length):
        self.screen = _screen
        self.id = _id
        self.start_pos = _start_pos
        self.length = _length

    def update(self):
        if self.id == 1:
            mouse_pos = pygame.mouse.get_pos()

            self.angle = m.atan2(mouse_pos[1]-self.start_pos[1],mouse_pos[0]-self.start_pos[0])
            self.a = self.start_pos
            self.b = (m.cos(self.angle)*self.length, m.sin(self.angle)*self.length)

            self.draw_line(self.a, self.b, r.black, 4)

    def draw_line(self, start, end, color, width):
        if self.id == 1:
            pygame.draw.line(self.screen, color, start, end, width)

    def get_data(self):
        return (self.start_pos, self.end_)
</code>```

I am seeing very different results when I run this that I would expect, it doesnt line up with my mouse and often just oscillates back and forth when the mouse is moved.

答:
EDIT: as skrx pointed out in comment: mouse position doesn't have to be converted to Vector2 because tuple-Vector2 gives Vector2.

You can do the same with python.math.Vector2

Your start point on the middle bottom of the screen

```<code>screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

start = pygame.math.Vector2(screen_rect.centerx, screen_rect.bottom)
</code>```

And end point using mouse positon and length

```<code>#mouse = pygame.math.Vector2(pygame.mouse.get_pos()) # edited
mouse = pygame.mouse.get_pos()
end = start + (mouse - start).normalize() * length
</code>```

And now you can draw

```<code>pygame.draw.line(screen, (255,0,0), start, end)
</code>```

Working example

```<code>import pygame

# === CONSTANS === (UPPER_CASE names)

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)

SCREEN_WIDTH  = 600
SCREEN_HEIGHT = 400

# === MAIN === (lower_case names)

# --- init ---

pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

# --- objects ---

start = pygame.math.Vector2(screen_rect.centerx, screen_rect.bottom)
end = start
length = 150

# --- mainloop ---

clock = pygame.time.Clock()
is_running = True

while is_running:

    # --- events ---

    for event in pygame.event.get():

        # --- global events ---

        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                is_running = False
        elif event.type == pygame.MOUSEMOTION:
            #mouse = pygame.math.Vector2(pygame.mouse.get_pos()) # edited
            mouse = pygame.mouse.get_pos()
            end = start + (mouse - start).normalize() * length

        # --- objects events ---

            # empty

    # --- updates ---

        # empty

    # --- draws ---

    screen.fill(BLACK)

    pygame.draw.line(screen, RED, start, end)

    pygame.display.update()

    # --- FPS ---

    clock.tick(25)

# --- the end ---

pygame.quit()
</code>```

Red line has always the same length and it shows direction to cursor.

Body:
I have code that draws a line from 2 points; One on the middle bottom of the screen, and the other to the mouse pointer. I am trying to constrain the point by not exceeding a length parameter that I set. Heres the code:

import pygame
import Resources as r
import math as m

pygame.init()

class Segment():

    def __init__(self, _screen, _id, _start_pos, _length):
        self.screen = _screen
        self.id = _id
        self.start_pos = _start_pos
        self.length = _length

    def update(self):
        if self.id == 1:
            mouse_pos = pygame.mouse.get_pos()

            self.angle = m.atan2(mouse_pos[1]-self.start_pos[1],mouse_pos[0]-self.start_pos[0])
            self.a = self.start_pos
            self.b = (m.cos(self.angle)*self.length, m.sin(self.angle)*self.length)

            self.draw_line(self.a, self.b, r.black, 4)

    def draw_line(self, start, end, color, width):
        if self.id == 1:
            pygame.draw.line(self.screen, color, start, end, width)

    def get_data(self):
        return (self.start_pos, self.end_)

I am seeing very different results when I run this that I would expect, it doesnt line up with my mouse and often just oscillates back and forth when the mouse is moved.

Body:
EDIT: as skrx pointed out in comment: mouse position doesn't have to be converted to Vector2 because tuple-Vector2 gives Vector2.

You can do the same with python.math.Vector2

Your start point on the middle bottom of the screen

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

start = pygame.math.Vector2(screen_rect.centerx, screen_rect.bottom)

And end point using mouse positon and length

#mouse = pygame.math.Vector2(pygame.mouse.get_pos()) # edited
mouse = pygame.mouse.get_pos()
end = start + (mouse - start).normalize() * length

And now you can draw

pygame.draw.line(screen, (255,0,0), start, end)

Working example

import pygame

# === CONSTANS === (UPPER_CASE names)

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)

SCREEN_WIDTH  = 600
SCREEN_HEIGHT = 400

# === MAIN === (lower_case names)

# --- init ---

pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

# --- objects ---

start = pygame.math.Vector2(screen_rect.centerx, screen_rect.bottom)
end = start
length = 150

# --- mainloop ---

clock = pygame.time.Clock()
is_running = True

while is_running:

    # --- events ---

    for event in pygame.event.get():

        # --- global events ---

        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                is_running = False
        elif event.type == pygame.MOUSEMOTION:
            #mouse = pygame.math.Vector2(pygame.mouse.get_pos()) # edited
            mouse = pygame.mouse.get_pos()
            end = start + (mouse - start).normalize() * length

        # --- objects events ---

            # empty

    # --- updates ---

        # empty

    # --- draws ---

    screen.fill(BLACK)

    pygame.draw.line(screen, RED, start, end)

    pygame.display.update()

    # --- FPS ---

    clock.tick(25)

# --- the end ---

pygame.quit()

Red line has always the same length and it shows direction to cursor.


问:
Inject specific instance into specific class
Is it possible to determine which class wants do inject my bean using Spring Context? I'm using the Java only configuration for my beans.

Let's say I've got this bean:

```<code>@Bean
@Scope("prototype")
public Helper helper() {
    return new Helper();
}
</code>```

Now I want to know in which class this instance will be injected in to inject a special instance meant for this class.

I want to do something like this, example pseudo code:

```<code>@Bean
@Scope("prototype")
public Helper helper(Class injectInto) {
    if (injectInto == SomeClass.class) {
        return new Helper("Only for SomeClass!");
    }
    return new Helper();
}
</code>```

The beans should be injected as always, for example:

```<code>@Autowired
private Helper helper;
</code>```

答:
Use the @Qualifier and @Bean(name="") annotations for this purpose. There are many online resources for how to use it.

```<code>@Bean(name="normal")
@Scope("prototype")
public Helper helper(Class injectInto) {
    return new Helper();
}

@Bean(name="special")
@Scope("prototype")
public Helper helper(Class injectInto) {
    return new Helper("Only for SomeClass!");
}
</code>```

Autowire in SomeClass:

```<code>@Autowired
@Qualifier(value = "special")
private Helper helper;
</code>```

Body:
Is it possible to determine which class wants do inject my bean using Spring Context? I'm using the Java only configuration for my beans.

Let's say I've got this bean:

@Bean
@Scope("prototype")
public Helper helper() {
    return new Helper();
}

Now I want to know in which class this instance will be injected in to inject a special instance meant for this class.

I want to do something like this, example pseudo code:

@Bean
@Scope("prototype")
public Helper helper(Class injectInto) {
    if (injectInto == SomeClass.class) {
        return new Helper("Only for SomeClass!");
    }
    return new Helper();
}

The beans should be injected as always, for example:

@Autowired
private Helper helper;

Body:
Use the @Qualifier and @Bean(name="") annotations for this purpose. There are many online resources for how to use it.

@Bean(name="normal")
@Scope("prototype")
public Helper helper(Class injectInto) {
    return new Helper();
}

@Bean(name="special")
@Scope("prototype")
public Helper helper(Class injectInto) {
    return new Helper("Only for SomeClass!");
}

Autowire in SomeClass:

@Autowired
@Qualifier(value = "special")
private Helper helper;


答:
This seems a fairly simple data manipulation task. What you are essentially trying is a simple group by and time difference.

The code snippet below does what it takes ::

Step 1: Add date and time to same variable so that we can calculate differences

Step 2: Calculate the difference between current time and minimum time for that group

I updated your data to have the two groups; just to show an example.

```<code>library(dplyr) # pipes, group by and mutate
library(lubridate) # times

input_data <- read.table(text = "Date    Time    Sample  Temp
                         2017-06-28  13:58   A1  13.67870139
                         2017-06-29  16:08   A1  13.34256319
                         2017-06-30  07:32   A1  12.84005139
                         2017-06-30  19:14   A1  12.84005139
                         2017-07-01  07:40   A1  11.83983472
                         2017-07-01  19:20   A1  11.83983472
                         2017-07-02  07:53   A1  11.75332292
                         2017-07-02  19:06   A2  11.75332292
                         2017-07-03  07:45   A2  11.74469167
                         2017-07-03  19:04   A2  11.74469167
                         2017-07-04  08:15   A2  11.45409583",
                         header = TRUE, stringsAsFactors = FALSE) %>%
  mutate(Actual_Time = paste(Date, Time, sep =" ") %>% parse_date_time(., "%y-%m-%d %H:%M")) %>%
  group_by(Sample) %>%
  mutate(Total_Time = difftime(Actual_Time, min(Actual_Time), units = "hours"))
</code>```

Output

```<code># A tibble: 11 x 6
# Groups:   Sample [2]
Date           Time  Sample   Temp       Actual_Time       Total_Time
<chr>         <chr>  <chr>    <dbl>         <dttm>            <time>
 1 2017-06-28 13:58     A1 13.67870 2017-06-28 13:58:00  0.00000 hours
 2 2017-06-29 16:08     A1 13.34256 2017-06-29 16:08:00 26.16667 hours
 3 2017-06-30 07:32     A1 12.84005 2017-06-30 07:32:00 41.56667 hours
 4 2017-06-30 19:14     A1 12.84005 2017-06-30 19:14:00 53.26667 hours
 5 2017-07-01 07:40     A1 11.83983 2017-07-01 07:40:00 65.70000 hours
 6 2017-07-01 19:20     A1 11.83983 2017-07-01 19:20:00 77.36667 hours
 7 2017-07-02 07:53     A1 11.75332 2017-07-02 07:53:00 89.91667 hours
 8 2017-07-02 19:06     A2 11.75332 2017-07-02 19:06:00  0.00000 hours
 9 2017-07-03 07:45     A2 11.74469 2017-07-03 07:45:00 12.65000 hours
10 2017-07-03 19:04     A2 11.74469 2017-07-03 19:04:00 23.96667 hours
11 2017-07-04 08:15     A2 11.45410 2017-07-04 08:15:00 37.15000 hours
</code>```

Title: Calculate total experimental time for each sample

Body:
This seems a fairly simple data manipulation task. What you are essentially trying is a simple group by and time difference.

The code snippet below does what it takes ::

Step 1: Add date and time to same variable so that we can calculate differences

Step 2: Calculate the difference between current time and minimum time for that group

I updated your data to have the two groups; just to show an example.

library(dplyr) # pipes, group by and mutate
library(lubridate) # times

input_data <- read.table(text = "Date    Time    Sample  Temp
                         2017-06-28  13:58   A1  13.67870139
                         2017-06-29  16:08   A1  13.34256319
                         2017-06-30  07:32   A1  12.84005139
                         2017-06-30  19:14   A1  12.84005139
                         2017-07-01  07:40   A1  11.83983472
                         2017-07-01  19:20   A1  11.83983472
                         2017-07-02  07:53   A1  11.75332292
                         2017-07-02  19:06   A2  11.75332292
                         2017-07-03  07:45   A2  11.74469167
                         2017-07-03  19:04   A2  11.74469167
                         2017-07-04  08:15   A2  11.45409583",
                         header = TRUE, stringsAsFactors = FALSE) %>%
  mutate(Actual_Time = paste(Date, Time, sep =" ") %>% parse_date_time(., "%y-%m-%d %H:%M")) %>%
  group_by(Sample) %>%
  mutate(Total_Time = difftime(Actual_Time, min(Actual_Time), units = "hours"))

Output

# A tibble: 11 x 6
# Groups:   Sample [2]
Date           Time  Sample   Temp       Actual_Time       Total_Time
<chr>         <chr>  <chr>    <dbl>         <dttm>            <time>
 1 2017-06-28 13:58     A1 13.67870 2017-06-28 13:58:00  0.00000 hours
 2 2017-06-29 16:08     A1 13.34256 2017-06-29 16:08:00 26.16667 hours
 3 2017-06-30 07:32     A1 12.84005 2017-06-30 07:32:00 41.56667 hours
 4 2017-06-30 19:14     A1 12.84005 2017-06-30 19:14:00 53.26667 hours
 5 2017-07-01 07:40     A1 11.83983 2017-07-01 07:40:00 65.70000 hours
 6 2017-07-01 19:20     A1 11.83983 2017-07-01 19:20:00 77.36667 hours
 7 2017-07-02 07:53     A1 11.75332 2017-07-02 07:53:00 89.91667 hours
 8 2017-07-02 19:06     A2 11.75332 2017-07-02 19:06:00  0.00000 hours
 9 2017-07-03 07:45     A2 11.74469 2017-07-03 07:45:00 12.65000 hours
10 2017-07-03 19:04     A2 11.74469 2017-07-03 19:04:00 23.96667 hours
11 2017-07-04 08:15     A2 11.45410 2017-07-04 08:15:00 37.15000 hours


问:
how make drop down not change after refresh in html and javascript?
I have drop down in HTML :

```<code><div>
    <select onchange="sesi(this.value)">
        <option id="tgl" value="tahun">PerBulan</option>
        <option id="bln" value="tgl">PerTanggal</option>
    </select>
</div>
<div class="col-sm-4">
    <div class="input-group" id="dateThn" >
        <input type="text" id="datepicker-autoclose" class="form-control" value="{{ Helpers.showTgl(tanggal, 'Y-m') }}" />
    </div>
    <div  id="dateTgl" style="display: none;" >
        <input type="text" id="datepickerTgl" value="{{ Helpers.showTgl(tanggal, 'Y-m-d') }}" />
    </div>
</div>
</code>```

with javascript :

```<code><script>
    function sesi(sesi){
        if (sesi == 'tgl') {
            $('#dateTgl').show();
            $('#dateThn').hide();
        } else {
            $('#dateTgl').hide();
            $('#dateThn').show();
        }}
</script>
</code>```

Why when I chose Pertanggal and refresh page drop down back to default .
and default is perbulan.

how I solved ?

答:
Why when I chose Pertanggal and refresh page drop down back to default . and default is perbulan.

If I guess correctly, you're having issue with postback. When you select pertanggal option, your page is refreshed and dropdown is back to PerBulan

Handle a change event with jquery as documented here https://api.jquery.com/change/.

And add event.preventDefault() to prevent postback.

$("#myselect").change(function(e) {
  var selectedSesi = $(this).val();
  console.log(selectedSesi);
  sesi(selectedSesi);

  e.preventDefault();
});

function sesi(sesi) {
  if (sesi == 'tgl') {
    $('#dateTgl').show();
    $('#dateThn').hide();
  } else {
    $('#dateTgl').hide();
    $('#dateThn').show();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" >

<div>
  <select id="myselect" class="form-control" >
    <option id="" value="">--Select Something--</option>
    <option id="tgl" value="tahun">PerBulan</option>
    <option id="bln" value="tgl">PerTanggal</option>
  </select>
</div>
<div class="col-sm-4">
  <div class="input-group" id="dateThn">
    <input type="text" id="datepicker-autoclose"
      class="form-control"
      value="{{ Helpers.showTgl(tanggal, 'Y-m') }}" />
  </div>
  <div id="dateTgl" style="display: none;">
    <input type="text"
      class="form-control"
      id="datepickerTgl"
      value="{{ Helpers.showTgl(tanggal, 'Y-m-d') }}" />
  </div>
</div></code>```

Body:
I have drop down in HTML :

    <select onchange="sesi(this.value)">
        <option id="tgl" value="tahun">PerBulan</option>
        <option id="bln" value="tgl">PerTanggal</option>
    </select>

        <input type="text" id="datepicker-autoclose" class="form-control" value="{{ Helpers.showTgl(tanggal, 'Y-m') }}" />

        <input type="text" id="datepickerTgl" value="{{ Helpers.showTgl(tanggal, 'Y-m-d') }}" />

with javascript :

Why when I chose Pertanggal and refresh page drop down back to default .
and default is perbulan.

how I solved ?

Body:
Why when I chose Pertanggal and refresh page drop down back to default . and default is perbulan.

If I guess correctly, you're having issue with postback. When you select pertanggal option, your page is refreshed and dropdown is back to PerBulan

Handle a change event with jquery as documented here https://api.jquery.com/change/.

And add event.preventDefault() to prevent postback.

$("#myselect").change(function(e) {
  var selectedSesi = $(this).val();
  console.log(selectedSesi);
  sesi(selectedSesi);

  e.preventDefault();
});

function sesi(sesi) {
  if (sesi == 'tgl') {
    $('#dateTgl').show();
    $('#dateThn').hide();
  } else {
    $('#dateTgl').hide();
    $('#dateThn').show();
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" >

<div>
  <select id="myselect" class="form-control" >
    <option id="" value="">--Select Something--</option>
    <option id="tgl" value="tahun">PerBulan</option>
    <option id="bln" value="tgl">PerTanggal</option>
  </select>
</div>
<div class="col-sm-4">
  <div class="input-group" id="dateThn">
    <input type="text" id="datepicker-autoclose"
      class="form-control"
      value="{{ Helpers.showTgl(tanggal, 'Y-m') }}" />
  </div>
  <div id="dateTgl" style="display: none;">
    <input type="text"
      class="form-control"
      id="datepickerTgl"
      value="{{ Helpers.showTgl(tanggal, 'Y-m-d') }}" />
  </div>
</div>


问:
Flutter - Pass a dynamic Item as Key
The code below is displaying the following error when I run in flutter run debug mode:

type 'List' is not a subtype of type 'String' of 'value' where

When I run in release mode flutter run --release the error does not appear and I can identify the item I selected to delete.

The problem is on line 39:
key: new Key(i),

The key only accepts string as value:
Key(String value) → Key

But I'm passing a List that appears to be a dynamic item:
dynamic i

But I need to pass a List on the Key to be able to identify what the excluded item will be.

How could I solve this problem in debug mode?

And why is this behavior happening and in the release mode the problem does not occur?

```<code>import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> tiles;
  List foos = [];

  @override
  void initState() {
    this.foos = [[0, 'foo1'], [1, 'foo2'], [2, 'foo3'], [3, 'foo4']];
    this.tiles = buildTile(this.foos);
    super.initState();
  }

  //function
  List<Widget> buildTile(List list) {
    var x = [];
    for(var i in list) {
      x.add(
        new ItemCategory(
          key: new Key(i),
          category: i[1],
          onPressed: () {
            setState(() {
              list.removeAt(i[0]);
              var list2 = [];
              for(var x = 0; x < list.length; x++) {
                list2.add([ x, list[x][1] ]);
              }
              this.tiles = buildTile(list2);
            });
          },
        )
      );
    }
    return x;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Categories'),
      ),
      body: new ListView(
        padding: new EdgeInsets.only(top: 8.0, right: 0.0, left: 0.0),
        children: this.tiles
      )
    );
  }
}

class ItemCategory extends StatefulWidget {
  ItemCategory({ Key key, this.category, this.onPressed}) : super(key: key);

  final String category;
  final VoidCallback onPressed;

  @override
  ItemCategoryState createState() => new ItemCategoryState();
}

class ItemCategoryState extends State<ItemCategory> with TickerProviderStateMixin {
  ItemCategoryState();

  AnimationController _controller;
  Animation<double> _animation;
  double flingOpening;
  bool startFling = true;

  void initState() {
    super.initState();
    _controller = new AnimationController(duration:
      const Duration(milliseconds: 246), vsync: this);

    _animation = new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.0, 1.0, curve: Curves.linear),
    );
  }

  void _move(DragUpdateDetails details) {
    final double delta = details.primaryDelta / 304;
    _controller.value -= delta;
  }

  void _settle(DragEndDetails details) {
    if(this.startFling) {
      _controller.fling(velocity: 1.0);
      this.startFling = false;
    } else if(!this.startFling){
      _controller.fling(velocity: -1.0);
      this.startFling = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _width = logicalSize.width;
    this.flingOpening = -(48.0/_width);

    return new GestureDetector(
      onHorizontalDragUpdate: _move,
      onHorizontalDragEnd: _settle,
      child: new Stack(
        children: <Widget>[
          new Positioned.fill(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFFE57373),
                  ),
                  child: new IconButton(
                    icon: new Icon(Icons.delete),
                    color: new Color(0xFFFFFFFF),
                    onPressed: widget.onPressed
                  )
                ),
              ],
            ),
          ),
          new SlideTransition(
            position: new Tween<Offset>(
              begin:  Offset.zero,
              end: new Offset(this.flingOpening, 0.0),
            ).animate(_animation),
            child: new Container(
              decoration: new BoxDecoration(
                border: new Border(
                  top: new BorderSide(style: BorderStyle.solid, color: Colors.black26),
                ),
                color: new Color(0xFFFFFFFF),
              ),
              margin: new EdgeInsets.only(top: 0.0, bottom: 0.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new Expanded(
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        new Container(
                          margin: new EdgeInsets.only(left: 16.0),
                          padding: new EdgeInsets.only(right: 40.0, top: 4.5, bottom: 4.5),
                          child: new Row(
                            children: <Widget>[
                              new Container(
                                margin: new EdgeInsets.only(right: 16.0),
                                child: new Icon(
                                  Icons.brightness_1,
                                  color: Colors.black,
                                  size: 35.0,
                                ),
                              ),
                              new Text(widget.category),
                            ],
                          )
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ),
        ],
      )
    );
  }
}
</code>```

答:
You should know that --release flag remove all assert and type checking from the app. Which is why your error disappear.
Asserts/Type Check are here only as tools for a better development to see potential errors without having to actually run the app. A release build don't need to be aware of these.

In your case, the problem occurs because you haven't specified the 'generic' type of list in List<Widget> buildTile(List list) ; which default list to List<dynamic>.
Consequence, the compiler don't know what type is an element of your list and therefore allows you to do new Key(i). Because i may be a String.

Modifying your function prototype to List<Widget> buildTile(List<List<String>> list) (which is the real type of your list here) will allow the compiler to alert you from a potential error.
And that error is List<String> can't be assigned to type String on new Key(i).

To fix that error, you can instead do new Key(i.toString(), which will serialize your list (thanks to being primitive objects).

Or use the ObjectKey that inherit from Key, but instead of using String as parameter, it takes anObject such as key: new ObjectKey(i)

Title: Flutter - Pass a dynamic Item as Key

Body:
The code below is displaying the following error when I run in flutter run debug mode:

type 'List' is not a subtype of type 'String' of 'value' where

When I run in release mode flutter run --release the error does not appear and I can identify the item I selected to delete.

The problem is on line 39:
key: new Key(i),

The key only accepts string as value:
Key(String value) → Key

But I'm passing a List that appears to be a dynamic item:
dynamic i

But I need to pass a List on the Key to be able to identify what the excluded item will be.

How could I solve this problem in debug mode?

And why is this behavior happening and in the release mode the problem does not occur?

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> tiles;
  List foos = [];

  @override
  void initState() {
    this.foos = [[0, 'foo1'], [1, 'foo2'], [2, 'foo3'], [3, 'foo4']];
    this.tiles = buildTile(this.foos);
    super.initState();
  }

  //function
  List<Widget> buildTile(List list) {
    var x = [];
    for(var i in list) {
      x.add(
        new ItemCategory(
          key: new Key(i),
          category: i[1],
          onPressed: () {
            setState(() {
              list.removeAt(i[0]);
              var list2 = [];
              for(var x = 0; x < list.length; x++) {
                list2.add([ x, list[x][1] ]);
              }
              this.tiles = buildTile(list2);
            });
          },
        )
      );
    }
    return x;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Categories'),
      ),
      body: new ListView(
        padding: new EdgeInsets.only(top: 8.0, right: 0.0, left: 0.0),
        children: this.tiles
      )
    );
  }
}

class ItemCategory extends StatefulWidget {
  ItemCategory({ Key key, this.category, this.onPressed}) : super(key: key);

  final String category;
  final VoidCallback onPressed;

  @override
  ItemCategoryState createState() => new ItemCategoryState();
}

class ItemCategoryState extends State<ItemCategory> with TickerProviderStateMixin {
  ItemCategoryState();

  AnimationController _controller;
  Animation<double> _animation;
  double flingOpening;
  bool startFling = true;

  void initState() {
    super.initState();
    _controller = new AnimationController(duration:
      const Duration(milliseconds: 246), vsync: this);

    _animation = new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.0, 1.0, curve: Curves.linear),
    );
  }

  void _move(DragUpdateDetails details) {
    final double delta = details.primaryDelta / 304;
    _controller.value -= delta;
  }

  void _settle(DragEndDetails details) {
    if(this.startFling) {
      _controller.fling(velocity: 1.0);
      this.startFling = false;
    } else if(!this.startFling){
      _controller.fling(velocity: -1.0);
      this.startFling = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _width = logicalSize.width;
    this.flingOpening = -(48.0/_width);

    return new GestureDetector(
      onHorizontalDragUpdate: _move,
      onHorizontalDragEnd: _settle,
      child: new Stack(
        children: <Widget>[
          new Positioned.fill(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFFE57373),
                  ),
                  child: new IconButton(
                    icon: new Icon(Icons.delete),
                    color: new Color(0xFFFFFFFF),
                    onPressed: widget.onPressed
                  )
                ),
              ],
            ),
          ),
          new SlideTransition(
            position: new Tween<Offset>(
              begin:  Offset.zero,
              end: new Offset(this.flingOpening, 0.0),
            ).animate(_animation),
            child: new Container(
              decoration: new BoxDecoration(
                border: new Border(
                  top: new BorderSide(style: BorderStyle.solid, color: Colors.black26),
                ),
                color: new Color(0xFFFFFFFF),
              ),
              margin: new EdgeInsets.only(top: 0.0, bottom: 0.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new Expanded(
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        new Container(
                          margin: new EdgeInsets.only(left: 16.0),
                          padding: new EdgeInsets.only(right: 40.0, top: 4.5, bottom: 4.5),
                          child: new Row(
                            children: <Widget>[
                              new Container(
                                margin: new EdgeInsets.only(right: 16.0),
                                child: new Icon(
                                  Icons.brightness_1,
                                  color: Colors.black,
                                  size: 35.0,
                                ),
                              ),
                              new Text(widget.category),
                            ],
                          )
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ),
        ],
      )
    );
  }
}


问:
Javascript .match regular expression with reverse quantifier (or parse right to left)
Given a string like such...

```<code>"ABCDEFG"
</code>```

Is it possible to have a quantifier that works in "reverse" so to say?

For instance:

```<code>var foo = "ABCDEFG";
foo.match(/.{1,3}/g);
</code>```

Results in:

```<code>// Array(3) ["ABC", "DEF", "G"]
</code>```

What I'm trying achieve:

```<code>// Array(3) ["A", "BCD", "EFG"]
</code>```

So regardless of the string length, the array is always a representation of the string, with each node 3 characters in length (except possibly the 1st) but always starting at the end of the string.  So the first array item might be 1, 2 or 3 characters long, simply depending on what's "left over".

I have tried using the following to error:

```<code>foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null
</code>```

Thinking perhaps I could use negatives similar to splitting strings, however each of those examples returns null.

I'm assuming this can be done within the pattern somehow and not the quantifier, so I'd like to understand how that would be written with .match().  Or would this require having to write a custom method that would involve other string manipulation in order to accomplish this?

答:
Regular expressions always match from left to right, but you can use a positive lookahead with an end-of-string anchor to achieve what you want:

```<code>var foo = "ABCDEFG";
foo.match(/.{1,3}(?=(.{3})*$)/g);  // ["A", "BCD", "EFG"]
</code>```

Here the subpattern (?=(.{3})*$) is a lookahead expression that matches zero or more repetitions of (exactly!) 3 characters, bounded at the end of the string ($).

Body:
Given a string like such...

"ABCDEFG"

Is it possible to have a quantifier that works in "reverse" so to say?

For instance:

var foo = "ABCDEFG";
foo.match(/.{1,3}/g);

Results in:

// Array(3) ["ABC", "DEF", "G"]

What I'm trying achieve:

// Array(3) ["A", "BCD", "EFG"]

So regardless of the string length, the array is always a representation of the string, with each node 3 characters in length (except possibly the 1st) but always starting at the end of the string.  So the first array item might be 1, 2 or 3 characters long, simply depending on what's "left over".

I have tried using the following to error:

foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null

Thinking perhaps I could use negatives similar to splitting strings, however each of those examples returns null.

I'm assuming this can be done within the pattern somehow and not the quantifier, so I'd like to understand how that would be written with .match().  Or would this require having to write a custom method that would involve other string manipulation in order to accomplish this?

Body:
Regular expressions always match from left to right, but you can use a positive lookahead with an end-of-string anchor to achieve what you want:

var foo = "ABCDEFG";
foo.match(/.{1,3}(?=(.{3})*$)/g);  // ["A", "BCD", "EFG"]

Here the subpattern (?=(.{3})*$) is a lookahead expression that matches zero or more repetitions of (exactly!) 3 characters, bounded at the end of the string ($).


问:
Where does IIS 7.5 log errors?
Where does IIS 7.5 log errors?

Event Viewer?
Log File?

I get a very nonspecific internal 500 error. I would like to find out more.

I'm running PHP and I did what this last comment on this post said. But still it is not logging to the C:\windows\temp folder.

答:
To report errors in Event Viewer, go to your php.ini file and make sure logging is on.

```<code>log_errors = On
</code>```

Then enable error_log to write to syslog (with is Event Viewer on a Windows machines)

```<code>error_log = syslog
</code>```

Title: Where does IIS 7.5 log errors?

Body:
To report errors in Event Viewer, go to your php.ini file and make sure logging is on.

log_errors = On

Then enable error_log to write to syslog (with is Event Viewer on a Windows machines)

error_log = syslog


答:
Its nearly impossible to remove filter you applied on body.

Its far more better to apply that filter only on specific object that you want to blur, for exaple give them class "blur_me" and aply blur on that class.

Title: How do you make a blurry background and in focus div

Body:
Im trying to make this effect.

Blurry background : in focus login div form

I manage to make everything blurry with filter: blur() . But I don't know how to remove the blur effect from my login form with id = newlogin .


问:
TensorFlow Dataset API Parsing Error
I'm using the TensorFlow Dataset API to parse a CSV file and run a logistic regression. I'm following the example from the TF documentation here.

The following code snippet shows how I am setting up the model:

```<code>def input_fn(path, num_epochs, batch_size):
    dataset = tf.data.TextLineDataset(path)
    dataset = dataset.map(parse_table, num_parallel_calls=12)
    dataset = dataset.repeat(num_epochs)
    dataset.batch(batch_size)

    iterator = dataset.make_one_shot_iterator()
    features, labels = iterator.get_next()
    return features, labels

def parse_table(value):
    cols = tf.decode_csv(value, record_defaults=TAB_COLUMN_DEFAULTS)
    indep_vars = dict(zip(CSV_COLS, cols))
    y = indep_vars.pop('y')
    return indep_vars, y

def build_indep_vars():
    continuous_vars = [
        tf.feature_column.numeric_column(x, shape=1) for x in CONT_COLS]
    categorical_vars = [
        tf.feature_column.categorical_column_with_hash_bucket(
            x, hash_bucket_size=100) for x in CAT_COLS]
    return categorical_vars + continuous_vars
</code>```

When calling lr.train(input_fn = lambda: input_fn(data_path, 1, 100)) (note: batch size is 100) I'm getting the error

```<code>ValueError: Feature (key: V1) cannot have rank 0. Give: Tensor("IteratorGetNext:0", shape=(), dtype=float32, device=/device:CPU:0)
</code>```

So I'm assuming this means one of the tf.feature_column.numeric_column calls is getting a scalar value which it doesn't like. However, I cannot figure out why this is the case. I've set batch_size to a positive integer and according to the documentation the shape of the NDarray resulting from tf.feature_column.numeric_column should be 1Xbatch_size by default. Can anyone explain why TensorFlow is returning this error?

I'm sure this question has a simple answer that will make me feel stupid for not figuring it out, but after spending some time on this I'm still stumped.

答:
The error is raised because the tf.feature_column methods expect the input to be batched, and
I think the cause is a simple typo, which is dropping out the Dataset.batch() transformation. Replace the dataset.batch(batch_size) with the following line:

```<code>dataset = dataset.batch(batch_size)
</code>```

Calling any of the tf.data.Dataset transformations methods (e.g. Dataset.map(), Dataset.repeat(), Dataset.batch()) does not modify the object on which you called those methods. Instead, these methods return a new Dataset object that you can either use for further transformations, or to make an Iterator.

Title: TensorFlow Dataset API Parsing Error

Body:
I'm using the TensorFlow Dataset API to parse a CSV file and run a logistic regression. I'm following the example from the TF documentation here.

The following code snippet shows how I am setting up the model:

def input_fn(path, num_epochs, batch_size):
    dataset = tf.data.TextLineDataset(path)
    dataset = dataset.map(parse_table, num_parallel_calls=12)
    dataset = dataset.repeat(num_epochs)
    dataset.batch(batch_size)

    iterator = dataset.make_one_shot_iterator()
    features, labels = iterator.get_next()
    return features, labels

def parse_table(value):
    cols = tf.decode_csv(value, record_defaults=TAB_COLUMN_DEFAULTS)
    indep_vars = dict(zip(CSV_COLS, cols))
    y = indep_vars.pop('y')
    return indep_vars, y

def build_indep_vars():
    continuous_vars = [
        tf.feature_column.numeric_column(x, shape=1) for x in CONT_COLS]
    categorical_vars = [
        tf.feature_column.categorical_column_with_hash_bucket(
            x, hash_bucket_size=100) for x in CAT_COLS]
    return categorical_vars + continuous_vars

When calling lr.train(input_fn = lambda: input_fn(data_path, 1, 100)) (note: batch size is 100) I'm getting the error

ValueError: Feature (key: V1) cannot have rank 0. Give: Tensor("IteratorGetNext:0", shape=(), dtype=float32, device=/device:CPU:0)

So I'm assuming this means one of the tf.feature_column.numeric_column calls is getting a scalar value which it doesn't like. However, I cannot figure out why this is the case. I've set batch_size to a positive integer and according to the documentation the shape of the NDarray resulting from tf.feature_column.numeric_column should be 1Xbatch_size by default. Can anyone explain why TensorFlow is returning this error?

I'm sure this question has a simple answer that will make me feel stupid for not figuring it out, but after spending some time on this I'm still stumped.

Body:
The error is raised because the tf.feature_column methods expect the input to be batched, and
I think the cause is a simple typo, which is dropping out the Dataset.batch() transformation. Replace the dataset.batch(batch_size) with the following line:

dataset = dataset.batch(batch_size)

Calling any of the tf.data.Dataset transformations methods (e.g. Dataset.map(), Dataset.repeat(), Dataset.batch()) does not modify the object on which you called those methods. Instead, these methods return a new Dataset object that you can either use for further transformations, or to make an Iterator.


问:
GWT cell widgets with overlay types issues
I have taken the Cell Table example from google developer's guide and made the following changes:

Use overlays instead of Java POJOs

Use a EditTextCell to edit one column

For my surprise, when running the code the Cell Table is adding an extra property to the overlay objects pushed into it. They should look like:

{"name":"John", "address":"123 Fourth Road"}
{"name":"Mary", "address":"222 Lancer Lane"}

But instead they look like:

{"name":"John", "address":"123 Fourth Road", "$H":1}
{"name":"Mary", "address":"222 Lancer Lane", "$H":2}

Here is the modified code that demonstrates the issue:

```<code>import java.util.Arrays;
import java.util.List;

import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Overlay implements EntryPoint {

    private static class Contact extends JavaScriptObject {

        protected Contact() {}

        public static native Contact create(String name, String address) /*-{
            return {"name" : name , "address" : address};
        }-*/;
        public final native String getName() /*-{
            return this["name"];
        }-*/;
        public final native void setName(String name) /*-{
            this["name"] = name;
        }-*/;
        public final native String getAddress() /*-{
            return this["address"];
        }-*/;
        public final native void setAddress(String address) /*-{
            this["address"] = address;
        }-*/;
    }

    private static List<Contact> CONTACTS = Arrays.asList(
            Contact.create("John", "123 Fourth Road"),
            Contact.create("Mary", "222 Lancer Lane"));

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        CellTable<Contact> table = new CellTable<Contact>();
        // Create name column.
        Column<Contact, String> nameColumn = new Column<Contact, String>(new EditTextCell()) {
            public String getValue(Contact object) {
                return object.getName();
            }
        };
        // Create address column.
        TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
            public String getValue(Contact contact) {
                return contact.getAddress();
            }
        };
        // Add the columns.
        table.addColumn(nameColumn, "Name");
        table.addColumn(addressColumn, "Address");
        table.setRowCount(CONTACTS.size(), true);
        // Push the data into the widget.
        printList();
        table.setRowData(0, CONTACTS);
        printList();
        RootPanel.get().add(table);
    }

    private void printList() {
        for(Contact contact : CONTACTS) {
            GWT.log(new JSONObject(contact).toString());
        }
    }

}
</code>```

I have checked that it is the editable column the one that causes the issue. If I remove it the table does not modify my overlays.

Anyway, this is a very weird behaviour. I don't feel it is safe to work with overlays if your widgets can add them unexpected properties.

Has anyone encountered this issue before or is this behaviour documented anywhere? Any hints to solve it?

Thanks a lot

答:
I doubt that CellTable can sneakily edit your JSONs. Check those overlays in Firebug/Chrome_Developer_Tools/... if they ok then most likely bug is in this line:

```<code>GWT.log(new JSONObject(contact).toString());
</code>```

There are atleast two issues for JSONObject.toString: Passing List to/from JSNI works in web mode but fails in hosted mode & toString() and JSNI.

In second issue there is comment according to which you can try this:

```<code>GWT.log( (String) new JSONObject(contact) );
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have taken the Cell Table example from google developer's guide and made the following changes:

Use overlays instead of Java POJOs

Use a EditTextCell to edit one column

For my surprise, when running the code the Cell Table is adding an extra property to the overlay objects pushed into it. They should look like:

{"name":"John", "address":"123 Fourth Road"}
{"name":"Mary", "address":"222 Lancer Lane"}

But instead they look like:

{"name":"John", "address":"123 Fourth Road", "$H":1}
{"name":"Mary", "address":"222 Lancer Lane", "$H":2}

Here is the modified code that demonstrates the issue:

import java.util.Arrays;
import java.util.List;

import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad().
 */
public class Overlay implements EntryPoint {

    private static class Contact extends JavaScriptObject {

        protected Contact() {}

        public static native Contact create(String name, String address) /*-{
            return {"name" : name , "address" : address};
        }-*/;
        public final native String getName() /*-{
            return this["name"];
        }-*/;
        public final native void setName(String name) /*-{
            this["name"] = name;
        }-*/;
        public final native String getAddress() /*-{
            return this["address"];
        }-*/;
        public final native void setAddress(String address) /*-{
            this["address"] = address;
        }-*/;
    }

    private static List<Contact> CONTACTS = Arrays.asList(
            Contact.create("John", "123 Fourth Road"),
            Contact.create("Mary", "222 Lancer Lane"));

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        CellTable<Contact> table = new CellTable<Contact>();
        // Create name column.
        Column<Contact, String> nameColumn = new Column<Contact, String>(new EditTextCell()) {
            public String getValue(Contact object) {
                return object.getName();
            }
        };
        // Create address column.
        TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
            public String getValue(Contact contact) {
                return contact.getAddress();
            }
        };
        // Add the columns.
        table.addColumn(nameColumn, "Name");
        table.addColumn(addressColumn, "Address");
        table.setRowCount(CONTACTS.size(), true);
        // Push the data into the widget.
        printList();
        table.setRowData(0, CONTACTS);
        printList();
        RootPanel.get().add(table);
    }

    private void printList() {
        for(Contact contact : CONTACTS) {
            GWT.log(new JSONObject(contact).toString());
        }
    }

}

I have checked that it is the editable column the one that causes the issue. If I remove it the table does not modify my overlays.

Anyway, this is a very weird behaviour. I don't feel it is safe to work with overlays if your widgets can add them unexpected properties.

Has anyone encountered this issue before or is this behaviour documented anywhere? Any hints to solve it?

Thanks a lot

Body:
I doubt that CellTable can sneakily edit your JSONs. Check those overlays in Firebug/Chrome_Developer_Tools/... if they ok then most likely bug is in this line:

GWT.log(new JSONObject(contact).toString());

There are atleast two issues for JSONObject.toString: Passing List to/from JSNI works in web mode but fails in hosted mode & toString() and JSNI.

In second issue there is comment according to which you can try this:

GWT.log( (String) new JSONObject(contact) );


问:
error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
Getting error:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  on g++

on the following code:

```<code>void* func(void *s)
{
    int i = 0;
    int self = (int *)s;
    printf("Thread Entered: %d\n", self);

    sm.lock(self);

    // Critical section (Only one thread
    // can enter here at a time)
    for (i=0; i<MAX; i++)
        ans++;

    sm.unlock(self);
}
</code>```

答: You need to change int self = (int *)s; to int self = *((int *)s); or to int * self = (int *)s;.

Body:
Getting error:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  on g++

on the following code:

void* func(void *s)
{
    int i = 0;
    int self = (int *)s;
    printf("Thread Entered: %d\n", self);

    sm.lock(self);

    // Critical section (Only one thread
    // can enter here at a time)
    for (i=0; i<MAX; i++)
        ans++;

    sm.unlock(self);
}


问:
Angular2 - Declaring a component in two different modules
I create DynamicForm component connect it in two NgModule.

//  Module 1
@NgModule({
    imports: [],
    exports: [],
    declarations: [
        DynamicForm
    ],
    providers: []
})

//  Module 2
@NgModule({
    imports: [],
    exports: [],
    declarations: [
        DynamicForm
    ],
    providers: []
})
```

But project dont work, any errors. When I remove DynamicForm from one of NgModule get error that I need include this component. Also I tryed connect DynamicForm to app.module and remove from NgModule and also did't work.

What to do?

答:
Extending on user: @peeskillet answer

Two ways of declaring a component in two different modules:

As suggested in the @peeskillet answer, create a shared module and declare your component (and any other shared components) there and then import the shared module in the another module where you want to use the shared component as a dependency.

Create a separate module for the dependent component itself, and import the component module in the another module where you want to use the shared component as a dependency. The advantage of doing this is that you just importing what you want and not the other components from the shared modules.

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my.component';

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [MyComponent],
  declarations: [MyComponent]
})
export class MyComponentModule { }
</code>```

Body:
I create DynamicForm component connect it in two NgModule.

//  Module 1
@NgModule({
    imports: [],
    exports: [],
    declarations: [
        DynamicForm
    ],
    providers: []
})

//  Module 2
@NgModule({
    imports: [],
    exports: [],
    declarations: [
        DynamicForm
    ],
    providers: []
})

But project dont work, any errors. When I remove DynamicForm from one of NgModule get error that I need include this component. Also I tryed connect DynamicForm to app.module and remove from NgModule and also did't work.

What to do?

Body:
Extending on user: @peeskillet answer

Two ways of declaring a component in two different modules:

As suggested in the @peeskillet answer, create a shared module and declare your component (and any other shared components) there and then import the shared module in the another module where you want to use the shared component as a dependency.

Create a separate module for the dependent component itself, and import the component module in the another module where you want to use the shared component as a dependency. The advantage of doing this is that you just importing what you want and not the other components from the shared modules.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my.component';

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [MyComponent],
  declarations: [MyComponent]
})
export class MyComponentModule { }


问:
Why letsencrypt SSL certificate display warning messages?
I'm new to letsencrypt SSL certificate.

I have followed the article here, but received the following warning messages upon loading the website :

```<code>Warning: stream_socket_client(): Peer certificate CN=`abc.com' did not match expected CN=`1.2.3.4' in /usr/share/nginx/html/wp-includes/class-wp-http-streams.php on line 150

Warning: stream_socket_client(): Failed to enable crypto in /usr/share/nginx/html/wp-includes/class-wp-http-streams.php on line 150

Warning: stream_socket_client(): unable to connect to ssl://1.2.3.4:443 (Unknown error) in /usr/share/nginx/html/wp-includes/class-wp-http-streams.php on line 150
</code>```

Any clue on what's going on?

答:
I finally found the answer.

I modified my DNS control panel to use 2 nameservers, where previously there were 4 nameservers, from 2 different web hosting providers.

Then I tried :

```<code>sudo certbot --nginx -d abc.com -d www.abc.com --force-renewal
</code>```

Refreshed the browser and voila, it works now.

Hopefully this will be useful to whom encounter the same problem.

Body:
I'm new to letsencrypt SSL certificate.

I have followed the article here, but received the following warning messages upon loading the website :

Warning: stream_socket_client(): Peer certificate CN=`abc.com' did not match expected CN=`1.2.3.4' in /usr/share/nginx/html/wp-includes/class-wp-http-streams.php on line 150

Warning: stream_socket_client(): Failed to enable crypto in /usr/share/nginx/html/wp-includes/class-wp-http-streams.php on line 150

Warning: stream_socket_client(): unable to connect to ssl://1.2.3.4:443 (Unknown error) in /usr/share/nginx/html/wp-includes/class-wp-http-streams.php on line 150

Any clue on what's going on?

Body:
I finally found the answer.

I modified my DNS control panel to use 2 nameservers, where previously there were 4 nameservers, from 2 different web hosting providers.

Then I tried :

sudo certbot --nginx -d abc.com -d www.abc.com --force-renewal

Refreshed the browser and voila, it works now.

Hopefully this will be useful to whom encounter the same problem.


问:
Linking a new third party library to a c++ program while working with eclipse on Ubuntu
I recently downloaded a third party library called spline-master from github and the file provides a header file called spline.h. I wanted to use this header file so as to create a spline. I am currently using eclipse oxygen for c/c++. I was pretty new to this and have been stuck on this problem since the last few days. I tried changing so many things to link this file. The file can be seen in my project tree and it's there in the includes but when I write #include"spline.h" it throws me an error telling "there exists no such file or directory".
  Can anyone please let me know how I can go about this problem? All the applications are of the latest version including Ubuntu. I would have attached a couple of screenshots so that you can have a better idea about the problem I am facingenter image description here
Thanking you.

Regards,
Sumanth

enter image description here

答:
There are 2 main ways to include a header file, and you need to know where your spline.h is located in order to know which one you can use.

```<code>#include "spline.h"
</code>```

Enclosing in quotes will tell the preprocessor that the path you have supplied is relative to the location of the code file you are including the file into. Your compiler can't find the file which means it must be located in a directory different to the code file you are working on.

```<code>#include <spline.h>
</code>```

This is probably the version you want to use. This version will tell the preprocessor to look for spline.h in any header directories you have defined in your project. Again, it considers the path relative to the header directory.

Body:
There are 2 main ways to include a header file, and you need to know where your spline.h is located in order to know which one you can use.

#include "spline.h"

Enclosing in quotes will tell the preprocessor that the path you have supplied is relative to the location of the code file you are including the file into. Your compiler can't find the file which means it must be located in a directory different to the code file you are working on.

#include <spline.h>

This is probably the version you want to use. This version will tell the preprocessor to look for spline.h in any header directories you have defined in your project. Again, it considers the path relative to the header directory.


问:
Multisort by distance
I have a multidimensional array and want to sort it by distance:

```<code>[clustermarkers] => [
            0 => [
                    0 => [
                      'name' => 'A',
                      'distance' => 10
                    ]
            ],
            1 => [
                    0 => [
                      'name' => 'B',
                      'distance' => 8
                    ]
            ],
            ...
];
</code>```

I have tried usort function, but something wrong:

```<code>usort($clustermarkers, function($a, $b) {
   return (int)$a['distance'] - (int)$b['distance'];
});
</code>```

答:
In your usort function, just add [0] to $a and $b before ['distance']

```<code>usort($clustermarkers, function ($a, $b) {
    return $a[0]['distance'] - $b[0]['distance'];
});

print_r($clustermarkers);
</code>```

Title: Multisort by distance

Body:
I have a multidimensional array and want to sort it by distance:

[clustermarkers] => [
            0 => [
                    0 => [
                      'name' => 'A',
                      'distance' => 10
                    ]
            ],
            1 => [
                    0 => [
                      'name' => 'B',
                      'distance' => 8
                    ]
            ],
            ...
];

I have tried usort function, but something wrong:

usort($clustermarkers, function($a, $b) {
   return (int)$a['distance'] - (int)$b['distance'];
});

Body:
In your usort function, just add [0] to $a and $b before ['distance']

usort($clustermarkers, function ($a, $b) {
    return $a[0]['distance'] - $b[0]['distance'];
});

print_r($clustermarkers);


问:
Bind a view without extra parameters
I'm trying to bind a divider decoration to a Recycler view

```<code>    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        app:dividerDirection="@{}"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</code>```

And then I have a BindingAdapter to bind the divider

```<code>@BindingAdapter("dividerDirection")
    public static void setItemDecoration(RecyclerView view) {
            LineDividerItemDecoration decoration =
                    new LineDividerItemDecoration(view.getContext());
            view.addItemDecoration(decoration);
    }
</code>```

What is the correct way to bind a view without any extra arguments?

If I use something like

```<code>app:dividerDirection="@{@drawable/line_divider}"
</code>```

It works fine

But it doesn't work with

```<code> app:dividerDirection="@{}"
</code>```

I just need a reference to the view in order to get the context

答:
You can't have a binding adapter without any parameter.
What you can do is to pass null.

app:dividerDirection="@{null}"

In this case, your binding adapter could look like this:

```<code>@BindingAdapter("dividerDirection")
public static void setItemDecoration(RecyclerView view, Integer direction) {
    LineDividerItemDecoration decoration =
                    new LineDividerItemDecoration(view.getContext());
   view.addItemDecoration(decoration);
}
</code>```

I suggest creating binding adapters with general logic, not having it for every single use-case you have.

In your case, if you want to provide divider direction, you may pass integer/enum which would have some logic with the parameter.

Title: Bind a view without extra parameters

Body:
I'm trying to bind a divider decoration to a Recycler view

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        app:dividerDirection="@{}"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

And then I have a BindingAdapter to bind the divider

@BindingAdapter("dividerDirection")
    public static void setItemDecoration(RecyclerView view) {
            LineDividerItemDecoration decoration =
                    new LineDividerItemDecoration(view.getContext());
            view.addItemDecoration(decoration);
    }

What is the correct way to bind a view without any extra arguments?

If I use something like

app:dividerDirection="@{@drawable/line_divider}"

It works fine

But it doesn't work with

 app:dividerDirection="@{}"

I just need a reference to the view in order to get the context

Body:
You can't have a binding adapter without any parameter.
What you can do is to pass null.

app:dividerDirection="@{null}"

In this case, your binding adapter could look like this:

@BindingAdapter("dividerDirection")
public static void setItemDecoration(RecyclerView view, Integer direction) {
    LineDividerItemDecoration decoration =
                    new LineDividerItemDecoration(view.getContext());
   view.addItemDecoration(decoration);
}

I suggest creating binding adapters with general logic, not having it for every single use-case you have.

In your case, if you want to provide divider direction, you may pass integer/enum which would have some logic with the parameter.