问:
VHDL: Button debouncing (or not, as the case may be)
I've read through the other posts but can't seem to fix mine. I'm new to VHDL so I'm sure it's a simple fix.

In short, the button isn't debouncing. The code compiles and the bitstream programs. In the testbench, button presses work, but the output LEDs don't change. On the board, pressing a button makes random LEDs light up (I presume because of bouncing). According to the schematic the inputs are going through the debouncers.

Can anyone identify the issue? And any other hints and tips are always appreciated :)

Thanks!

EDIT1: Added rising_edge(clk).
Also note, when I press either button, at the time it's depressed all the LEDs light up.

button_counter.vhd

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity button_counter is
    port( clk : in std_logic;
         btnU : in std_logic;
         btnD : in std_logic;
          led : out std_logic_vector (15 downto 0));
end button_counter;

architecture behavioral of button_counter is

    component debouncer is
        port(    clk : in std_logic;
                 btn : in std_logic;
             btn_clr : out std_logic);
    end component;

    signal btnU_clr : std_logic;
    signal btnD_clr : std_logic;

    begin

    debouncer_btnU : debouncer port map (clk => clk, btn => btnU, btn_clr => btnU_clr);
    debouncer_btnD : debouncer port map (clk => clk, btn => btnD, btn_clr => btnD_clr);

    process(clk)
        variable count : integer := 0;
        begin
        if (rising_edge(clk)) then
            if(btnU_clr = '1') then count := count + 1;
            elsif(btnD_clr = '1') then count := count - 1;
            end if;
            led <= std_logic_vector(to_unsigned(count, led'length));
        end if;
    end process;

end behavioral;
</code>```

Debouncer.vhd

```<code>library IEEE;
    use IEEE.std_logic_1164.all;
    use IEEE.numeric_std.all;

entity debouncer is
    port(    clk : in std_logic;
             btn : in std_logic;
         btn_clr : out std_logic);
end debouncer;

architecture behavioural of debouncer is

    constant delay : integer := 650000; -- 6.5ms
    signal count : integer := 0;
    signal btn_tmp : std_logic := '0';

    begin

    process(clk)
    begin
        if rising_edge(clk) then
            if (btn /= btn_tmp) then
                btn_tmp <= btn;
                count <= 0;
            elsif (count = delay) then
                btn_clr <= btn_tmp;
            else
                count <= count + 1;
            end if;
        end if;
    end process;

end behavioural;
</code>```

button_counter_tb.vhd

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity button_counter_tb is
end button_counter_tb;

architecture behavioral of button_counter_tb is

signal clk_tb    : std_logic;
signal btnU_tb   : std_logic;
signal btnD_tb   : std_logic;
signal led_tb    : std_logic_vector (15 downto 0);

component button_counter
port(clk    : in std_logic;
     btnU   : in std_logic;
     btnD   : in std_logic;
     led    : out std_logic_vector (15 downto 0));
end component;

begin

UUT: button_counter port map (clk => clk_tb, btnU => btnU_tb, btnD => btnD_tb, led => led_tb);

process
begin

btnU_tb <= '0';
btnD_tb <= '0';

wait for 100ns;
btnU_tb <= '1';

wait for 100ns;
btnU_tb <= '0';

wait for 100ns;
btnU_tb <= '1';

wait for 100ns;
btnD_tb <= '1';

wait for 100ns;
btnU_tb <= '0';

wait for 100ns;
btnD_tb <= '0';

end process;

end behavioral;
</code>```

答:
The question has been answered well, but I would like to highlight different techniques for synchronising and debouncing.

Synchronising

For synchronising, a simple buffer or chain can be used which avoids creating separate signals/variables for each stage in the buffer or chain. A generic constant can be used to control the length of the chain (minimum of 2):

signal sync_buffer: std_logic_vector(SYNC_BUFFER_MSB downto 0);  -- N-bit synchronisation buffer.
...
sync_buffer <= sync_buffer(SYNC_BUFFER_MSB - 1 downto 0) & input;
```

<h1>Debouncing</h1>

<p>For debouncing, hysteresis (a fancy word for history or memory) can be used to create a kind of low pass filter that will debounce both the press and release of a button, and detect edges (both positive and negative) irrespective of whether the signal is active high or active low. The output will stay in its current state until the synchronised input remains in the opposite state for N consecutive clock cycles:</p>

<pre class="lang-vhdl prettyprint-override"><code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity Debounce is
    generic
    (
        CLOCK_PERIOD   : time := 20 ns;
        DEBOUNCE_PERIOD: time := 125 ms;  -- 1/8th second as a rule of thumb for a tactile button/switch.
        SYNC_BITS      : positive := 3    -- Number of bits in the synchronisation buffer (2 minimum).
    );
    port
    (
        clock : in std_logic;
        input : in std_logic;   -- Asynchronous and noisy input.
        output: out std_logic := '0';  -- Synchronised, debounced and filtered output.
        edge  : out std_logic := '0';  -- Goes high for 1 clock cycle on either edge of synchronised and debounced input.
        rise  : out std_logic := '0';  -- Goes high for 1 clock cycle on the rising edge of synchronised and debounced input.
        fall  : out std_logic := '0'   -- Goes high for 1 clock cycle on the falling edge of synchronised and debounced input.
    );
end entity;

architecture V1 of Debounce is

    constant SYNC_BUFFER_MSB: positive := SYNC_BITS - 1;
    signal sync_buffer: std_logic_vector(SYNC_BUFFER_MSB downto 0) := (others => '0');  -- N-bit synchronisation buffer (2 bits minimum).
    alias sync_input: std_logic is sync_buffer(SYNC_BUFFER_MSB);  -- The synchronised input is the MSB of the synchronisation buffer.

    constant MAX_COUNT: natural := DEBOUNCE_PERIOD / CLOCK_PERIOD;
    signal counter: natural range 0 to MAX_COUNT := 0;  -- Specify the range to reduce number of bits that are synthesised.

begin

    assert SYNC_BITS >= 2 report "Need a minimum of 2 bits in the synchronisation buffer.";

    process(clock)
        variable edge_internal: std_logic := '0';
        variable rise_internal: std_logic := '0';
        variable fall_internal: std_logic := '0';
    begin
        if rising_edge(clock) then
            -- Synchronise the asynchronous input.
            -- MSB of sync_buffer is the synchronised input.
            sync_buffer <= sync_buffer(SYNC_BUFFER_MSB - 1 downto 0) & input;

            edge <= '0';  -- Goes high for 1 clock cycle on either edge.
            rise <= '0';  -- Goes high for 1 clock cycle on the rising edge.
            fall <= '0';  -- Goes high for 1 clock cycle on the falling edge.

            if counter = MAX_COUNT - 1 then  -- If successfully debounced, notify what happened, and reset the counter.
                output <= sync_input;
                edge <= edge_internal;  -- Goes high for 1 clock cycle on either edge.
                rise <= rise_internal;  -- Goes high for 1 clock cycle on the rising edge.
                fall <= fall_internal;  -- Goes high for 1 clock cycle on the falling edge.
                counter <= 0;
            elsif sync_input /= output then
                counter <= counter + 1;
            else
                counter <= 0;
            end if;
        end if;

        -- Edge detection.
        edge_internal := sync_input xor output;
        rise_internal := sync_input and not output;
        fall_internal := not sync_input and output;
    end process;

end architecture;
</code>```

Button Counter

Much the same as the other answers, but I've used the rise outputs of the debouncers to trigger the counting. I also added a couple of LEDs for visual button feedback.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity ButtonCounter is
    generic
    (
        CLOCK_PERIOD   : time := 20 ns;
        DEBOUNCE_PERIOD: time := 125 ms
    );
    port
    (
        clock : in std_logic;
        btn_up: in std_logic;
        btn_dn: in std_logic;
        led_up: out std_logic;
        led_dn: out std_logic;
        leds  : out std_logic_vector(15 downto 0)
    );
end entity;

architecture V1 of ButtonCounter is

    signal count_up: std_logic;
    signal count_dn: std_logic;

    component Debounce is
        generic
        (
            CLOCK_PERIOD   : time := 20 ns;
            DEBOUNCE_PERIOD: time := 125 ms
        );
        port
        (
            clock : in std_logic;
            input : in std_logic;
            output: out std_logic;
            rise  : out std_logic
        );
    end component;

begin

    DEBOUNCE_BTN_UP:
    Debounce
    generic map
    (
        CLOCK_PERIOD    => CLOCK_PERIOD,
        DEBOUNCE_PERIOD => DEBOUNCE_PERIOD
    )
    port map
    (
        clock  => clock,
        input  => btn_up,
        output => led_up,
        rise   => count_up  -- Goes high for 1 clock cycle on the rising edge of btn_up.
    );

    DEBOUNCE_BTN_DN:
    Debounce
    generic map
    (
        CLOCK_PERIOD    => CLOCK_PERIOD,
        DEBOUNCE_PERIOD => DEBOUNCE_PERIOD
    )
    port map
    (
        clock  => clock,
        input  => btn_dn,
        output => led_dn,
        rise   => count_dn  -- Goes high for 1 clock cycle on the rising edge of btn_dn.
    );

    process(clock)
        variable counter: natural range 0 to 2 ** leds'length - 1 := 0;  -- Specify the range to reduce number of bits that are synthesised.
    begin
        if rising_edge(clock) then
            if count_up then
                counter := counter + 1;
            elsif count_dn then
                counter := counter - 1;
            end if;
            leds <= std_logic_vector(to_unsigned(counter, leds'length));
        end if;
    end process;

end architecture;
```

<h1>Test Bench</h1>

<p>Some asynchronous and noisy input buttons are synchronised, debounced and filtered. The positive edges of the reformed input signals trigger the counting.</p>

<pre class="lang-vhdl prettyprint-override"><code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.math_real.all;

entity ButtonCounter_TB is
end;

architecture V1 of ButtonCounter_TB is

    constant CLOCK_PERIOD   : time := 50 ns;
    constant DEBOUNCE_PERIOD: time := 200 ns;

    signal halt_sys_clock: boolean := false;

    signal clock: std_logic := '0';
    signal btn_up: std_logic;
    signal btn_dn: std_logic;
    signal leds: std_logic_vector(15 downto 0);

    component ButtonCounter is
        generic
        (
            CLOCK_PERIOD   : time := 10 ns;
            DEBOUNCE_PERIOD: time := 125 ms
        );
        port
        (
            clock : in std_logic;
            btn_up: in std_logic;
            btn_dn: in std_logic;
            leds  : out std_logic_vector(15 downto 0)
        );
    end component;

begin

    ClockGenerator:
    process
    begin
        while not halt_sys_clock loop
            clock <= not clock;
            wait for CLOCK_PERIOD / 2.0;
        end loop;
        wait;
    end process ClockGenerator;

    Stimulus:
    process
        constant NUM_NOISE_SAMPLES: positive := 10;
        constant SWITCH_TIME: time := 2 * DEBOUNCE_PERIOD;
        variable seed1: positive := 1;
        variable seed2: positive := 1;
        variable rrand: real;
        variable nrand: natural;

        -- Performs noisy transition of sig from current value to final value.
        procedure NoisyTransition(signal sig: out std_logic; final: std_logic) is
        begin
            for n in 1 to NUM_NOISE_SAMPLES loop
                uniform(seed1, seed2, rrand);
                nrand := natural(round(rrand));
                if nrand = 0 then
                    sig <= not final;
                else
                    sig <= final;
                end if;
                wait for CLOCK_PERIOD / 5.0;
            end loop;
            sig <= final;
            wait for SWITCH_TIME;
        end;

    begin
        btn_up <= '0';
        btn_dn <= '0';
        wait for 3 ns;

        --
        -- Up Button
        --

        -- Perform 4 noisy presses and releases.
        for n in 1 to 4 loop
            NoisyTransition(btn_up, '1');
            NoisyTransition(btn_up, '0');
        end loop;

        --
        -- Down Button
        --

        -- Perform 1 noisy press and release.
        NoisyTransition(btn_dn, '1');
        NoisyTransition(btn_dn, '0');

        halt_sys_clock <= true;
        wait;
    end process;

    DUT:
    ButtonCounter
    generic map
    (
        CLOCK_PERIOD    => CLOCK_PERIOD,
        DEBOUNCE_PERIOD => DEBOUNCE_PERIOD
    )
    port map
    (
        clock  => clock,
        btn_up => btn_up,
        btn_dn => btn_dn,
        leds   => leds
    );

end architecture;
</code>```

Simulation

Body:
I've read through the other posts but can't seem to fix mine. I'm new to VHDL so I'm sure it's a simple fix.

In short, the button isn't debouncing. The code compiles and the bitstream programs. In the testbench, button presses work, but the output LEDs don't change. On the board, pressing a button makes random LEDs light up (I presume because of bouncing). According to the schematic the inputs are going through the debouncers.

Can anyone identify the issue? And any other hints and tips are always appreciated :)

Thanks!

EDIT1: Added rising_edge(clk).
Also note, when I press either button, at the time it's depressed all the LEDs light up.

button_counter.vhd

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity button_counter is
    port( clk : in std_logic;
         btnU : in std_logic;
         btnD : in std_logic;
          led : out std_logic_vector (15 downto 0));
end button_counter;

architecture behavioral of button_counter is

    component debouncer is
        port(    clk : in std_logic;
                 btn : in std_logic;
             btn_clr : out std_logic);
    end component;

    signal btnU_clr : std_logic;
    signal btnD_clr : std_logic;

    begin

    debouncer_btnU : debouncer port map (clk => clk, btn => btnU, btn_clr => btnU_clr);
    debouncer_btnD : debouncer port map (clk => clk, btn => btnD, btn_clr => btnD_clr);

    process(clk)
        variable count : integer := 0;
        begin
        if (rising_edge(clk)) then
            if(btnU_clr = '1') then count := count + 1;
            elsif(btnD_clr = '1') then count := count - 1;
            end if;
            led <= std_logic_vector(to_unsigned(count, led'length));
        end if;
    end process;

end behavioral;

Debouncer.vhd

library IEEE;
    use IEEE.std_logic_1164.all;
    use IEEE.numeric_std.all;

entity debouncer is
    port(    clk : in std_logic;
             btn : in std_logic;
         btn_clr : out std_logic);
end debouncer;

architecture behavioural of debouncer is

    constant delay : integer := 650000; -- 6.5ms
    signal count : integer := 0;
    signal btn_tmp : std_logic := '0';

    begin

    process(clk)
    begin
        if rising_edge(clk) then
            if (btn /= btn_tmp) then
                btn_tmp <= btn;
                count <= 0;
            elsif (count = delay) then
                btn_clr <= btn_tmp;
            else
                count <= count + 1;
            end if;
        end if;
    end process;

end behavioural;

button_counter_tb.vhd

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity button_counter_tb is
end button_counter_tb;

architecture behavioral of button_counter_tb is

signal clk_tb    : std_logic;
signal btnU_tb   : std_logic;
signal btnD_tb   : std_logic;
signal led_tb    : std_logic_vector (15 downto 0);

component button_counter
port(clk    : in std_logic;
     btnU   : in std_logic;
     btnD   : in std_logic;
     led    : out std_logic_vector (15 downto 0));
end component;

begin

UUT: button_counter port map (clk => clk_tb, btnU => btnU_tb, btnD => btnD_tb, led => led_tb);

process
begin

btnU_tb <= '0';
btnD_tb <= '0';

wait for 100ns;
btnU_tb <= '1';

wait for 100ns;
btnU_tb <= '0';

wait for 100ns;
btnU_tb <= '1';

wait for 100ns;
btnD_tb <= '1';

wait for 100ns;
btnU_tb <= '0';

wait for 100ns;
btnD_tb <= '0';

end process;

end behavioral;

Body:
The question has been answered well, but I would like to highlight different techniques for synchronising and debouncing.

Synchronising

For synchronising, a simple buffer or chain can be used which avoids creating separate signals/variables for each stage in the buffer or chain. A generic constant can be used to control the length of the chain (minimum of 2):

signal sync_buffer: std_logic_vector(SYNC_BUFFER_MSB downto 0);  -- N-bit synchronisation buffer.
...
sync_buffer <= sync_buffer(SYNC_BUFFER_MSB - 1 downto 0) & input;

Debouncing

For debouncing, hysteresis (a fancy word for history or memory) can be used to create a kind of low pass filter that will debounce both the press and release of a button, and detect edges (both positive and negative) irrespective of whether the signal is active high or active low. The output will stay in its current state until the synchronised input remains in the opposite state for N consecutive clock cycles:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity Debounce is
    generic
    (
        CLOCK_PERIOD   : time := 20 ns;
        DEBOUNCE_PERIOD: time := 125 ms;  -- 1/8th second as a rule of thumb for a tactile button/switch.
        SYNC_BITS      : positive := 3    -- Number of bits in the synchronisation buffer (2 minimum).
    );
    port
    (
        clock : in std_logic;
        input : in std_logic;   -- Asynchronous and noisy input.
        output: out std_logic := '0';  -- Synchronised, debounced and filtered output.
        edge  : out std_logic := '0';  -- Goes high for 1 clock cycle on either edge of synchronised and debounced input.
        rise  : out std_logic := '0';  -- Goes high for 1 clock cycle on the rising edge of synchronised and debounced input.
        fall  : out std_logic := '0'   -- Goes high for 1 clock cycle on the falling edge of synchronised and debounced input.
    );
end entity;

architecture V1 of Debounce is

    constant SYNC_BUFFER_MSB: positive := SYNC_BITS - 1;
    signal sync_buffer: std_logic_vector(SYNC_BUFFER_MSB downto 0) := (others => '0');  -- N-bit synchronisation buffer (2 bits minimum).
    alias sync_input: std_logic is sync_buffer(SYNC_BUFFER_MSB);  -- The synchronised input is the MSB of the synchronisation buffer.

    constant MAX_COUNT: natural := DEBOUNCE_PERIOD / CLOCK_PERIOD;
    signal counter: natural range 0 to MAX_COUNT := 0;  -- Specify the range to reduce number of bits that are synthesised.

begin

    assert SYNC_BITS >= 2 report "Need a minimum of 2 bits in the synchronisation buffer.";

    process(clock)
        variable edge_internal: std_logic := '0';
        variable rise_internal: std_logic := '0';
        variable fall_internal: std_logic := '0';
    begin
        if rising_edge(clock) then
            -- Synchronise the asynchronous input.
            -- MSB of sync_buffer is the synchronised input.
            sync_buffer <= sync_buffer(SYNC_BUFFER_MSB - 1 downto 0) & input;

            edge <= '0';  -- Goes high for 1 clock cycle on either edge.
            rise <= '0';  -- Goes high for 1 clock cycle on the rising edge.
            fall <= '0';  -- Goes high for 1 clock cycle on the falling edge.

            if counter = MAX_COUNT - 1 then  -- If successfully debounced, notify what happened, and reset the counter.
                output <= sync_input;
                edge <= edge_internal;  -- Goes high for 1 clock cycle on either edge.
                rise <= rise_internal;  -- Goes high for 1 clock cycle on the rising edge.
                fall <= fall_internal;  -- Goes high for 1 clock cycle on the falling edge.
                counter <= 0;
            elsif sync_input /= output then
                counter <= counter + 1;
            else
                counter <= 0;
            end if;
        end if;

        -- Edge detection.
        edge_internal := sync_input xor output;
        rise_internal := sync_input and not output;
        fall_internal := not sync_input and output;
    end process;

end architecture;

Button Counter

Much the same as the other answers, but I've used the rise outputs of the debouncers to trigger the counting. I also added a couple of LEDs for visual button feedback.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity ButtonCounter is
    generic
    (
        CLOCK_PERIOD   : time := 20 ns;
        DEBOUNCE_PERIOD: time := 125 ms
    );
    port
    (
        clock : in std_logic;
        btn_up: in std_logic;
        btn_dn: in std_logic;
        led_up: out std_logic;
        led_dn: out std_logic;
        leds  : out std_logic_vector(15 downto 0)
    );
end entity;

architecture V1 of ButtonCounter is

    signal count_up: std_logic;
    signal count_dn: std_logic;

    component Debounce is
        generic
        (
            CLOCK_PERIOD   : time := 20 ns;
            DEBOUNCE_PERIOD: time := 125 ms
        );
        port
        (
            clock : in std_logic;
            input : in std_logic;
            output: out std_logic;
            rise  : out std_logic
        );
    end component;

begin

    DEBOUNCE_BTN_UP:
    Debounce
    generic map
    (
        CLOCK_PERIOD    => CLOCK_PERIOD,
        DEBOUNCE_PERIOD => DEBOUNCE_PERIOD
    )
    port map
    (
        clock  => clock,
        input  => btn_up,
        output => led_up,
        rise   => count_up  -- Goes high for 1 clock cycle on the rising edge of btn_up.
    );

    DEBOUNCE_BTN_DN:
    Debounce
    generic map
    (
        CLOCK_PERIOD    => CLOCK_PERIOD,
        DEBOUNCE_PERIOD => DEBOUNCE_PERIOD
    )
    port map
    (
        clock  => clock,
        input  => btn_dn,
        output => led_dn,
        rise   => count_dn  -- Goes high for 1 clock cycle on the rising edge of btn_dn.
    );

    process(clock)
        variable counter: natural range 0 to 2 ** leds'length - 1 := 0;  -- Specify the range to reduce number of bits that are synthesised.
    begin
        if rising_edge(clock) then
            if count_up then
                counter := counter + 1;
            elsif count_dn then
                counter := counter - 1;
            end if;
            leds <= std_logic_vector(to_unsigned(counter, leds'length));
        end if;
    end process;

end architecture;

Test Bench

Some asynchronous and noisy input buttons are synchronised, debounced and filtered. The positive edges of the reformed input signals trigger the counting.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.math_real.all;

entity ButtonCounter_TB is
end;

architecture V1 of ButtonCounter_TB is

    constant CLOCK_PERIOD   : time := 50 ns;
    constant DEBOUNCE_PERIOD: time := 200 ns;

    signal halt_sys_clock: boolean := false;

    signal clock: std_logic := '0';
    signal btn_up: std_logic;
    signal btn_dn: std_logic;
    signal leds: std_logic_vector(15 downto 0);

    component ButtonCounter is
        generic
        (
            CLOCK_PERIOD   : time := 10 ns;
            DEBOUNCE_PERIOD: time := 125 ms
        );
        port
        (
            clock : in std_logic;
            btn_up: in std_logic;
            btn_dn: in std_logic;
            leds  : out std_logic_vector(15 downto 0)
        );
    end component;

begin

    ClockGenerator:
    process
    begin
        while not halt_sys_clock loop
            clock <= not clock;
            wait for CLOCK_PERIOD / 2.0;
        end loop;
        wait;
    end process ClockGenerator;

    Stimulus:
    process
        constant NUM_NOISE_SAMPLES: positive := 10;
        constant SWITCH_TIME: time := 2 * DEBOUNCE_PERIOD;
        variable seed1: positive := 1;
        variable seed2: positive := 1;
        variable rrand: real;
        variable nrand: natural;

        -- Performs noisy transition of sig from current value to final value.
        procedure NoisyTransition(signal sig: out std_logic; final: std_logic) is
        begin
            for n in 1 to NUM_NOISE_SAMPLES loop
                uniform(seed1, seed2, rrand);
                nrand := natural(round(rrand));
                if nrand = 0 then
                    sig <= not final;
                else
                    sig <= final;
                end if;
                wait for CLOCK_PERIOD / 5.0;
            end loop;
            sig <= final;
            wait for SWITCH_TIME;
        end;

    begin
        btn_up <= '0';
        btn_dn <= '0';
        wait for 3 ns;

        --
        -- Up Button
        --

        -- Perform 4 noisy presses and releases.
        for n in 1 to 4 loop
            NoisyTransition(btn_up, '1');
            NoisyTransition(btn_up, '0');
        end loop;

        --
        -- Down Button
        --

        -- Perform 1 noisy press and release.
        NoisyTransition(btn_dn, '1');
        NoisyTransition(btn_dn, '0');

        halt_sys_clock <= true;
        wait;
    end process;

    DUT:
    ButtonCounter
    generic map
    (
        CLOCK_PERIOD    => CLOCK_PERIOD,
        DEBOUNCE_PERIOD => DEBOUNCE_PERIOD
    )
    port map
    (
        clock  => clock,
        btn_up => btn_up,
        btn_dn => btn_dn,
        leds   => leds
    );

end architecture;

Simulation


来源: stackexchange

问:
Excel mutual pairing
How can I pair members of a list such that if the pair of member 'a' is member 'b' then the pair of 'b' is 'a', in MS Excel?

Ideally, the pairing randomizes at each calculation.

Attempt:

1) I have a list of names in a column, (column B).

2) I put the natural numbers up to the list length in column A:

```<code>=ROW(B2)-1
</code>```

3) Random numbers in column C:

```<code>=RAND()
</code>```

4) I ranked ordered the randoms in column D.

```<code>=RANK(C2, $C$2:$C$178)
</code>```

Thus I have two orderings. The order of appearance in comumn A and a random order in D.

However, for example, row by row the "pair of 11" does not have 11 as its pair, in turn. How can I achieve a mutual pairing? If 11 is paired with 27 I need 27 to be paired with 11 also.

(I can then VLOOKUP to pull the names.)

```<code>=VLOOKUP(D2,$A$2:$B$178,2,0)
</code>```

EDIT:

Bellow is my output. You can see that 'c' is the pair of 'a' but 'a' is not pair of 'c'. (The F column checks if someone is paired to themselves.)

So basicly in the output E column I am taking the name corresponding to the random rank ordering. I would like to acheve mutual pairs in some way.

答:
In order to randomly pair up the numbers like this, you need to take into account what numbers have already been picked.  Then, you need to randomly select from the remaining numbers.

So, to do this, I am going to scrap your "Random Number" column, and calculate "Rank" directly.  To start with, we check if this item already has a pair.  All we will do is use MATCH to find if this entry already exists earlier in Column D, and (if so) use INDEX to find what number it has been paired up with:

```<code>=INDEX(A:A, MATCH(A2, D$1:D1, 0))
</code>```

All code, except the last example, will be written for Cell D2

If this entry has already been paired up, it will return an error.  Otherwise, it will return a match.  If no match was found, we need to pick one at random.  This condition is just an IFERROR:

```<code>=IFERROR(INDEX(A:A, MATCH(A2, D$1:D1, 0)), <FIND_RANDOM_RANK>)
</code>```

There are several ways to get the a Rank at Random, but I am going to use AGGREGATE and RANDBETWEEN.  We will create a list of the un-picked numbers in AGGREGATE (e.g. {2, 3, 7, 8, 12}), then use RANDBETWEEN to select a position at random (e.g. RANDBETWEEN(1, 5), because there are 5 items to choose from).  Our list will be made of Row Numbers, so we will need to convert them to Sequence Numbers with INDEX.

```<code>=IFERROR(INDEX(A:A, MATCH(A2, D$1:D1, 0)), INDEX(A:A, <FIND_RANDOM_ROW>))
</code>```

Since our Row Number are numbers, so we can put them in order and pick the kth SMALLest

```<code>AGGREGATE(15, 6, <NUMBER_LIST>, RANDBETWEEN(1, <NUMBER_OF_ITEMS>))
</code>```

The Number of Items will be the total Number, minus how many items have already been paired.  The number of items already paired will be the number of items above us in the list, PLUS however many of those are paired with items further down.

```<code>AGGREGATE(15, 6, <NUMBER_LIST>, RANDBETWEEN(1, COUNTA(A:A)-(Row()+COUNTIF(D$1:D1,">"&A2))))
</code>```

In the Number List, we can use #DIV0! errors to mark items as Excluded.  We exclude them if they have already been paired up: either above us in the list, or paired to an item above us in the list.

```<code>ROW(A:A) / ((Row(A:A)>Row()) * (COUNTIF(D$1:D1,A:A)=0))
</code>```

Now, before we stick everything together, we need to limit our column sizes in this part (which will work as an Array Formula).  If we try to calculate this for all 1048576 rows in the Worksheet, then not only would it take ages, but you would be matching against a lot of empty rows.

To do this, we can use INDEX and COUNTA to work out how many rows of record we have.  This means, for example, changing A:A to A$1:INDEX(A:A,COUNTA(A:A)).  If you have 10 rows of data, then this will go A$1:INDEX(A:A,COUNTA(A:A)) → A$1:INDEX(A:A,10) → A$1:A10, which is 100,000 times less data to process!

```<code>ROW(A$1:INDEX(A:A,COUNTA(A:A))) / ((Row(A$1:INDEX(A:A,COUNTA(A:A)))>Row()) * (COUNTIF(D$1:D1,A:A)=0))
</code>```

Now, we can put that all together, to get our final equation:

```<code>=IFERROR(INDEX(A:A, MATCH(A2, D$1:D1, 0)), INDEX(A:A,AGGREGATE(15, 6, ROW(A$1:INDEX(A:A,COUNTA(A:A))) / ((ROW(A$1:INDEX(A:A,COUNTA(A:A)))>ROW()) * (COUNTIF(D$1:D1,A:A)=0)), RANDBETWEEN(1, COUNTA(A:A)-(ROW()+COUNTIF(D$1:D1,">"&A2))))))
</code>```

This will give us our Matched Rank.  All we need to do then is a quick VLOOKUP on Columns A and B to work out what the name is:

```<code>=VLOOKUP(D2,A:B,2,FALSE)
</code>```

This code is for Cell E2

(All-in-all, this code will be a lot more efficient if your list is of a fixed size, and you can then replace the COUNTA(A:A) and A$1:INDEX(A:A,COUNTA(A:A)) bits with the correct numbers and cell references directly, such as 5 and A$1:A$5)

ContentLicense: CC BY-SA 4.0

Title: Excel mutual pairing

Body:
How can I pair members of a list such that if the pair of member 'a' is member 'b' then the pair of 'b' is 'a', in MS Excel?

Ideally, the pairing randomizes at each calculation.

Attempt:

1) I have a list of names in a column, (column B).

2) I put the natural numbers up to the list length in column A:

=ROW(B2)-1

3) Random numbers in column C:

=RAND()

4) I ranked ordered the randoms in column D.

=RANK(C2, $C$2:$C$178)

Thus I have two orderings. The order of appearance in comumn A and a random order in D.

However, for example, row by row the "pair of 11" does not have 11 as its pair, in turn. How can I achieve a mutual pairing? If 11 is paired with 27 I need 27 to be paired with 11 also.

(I can then VLOOKUP to pull the names.)

=VLOOKUP(D2,$A$2:$B$178,2,0)

EDIT:

Bellow is my output. You can see that 'c' is the pair of 'a' but 'a' is not pair of 'c'. (The F column checks if someone is paired to themselves.)

So basicly in the output E column I am taking the name corresponding to the random rank ordering. I would like to acheve mutual pairs in some way.

Body:
In order to randomly pair up the numbers like this, you need to take into account what numbers have already been picked.  Then, you need to randomly select from the remaining numbers.

So, to do this, I am going to scrap your "Random Number" column, and calculate "Rank" directly.  To start with, we check if this item already has a pair.  All we will do is use MATCH to find if this entry already exists earlier in Column D, and (if so) use INDEX to find what number it has been paired up with:

=INDEX(A:A, MATCH(A2, D$1:D1, 0))

All code, except the last example, will be written for Cell D2

If this entry has already been paired up, it will return an error.  Otherwise, it will return a match.  If no match was found, we need to pick one at random.  This condition is just an IFERROR:

=IFERROR(INDEX(A:A, MATCH(A2, D$1:D1, 0)), <FIND_RANDOM_RANK>)

There are several ways to get the a Rank at Random, but I am going to use AGGREGATE and RANDBETWEEN.  We will create a list of the un-picked numbers in AGGREGATE (e.g. {2, 3, 7, 8, 12}), then use RANDBETWEEN to select a position at random (e.g. RANDBETWEEN(1, 5), because there are 5 items to choose from).  Our list will be made of Row Numbers, so we will need to convert them to Sequence Numbers with INDEX.

=IFERROR(INDEX(A:A, MATCH(A2, D$1:D1, 0)), INDEX(A:A, <FIND_RANDOM_ROW>))

Since our Row Number are numbers, so we can put them in order and pick the kth SMALLest

AGGREGATE(15, 6, <NUMBER_LIST>, RANDBETWEEN(1, <NUMBER_OF_ITEMS>))

The Number of Items will be the total Number, minus how many items have already been paired.  The number of items already paired will be the number of items above us in the list, PLUS however many of those are paired with items further down.

AGGREGATE(15, 6, <NUMBER_LIST>, RANDBETWEEN(1, COUNTA(A:A)-(Row()+COUNTIF(D$1:D1,">"&A2))))

In the Number List, we can use #DIV0! errors to mark items as Excluded.  We exclude them if they have already been paired up: either above us in the list, or paired to an item above us in the list.

ROW(A:A) / ((Row(A:A)>Row()) * (COUNTIF(D$1:D1,A:A)=0))

Now, before we stick everything together, we need to limit our column sizes in this part (which will work as an Array Formula).  If we try to calculate this for all 1048576 rows in the Worksheet, then not only would it take ages, but you would be matching against a lot of empty rows.

To do this, we can use INDEX and COUNTA to work out how many rows of record we have.  This means, for example, changing A:A to A$1:INDEX(A:A,COUNTA(A:A)).  If you have 10 rows of data, then this will go A$1:INDEX(A:A,COUNTA(A:A)) → A$1:INDEX(A:A,10) → A$1:A10, which is 100,000 times less data to process!

ROW(A$1:INDEX(A:A,COUNTA(A:A))) / ((Row(A$1:INDEX(A:A,COUNTA(A:A)))>Row()) * (COUNTIF(D$1:D1,A:A)=0))

Now, we can put that all together, to get our final equation:

=IFERROR(INDEX(A:A, MATCH(A2, D$1:D1, 0)), INDEX(A:A,AGGREGATE(15, 6, ROW(A$1:INDEX(A:A,COUNTA(A:A))) / ((ROW(A$1:INDEX(A:A,COUNTA(A:A)))>ROW()) * (COUNTIF(D$1:D1,A:A)=0)), RANDBETWEEN(1, COUNTA(A:A)-(ROW()+COUNTIF(D$1:D1,">"&A2))))))

This will give us our Matched Rank.  All we need to do then is a quick VLOOKUP on Columns A and B to work out what the name is:

=VLOOKUP(D2,A:B,2,FALSE)

This code is for Cell E2

(All-in-all, this code will be a lot more efficient if your list is of a fixed size, and you can then replace the COUNTA(A:A) and A$1:INDEX(A:A,COUNTA(A:A)) bits with the correct numbers and cell references directly, such as 5 and A$1:A$5)


问:
Determine array size in constructor initializer
In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?</p>

```<code>class Class
{
public:
  int array[];
  Class(int x) : ??? { }
}
</code>```

答:
Like already suggested, vector is a good choice for most cases.

Alternatively, if dynamic memory allocation is to be avoided and the maximum size is known at compile time, a custom allocator can be used together with std::vector or a library like the embedded template library can be used.

See here: https://www.etlcpp.com/home.html

Example class:

#include <etl/vector.h>

class TestDummyClass {
public:
    TestDummyClass(size_t vectorSize) {
        if(vectorSize < MAX_SIZE) {
            testVector.resize(vectorSize);
        }
    }

private:
    static constexpr uint8_t MAX_SIZE = 20;
    etl::vector<int, MAX_SIZE> testVector;
    uint8_t dummyMember = 0;
};
```

ContentLicense: CC BY-SA 2.5

Body:
In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?

class Class
{
public:
  int array[];
  Class(int x) : ??? { }
}


问:
Redirect output from Start.Process
I am trying to redirect the output of my command line program when it is called with Process.Start(). I've tried all permutations of RedirectStandardOutput, UseShellExecute and CreateNowWindow and had no luck.

I know there are other ways of accomplishing this such as reading StandardOutput after this but I would prefer to redirect it with arguments if possible into a file. I only care about the return code and only need the output of myprog.exe to go to a file. My program doesn't need to know what the output is.

```<code>var p = new Process();
p.StartInfo.FileName = @"myprog.exe";
p.StartInfo.Arguments = " " + InputFilename + " > " + OutputFilename;

p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;

p.Start();
p.WaitForExit();
var result = p.ExitCode;
</code>```

答: This will work for my issue. Get the output with p.StandardOutput.ReadToEnd() and write it to a file. </p>

Title: Redirect output from Start.Process

Body:
I am trying to redirect the output of my command line program when it is called with Process.Start(). I've tried all permutations of RedirectStandardOutput, UseShellExecute and CreateNowWindow and had no luck.

I know there are other ways of accomplishing this such as reading StandardOutput after this but I would prefer to redirect it with arguments if possible into a file. I only care about the return code and only need the output of myprog.exe to go to a file. My program doesn't need to know what the output is.

var p = new Process();
p.StartInfo.FileName = @"myprog.exe";
p.StartInfo.Arguments = " " + InputFilename + " > " + OutputFilename;

p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;

p.Start();
p.WaitForExit();
var result = p.ExitCode;


问:
How can I execute command line arguments in a node.js script
Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

```<code>const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})
</code>```

But if I run the script now, nothing happens.

What i've tried so far:
1. I tried to save the output in a constant and tried to output this on a console

```<code>const found = find().then(devices => {
    devices
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);
</code>```

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards,
Michael

答:
When a function returns a Promise it means that it is running asynchronously (there are various tutorials on the web about this). Long story short, the find() function will return immediately with a Promise object and then it will go and find the ip addresses, and once it finds it it will populate the Promise (i.e. fulfill it).

The then() part is a callback to be executed once the Promise is fulfilled. So what you can do is:

```<code>const find = require('local-devices');

async function findIP() {
  // Find all local network devices.
  const found = find().then(devices => {
    console.log(devices);
  })

  await found;
}

findIP();
</code>```

Essentially the await is telling JS to wait until the found Promise object is fulfilled - right now JS is just exiting before the ip addresses are found.

Body:
Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

But if I run the script now, nothing happens.

What i've tried so far:
1. I tried to save the output in a constant and tried to output this on a console

const found = find().then(devices => {
    devices
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards,
Michael

Body:
When a function returns a Promise it means that it is running asynchronously (there are various tutorials on the web about this). Long story short, the find() function will return immediately with a Promise object and then it will go and find the ip addresses, and once it finds it it will populate the Promise (i.e. fulfill it).

The then() part is a callback to be executed once the Promise is fulfilled. So what you can do is:

const find = require('local-devices');

async function findIP() {
  // Find all local network devices.
  const found = find().then(devices => {
    console.log(devices);
  })

  await found;
}

findIP();

Essentially the await is telling JS to wait until the found Promise object is fulfilled - right now JS is just exiting before the ip addresses are found.


问:
Can't turn off HttpClient Wire debug log messages
I have been trying to set Wire to not send DEBUG to console, but no matter what I do, it won't listen.

I have log4j initialized properly:  I do not get any appender messages,  log4j is obeying my class and console levels.

In log4j.properties I have every foreseeable way to write wire:

```<code>    log4j.logger.org.httpclient=ERROR
    log4j.logger.org.apache=ERROR
    log4j.logger.org.apache.http=ERROR
    log4j.logger.org.apache.http.wire=ERROR
    log4j.logger.org.apache.http.wire.headers=ERROR
    log4j.logger.httpclient.wire=ERROR
    log4j.logger.httpclient.headers=ERROR
    log4j.logger.httpclient.content=ERROR
    log4j.logger.org.apache.hc.client5.http.wire=ERROR
    log4j.logger.httpclient=ERROR
    wire=ERROR
    http=ERROR
</code>```

I then thought why not print all loggers after calling it?
So i did just that.  I get a nice printout of everything mentioned above, and my current class.  Nothing else prints from iterating through LogManager.getCurrentLoggers()

I think I've read every result on Google at this point.  Any guidance would be appreciated.

About the project: Project is a maven Project - pom.xml includes the resource folder. To make this work I literally made a ControlLogging class and PropertyConfiguratior.configure("log4j.properties") is called first. I call this function @Before test runs, and in the static class that's making the API calls. Doing the printing at any point doesn't reveal the Wire logger.

答:
Well, I was able to make my log4j properties work using deps:

```<code>implementation group: 'org.slf4j', name: 'slf4j-log4j12', version: 1.7.25
implementation group: 'org.slf4j', name: 'slf4j-api', version: 1.7.25
implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: 1.7.25
</code>```

or

```<code><dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.25</version>
</dependency>
</code>```

And have a src/java/(main|test)/resources/log4j.properties:

```<code>log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n
log4j.logger.org.apache.http=ERROR
log4j.logger.org.apache.http.wire=ERROR
</code>```

Body:
I have been trying to set Wire to not send DEBUG to console, but no matter what I do, it won't listen.

I have log4j initialized properly:  I do not get any appender messages,  log4j is obeying my class and console levels.

In log4j.properties I have every foreseeable way to write wire:

    log4j.logger.org.httpclient=ERROR
    log4j.logger.org.apache=ERROR
    log4j.logger.org.apache.http=ERROR
    log4j.logger.org.apache.http.wire=ERROR
    log4j.logger.org.apache.http.wire.headers=ERROR
    log4j.logger.httpclient.wire=ERROR
    log4j.logger.httpclient.headers=ERROR
    log4j.logger.httpclient.content=ERROR
    log4j.logger.org.apache.hc.client5.http.wire=ERROR
    log4j.logger.httpclient=ERROR
    wire=ERROR
    http=ERROR

I then thought why not print all loggers after calling it?
So i did just that.  I get a nice printout of everything mentioned above, and my current class.  Nothing else prints from iterating through LogManager.getCurrentLoggers()

I think I've read every result on Google at this point.  Any guidance would be appreciated.

About the project: Project is a maven Project - pom.xml includes the resource folder. To make this work I literally made a ControlLogging class and PropertyConfiguratior.configure("log4j.properties") is called first. I call this function @Before test runs, and in the static class that's making the API calls. Doing the printing at any point doesn't reveal the Wire logger.

Body:
Well, I was able to make my log4j properties work using deps:

implementation group: 'org.slf4j', name: 'slf4j-log4j12', version: 1.7.25
implementation group: 'org.slf4j', name: 'slf4j-api', version: 1.7.25
implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: 1.7.25

or

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.25</version>
</dependency>

And have a src/java/(main|test)/resources/log4j.properties:

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n
log4j.logger.org.apache.http=ERROR
log4j.logger.org.apache.http.wire=ERROR


问:
popup content menu using js
I was trying to use whats used in this demo: http://tympanus.net/Tutorials/AnimatedContentMenu/

after clicking one of the restaurant menu items the content menu appears..
I couldn't use the same code to get the idea of creating a popup content menu.

my question: can anyone help with tutorials or examples of how can I show a popup menu after clicking an  tag?

I hope that my question is clear enough,
thnx

答:
For the ppl who have the same question, I finally found something I can use, after applying some changes..
here is the folder: http://www.2shared.com/file/Osok6qFo/popupBox.html

thnx everyone..

ContentLicense: CC BY-SA 3.0

Title: popup content menu using js


问:
make height responsive amp-list
I'm trying to make the height of amp-list responsive

```<code><amp-list width="100" height="1980" [height]="660 * page.items.posts.length" layout="responsive" src="/get_posts/" [src]="'/get_posts?page=' + page" binding="no" reset-on-refresh single-item>
  <template type="amp-mustache">
    {{#posts}}
      <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12 col-xs-12">
      Post
      </div>
    {{/posts}}
  </template>
</amp-list>
</code>```

as you see the height changes every time when I get new posts. the problem is it's working well on desktop but on mobile, I see only the first three posts because the height is small.
on the desktop, I have a large width so I can get 3 columns by line but on mobile, I can get only one column by line that's why I need more height, is there something that can fix this problem?

答:
You can use Media attribute over amp elements, refer amp page -

https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/control_layout/

example -

```<code><amp-img
    media="(min-width: 650px)"
    src="wide.jpg"
    width="527"
    height="355"
    layout="responsive">
</amp-img>

<amp-img
    media="(max-width: 640px)"
    src="small.jpg"
    width="527"
    height="355"
    layout="responsive">
</amp-img>
</code>```

Above 2 elemts will display based on media attribute condition written in each of them. First will display when display size min-width: 650px ].

Title: make height responsive amp-list

Body:
I'm trying to make the height of amp-list responsive

<amp-list width="100" height="1980" [height]="660 * page.items.posts.length" layout="responsive" src="/get_posts/" [src]="'/get_posts?page=' + page" binding="no" reset-on-refresh single-item>
  <template type="amp-mustache">
    {{#posts}}

      Post

    {{/posts}}
  </template>
</amp-list>

as you see the height changes every time when I get new posts. the problem is it's working well on desktop but on mobile, I see only the first three posts because the height is small.
on the desktop, I have a large width so I can get 3 columns by line but on mobile, I can get only one column by line that's why I need more height, is there something that can fix this problem?

Body:
You can use Media attribute over amp elements, refer amp page -

https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/control_layout/

example -

<amp-img
    media="(min-width: 650px)"
    src="wide.jpg"
    width="527"
    height="355"
    layout="responsive">
</amp-img>

<amp-img
    media="(max-width: 640px)"
    src="small.jpg"
    width="527"
    height="355"
    layout="responsive">
</amp-img>

Above 2 elemts will display based on media attribute condition written in each of them. First will display when display size min-width: 650px ].


问:
Templated struct inside function
I want to define a helper templated struct inside a function. (Has to be inside the current function due to our own convention)

Why doesn't the following work? How do I fix it?

```<code>void foo() {
  template<typename T>
  struct MyHelper {
     // ....
     void func(int x, int y, ...) {
        some_other<T>(...);
     }
  };

  // Use MyHelper with different types.
  if (some_logic) {
      MyHelper<TypeA> helper;
      helper.func(x, y, z);
  } else if (some_other) {
     MyHelper<TypeB> helper;
     // ....
  }
  // ... more
  // TypeA, TypeB, TypeC, ... don't share common parents.
}
</code>```

答:
Your convention is (in this case) not compatible with the C++ standard. Either define the struct outside of your function or specialize the struct "by hand", i.e. struct MyHelperInt, struct MyHelperDouble, ...

The latter approach is possible as you actually know what types to expect in your local function but it is obviously not a good option because of code duplication.

Title: Templated struct inside function

Body:
I want to define a helper templated struct inside a function. (Has to be inside the current function due to our own convention)

Why doesn't the following work? How do I fix it?

void foo() {
  template<typename T>
  struct MyHelper {
     // ....
     void func(int x, int y, ...) {
        some_other<T>(...);
     }
  };

  // Use MyHelper with different types.
  if (some_logic) {
      MyHelper<TypeA> helper;
      helper.func(x, y, z);
  } else if (some_other) {
     MyHelper<TypeB> helper;
     // ....
  }
  // ... more
  // TypeA, TypeB, TypeC, ... don't share common parents.
}


问:
Pass generic parameter optionally?
I have the following NetworkUseCase interface which processes a network request. P is the type of requestData and R the type of responseData.

```<code>interface NetworkUseCase<in P, out R> {
    fun process(requestData: P) : R
}
</code>```

The way it is normally used is the following:

```<code>class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(requestData)
</code>```

However, there are some use cases where there are no requestData needed. In that case, there should be no requestData argument passed. But I am not sure how to achieve that.

```<code>val responseData = ConcreteUseCase().process()
</code>```

What I have done so far is to set the type of requestData to Unit but then I still need to pass Unit as a parameter:

```<code>class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(Unit)
</code>```

Is there a way to achieve not being forced to always pass an argument in process()?

答:
Seems that you need a nullable input type with a default value

```<code>interface NetworkUseCase<in P, out R> {
    fun process(requestData: P? = null) : R
}

class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData?): ConcreteResponseData {
        //...
    }
}
</code>```

Then you can just call it like that:

```<code>val responseData = ConcreteUseCase().process()
</code>```

EDIT:

This solution is gonna work just fine when it is necessary to pass a parameter to the process function:

```<code>val resquestData: ConcreteRequestData = ...
ConcreteUseCase().process(resquestData)
</code>```

It is due to the fact that a non-nullable type is a subtype of its correposding nullable one.

EDIT 2:

Revisiting this answer I realized that the concrete use case may always have no parameter expected. The interface still works and the concrete class should be like that:

```<code>class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit?): ConcreteResponseData {
        //...
    }
}
</code>```

Title: Pass generic parameter optionally?

Body:
I have the following NetworkUseCase interface which processes a network request. P is the type of requestData and R the type of responseData.

interface NetworkUseCase<in P, out R> {
    fun process(requestData: P) : R
}

The way it is normally used is the following:

class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(requestData)

However, there are some use cases where there are no requestData needed. In that case, there should be no requestData argument passed. But I am not sure how to achieve that.

val responseData = ConcreteUseCase().process()

What I have done so far is to set the type of requestData to Unit but then I still need to pass Unit as a parameter:

class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(Unit)

Is there a way to achieve not being forced to always pass an argument in process()?

Body:
Seems that you need a nullable input type with a default value

interface NetworkUseCase<in P, out R> {
    fun process(requestData: P? = null) : R
}

class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData?): ConcreteResponseData {
        //...
    }
}

Then you can just call it like that:

val responseData = ConcreteUseCase().process()

EDIT:

This solution is gonna work just fine when it is necessary to pass a parameter to the process function:

val resquestData: ConcreteRequestData = ...
ConcreteUseCase().process(resquestData)

It is due to the fact that a non-nullable type is a subtype of its correposding nullable one.

EDIT 2:

Revisiting this answer I realized that the concrete use case may always have no parameter expected. The interface still works and the concrete class should be like that:

class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit?): ConcreteResponseData {
        //...
    }
}


问:
PYOMO ERROR: KeyError: "Index '0' is not valid for indexed component 'y' "
This is the hole Error:

```<code>ERROR: Rule failed when generating expression for objective FObj: KeyError:
    "Index '4' is not valid for indexed component 'y'"
ERROR: Constructing component 'FObj' from data=None failed:
        KeyError: "Index '4' is not valid for indexed component 'y'"
</code>```

I've proved everything, checking every RangeSet and it's ok so I don't why it doesn't work well. Thanks for reading this, if anyone could help...

```<code>from pyomo.environ import *
from pyomo.opt import SolverFactory
from pyomo.core.base.PyomoModel import AbstractModel
from pyomo.core.base.constraint import Constraint
from pyomo.core.base.set import RangeSet
#import pyomo.dae
import numpy as np
import logging
logging.getLogger('pyomo.core').setLevel(logging.ERROR)

   model = AbstractModel()

   model.personas = RangeSet(0, 29)
   model.sabados = RangeSet(0,3)

   model.y = Var(model.personas,model.sabados, within = Binary)

   def ObjFunction(model):
      return sum(model.y[i][s] for i in model.personas for s in model.sabados)
   model.FObj= Objective(rule=ObjFunction, sense = maximize)
</code>```

答:
Problem discovered.  I think you must have just changed the model type to Abstract as when I change it back to Concrete the problem with y shows up.

You are indexing model.y with double indexing (Python standard).  Pyomo ... for whatever reason ... uses comma separated indices for multiple indexing.  Note the change in my code below.  If this is a head-hurter, I've built models and put the indices in a tuple just to keep myself sane.  Such as:  model.y[(i, s)] which is unnecessary, but works and makes it look more distinct for pyomo.

Couple other notes...

I removed some of the unnecceary imports.  One was causing some kind
of warning.

I chopped down your indices just to see a smaller printout

```<code>from pyomo.environ import *
from pyomo.opt import SolverFactory
#from pyomo.core.base.PyomoModel import AbstractModel
#from pyomo.core.base.constraint import Constraint
#from pyomo.core.base.set import RangeSet
#import pyomo.dae
import numpy as np
import logging
#logging.getLogger('pyomo.core').setLevel(logging.ERROR)

model = ConcreteModel()

model.personas = RangeSet(0, 3)
model.sabados = RangeSet(0,2)

model.y = Var(model.personas,model.sabados, within = Binary)

def ObjFunction(model):
  return sum(model.y[i,s] for i in model.personas for s in model.sabados)
model.FObj= Objective(rule=ObjFunction, sense = maximize)

model.pprint()
</code>```

Yields:

```<code>1 Set Declarations
    y_index : Dim=0, Dimen=2, Size=12, Domain=None, Ordered=True, Bounds=None
        Virtual

2 RangeSet Declarations
    personas : Dim=0, Dimen=1, Size=4, Domain=Integers, Ordered=True, Bounds=(0, 3)
        Virtual
    sabados : Dim=0, Dimen=1, Size=3, Domain=Integers, Ordered=True, Bounds=(0, 2)
        Virtual

1 Var Declarations
    y : Size=12, Index=y_index
        Key    : Lower : Value : Upper : Fixed : Stale : Domain
        (0, 0) :     0 :  None :     1 : False :  True : Binary
        (0, 1) :     0 :  None :     1 : False :  True : Binary
        (0, 2) :     0 :  None :     1 : False :  True : Binary
        (1, 0) :     0 :  None :     1 : False :  True : Binary
        (1, 1) :     0 :  None :     1 : False :  True : Binary
        (1, 2) :     0 :  None :     1 : False :  True : Binary
        (2, 0) :     0 :  None :     1 : False :  True : Binary
        (2, 1) :     0 :  None :     1 : False :  True : Binary
        (2, 2) :     0 :  None :     1 : False :  True : Binary
        (3, 0) :     0 :  None :     1 : False :  True : Binary
        (3, 1) :     0 :  None :     1 : False :  True : Binary
        (3, 2) :     0 :  None :     1 : False :  True : Binary

1 Objective Declarations
    FObj : Size=1, Index=None, Active=True
        Key  : Active : Sense    : Expression
        None :   True : maximize : y[0,0] + y[0,1] + y[0,2] + y[1,0] + y[1,1] + y[1,2] + y[2,0] + y[2,1] + y[2,2] + y[3,0] + y[3,1] + y[3,2]

5 Declarations: personas sabados y_index y FObj
[Finished in 2.6s]
</code>```

Body:
This is the hole Error:

ERROR: Rule failed when generating expression for objective FObj: KeyError:
    "Index '4' is not valid for indexed component 'y'"
ERROR: Constructing component 'FObj' from data=None failed:
        KeyError: "Index '4' is not valid for indexed component 'y'"

I've proved everything, checking every RangeSet and it's ok so I don't why it doesn't work well. Thanks for reading this, if anyone could help...

from pyomo.environ import *
from pyomo.opt import SolverFactory
from pyomo.core.base.PyomoModel import AbstractModel
from pyomo.core.base.constraint import Constraint
from pyomo.core.base.set import RangeSet
#import pyomo.dae
import numpy as np
import logging
logging.getLogger('pyomo.core').setLevel(logging.ERROR)

   model = AbstractModel()

   model.personas = RangeSet(0, 29)
   model.sabados = RangeSet(0,3)

   model.y = Var(model.personas,model.sabados, within = Binary)

   def ObjFunction(model):
      return sum(model.y[i][s] for i in model.personas for s in model.sabados)
   model.FObj= Objective(rule=ObjFunction, sense = maximize)

Body:
Problem discovered.  I think you must have just changed the model type to Abstract as when I change it back to Concrete the problem with y shows up.

You are indexing model.y with double indexing (Python standard).  Pyomo ... for whatever reason ... uses comma separated indices for multiple indexing.  Note the change in my code below.  If this is a head-hurter, I've built models and put the indices in a tuple just to keep myself sane.  Such as:  model.y[(i, s)] which is unnecessary, but works and makes it look more distinct for pyomo.

Couple other notes...

I removed some of the unnecceary imports.  One was causing some kind
of warning.

I chopped down your indices just to see a smaller printout

from pyomo.environ import *
from pyomo.opt import SolverFactory
#from pyomo.core.base.PyomoModel import AbstractModel
#from pyomo.core.base.constraint import Constraint
#from pyomo.core.base.set import RangeSet
#import pyomo.dae
import numpy as np
import logging
#logging.getLogger('pyomo.core').setLevel(logging.ERROR)

model = ConcreteModel()

model.personas = RangeSet(0, 3)
model.sabados = RangeSet(0,2)

model.y = Var(model.personas,model.sabados, within = Binary)

def ObjFunction(model):
  return sum(model.y[i,s] for i in model.personas for s in model.sabados)
model.FObj= Objective(rule=ObjFunction, sense = maximize)

model.pprint()

Yields:

1 Set Declarations
    y_index : Dim=0, Dimen=2, Size=12, Domain=None, Ordered=True, Bounds=None
        Virtual

2 RangeSet Declarations
    personas : Dim=0, Dimen=1, Size=4, Domain=Integers, Ordered=True, Bounds=(0, 3)
        Virtual
    sabados : Dim=0, Dimen=1, Size=3, Domain=Integers, Ordered=True, Bounds=(0, 2)
        Virtual

1 Var Declarations
    y : Size=12, Index=y_index
        Key    : Lower : Value : Upper : Fixed : Stale : Domain
        (0, 0) :     0 :  None :     1 : False :  True : Binary
        (0, 1) :     0 :  None :     1 : False :  True : Binary
        (0, 2) :     0 :  None :     1 : False :  True : Binary
        (1, 0) :     0 :  None :     1 : False :  True : Binary
        (1, 1) :     0 :  None :     1 : False :  True : Binary
        (1, 2) :     0 :  None :     1 : False :  True : Binary
        (2, 0) :     0 :  None :     1 : False :  True : Binary
        (2, 1) :     0 :  None :     1 : False :  True : Binary
        (2, 2) :     0 :  None :     1 : False :  True : Binary
        (3, 0) :     0 :  None :     1 : False :  True : Binary
        (3, 1) :     0 :  None :     1 : False :  True : Binary
        (3, 2) :     0 :  None :     1 : False :  True : Binary

1 Objective Declarations
    FObj : Size=1, Index=None, Active=True
        Key  : Active : Sense    : Expression
        None :   True : maximize : y[0,0] + y[0,1] + y[0,2] + y[1,0] + y[1,1] + y[1,2] + y[2,0] + y[2,1] + y[2,2] + y[3,0] + y[3,1] + y[3,2]

5 Declarations: personas sabados y_index y FObj
[Finished in 2.6s]


问:
Tornadofx application not launching
I'm new to JavaFX and TornadoFX but know Kotlin.
I am working on new desktop application and was trying TornadoFX.
I installed TornadoFX plugin in IntelliJ and create a new TornadoFX project (gradle based).
With the template code, when I run the app I get the following error :

```<code>Jan 28, 2020 4:06:22 PM tornadofx.DefaultErrorHandler uncaughtException
SEVERE: Uncaught error
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:875)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(LauncherImpl.java:157)
    at com.sun.javafx.application.LauncherImpl$$Lambda$49/458209687.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: javafx.stage.Window.getProperties()Ljavafx/collections/ObservableMap;
    at tornadofx.FXKt.setAboutToBeShown(FX.kt:663)
    at tornadofx.App.start(App.kt:84)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821)
    at com.sun.javafx.application.LauncherImpl$$Lambda$52/707342127.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
    at com.sun.javafx.application.PlatformImpl$$Lambda$46/1637506559.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
    at com.sun.javafx.application.PlatformImpl$$Lambda$48/1602612637.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/2117255219.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
</code>```

MyApp Class:
class MyApp: App(MainView::class, Styles::class)

Styles Class:

```<code>class Styles : Stylesheet() {
    companion object {
        val heading by cssclass()
    }

    init {
        label and heading {
            padding = box(10.px)
            fontSize = 20.px
            fontWeight = FontWeight.BOLD
        }
    }
}
</code>```

MainView Class:

```<code>class MainView : View("Hello TornadoFX") {
    override val root = hbox {
        label(title) {
            addClass(Styles.heading)
        }
    }
}
</code>```

I'm using java 1.8, kotlin 1.3  and tornadofx 1.7.17
I also tried by creating a new "Application" configuration to run the app.

Any help is appreciated.

答:
The gradle configuration produced by the TornadoFX plugin is obsolete and has a number of problems. Not only because of the older versions selected for kotlin and tornadofx, but also the buildscript method has been deprecated for kotlin applications that use gradle.  Additionaly, the gradle version is quite old and must be updated to work with newer Java versions.

To get a running build starting with the demo app created by the TornadoFX wizard and Java 8 do the following:

Make sure you have a Java 8 JDK that includes JavaFX. Most open JDKs such as Adopt OpenJDK do not. The oracle JDK 8 should include Java FX.  For open JDKs, I suggest Zulu or Liberica (they have a build for raspery pi).  When you download, make sure to select the JDK with Java FX included.  For Zulu, you have to select "JDK FX", for Liberica you have to select "Full JDK".

Edit gradle/wrapper/gradle-wrapper.properties and change the gradle-4.4-bin.zip in the URL to gradle-6.3-bin.zip  Version 6.3 will work with JDK up to version 14.

If on Mac or Linux, you have to convert the gradlew script to use unix line endings.  The one produced by the TornadoFX plugin uses windows new lines "\r\n" which the "sh" interpreter can't handle.  On linux, you can use dos2unix command or sed if you don't have dos2unix installed:sed -i 's/\x0D$//' gradlew

Edit build.gradle using the code below. This is the simplest config to build and run the demo app

Execute the gradlew script to build and run

Mac/Linux: ./gradlew run

Windows: gradlew.bat run

It's a good idea to update the wrapper

Mac/Linux: ./gradlew wrapper

Windows: gradlew.bat wrapper

JDK 8 build.gradle

    plugins {
        // Apply the Kotlin JVM plugin to add support for Kotlin.
        id 'org.jetbrains.kotlin.jvm' version '1.3.70'

        // Apply the application plugin to add support for building a CLI application.
        id 'application'
    }

    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }

    repositories {
        mavenLocal()
        mavenCentral()
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
    }

    dependencies {
        // Align versions of all Kotlin components
        implementation platform('org.jetbrains.kotlin:kotlin-bom')

        // Use the Kotlin JDK 8 standard library.
        implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'

        // Use the tornadofx
        implementation "no.tornado:tornadofx:1.7.20"
    }

    mainClassName = "com.example.demo.app.MyApp"
```

<p><strong>JDK 9+</strong></p>

<p>For JDK 9+, start at step 2 above plus modify the build.gradle to download JavaFX since it was separated from the JDK starting with 9. </p>

<p>Add to the plugins section:</p>

<pre class="lang-groovy prettyprint-override"><code>    // Apply the javafx plugin
    id 'org.openjfx.javafxplugin' version '0.0.8'
</code>```

And then add a javafx section:

javafx {
    version = "13"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}
```

<p>Finally, change tornadofx version to the 2.0 snapshot </p>

<pre class="lang-groovy prettyprint-override"><code>    // Use the tornadofx
    implementation "no.tornado:tornadofx:2.0.0-SNAPSHOT"
</code>```

At this point the demo app should run.  There are some gotchas with running a JDK 9+ version with TornadoFX but you should be able to find those answers in other questions.

Title: Tornadofx application not launching

Body:
I'm new to JavaFX and TornadoFX but know Kotlin.
I am working on new desktop application and was trying TornadoFX.
I installed TornadoFX plugin in IntelliJ and create a new TornadoFX project (gradle based).
With the template code, when I run the app I get the following error :

Jan 28, 2020 4:06:22 PM tornadofx.DefaultErrorHandler uncaughtException
SEVERE: Uncaught error
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:875)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(LauncherImpl.java:157)
    at com.sun.javafx.application.LauncherImpl$$Lambda$49/458209687.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: javafx.stage.Window.getProperties()Ljavafx/collections/ObservableMap;
    at tornadofx.FXKt.setAboutToBeShown(FX.kt:663)
    at tornadofx.App.start(App.kt:84)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821)
    at com.sun.javafx.application.LauncherImpl$$Lambda$52/707342127.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
    at com.sun.javafx.application.PlatformImpl$$Lambda$46/1637506559.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
    at com.sun.javafx.application.PlatformImpl$$Lambda$48/1602612637.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/2117255219.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)

MyApp Class:
class MyApp: App(MainView::class, Styles::class)

Styles Class:

class Styles : Stylesheet() {
    companion object {
        val heading by cssclass()
    }

    init {
        label and heading {
            padding = box(10.px)
            fontSize = 20.px
            fontWeight = FontWeight.BOLD
        }
    }
}

MainView Class:

class MainView : View("Hello TornadoFX") {
    override val root = hbox {
        label(title) {
            addClass(Styles.heading)
        }
    }
}

I'm using java 1.8, kotlin 1.3  and tornadofx 1.7.17
I also tried by creating a new "Application" configuration to run the app.

Any help is appreciated.

Body:
The gradle configuration produced by the TornadoFX plugin is obsolete and has a number of problems. Not only because of the older versions selected for kotlin and tornadofx, but also the buildscript method has been deprecated for kotlin applications that use gradle.  Additionaly, the gradle version is quite old and must be updated to work with newer Java versions.

To get a running build starting with the demo app created by the TornadoFX wizard and Java 8 do the following:

Make sure you have a Java 8 JDK that includes JavaFX. Most open JDKs such as Adopt OpenJDK do not. The oracle JDK 8 should include Java FX.  For open JDKs, I suggest Zulu or Liberica (they have a build for raspery pi).  When you download, make sure to select the JDK with Java FX included.  For Zulu, you have to select "JDK FX", for Liberica you have to select "Full JDK".

Edit gradle/wrapper/gradle-wrapper.properties and change the gradle-4.4-bin.zip in the URL to gradle-6.3-bin.zip  Version 6.3 will work with JDK up to version 14.

If on Mac or Linux, you have to convert the gradlew script to use unix line endings.  The one produced by the TornadoFX plugin uses windows new lines "\r\n" which the "sh" interpreter can't handle.  On linux, you can use dos2unix command or sed if you don't have dos2unix installed:sed -i 's/\x0D$//' gradlew

Edit build.gradle using the code below. This is the simplest config to build and run the demo app

Execute the gradlew script to build and run

Mac/Linux: ./gradlew run

Windows: gradlew.bat run

It's a good idea to update the wrapper

Mac/Linux: ./gradlew wrapper

Windows: gradlew.bat wrapper

JDK 8 build.gradle

    plugins {
        // Apply the Kotlin JVM plugin to add support for Kotlin.
        id 'org.jetbrains.kotlin.jvm' version '1.3.70'

        // Apply the application plugin to add support for building a CLI application.
        id 'application'
    }

    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }

    repositories {
        mavenLocal()
        mavenCentral()
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
    }

    dependencies {
        // Align versions of all Kotlin components
        implementation platform('org.jetbrains.kotlin:kotlin-bom')

        // Use the Kotlin JDK 8 standard library.
        implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'

        // Use the tornadofx
        implementation "no.tornado:tornadofx:1.7.20"
    }

    mainClassName = "com.example.demo.app.MyApp"

JDK 9+

For JDK 9+, start at step 2 above plus modify the build.gradle to download JavaFX since it was separated from the JDK starting with 9.

Add to the plugins section:

    // Apply the javafx plugin
    id 'org.openjfx.javafxplugin' version '0.0.8'

And then add a javafx section:

javafx {
    version = "13"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}

Finally, change tornadofx version to the 2.0 snapshot

    // Use the tornadofx
    implementation "no.tornado:tornadofx:2.0.0-SNAPSHOT"

At this point the demo app should run.  There are some gotchas with running a JDK 9+ version with TornadoFX but you should be able to find those answers in other questions.


问:
What is the proper way to repeat a format string in Julia?
I have an array of floats x and would like to print the last row to screen as integers. The following code does not work and yields ArgumentError: @printf: first or second argument must be a format string. How can I print with a variable format string?

```<code>using Printf
@printf("%i "^length(x[end,:]), x[end,:]...)
</code>```

答:
Our "constants" are still run-time values – they are write-once rather than compile-time constants like in C.

As a hack until julia gets real support for runtime format strings, this works:

```<code>using Printf
const fmt = "%i "^length(x[end,:])
@eval @printf($fmt, x[end,:]...)
</code>```

Body:
I have an array of floats x and would like to print the last row to screen as integers. The following code does not work and yields ArgumentError: @printf: first or second argument must be a format string. How can I print with a variable format string?

using Printf
@printf("%i "^length(x[end,:]), x[end,:]...)

Body:
Our "constants" are still run-time values – they are write-once rather than compile-time constants like in C.

As a hack until julia gets real support for runtime format strings, this works:

using Printf
const fmt = "%i "^length(x[end,:])
@eval @printf($fmt, x[end,:]...)


问:
Javascript / Json / Firestore code to firestore bulk upload
We are looking for ways to bulk upload data into google firestore and found here in Stack Overflow an awesome script to do so, sort of. The problem is that when data is uploaded the collection is fine,  document is fine, but nesting some data we can only manage to import as "map" type when we need "array" and "map". Since we are basically newbies trial and error has not been enough. We appreciate if you can take a look at the code and help us with that.

So far, with the following code:

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-firestore.js"></script>
    </head>

<body>

    <script>
        var config = {
            apiKey: 'MY API KEY',
            authDomain: 'MY AUTHDOMAIN',
            projectId: 'MY PROJECT ID'
        };
        firebase.initializeApp(config);

        var firestore = firebase.firestore();

        //Paste from the CSV to JSON converter
        const data = [
            {
                "collection": "sub_cats",
                "uid": "Av9vJ0EoFfxhAR2",
                "class": "especialidades_medicas",
                "id": 0,
                "name": "Cardiologo",
                "ind": "11",
                "district": ""
            },
            {
                "collection": "sub_cats",
                "uid": "Av9vJ0EoFfxhAR2",
                "class": "especialidades_medicas",
                "id": 1,
                "name": "Urologo",
                "ind": "12",
                "district": ""
            }
        ]

        var promises = [];

        data.forEach(function (arrayItem) {
        var docRef = firestore.collection(arrayItem.collection).doc(arrayItem.uid);
        var objClass = {};
        var objId = {};
        objId[arrayItem.id] = { name: arrayItem.name, ind: arrayItem.ind };
        objClass[arrayItem.class] = objId;

        promises.push(docRef.set(objClass, { merge: true }));
    });

    </script>
</body>

</html>
</code>```

we get this:

data structure current / needed

How would you modify this code to get the array / map structure?

Thanks a lot!!!

答:
You will need to use arrayUnion() of fieldValue that can be used with set() or update(). So basically if you use it with update it will "merge" the new value with the existing array values in your document. Inside that you can have your map or any datatype you want.

An example code looks like this:

```<code>db.collection("users").doc(props.uid).update({
    points: db.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
</code>```

Body:
We are looking for ways to bulk upload data into google firestore and found here in Stack Overflow an awesome script to do so, sort of. The problem is that when data is uploaded the collection is fine,  document is fine, but nesting some data we can only manage to import as "map" type when we need "array" and "map". Since we are basically newbies trial and error has not been enough. We appreciate if you can take a look at the code and help us with that.

So far, with the following code:

<!DOCTYPE html>

    <meta charset="utf-8">

we get this:

data structure current / needed

How would you modify this code to get the array / map structure?

Thanks a lot!!!

Body:
You will need to use arrayUnion() of fieldValue that can be used with set() or update(). So basically if you use it with update it will "merge" the new value with the existing array values in your document. Inside that you can have your map or any datatype you want.

An example code looks like this:

db.collection("users").doc(props.uid).update({
    points: db.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});


问:
How to insert variable parameter to SQL stored procedure in Flask app
I am looking for some advice for my Flask app. I want for a user to be able to click on a name of a product and when they click, it brings user to a new page with table of historical orders for that specific item. I have looked at these two questions (and more) but they don't seem to have the answer I'm looking for.
Table Variable As a parameter In My sql Stored Procedures
how to pass output parameter to ms-sql stored procedure using knex.

In my app.py file, I have the following stored procedure -

```<code>order_history = '''exec Web_ProductHistory ?'''
</code>```

And here is the associated route and function for it -

```<code>@app.route('/prev-orders/')
def previous_orders():
   ItemID = request.form.get('ItemID')
   cursor = cnxn.cursor()
   cursor.execute(order_history, (ItemID))
   data = cursor.fetchall()
   return render_template('previous-orders.html', data=data)
</code>```

I have a table filled with stock items working and here is the table -

```<code>{% for value in data %}
       <tr>
          <td class="hidden"></td>
          <td></td>
          <td><span style="margin-left: 40px">{{ value[1] }}</span></td>
          <td><a name="{{ value[0] }}" class="black-text" href="{{url_for('previous_orders')}}" target="_blank">{{ value[3] }}</a></td>
          <td>{{ value[12] }}</td>
          <td>{{ value[23] }}</td>
          <td class="over-25">{{ value[18] }}</td>
          <td>{{ value[6] }}</td>
          <td>{{ value[7] }}</td>
          <td><a name="{{ value[0] }}" class="black-text" href="{{url_for('live_so')}}" target="_blank">{{ value[14] }}</a></td>
          <td>{{ value[16] }}</td>
          <td>{{ value[15] }}</td>
          <td>{{ value[22] }}</td>
          <td>{{ value[2] }}</td>
       </tr>
   {% endfor %}
</code>```

value[0] is the ItemID integer.

So far, I have tried to change the route to @app.route('/prev-orders/') or @app.route('/prev-orders/ItemID') but that doesn't do it. I then tried to change the second line to
def previous_orders(ItemID) but that doesn't get it working either.

Have you any tips for me to try to get this working? Thanks!

答:
```<code>request.form.get('ItemID')
</code>```

This expects the ItemID to be posted.  If you want to pass it within the URL, then do something like:

```<code>@app.route('/prev-orders/<integer:ItemID>')
def previous_orders(ItemID):
   cursor = cnxn.cursor()
   # ... rest of code
</code>```

Then generate the link in your HTML with:

```<code><a href="{{ url_for('previous_orders', ItemID = value[0]) }}">{{ value[3] }}</a>
</code>```

Also, as a side note, I think the following line should be:

```<code>cursor.execute(order_history, (ItemID,))
</code>```

(note the extra comma which makes that second argument a valid tuple, which I think is what the execute method expects)

Body:
I am looking for some advice for my Flask app. I want for a user to be able to click on a name of a product and when they click, it brings user to a new page with table of historical orders for that specific item. I have looked at these two questions (and more) but they don't seem to have the answer I'm looking for.
Table Variable As a parameter In My sql Stored Procedures
how to pass output parameter to ms-sql stored procedure using knex.

In my app.py file, I have the following stored procedure -

order_history = '''exec Web_ProductHistory ?'''

And here is the associated route and function for it -

@app.route('/prev-orders/')
def previous_orders():
   ItemID = request.form.get('ItemID')
   cursor = cnxn.cursor()
   cursor.execute(order_history, (ItemID))
   data = cursor.fetchall()
   return render_template('previous-orders.html', data=data)

I have a table filled with stock items working and here is the table -

{% for value in data %}

          {{ value[1] }}
          {{ value[3] }}
          {{ value[12] }}
          {{ value[23] }}
          {{ value[18] }}
          {{ value[6] }}
          {{ value[7] }}
          {{ value[14] }}
          {{ value[16] }}
          {{ value[15] }}
          {{ value[22] }}
          {{ value[2] }}

   {% endfor %}

value[0] is the ItemID integer.

So far, I have tried to change the route to @app.route('/prev-orders/') or @app.route('/prev-orders/ItemID') but that doesn't do it. I then tried to change the second line to
def previous_orders(ItemID) but that doesn't get it working either.

Have you any tips for me to try to get this working? Thanks!

Body:
request.form.get('ItemID')

This expects the ItemID to be posted.  If you want to pass it within the URL, then do something like:

@app.route('/prev-orders/<integer:ItemID>')
def previous_orders(ItemID):
   cursor = cnxn.cursor()
   # ... rest of code

Then generate the link in your HTML with:

<a href="{{ url_for('previous_orders', ItemID = value[0]) }}">{{ value[3] }}</a>

Also, as a side note, I think the following line should be:

cursor.execute(order_history, (ItemID,))

(note the extra comma which makes that second argument a valid tuple, which I think is what the execute method expects)


问:
Shape tween in javascript
Is there a way to do a shape tween in javascript?
Using canvas maybe... </p>

答:
Shape tween as in Flash is harder to find than motion tween and simple attributes interpolation (like in JSTweener, Tween.lib, JQuery's animate(), d3's transition(), RaphaelJS's animate(), etc.). Those libraries, some cited in the other answers, don't do shape tweening.

You first need to know if you want to draw with SVG or with canvas and what library you will be using. Then, you need an interpolator, a function that will compute the transition between two given shapes, that can write a proper path in SVG or canvas. I wrote an implementation for SVG in D3.js to do some animated transitions between a lot of different shapes (using Gielis's superformula), if someone still need one. You can find an example here

Title: Shape tween in javascript


问:
How deploy React app locally only in my PC?
I’m working on a project. In this project, I'm creating a React user interfaces to enter data. So now, I only can run the React project with npm start. That mean I need code to run the project

Is there any way to deploy my project locally? I mean, I need a way to run the React project without use of code. I need to deploy only on my local PC.

答:
Consider checkbox:

If you check those checkboxes, others can access your site.


问:
How To exclude vertex with label name = 'Kpi' in gremlin
i have the next Query in GremlinDb:

```<code>g.V('61f4e0c0-2f17-4a0a-a874-ee7325c110e5').outE().has(label,'HasActionBook').inV().outE().has(label,'ActionBookHasSwimlane').inV().outE().inV()
</code>```

and returns to me all items but i have a item with label 'Kpi' how to do to exclude this items with this label ?

thanks for all.

答:
You can put a not in front of a hasLabel step as in :

```<code>not(hasLabel('Kpi'))
</code>```

Body:
i have the next Query in GremlinDb:

g.V('61f4e0c0-2f17-4a0a-a874-ee7325c110e5').outE().has(label,'HasActionBook').inV().outE().has(label,'ActionBookHasSwimlane').inV().outE().inV()

and returns to me all items but i have a item with label 'Kpi' how to do to exclude this items with this label ?

thanks for all.

Body:
You can put a not in front of a hasLabel step as in :

not(hasLabel('Kpi'))


问:
Input value doesn't display. How is that possible?
This must be something utterly stupid that I've done or am doing, but I have an input with a value attribute that simply isn't being displayed:

```<code><div class="input text required">
  <label for="Product0Make">Make</label>
  <input name="data[Product][0][make]"
         type="text"
         maxlength="255"
         value="AC Make"
         id="Product0Make">
</div>
</code>```

Has anyone ever seen this before? Do I have some kind of typo that I'm just blind to? For whatever it may be worth, here's the CakePHP code that's generating this line:

```<code><?php echo $this->Form->input( 'Product.' . $index . '.make', array( 'default' => $product['Product']['make'] ) ) ?>
</code>```

I have a small form with a handful of text inputs, 1 textarea and 2 selects. None of the text input values display, but everything else is fine.

Any thoughts would be appreciated. I can't even believe I'm having to ask this question, but that's how crazy it's making me.

答:
I had the same problem of @Rob Wilkerson, a onchange() was cleaning the value of the input with "", so i changed to 1. Such a dumb problem!

```<code>HTML
<input class="form-control inputCustomDay" type="text" id="txtNumIntervalo" onkeyup="changeTipoOptions()" value="1" min="1" />
</code>```

```<code>Jquery
$("#txtNumIntervalo").val(1);
</code>```

Body:
This must be something utterly stupid that I've done or am doing, but I have an input with a value attribute that simply isn't being displayed:

  Make
  <input name="data[Product][0][make]"
         type="text"
         maxlength="255"
         value="AC Make"
         id="Product0Make">

Has anyone ever seen this before? Do I have some kind of typo that I'm just blind to? For whatever it may be worth, here's the CakePHP code that's generating this line:

<?php echo $this->Form->input( 'Product.' . $index . '.make', array( 'default' => $product['Product']['make'] ) ) ?>

I have a small form with a handful of text inputs, 1 textarea and 2 selects. None of the text input values display, but everything else is fine.

Any thoughts would be appreciated. I can't even believe I'm having to ask this question, but that's how crazy it's making me.

Body:
I had the same problem of @Rob Wilkerson, a onchange() was cleaning the value of the input with "", so i changed to 1. Such a dumb problem!

HTML
<input class="form-control inputCustomDay" type="text" id="txtNumIntervalo" onkeyup="changeTipoOptions()" value="1" min="1" />

Jquery
$("#txtNumIntervalo").val(1);