text:
Q: Highcharts Label Date Format We're currently using highcharts with date format being displayed as 'Tuesday, 18.February'.
How can we change this format to 'Tues 18 Feb'

A: After doing some research, Below worked seamlessly:
xAxis: {
        dateTimeLabelFormats: {
            day: '%a  %e  %b'
         }
       }

Please also refer to https://api.highcharts.com/highcharts/xAxis.dateTimeLabelFormats


text:
Q: \rowcolor not working in latex IEEEtrans I am trying to colour rows in some tables in a latex IEEEtran article but the colouring does not show at all, and no error is thrown as well.
Here is the snippet of code I used:
\usepackage{array, booktabs, makecell, tabularx}
\usepackage[pdftex]{graphicx}
\usepackage{graphicx}
\usepackage[export]{adjustbox}
\usepackage{subfigure}
\usepackage{float}
\usepackage[colorlinks,allcolors=blue]{hyperref}
\usepackage{amsmath}
\setcellgapes{4pt}%parameter for the spacing
\usepackage{mdwmath}
\usepackage{mdwtab}
\usepackage{colortbl}
\usepackage{xcolor}
\usepackage{multirow}
\begin{document}
            \begin{table*}[t]
             \centering
             \caption{Some of the previous DBQ studies in the literature} \label{tab:Studies}
             \begin{tabular}{lccl}
               &&&\\
               \rowcolor{gray!20}
               \multirow{-2}{*}{\textbf{Country}} & \multirow{-2}{*}{\textbf{DBQ type}} & \multirow{-2}{*}{\textbf{Year published}} & \multirow{-2}{*}{\textbf{Resulting factors}}\\
                \rowcolor{gray!20}
                \midrule
                \multirow{2}{*}{UK\cite{parker1995}}& \multirow{3}{*}{....} & \multirow{3}{*}{1995} & driving under influence \\
                &&& driving while texting\\
                \bottomrule
             \end{tabular}
            \end{table*}
\end{document}

A: *

*package mdwtab is not compatible with the package colortbl, consequently with it row colors not show up

*ieee journals doesn't allows colored tables

*your table code is unnecessary complicated. do you really need all this multirows and table over two columns? with example of table, which you provide it can be easily fit in one column.

*if you persist with colored row with column headers than a possible mwe (mnimal working example) can be:
\documentclass[twocolumn]{IEEEtran}
\usepackage{booktabs, cellspace, multirow, tabularx}
    \setlength\cellspacetoplimit{4pt}
    \setlength\cellspacebottomlimit{4pt}
    \newcolumntype{R}{>{\raggedright\arraybackslash}X}
    \addparagraphcolumntypes{R}
\usepackage{ragged2e}

\usepackage[table]{xcolor}
\usepackage[export]{adjustbox}
\usepackage{amsmath}

\usepackage[colorlinks,allcolors=blue]{hyperref}
\usepackage{lipsum}

\begin{document}
\lipsum[66]
    \begin{table}[htb]
\centering
\caption{Some of the previous DBQ studies in the literature} \label{tab:Studies}
\begin{tabularx}{\linewidth}{l c c S{R}}
\rowcolor{gray!20}
\textbf{Country}
    & \textbf{DBQ type} & \textbf{Year published} & \textbf{Resulting factors}  \\
%
UK\cite{parker1995}
    &                   & 1995                      & driving under influence   \\
...
    & ...               & ...                       & driving while texting     \\
    \bottomrule
\end{tabularx}
    \end{table}
\lipsum[1-5]
\end{document}

*

*above table is simple to extend to table*

*if cell contents in your table is bigger, please provide three rows of table which emulate your real table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Secure WCF service and Methods I have created a WCF service in our Project. There are many methods inside this. Now its opened. That means anyone form outside can create a proxy of our service and could easily use our methods. How to secure this thing. I used BasicHttpbinding and read on the Certificate security. But not able to make secure. Please guide me. Its urgent. I cannot change the basicHttpBindings. So give me a solution to protect my service.

A: i believe enbale windows authentication is the best solution but it all depends who is allowed and how is not allowed, check the following link http://social.msdn.microsoft.com/Forums/en/wcf/thread/0e8a4cda-e942-434b-a3d5-8c0ab3502b9b


text:
Q: Python function not returning values I'm creating a digital clock timer with two timers. The first is 30 mins and second is 30 to 20 secs depending on how long is left in the first timer. To reset the second clock every 30 or 20 seconds i created a function to call it to set the shottimer back to 30. However it is not returning the value of the shot timer any ideas why. Code is below
def countdown(matchtime,shottime):
    matchstr = str(datetime.timedelta(seconds=matchtime))
    shottimestr = str(datetime.timedelta(seconds=shottime))
    lbl_text['text'] = matchstr
    lbl_textshot['text'] = shottimestr
    if shottime == 0:

        ShotTime(matchtime, shottime)
        print (shottime)
    if matchtime > 0:
        root.after(1000, countdown, matchtime-1, shottime-1)
        print (shottime)
        matchstr = str(datetime.timedelta(seconds=matchtime))
        shottimestr = str(datetime.timedelta(seconds=shottime))

        lbl_text['text'] = matchstr
        lbl_textshot['text'] = shottimestr

    elif(matchtime == 0):
        global NewForm
        NewForm = Toplevel()
        NewForm.title("Sourcecodester")
        width = 500
        height = 300
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        x = (screen_width/2) - (width/2)
        y = (screen_height/2) - (height/2)
        NewForm.geometry("%dx%d+%d+%d" % (width, height, x, y))
        NewForm.resizable(0, 0)
        lbl_blast = Label(NewForm, text="Blast Off!", font=('arial', 50))
        lbl_blast.pack(fill=BOTH, pady=100)
        btn_back = Button(NewForm, text="Reset", font=('arial', 16), command=BackBtn)
        btn_back.pack(side=TOP)

def ShotTime(matchtime, shottime):
        if shottime == 0 and matchtime > 900:
            shottime = 30
            return matchtime, shottime
        elif matchtime <= 900 and shottime == 0:
            shottime = 20
            return matchtime, shottime

A: You have a return statement in def ShotTime but you don't have ShotTime equal to anything.
Edit:
To elaborate more you have
`def ShotTime(matchtime, shottime):
if shottime == 0 and matchtime > 900:
    shottime = 30
    return matchtime, shottime
elif matchtime <= 900 and shottime == 0:
    shottime = 20
    return matchtime, shottime`

So you have return statements there.
if shottime == 0:

ShotTime(matchtime, shottime)
print (shottime)

but in def countdown() you dont have it being set equal to anything. I believe in python you have to do something like x = ShotTime(matchtime,shottime) and that will return a array, then do like matchtime = x[0] then shottime = x[1]
edit2: this is a better way thx @kevin   matchtime, shottime = ShotTime(matchtime, shottime)
This has to do with variable scope. Unless it is a global variable, variables stay in the function they are created. Just because it has the same name does not mean it is the same variable.

A: The function ShotTime(matchtime, shottime) takes its parameters by value not by reference. Setting
shottime = 30

Will only affect the value you return. You're not using that value. e.g.
ShotTime(matchtime, shottime)

You may wish to change to
matchtime, shottime = ShotTime(matchtime, shottime)


text:
Q: LicenseMemo displays plain texts after changing Parent to CustomForm I have created Custom Form (CreateCustomForm) and changed LicenseMemo.Parent to this Form.
Unfortunately that results quite not as expected as the LicenseFile RTF is always displayed as Plain Text - all RTF formatting is gone (Font, Font Styles, Font Sizes, etc.).
Should I set additional formatting for LicenseMemo after changing it's parent?

A: This happens because when you are re-parenting a control, the control's window is internally re-created and since the TRichEditViewer component doesn't store the RTF stream anyhow, nor reload it when the control is being recreated, it simply loses its RTF content and shows only plain text which stored is.
What is also bad for this case is that even the RTFText property doesn't implement reading of the RTF stream from existing control instance, so you cannot even save the RTF by yourself before re-parenting for restoring it later on.
There is a way to get the RTF stream by using EM_STREAMOUT message, but that's a quite a lot of work which might finally be untranslatable for Inno Setup Pascal Script due to lack of missing pointer support.
The only easy workaround I can think of is to reload the RTF content file after re-parenting the control. I know that you'll need to include the license file into [Files] entries and extract it manually, but it's the least painful way to go.


text:
Q: VMWARE ESXi and SSD - ext4 trim discard I'm running ESXi 5.5 box with Debian as guest OS. and I'm planning to use SSD disk(with ext4) for MySQL database for performance reasons.
ESXi recognizes that I'm using SSD disk.
But how to let know guest OS that it is SSD disk? Or it isn't needed?

A: Shouldn't be needed.  What the guest OS "sees" is the virtual file system provided by the hypervisor, vice the underlying hardware.


text:
Q: VHDL Factorial calculator I am attempting to create a 16-bit factorial calculator for an unsigned binary number.  In doing so I have created a data path and a state machine that
a.) outputs a final value of 1 if the value input is 0
b.) displays and overflow flag if the input is over 8!
c.) Calculates the value for the factorial if the value input is less then 8 and not zero.
The system seems to fall apart if the value I input is anything over 3 yet still not an overflow.  I think the issue is somewhere in Test3, Update 1, update 2 in my state machine.  Could anyone help explain what is going wrong?
State Machine:
library IEEE;
use IEEE.STD_LOGIC_1164.all;

entity fact_16_ctrlv2 is
     port(
         go : in STD_LOGIC;
         clk : in STD_LOGIC;
         clr : in STD_LOGIC;
         overflow : in STD_LOGIC;
         numeqcnt : in STD_LOGIC;
         factzero : in STD_LOGIC;
         flag: out STD_logic;
         xload : out STD_LOGIC;
         cntmux : out STD_LOGIC;
         cntload : out STD_LOGIC;
         factload : out STD_LOGIC;
         factmux : out STD_LOGIC;
         finalload : out STD_LOGIC;
         finalmuxselect: out STD_logic;
         decimalpoint: out std_logic
         );
end fact_16_ctrlv2;

--}} End of automatically maintained section

architecture fact_16_ctrlv2 of fact_16_ctrlv2 is
type state_type is (start, input, test1, test2, test3, update1, update2, update3, done);
signal present_state, next_state: state_type;
begin

    sreg: process(clk, clr)
    begin
    if clr='1' then
    present_state <= start;

    elsif clk'event and clk='1' then
        present_state <= next_state;
    end if;
    end process;

    c1: process(present_state, go, overflow, factzero, numeqcnt)
    begin
        case present_state is
            when start =>
            if go = '1' then
                next_state <= input;
            else
                next_state <= start;
            end if;

            when input =>
            next_state <= test1;

            when test1 =>
            if factzero= '1' then
                next_state <= done;
            else
                next_state <= test2;
            end if;

            when test2 =>
            if overflow = '1' then
                next_state <= done;
            else
                next_state <= update3;
            end if;

            when update3 =>
            next_state <= test3;

            when test3 =>
            if numeqcnt = '1' then
                next_state <= done;
            else
                next_state <= update1;
            end if;

            when update1 =>
            next_state <= update2;

            when update2 =>
            next_state <= test3;

            when done =>
            next_state <= done;

            when others =>
            null;

            end case;
            end process;

    C2: process(present_state, overflow, numeqcnt, factzero)
    begin
        xload<= '0';
        flag <= '0';
        cntmux <= '0';
        cntload<= '0';
        factload<='0';
        factmux<='0';
        finalload <='0';
        finalmuxselect<='0';
        decimalpoint<='0';

        case present_state is

            when input =>
            xload<='1';
            --cntmux<='1';
            --cntload<='1';

            when test2 =>
            if  overflow ='1' then
                flag <= '1';
                finalmuxselect<='0';
                finalload<='1';
                factload <='1';
                decimalpoint <='1';

            end if;

            when test1 =>

            if factzero ='1' then
                flag <= '1';
                finalmuxselect <='1';
                finalload <='1';
            end if;

            when update3 =>
               cntmux<='1';
               cntload<='1';
               factmux<= '1';
               factload<= '1';

            when test3 =>

            if numeqcnt ='1' then
            finalmuxselect<='0';
            --finalload<='1';
            factload <='1';
            cntload<='1';
            factmux<='0';
            else

            end if;

            when update1 =>

            factmux<='0';
            factload<='1';

            when update2 =>

            cntmux<='0';
            cntload<='1';
            --factload<='1';

            when done =>
            finalload<='1';
            when others =>
            null;

        end case;
        end process;

    end fact_16_ctrlv2;

Data Path
library IEEE;
use IEEE.STD_LOGIC_1164.all;

entity fact_16_dp is
    port(
         clr : in STD_LOGIC;
         clk : in STD_LOGIC;
         X : in STD_LOGIC_VECTOR(3 downto 0);
         overflow : out STD_LOGIC;
         finalfact : out STD_LOGIC_VECTOR(15 downto 0);
         cntload, cntmult, factload, factmult, xload, finalload :in Std_logic;
         equalone, numcnt : out Std_logic;
         finalmuxselect, flagin: in STD_logic
         );
end fact_16_dp;

--}} End of automatically maintained section

architecture fact_16_dp of fact_16_dp is
    -- Component declaration of the "mult16b(mult16b)" unit defined in
    -- file: "./../src/multiplier.vhd"
    component mult16b
    port(
        a : in STD_LOGIC_VECTOR(15 downto 0);
        b : in STD_LOGIC_VECTOR(15 downto 0);
        p : out STD_LOGIC_VECTOR(15 downto 0));
    end component;
    for all: mult16b use entity work.mult16b(mult16b);

        -- Component declaration of the "comp(comp)" unit defined in
    -- file: "./../src/comparitor.vhd"
    component comp
    generic(
        N : INTEGER := 8);
    port(
        x : in STD_LOGIC_VECTOR(N-1 downto 0);
        y : in STD_LOGIC_VECTOR(N-1 downto 0);
        gt : out STD_LOGIC;
        eq : out STD_LOGIC;
        lt : out STD_LOGIC);
    end component;
    for all: comp use entity work.comp(comp);
        -- Component declaration of the "adder(adder)" unit defined in
    -- file: "./../src/adder.vhd"
    component adder
    generic(
        N : INTEGER := 8);
    port(
        a : in STD_LOGIC_VECTOR(N-1 downto 0);
        b : in STD_LOGIC_VECTOR(N-1 downto 0);
        y : out STD_LOGIC_VECTOR(N-1 downto 0));
    end component;
    for all: adder use entity work.adder(adder);

        -- Component declaration of the "reg(reg)" unit defined in
    -- file: "./../src/reg.vhd"
    component reg
    generic(
        N : INTEGER := 8);
    port(
        load : in STD_LOGIC;
        clk : in STD_LOGIC;
        clr : in STD_LOGIC;
        d : in STD_LOGIC_VECTOR(N-1 downto 0);
        q : out STD_LOGIC_VECTOR(N-1 downto 0));
    end component;
    for all: reg use entity work.reg(reg);
        -- Component declaration of the "mux2g(mux2g)" unit defined in
    -- file: "./../src/mux21.vhd"
    component mux2g
    generic(
        N : INTEGER);
    port(
        a : in STD_LOGIC_VECTOR(N-1 downto 0);
        b : in STD_LOGIC_VECTOR(N-1 downto 0);
        s : in STD_LOGIC;
        y : out STD_LOGIC_VECTOR(N-1 downto 0));
    end component;
    for all: mux2g use entity work.mux2g(mux2g);

        -- Component declaration of the "mux4g(mux4g)" unit defined in
    -- file: "./../src/mux4to1.vhd"
    component mux4g
    generic(
        N : INTEGER);
    port(
        a : in STD_LOGIC_VECTOR(N-1 downto 0);
        b : in STD_LOGIC_VECTOR(N-1 downto 0);
        c : in STD_LOGIC_VECTOR(N-1 downto 0);
        s : in STD_LOGIC_VECTOR(1 downto 0);
        y : out STD_LOGIC_VECTOR(N-1 downto 0));
    end component;
    for all: mux4g use entity work.mux4g(mux4g);

--signal cntload, cntmult, numcnt, factload, factmult, xload, numload, equalone, finalload :Std_logic;
signal  adderout, cntregout, cntregin, x2 :Std_logic_vector(3 downto 0);
signal xin, factregin, factregout, overin, factmout, checkzero, numregout, flag, finalmuxout, cntregoutb :Std_logic_vector(15 downto 0);

begin
    x2 <= x;
    xin <= "000000000000" & x2;  --Change 4 bit number input into a 16 bit number
    cntregoutb <= "000000000000" & cntregout; --change count from 4 bit value to a 16 bit value
    flag <= "000000000000000" & flagin;
    cntreg : reg --4-bit counter register
    generic map(
        N => 4
    )
    port map(
        load => cntload,
        clk => clk,
        clr => clr,
        d => cntregin,  --not in drawing
        q => cntregout
    );

    factreg : reg  --16-bit fact register
    generic map(
        N => 16
    )
    port map(
        load => factload,
        clk => clk,
        clr => clr,
        d => factregin,
        q => factregout
    );

    --numreg : reg --16-bit num register
    --generic map(
        --N => 16
    --)
    --port map(
        --load => numload,
        --clk => clk,
        --clr => clr,
        --d => xin,
        --q => numregout
    --);

    xreg : reg  --4-bit initial x vlaue register
    generic map(
        N => 4
    )
    port map(
        load => xload,
        clk => clk,
        clr => clr,
        d => x,   --x(3:0)
        q => x2
    );

    finalreg : reg   --16-bit final fact register
    generic map(
        N => 16
    )
    port map(
        load => finalload,
        clk => clk,
        clr => clr,
        d => finalmuxout,
        q => finalfact
    );

     cntmux : mux2g --4-bit cnt mux
    generic map(
        N => 4
    )
    port map(
        b => "0001",  --initial value set
        a => adderout, --value after initial run through
        s => cntmult,
        y => cntregin  --cntregin not in drawing
    );

    factmux : mux2g  --16-bit fact mux
    generic map(
        N => 16
    )
    port map(
        b => "0000000000000001", --initial value set
        a => factmout,  --value after initial run through
        s => factmult,
        y => factregin
    );

    add1 : adder  --Increment counter 4-bit
    generic map(
        N => 4
    )
    port map(
        a => cntregout, --add 1
        b => "0001", --1
        y => adderout --out of the adder
    );

    multiplier : mult16b  --multiply cnt and fact 16-bit
    port map(
        a => factregout,
        b => cntregoutb,  --cnt plus 12 zeros to 16-bit
        p => factmout --Multiplier out
    );

    greater8 : comp --16-bit check x overflow if greater then 8
    generic map(
        N => 16
    )
    port map(
        x => xin,  --check value to 8
        y => "0000000000001000",
        gt => overflow  --send overflow flag
        --eq => eq,
        --lt => lt
    );

    check0 : comp  --16-bit check x not equal to zero
    generic map(
        N => 16
    )
    port map(
        x => xin,
        y => "0000000000000000",
        --gt => gt,
        eq => equalone
        --lt => lt
    );

    numeqcnt : comp  --16-bit check if num equals cnt
    generic map(
        N => 16
    )
    port map(
        x => xin,
        y => cntregoutb,  --need 16 bit
        --gt => gt,
        eq => numcnt --not in drawing
        --lt => lt
    );

    finalmux: mux2g
    generic map(
        N => 16
    )
    port map(
        a => factregout,
        b => flag,
        s => finalmuxselect,
        y => finalmuxout
    );

end fact_16_dp;

Connected together
-------------------------------------------------------------------------------
--
-- Title       : fact_16
-- Design      : lab4
-- Author      :
-- Company     :
--
-------------------------------------------------------------------------------
--
-- File        : c:\My_Designs\lab4\lab4\src\fact_16.vhd
-- Generated   : Tue Oct 14 16:40:38 2014
-- From        : interface description file
-- By          : Itf2Vhdl ver. 1.22
--
-------------------------------------------------------------------------------
--
-- Description :
--
-------------------------------------------------------------------------------

--{{ Section below this comment is automatically maintained
--   and may be overwritten
--{entity {fact_16} architecture {fact_16}}

library IEEE;
use IEEE.STD_LOGIC_1164.all;

entity fact_16 is
     port(
         go : in STD_LOGIC;
         clk : in STD_LOGIC;
         clr : in STD_LOGIC;
         x : in STD_LOGIC_VECTOR(3 downto 0);
         overflowB : out STD_LOGIC;
         factout : out STD_LOGIC_VECTOR(15 downto 0)
         );
end fact_16;

 architecture fact_16 of fact_16 is

    -- Component declaration of the "fact_16_dp(fact_16_dp)" unit defined in
    -- file: "./../src/fact_16_dp.vhd"
    component fact_16_dp
    port(
        clr : in STD_LOGIC;
        clk : in STD_LOGIC;
        X : in STD_LOGIC_VECTOR(3 downto 0);
        overflow : out STD_LOGIC;
        finalfact : out STD_LOGIC_VECTOR(15 downto 0);
        cntload : in STD_LOGIC;
        cntmult : in STD_LOGIC;
        factload : in STD_LOGIC;
        factmult : in STD_LOGIC;
        xload : in STD_LOGIC;
        finalload : in STD_LOGIC;
        equalone : out STD_LOGIC;
        numcnt : out STD_LOGIC;
        finalmuxselect : in STD_LOGIC;
        flagin : in STD_LOGIC);
    end component;
    for all: fact_16_dp use entity work.fact_16_dp(fact_16_dp);

    -- Component declaration of the "fact_16_ctrlv2(fact_16_ctrlv2)" unit defined in
    -- file: "./../src/fact_16_ctrlv2.vhd"
    component fact_16_ctrlv2
    port(
        go : in STD_LOGIC;
        clk : in STD_LOGIC;
        clr : in STD_LOGIC;
        overflow : in STD_LOGIC;
        numeqcnt : in STD_LOGIC;
        factzero : in STD_LOGIC;
        flag : out STD_LOGIC;
        xload : out STD_LOGIC;
        cntmux : out STD_LOGIC;
        cntload : out STD_LOGIC;
        factload : out STD_LOGIC;
        factmux : out STD_LOGIC;
        finalload : out STD_LOGIC;
        finalmuxselect : out STD_LOGIC;
        decimalpoint : out STD_LOGIC);
    end component;
    for all: fact_16_ctrlv2 use entity work.fact_16_ctrlv2(fact_16_ctrlv2);

signal overflow, numeqcnt, factzero, xload, cntmux, cntload, factload, flag, factmux, numload, finalload: STD_logic;
signal finalmuxselect: std_logic;

begin

Dpath : fact_16_dp
    port map(
        clr => clr,
        clk => clk,
        X => X,
        overflow => overflow,
        finalfact => factout,
        cntload => cntload,
        cntmult => cntmux,
        factload => factload,
        factmult => factmux,
        xload => xload,
        finalload => finalload,
        equalone => factzero,
        numcnt => numeqcnt,
        finalmuxselect => finalmuxselect,
        flagin => flag
    );

Cunit : fact_16_ctrlv2
    port map(
        go => go,
        clk => clk,
        clr => clr,
        overflow => overflow,
        numeqcnt => numeqcnt,
        factzero => factzero,
        flag => flag,
        xload => xload,
        cntmux => cntmux,
        cntload => cntload,
        factload => factload,
        factmux => factmux,
        finalload => finalload,
        finalmuxselect => finalmuxselect,
        decimalpoint => overflowB
    );

end fact_16;


text:
Q: Counting images in an MS-ACCESS 2003 column Warning - Newbie ahead
I have a table with one column that has an OLE/object format with images in it.
Some cells have images and some don't.
I want to count the number of images in the column.
I thought of maybe to add a column that will have a formula that will detect if the cell with the image is empty or full and then export the table to Excel and count the result.
I don't know how to do create a column with a formula
Maybe there is another way of doing what I want to do.
Any help will be appreciated.
Thanks.

A: I think this formula might work:

SUM(Iif([image_column] IS NULL, 0, 1))

You'll have to GROUP BY your other columns if you have other fields in your query.

A: I am such a noob! I forgot that I can use SQL to query an ACCESS table.
This just works
select count(image) from table where 2011=1


text:
Q: Image summaries with TensorFlow 2 Dataset API How can I create an image summary in tensorboard using tensorflow >2? It is clear to me how I should do with tensorflow 1 (e.g. using placeholder), but I'm not sure about the new tensorflow.
This is my current code:
# create dataset using tf.data.Dataset :
train_data = create_dataset_pipeline(train_filenames)  # returns (image, mask) pairs
valid_data = create_dataset_pipeline(valid_filenames)  # exactly as train_data, but on different images

# define a model:
model = UNet()

# train model:
for image, mask in train_data:
   with tf.GradientTape() as tape:
      predictions = model(image, training=True)
      loss = weighted_cross_entropy(predictions, labels)

   # apply gradients
   gradients = tape.gradient(loss, model.trainable_variables)
   optimizer.apply_gradients(zip(gradients, model.trainable_variables))

   # ....

And during the validation step, I'd like to show some examples of an input image, and the respective model prediction and ground-truth segmentation mask.
with writer.as_default():
   tf.summary.image("Validation", ????, step=0, max_outputs=3)

What should I put in ?????


text:
Q: How to clearly define boundaries of a bounded context After a month or so of reading and researching DDD, I decided to start my own project and created DDD with these bounded contexts>

*

*Clients

*Products

*Orders

*Billing

Each bounded context has rest API as a presentation layer, domain layer, persistent layer.
So far so good, code is running smooth, but coming from a monolithic world, I am still trying to figure out the following:

*

*when I want to create a new client, issue new invoice, create new order I want to for example access list of countries. Do I:

a) create a list of countries in each BC
b) create a Countries BC -> API and use it to get a list of available countries
c) use a 3rd party API and pull data via anticoruption layer in each BC

*

*when integrating with 3rd party API using an anti-coruption layer or an adapter layer, what data has to be included in my domain model? For example if I want to integrate a zendesk API with a Client BC. Do I need just a ticketID in my domain, or I have to extract all the data from Zendesk that I want to access and use in a Client BC?

If my MVC app is actually getting data from APIs (presentation layers of my bounded contexts) I find it very difficult to clearly define boundaries of each BC. Does it mean that a properly designed BC would serve a single MVC controller without a need to consume additional APIs?

A: From your questions, I think you misunderstand bounded context.  You may want to reread Chapter 14 of the blue book.
Trying to answer generally - you have to be careful about sharing concepts between two different bounded contexts.  After all, part of the reason that the boundary exists is that the ubiquitous language changes.  To assume that the same data (and the same representation) of an entity can be used in both contexts is naive -- it may be right, it may be wrong, but there's no good way for those of us on the outside, without access to your domain experts, to judge.
For example, in the client domain, "country" could be related to residence or citizenship.  In billing, it might be related to currency exchange rates.  In some of those domains, you might need to worry about tariffs and the like.
A second question that you need to raise is which of your models is the book of record for the "shared" data.  In the case of "country", the right answer is probably that none of them are!  Geopolitical topology is not controlled by your model.
What is supposed to happen in your domain models when a country is occupied by a foreign power?
Keep in mind; a lot of us are accustomed to thinking about data structure; what is the relationship between one piece of data and another.  And that's great when you are considering reports, and trying to ensure that all of the data that you need has been collected by your solution.  But domain models are not just about structure, but about change.  You need to put your attention on that part too, and make sure that you well understand how the data constrains the changes (and how those constraints vary from one bounded context to the next).

A: If your different bounded contexts understand the meaning/purpose of a country differently, then you need to model it appropriately different in each one. However, if we are speaking simply of reference data of ISO codes and names, then I believe it's pretty fair and standard to stash it wherever is convenient and make it accessible to all interested parties. For example: a database, a configuration file, a web service, etc.
I also wanted to look at your model a little bit. The pieces you have listed could very well be "entities" in one "bounded context", depending on the company's structure. BCs often end up being defined around different areas/departments/teams, since that's frequently the natural boundary between "ubiquitous language"s. So for example, instead of Sales/Products/Orders I'd expect the BCs to be along the lines of Sales/Manufacturing/Warehousing.
Inside those BCs, you don't focus on the nouns. You focus on the use cases, and create models of the nouns that can fulfill the use cases. The methods on an "aggregate root" execute use cases and make the appropriate changes to the related models.

... all models are wrong, but some are useful.

Also bear in mind that each BC may use an entirely different system or architecture. A given BC may not merit using "DDD software components" at all, and most of them probably don't. DDD is less about prescriptive software components and more about the process of designing software. The point is to focus on understanding the company's bounded contexts, mapping out each context's ubiquitous languages, and modeling the code for that context using their ubiquitous language. That way when you interact with stake holders and refer to the code, it sounds to them like you are speaking in business terms they understand. And recognizing that the same word has different meanings in different BCs.
There are specific patterns brought forth by DDD (e.g. repository, specific layering, etc.) that are means to an end. But these patterns are not guaranteed to be the best patterns for every case, even within DDD. Just like DDD is not "the" answer for every project. You just have to do what your analysis suggests is the most practical thing to do.

A: The concepts you mention (Clients, Products, Orders, Billing) are typically represented in a single Domain Model and hence Bounded Context.  I suggest you are understanding these concepts incorrectly.

A: My take on this subject is to define bounded context using a business-capability mapping or other similar techniques like Value-chain analysis. It comes down to following steps:

*

*Define your system's higher-level responsibilities, or business-capabilities. The best way to do it I think is to conjure up with steps your enterprise goes through to obtain a business-value. The logical boundaries you come up with are your business-services, or, if you like, bounded contexts.

*Delve deeper within each service.

*Identify the communications between your services alongside the first two points.

So the initial focus is on how your business operates.
Couple of practical advises:

*

*If one of your contexts/services/etc need some other context's data, most probably your boundaries are wrong.

*The highly desirable way of context communication is event-based. This is a key to scalability and reliability. If you need synchronous communication, most probably than not you boundaries are wrong, again. Besides that, synchronous communication will kill your system.

*Your domain is more eventually-consistent than you think. Just like everyone else's. Don't try to make everything 100% consistent. There is no practical sense in that.

*Contexts don't need to be orchestrated. They are self-contained. Like humans.

With this approach you end up with highly autonomous, maintainable and reliable services. You might want to check an example of defining context boundaries.


text:
Q: CentOS Virtualbox no internet access I have the following problem:
I have a VM with CentOS installed. From this machine, I can't connect to internet, so I can't upgrade nothing installed on it.
The VM configuration is:
Under Settings -> Network

*

*Adapter 1

*

*NAT

*Adapter 2

*

*Host-only Adapter

*Name: vboxnet0

*Promiscuous Mode: Deny

*Calbe Connected: true

Under File->Preferences->Network, in Host-only Networks, vbonenet0:

*

*IPv4 Address: 192.168.101.1

*Ipv4 Newroks Mask: 255.255.255.0

*IPv6 Address: fe80:0000:0000:0000:0800:27ff:fe00:0000

*IPv6 Prefix Length: 64

When I'm on the machine:
ifconfig -a
eth0      Link encap:Ethernet  HWaddr 08:00:27:55:45:B3
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe55:45b3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:7 errors:0 dropped:0 overruns:0 frame:0
          TX packets:15 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1699 (1.6 KiB)  TX bytes:1414 (1.3 KiB)

eth1      Link encap:Ethernet  HWaddr 08:00:27:D7:3D:E9
          inet addr:192.168.101.129  Bcast:192.168.101.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fed7:3de9/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:477 errors:0 dropped:0 overruns:0 frame:0
          TX packets:452 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:89736 (87.6 KiB)  TX bytes:183141 (178.8 KiB)

ping 192.168.101.129
PING 192.168.101.129 (192.168.101.129) 56(84) bytes of data.
64 bytes from 192.168.101.129: icmp_seq=1 ttl=64 time=0.013 ms
64 bytes from 192.168.101.129: icmp_seq=2 ttl=64 time=0.027 ms
64 bytes from 192.168.101.129: icmp_seq=3 ttl=64 time=0.031 ms
64 bytes from 192.168.101.129: icmp_seq=4 ttl=64 time=0.048 ms
64 bytes from 192.168.101.129: icmp_seq=5 ttl=64 time=0.062 ms

ping www.google.com
PING www.google.com (216.58.205.164) 56(84) bytes of data.
From 192.168.101.129 icmp_seq=2 Destination Host Unreachable
From 192.168.101.129 icmp_seq=3 Destination Host Unreachable
From 192.168.101.129 icmp_seq=4 Destination Host Unreachable

Under /etc/sysconfig/network-scripts/, the ifcfg-eh0 file:
DEVICE=eth0
ONBOOT=yes
BOOTPROTO=DHCP
DNS1=8.8.8.8
DNS2=8.8.4.4

the ifcfg-eh1 file:
DEVICE=eth1
ONBOOT=yes
TYPE=Ethernet
BOOTPROTO=static
IPADDR=192.168.101.129
NETMASK=255.255.255.0
NETWORK=192.168.101.0
BROADCAST=192.168.101.255
NM_CONTROLLED=no
DNS1=8.8.8.8
DNS2=8.8.4.4

route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.101.0   *               255.255.255.0   U     0      0        0 eth0
10.0.3.0        *               255.255.255.0   U     0      0        0 eth1
192.168.56.0    *               255.255.255.0   U     0      0        0 eth0
link-local      *               255.255.0.0     U     1002   0        0 eth0
link-local      *               255.255.0.0     U     1003   0        0 eth1
default         192.168.101.2   0.0.0.0         UG    0      0        0 eth0

Can someone help me? Thanks for the support.
UPDATE
The default gateway is:
ip r | grep default
default via 192.168.101.2 dev eth1

A: Make sure that the MAC Address from your VirtualBox Network Adapters it is been equal to the hardware Address (HWADDR) declared in your files  ifcfg-eh0 and  ifcfg-eh1. Until I fixed that I was able to make work my network.


text:
Q: Paperclip not Uploading to Bucket, No Error Returned I have been battling this one for a while now. I have am using Paperclip and AWS-SDK. I have my bucket and account configured. Permissions are granted. The form data, including the Paperclip model values all save to my Sqlite3 table. However, the image does not upload to my bucket on S3. I receive no errors. Any suggestions on what could be going wrong here?
Thanks in advance.
Here's is the attachment control, which is inside my form. The form routes to the Create method on my Animal controller.
Development Config (I have verified I am in dev mode)
Paperclip.options[:command_path] = "/usr/local/bin/"

 config.paperclip_defaults = {
  :storage => :s3,
  :bucket => ENV["my bucket"],
  :s3_credentials => {
      :access_key_id => ENV["My ID"],
      :secret_access_key => ["My Secret"]
  }
}

  Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
  Paperclip::Attachment.default_options[:path] =    '/:class/:attachment/:id_partition/:style/:filename'

Animal/new.html.erb

      <%= f.file_field :animal_image %>
      Attach Your Photo

Animal Controller
 def create

@animal = Animal.new(animal_params)
respond_to do |format|
    if @animal.save
      flash[:notice] = "#{@animal.full_name} has been added to your profile."
      format.json { render json: @animal, status: :created, location: @animal }
      format.html { render "animal/index" }
    else
      flash.now[:error] = @animal.errors.full_messages
      format.html { render action: "new" }
      format.json { render json: @animal.errors, status: :unprocessable_entity }
    end
  end
end

private
def animal_params

params.require(:animal).permit(:full_name, :profile_id, :age, :gender, :purr_factor,           :weight, :height,
                                            :length, :fixed, :shots, :papers, :animal_desc, :breed_id, :animal_image)
end

Animal.rb
        :animal_image_content_type
        :animal_image_file_name

        has_attached_file :animal_image, style: {
         thumb: '100x100>',
         square: '200x200#',
         medium: '300x300>'
        }

        # Validate the attached image is image/jpg, image/png, etc
       validates_attachment_content_type :animal_image, :content_type => /\Aimage\/.*\Z/

A: So I figured it out and I figured I should post the solution, so that way I can get more down votes. Even though I have seen countless Paperclip posts on here with similar problems, whom, received multiple up votes.
Removing the credentials from my config/environments/development file and placing all configuration in my model seemed to do the trick. Also, I had a hash symbol in my style field.
  has_attached_file :animal_image,
                    :style => {:medium => "300x300>", :thumb => "100x100>"},
                    :storage => :s3,
                    :bucket  => "my bucket",
                    :s3_credentials => {
                        :bucket  => "my bucket",
                        :access_key_id => ENV["My key"],
                        :secret_access_key => ENV["My Secret"]
                    },
                    :s3_permissions => "private",
                    :url => ":s3_domain_url"
                    Paperclip::Attachment.default_options[:url] = ":s3_domain_url"
                    Paperclip::Attachment.default_options[:path] = "/:class/:attachment/:id_partition/:style/:filename"


text:
Q: Break down this list using list comprehension I was wondering if there is a good pythonic way to break down this list:
['1,2,3', '22', '33']

into the list:
['1','2','3','22','33']

using list comprehension?

A: With a list comprehension, it would look like this:
>>> L = ['1,2,3', '22', '33']
>>> [x for s in L for x in s.split(",")]
['1', '2', '3', '22', '33']

A: Since there were two answers already posted using the sum() function as a solution, I thought I would contribute one more way, using itertools.chain
from itertools import chain
x = ['1,2,3', '22', '33']
result = chain.from_iterable(i.split(',') for i in x)

print result
#<itertools.chain object at 0x1004b5e10>

The result of the chain command is a generator. So you could loop over the result, or cast it to another sequence type (tuple, list, set, ...)

A: I wouldn't use sum, since it does repeated concatenation and creates a lot of copies. I would do this:
>>> import itertools
>>> l =  ['1,2,3', '22', '33']
>>> list(itertools.chain.from_iterable(s.split(',') for s in l))
['1', '2', '3', '22', '33']

It's true that it's slightly slower for very short lists:
>>> %timeit sum((s.split(',') for s in l), [])
100000 loops, best of 3: 2.38 us per loop
>>> %timeit list(itertools.chain.from_iterable(s.split(',') for s in l))
100000 loops, best of 3: 3.51 us per loop

But for long lists, it's way faster than using sum:
>>> l =  ['1,2,3', '22', '33'] * 500
>>> %timeit sum((s.split(',') for s in l), [])
100 loops, best of 3: 6.22 ms per loop
>>> %timeit list(itertools.chain.from_iterable(s.split(',') for s in l))
1000 loops, best of 3: 664 us per loop

Actually, though, I rather like wim's answer. And a quick test shows that it's the fastest in all cases, to boot:
>>> l =  ['1,2,3', '22', '33']
>>> %timeit [x for s in l for x in s.split()]
1000000 loops, best of 3: 1.45 us per loop
>>> l =  ['1,2,3', '22', '33'] * 500
>>> %timeit [x for s in l for x in s.split()]
1000 loops, best of 3: 559 us per loop

A: Break down your problem. You can never see how to solve the whole problem at once, and Python never has simple built in solutions to whole problems. Figure out what the most basic pieces of your problem are, and there are often simple direct solutions to each piece. Then combine the solutions. Also, don't expect that you can wave a magic catch phrase like "list comprehension" at the problem to make it go away. Figure out what your solution needs to do, then think about whether a list comprehension can do that.
You have a string '1,2,3'. You need to split that into a list of multiple strings, containing the bits of your original string that were separated by commas:
>>> help(str.split)
Help on method_descriptor:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '3'.split(',')
['3']

Now, you have a list of strings, and you want to split each of them into a list as above:
>>> [s.split(',') for s in ['1','2','3','22','33']]
[['1'], ['2'], ['3'], ['22'], ['33']]

Now you've got a list of lists. You want a single list containing the elements of each of the lists in your list of lists. The operation "give me each thing in each of the lists in a list of lists" maps fairly naturally to a list comprehension as follows:
>>> list_of_lists = [[1, 2, 3], ['a', 'b', 'c']]
>>> [thing for alist in list_of_lists for thing in alist]
[1, 2, 3, 'a', 'b', 'c']

Putting it all together:
>>> [bit for string in ['1','2','3','22','33'] for bit in string.split(',')]
['1', '2', '3', '22', '33']

So that's how you solve this with list comprehensions. There are lots of other potential solutions in other answers that are better on technical grounds. But if you're new to Python learning the entire standard library (especially powerful but abstract things like itertools) will be difficult, and don't feel like you have to. Getting comfortable with the basics will serve you more in the long run.

A: This is the simplest solution I can think of.
It's using sum() with a generator expression, since you don't actually need to keep the sub-lists created.
>>> a = ['1,2,3', '22', '33']
>>> sum((s.split(',') for s in a), [])
['1', '2', '3', '22', '33']

A: A simple way to do it, is:
>>> lst = ['1,2,3', '22', '33']
>>> res = []
>>> for x in lst:
...     res.extend(x.split(','))
>>> res
['1', '2', '3', '22', '33']

It doesn't use list comprehension though, but I don't see why you would use it in this case.

A: You could do something like this (suppose your list is called l):
sum([s.split(',') for s in l], [])


text:
Q: Taking usernames with numbers without using break in for loop username='smith123'
numbers='1234567890'
for i in username:
    if i in numbers:
        print(username)
        #break

Hello, I  write a code that if a number exist in username, then it is printed, but in such usernames, the usernames are printed 3 times. To make sure that it will be printed just one time, is there any method without using break? Thanks.

A: Try this:
username='smith123'

if any(char.isdigit() for char in username):
    print(username)

docs:
any,
isdigit,
(list) comprehension

A: Just another way using re:

\w
For Unicode (str) patterns:
Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.

import re
username="smith123"
if re.match(r"^\w+$", username):
    print(username)


text:
Q: Generating select options using Json and Angular This is an issue that has bothered me to no end. I need to somehow generate options for a select tag from a Json object using Angular. The code looks something like this:
<select id="cargo" ng-model="cargo.values.cargoList">
    <option ng-repeat="(class, name, weight) in cargo.values.cargolist
            ng-click="orderList()">
</select>

The class cargo.js looks a little like:
function setCargo(){
    this.cargo = {
        values: {
            forkliftNeeded: false,
            cargoList: {
                class: "class",
                name: "name",
                weight: "weight"
            }
    }
};

this.setData = function(input); {
    this.cargo.value.cargoList = input.cargo.cargoList;
    this.cargo.value.forkliftNeeded = input.cargo.forkliftNeeded;
}:

And the actual Json object:
[{"cargo":{"forkliftNeeded":true,"cargoList":[{"class":"A","name":"Book","weight":"1"}]}}]

The idea it to generate the appropriate number of option tags based on the number of items in the cargo list. Each option needs to display in order and also needs to display the class, name, and weight for each item (for the record, I'm delegating the forkliftNeeded item to a check box).
To make things even more complicated, I also want to make it so that clicking on a given option moves said option to the top of the list. Not just the options, either- it has to actually change the order of the Json object.
As you can imagine, I'm not nearly skilled enough in angular to make this work by myself. Any help you can give me will be greatly appreciated.
EDIT:
I managed to make some headway. Turns out you can do just fine using:
<select id="cargo">
    <option ng-repeat="item in cargo.values.cargolist"
            ng-click="orderList()">
        {{ item.class + " " + item.name + " " + item.weight }}
    </option>
</select>

Now all I need to know is how to do the orderList() function. Is there a way I can get the index for the order tags on click?

A: What you're looking for is ngOptions. Adding that parameter into your <select> tag will automatically fill out the <options> based on your array.
<select id="cargo"
    ng-model="cargo.values.cargoList"
    ng-options="option.class + ' ' + option.name + ' ' + option.weight as option.name for option in cargo.values.cargoList">
</select>

More on ngOptions here:
https://docs.angularjs.org/api/ng/directive/ngOptions


text:
Q: Are these notions of the convergence of two sided series equivalent? From Stein and Shakarchi's text on Fourier analysis, the definition of a convergent Fourier series is when the following sequence of partial sum converges:
Definition 2.2. We define the $N^{t h}$ partial sum of the Fourier series of $f, N \in \mathbb{N}$ by
$$
S_N(f)(x):=\sum_{n=-N}^N \hat{f}(n) e^{2 \pi i n x / L} .
$$
Now Sheldon Axler's measure and integration also has a chapter on what it means for Fourier series to converge using the notion of an unordered series:
Definition: unordered sum: $\sum_{k \in \Gamma} f_k$
Suppose $\left\{f_k\right\}_{k \in \Gamma}$ is a family in a normed vector space $V$. The unordered sum $\sum_{k \in \Gamma} f_k$ is said to converge if there exists $g \in V$ such that for every $\varepsilon>0$, there exists a finite subset $\Omega$ of $\Gamma$ such that
$$
\left\|g-\sum_{j \in \Omega^{\prime}} f_j\right\|<\varepsilon
$$
for all finite sets $\Omega^{\prime}$ with $\Omega \subset \Omega^{\prime} \subset \Gamma$. If this happens, we set $\sum_{k \in \Gamma} f_k=g$. If there is no such $g \in V$, then $\sum_{k \in \Gamma} f_k$ is left undefined.
and he defined the convergence of a Fourier series to be when the unordered sum converges.
I would like to ask if these two notions of convergence are the same as far as Fourier series are concerned?
And what about in general like in the case of $l^1\mathbb(Z)$ which is the space of all summable double-sided sequences of complex numbers?


text:
Q: FileNotFoundError: [Errno 2] No such file or directory: 'o' I'm getting this error message when using yield.
When I remove the yield results and yield timeout the code works fine without the error message
I don't know what is directory or file 'o' since I'm not using it in any way in the code.
here is my full code:
import gradio as gr
import ipaddress
import requests
from requests.auth import HTTPBasicAuth
import os
import string
from datetime import date, datetime

####SETTING UP DATE AND TIME WITH ISRAELI FORMAT###
current_date = date.today()
current_month = current_date.strftime('%B')
current_year = current_date.strftime('%Y')
date_reformat = current_date.strftime('%d/%m/%y')
current_day = current_date.strftime('%d')

###SWITCH###
def switch_ver(ip):
    with open('switches_successful_results.txt','w') as switches_successful, open('switches_failed_results.txt', 'w') as switches_failed:
        ip_addr = ip.split()
        for i in ip_addr:
            ip_addr = list(ipaddress.ip_network(i))
            try:
                basic=HTTPBasicAuth('some','password')
                login = requests.post('http://'+i+':80/rest/v7/login-sessions', auth=basic)
                cookie = login.cookies
                get_ver = requests.get('http://'+i+':80/rest/v7/system/status', cookies=cookie)
                get_ver = get_ver.json()
                get_ver = get_ver['firmware_version']
                get_ver = get_ver
                with open('switches_successful_results.txt', 'a+') as sw:
                    results = 'Switch version for {} is: {} \n'.format(i, get_ver)
                    sw.write(results)
                yield results

            except requests.exceptions.ConnectTimeout:
                timeout = 'Could not connect to switch: '+i+' REQUEST TIMED OUT\n'
                with open('switches_failed_results.txt', 'a+') as sw:
                    sw.write(timeout)
                yield timeout

    with open('switches_successful_results.txt','r') as switches_successful, open('switches_failed_results.txt', 'r') as switches_failed:
        summary = switches_failed.read() + switches_successful.read()

    return (summary),['switches_successful_results.txt', 'switches_failed_results.txt']

###IPBlockerK###
def block_ip(ip):
    duplicate_ips = []
    blocked_ips = []
    invalid_ips = []
    with open('fortigate_ips.txt','r+') as f, open('fortigate_urls.txt', 'r+') as u:
        fortigate_ips = f.read()
        fortigate_urls = u.read()
        ip_addr = ip.split()
        for i in ip_addr:
            try:
                list(ipaddress.ip_network(i))
                if i in fortigate_ips:
                    duplicate_ips.append(i)
                elif ipaddress.ip_address(i).is_private:
                    invalid_ips.append(i)
                else:
                    blocked_ips.append(i)
                    f.write(i + '\n')
            except ValueError:
                if i in fortigate_ips or i in fortigate_urls:
                    duplicate_ips.append(i)
                elif i[0] in string.ascii_letters or i[0] == '*':
                    blocked_ips.append(i)
                    u.write(i + '\n')

                else:
                    invalid_ips.append(i)

    current_time = datetime.now()
    current_time = current_time.strftime('%H:%M:%S')
    if os.path.exists(current_year) == False:
        os.makedirs(current_year + '\\'+ current_month + '\\' + current_day)
        os.chdir(current_year+ '\\' + current_month +'\\'+ current_day)
        with open('Blocked_IPs.txt', 'a+') as Blocked_IPs:
            to_file = ('###############{}###############\n'.format(current_time)+'\n'.join(blocked_ips))+'\n'
            Blocked_IPs.write(to_file)
        os.chdir('D:\\programs\\Python310\\Projects\\net_sec')
    elif os.path.exists(current_year) == True and os.path.exists(current_year + '\\'+ current_month) == False:
        os.chdir(current_year)
        os.makedirs(current_month + '\\' + current_day)
        os.chdir(current_month +'\\'+ current_day)
        with open('Blocked_IPs.txt', 'a+') as Blocked_IPs:
            to_file = ('###############{}###############\n'.format(current_time)+'\n'.join(blocked_ips))+'\n'
            Blocked_IPs.write(to_file)
        os.chdir('D:\\programs\\Python310\\Projects\\net_sec')
    elif os.path.exists(current_year) == True and os.path.exists(current_year + '\\'+ current_month) == True and os.path.exists(current_year + '\\'+ current_month + '\\' + current_day) == False:
        os.chdir(current_year + '\\'+ current_month)
        os.mkdir(current_day)
        os.chdir(current_day)
        with open('Blocked_IPs.txt', 'a+') as Blocked_IPs:
            to_file = ('###############{}###############\n'.format(current_time)+'\n'.join(blocked_ips))+'\n'
            Blocked_IPs.write(to_file)
        os.chdir('D:\\programs\\Python310\\Projects\\net_sec')
    else:
        os.chdir(current_year + '\\' + current_month + '\\' + current_day)
        with open('Blocked_IPs.txt', 'a+') as Blocked_IPs:
            to_file = ('###############{}###############\n'.format(current_time)+'\n'.join(blocked_ips))+'\n'
            Blocked_IPs.write(to_file)
        os.chdir('D:\\programs\\Python310\\Projects\\net_sec')

    blocked_ips_result = 'Following IP\s or URLs were Blocked!: \n'+'\n'.join(blocked_ips) +'\n'
    duplicate_ips_result = 'Skipped!...Found duplicates IP\s for: \n'+'\n'.join(duplicate_ips) +'\n'
    invalid_ips_result = 'Skipped!..Invalid IP\s for \n'+'\n'.join(invalid_ips) +'\n'

    with open('fortigate_ips.txt', 'r') as f, open('fortigate_urls.txt', 'r') as u:
        current_commit_stats = len(blocked_ips)
        ips_stats = len(f.readlines())
        urls_stats = len(u.readlines())
        total_stats = ips_stats + urls_stats

    if bool(duplicate_ips) == True and bool(blocked_ips) == False:
        print(1)
        return duplicate_ips_result, current_commit_stats, ips_stats, urls_stats, total_stats
    elif bool(duplicate_ips) == True and bool(blocked_ips) == True and bool(invalid_ips) == True:
        print(2)
        return invalid_ips_result + duplicate_ips_result + blocked_ips_result, current_commit_stats, ips_stats, urls_stats, total_stats
    elif bool(invalid_ips) == True and bool(blocked_ips) == True:
        print(3)
        return invalid_ips_result + blocked_ips_result, current_commit_stats, ips_stats, urls_stats, total_stats
    elif bool(invalid_ips) == True and bool(blocked_ips) == True:
        print(4)
        return invalid_ips_result + blocked_ips_result, current_commit_stats, ips_stats, urls_stats, total_stats
    else:
        print(5)
        return (blocked_ips_result), current_commit_stats, ips_stats, urls_stats, total_stats

###GRADIO GUI###
#f = open('fortigate_ips.txt', 'r')
#fortigate = (f.read().split())
#f.close()
with gr.Blocks(title = 'Switcher') as switches_ver:
    gr.Markdown('Welcome to IPBlocker')
    with gr.Tab(label = 'IPBlocker'):
        with gr.Row():
            with gr.Column():
                ips_to_block = gr.Textbox(label = "IPs", lines = 10, placeholder=('Please fill Ips to block'))
                block_btn = gr.Button('Block')
                #ip_lookup = gr.Dropdown(fortigate)
            with gr.Column():
                output_textbox = gr.Textbox(label = "Results", lines=10)
                with gr.Row():
                    current_commit_stats = gr.Textbox(label = 'Current IP\s or URLs added to block:')
                    forti_ips_stats = gr.Textbox(label = 'Total blocked IP\s on Fortigate: ')
                    forti_urls_stats = gr.Textbox(label = 'Total URLs blocked on Fortigate')
                    forti_total_stats = gr.Textbox(label = 'Total blocked IP\s and URLs on Fortigate')
                    block_btn.click(fn=block_ip, inputs = ips_to_block, outputs = [output_textbox, current_commit_stats, forti_ips_stats, forti_urls_stats, forti_total_stats])

    with gr.Tab(label = 'Switcher'):
        with gr.Row():
            with gr.Column():
                switch_box = gr.Textbox(label = 'Switches', lines = 10, placeholder='Please fill switches IPs...')
                show_ver = gr.Button('Show current switches version')
                upgrade_ver = gr.Button('Upgrade selected switches')
            with gr.Column():
                output_textbox = gr.Textbox(label='Results',lines = 10)
                output_file = gr.File(['switches_successful_results.txt', 'switches_failed_results.txt'])
                show_ver.click(fn=switch_ver, inputs = switch_box, outputs = [output_textbox, output_file])
                upgrade_ver.click(fn=block_ip, inputs = ips_to_block, outputs=[output_textbox, output_file])

switches_ver.queue(concurrency_count=20, max_size=20).launch()

full error traceback:
Traceback (most recent call last):
  File "D:\programs\Python310\lib\site-packages\gradio\routes.py", line 273, in run_predict
    output = await app.blocks.process_api(
  File "D:\programs\Python310\lib\site-packages\gradio\blocks.py", line 757, in process_api
    predictions = self.postprocess_data(fn_index, result["prediction"], state)
  File "D:\programs\Python310\lib\site-packages\gradio\blocks.py", line 721, in postprocess_data
    block.postprocess(prediction_value)
  File "D:\programs\Python310\lib\site-packages\gradio\components.py", line 2147, in postprocess
    "name": processing_utils.create_tmp_copy_of_file(
  File "D:\programs\Python310\lib\site-packages\gradio\processing_utils.py", line 323, in create_tmp_copy_of_file
    shutil.copy2(file_path, file_obj.name)
  File "D:\programs\Python310\lib\shutil.py", line 434, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "D:\programs\Python310\lib\shutil.py", line 254, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'o'

A: If you are using yield you can iterate only once. It doesn't keep data on memory for all time. Check this out: https://stackoverflow.com/a/231855/17318894

A: The 'o' came from the timeout text "Could not connect..."
From what I understand about gradio, the result, for both yield and return seems to be processed to outputs, which is output_textbox and output_file
As the yield result is timeout (similar goes for results yield case):

*

*output_textbox = timeout[0] = 'C'

*output_file = timeout[1] = 'o'
If you want to remove the errors, you should change the yield result to be compatible to the outputs.
For example:
yield timeout, ['switches_successful_results.txt', 'switches_failed_results.txt']


text:
Q: Good practices to organize attributes in a class? I have in my class many parameters, many of which are related with each others.
First, I had something like:
public class MyClass {
    private int[] filterA = {4,40};
    private int filterAPasses = 3;

    private String dataFilePath = "...";
    private int dataChannels = 4;
    private int dataFreq = 300;

    private int[] timeRange = {30,40};
}

Well, I wasn't really satisfied, not easily readable in the declarations themselves, neither very handy to use , because I had many filterA[0] where I had to remember the meaning of index 0, and index 1.
So instead of that, I did :
public class MyClass {
    private interface filterA {
        int left = 4;
        int right = 40;
        int passes = 4;
    }

    private interface dataFile {
        String path = "...";
        int channels = 4;
        int frequency = 300;
    }

    private interface timeRange {
        int from = 30;
        int to = 40;
    }
}

which is way better, and allows me to do nice things such as filterA.left, or even adding javadoc to left
But somehow I feel bad to use interface to do that. Is that a good way ? are there better practices for such things ?
Edit:
Okay, I was completely wrong since I didn't know that using interface those parameters will be final.
It definitely isn't a good way. So what is a good way ?

A: Your second approach won't work: all fields in your interfaces are final, you won't be able to change any value (use classes instead of interfaces if you want to use the fields like in the first example).
The names in your second example aren't good practise: interface names shall start with a capital, (non-static) field names with a non-capital letter.

A: You should create Constants as follows,
public class FilterA {
  public static final int LEFT = 4;
  public static final int RIGHT = 40;
  public static final int PASSES = 4;
}

And different class for other type, each class will probably in separate file, and you can access above values as follows,
FilterA.LEFT

As "LEFT" is whole capital it is quite understandable that it is constant and you just want to use that. If you want to modify them you can remove final.

A: You don't want to use interfaces for defining constants, this is common antipattern as you can read from Effective Java (2nd edition), item 19. Interfaces should be only used to define types, not constants.
The answer Rahul gave is more a correct way. You may want to put a private constructor in FilterA to avoid the possibility of instantiate that class.
If you want, you can define accessor methods in the interface (getFilter - for example). This is what interfaces are made for (defining behaviour, not implementation).

A: You can use nested classes if you feel this is clearer.
public class MyClass {
    static class FilterA {
        int left = 4;
        int right = 40;
        int passes = 4;
    }
    private final FilterA filterA = new FilterA();

    static class DataFile {
        String path = "...";
        int channels = 4;
        int frequency = 300;
    }
    private final DataFile dataFile = new DataFile();

    private interface TimeRange {
        int from = 30;
        int to = 40;
    }
    private final TimeRange timeRange = new TimeRange();
}

or just use comments and meaningful names. (My preference)
public class MyClass {
    // fliter settings
    private int filterALeft = 4;
    private int filterARight = 40;
    private int filterAPasses = 3;

    // data path attributes
    private String dataFilePath = "...";
    private int dataChannels = 4;
    private int dataFreq = 300;

    // time range
    private int timeRangeFrom = 30;
    private int timeRangeTo = 40;
}

A: This is a bit subjective, but imho, you'd do better to go further and actually create classes for your data clumps, and have your class fields be references to instances of these classes instead of the primitives you have now.


text:
Q: Printing Entire QWebView Content does not result as expected I have been trying to get the QWebView printed. Initially it looked simple.
class myView:public QWebView
{
...
}

In one of the public Member Function of myView
  QPrinter printer;

  printer.setPageSize(QPrinter::A4);
  printer.setOrientation(QPrinter::Portrait);

  QPrintDialog *dlog = new QPrintDialog (&printer, this);

  qDebug () <<" HoHoooo.. Going to print ";
  if ( dlog->exec ()  != QDialog::Accepted)
  {
      qDebug () <<"Printing Not accepted.. :( ";

  }
  else
  {
      print(&printer);

  }

The output for the print is not getting properly. Kindly suggest, if i miss something?

A: Check the HTML code you want to print if it conforms to the HTML specification (use a HTML-checking tool!), even though your code renders fine to the screen, print-rendering is totally different code and thus can behave differently in case your HTML page does not conform to the standard.
In case it conforms, you can check printing in Safari or any other WebKit based browser to see, if it prints correctly there.


text:
Q: Can you remove 'description' from facebook feed dialog I'm using, but not married to, the feed dialog to share to a users wall on facebook.
var obj = {
method: 'feed',
to: shareTarget,
from: shareTarget,
link: 'myLink.html',
picture: 'myPic.jpg',
name: 'auto populated if left blank',
caption:'also auto populated if left blank',
description:'again, also auto populated if left blank'
};

FB.ui(obj, callback);

The feed dialog contains/displays several params which I would prefer not display. However, when I remove the 'description' or 'caption' field from the above code they still appear in the feed dialog, displaying auto-generated copy such as 'apps.facebook.com'.
I've shared items to walls that do not contain these fields but can't figure out how it's done.
For example, this polling app will display only the few fields it needs with no description or caption (https://apps.facebook.com/my-polls/).
Any insight is appreciated.

A: I had the same issue and I found that putting a space in the description field instead of leaving it blank worked.


text:
Q: Access to the neighboring scope I have a few panels (ng-repeat) and respectively, I have a few scopes. A few scopes and few controllers.
When I close last panel (scope) I need refresh the data in last panel.

I have an update function in each controllers. But have can I run function from neighboring scope?
Does anybody have any ideas?

A: There are 2 options for your scenario:

*

*you could pass a callback to your panels that you trigger in your close method. The disadvantage of this approach is that you end up with some tight coupling between your components and the code can quickly become cluttered the more callbacks you begin passing around

*you could broadcast an event in your close method and have the other panels listen for this event. Here is a nice resource that explains how to do this (it's pretty straightforwards and with lots of examples): http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/


text:
Q: converting date to string and back to date in java In my program I am trying to convert the date to string to specified format and then back to date. I need the date to be in dd-MMM-yy format. So, I am converting the date to dd-MMM-yy format using SimpleDateFormat like,
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
String bookingDate = sdf.format(myDate);

The result is what I expected, that is 23-May-12 but when I convert the string back to date
using parse(), it is changing to Wed May 23 13:16:14 IST 2012.
Is there any way to convert the string back to date without changing format? I strictly need to pass the date object in the specified format to the query.

A:
when i convert the string back to date using parse(), it is changing to Wed May 23 13:16:14 IST 2012.

That is not true, It converts back to Date correctly, When you try to print Date instance,  It invokes toString() method and it has fixed formated output so if you want the formatted date you need to use format() method
In short parse method parses the String to Date there is no property of Date which holds format so you need to use format() method anyhow

A: How are you passing the date object in your query, if you are simply appending date in your query string why you need to convert your string date back to date object ? And If you are using prepared statement then you need not worry about the format. And as suggested above Date object does not hold any format information

A: If You strictly need to pass the date object then there is no worries about its format as Date object has understanding with its format either Java, any java framework or SQL..
And if you are passing the date directly in sql query (concatenating) then you can pass Date String in the same format you see in DB, it will process the same correctly.

A: You can use DateFormat.getDateInstance(DateFormat.SHORT, <locale>).parse(myDate);.
You will, however, have a date in a standard format like dd/MM/yy, not custom. Template depends on which Locale you use.
You can try building your own Pattern using the standard Java Library or through ThreeTen/JSR-310

A: We now have a more modern way to do this work.
java.time
The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome confusing old classes, java.util.Date/.Calendar et al.
Date-only class
The new framework offers a class, LocalDate, to represent a date-only without any time-of-day nor time zone.
By the way, using two-digits for year is asking for trouble. I strongly recommend using four-digit years whenever possible. The java.time framework assumes any two-digit years are in the 20xx century, years 2000 to 2099 inclusive.
To parse the string, specify the expected format. You are not using any of the standard ISO 8601 formats, so we must define a format pattern. Specify a Locale that includes the language we expect to find for name-of-month.
// Parse String representation.
String input = "23-May-12";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "d-MMMM-yy" , Locale.ENGLISH );  // Using four "M" characters means we expect the full name of the month.
LocalDate localDate = formatter.parse ( input , LocalDate :: from );

To go the other direction, to generate a string representation of the date value, we can recycle the same formatter.
    // Generate String representation.
    String output = localDate.format ( formatter );

Dump to console.
    System.out.println ( "input: " + input + " → localDate : " + localDate );
    System.out.println ( "localDate : " + localDate + " → output: " + output );

When run.

input: 23-May-12 → localDate : 2012-05-23
localDate : 2012-05-23 → output: 23-May-12


text:
Q: Using AngularJS custom field validation I'm using $asyncValidators to validate a field but would like it to trigger only when the field loses focus and not on every change. Is this possible or must I use something else than $asyncValidators?
Code example of using $asyncValidators (taken from the documentation)
ngModel.$asyncValidators.uniqueUsername = function (modelValue, viewValue) {
    var value = modelValue || viewValue;

    // Lookup user by username
    return $http.get('/api/users/' + value).
        then(function resolved() {
            //username exists, this means validation fails
            return $q.reject('exists');
        }, function rejected() {
            //username does not exist, therefore this validation passes
            return true;
        });
};

A: I think you can use the ngModelOptions directive to achieve that.
ng-model-options="{ updateOn: 'blur' }"

You can force your model to be "evaluated" only on some predefined events.
In your case, you want to evaluate it when you leave the field, so on the blur event.
Official documentation of ngModelOptions directive


text:
Q: How can I find out the value of the keys in a dictionary object? I have this API call:
HttpResponse<string> response =
    Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word.Name)
    .header("X-Mashape-Key", "xxxx")
    .header("Accept", "application/json")
    .asJson<string>();

Here is the class for the HttpResponse:
public class HttpResponse<T>
{
    public HttpResponse(HttpResponseMessage response);

    public T Body { get; set; }
    public int Code { get; }
    public Dictionary<string, string> Headers { get; }
    public Stream Raw { get; }
}

I have no problem getting the Body (response.Body) or the Code but what I would like to do is to get this header:
[7] = {[X-RateLimit-requests-Remaining, 2498]}

Can someone tell me how I could check the response returned and find out the value of the X-RateLimit-requests-Remaining?

A: Dictionaries have something called an indexer. The datatype of your indexer is the datatype of your Key (Dictionary<Key,Value>).
Indexers are similar to property getters and setters and are implemented like this:
public TValue this[TKey index]
{
    // this will return when being called e.g. 'var x = dictionary[key];'
    get { return whatever; }

    // and here 'value' is whatever you pass to the setter e.g. 'dictionary[kex] = x;'
    set { whatever = value; }
}

In you case that would be:
// "Key" is just an example, use "X-RateLimit-requests-Remaining" instead ;)
response.Headers["Key"];


text:
Q: Graph Theory - Finding Number of paths
Consider a directed graph $D(n)$ whose vertex set $V$ consists of the integers
$1,2,\dots,n$, and whose edge set $E$ consists of ordered pairs of integers $(i,j)$ whenever $i < j$. In other words, there is a directed edge from $i$ to $j$ if and only if $i < j$. For example, the figure below shows $D(5).$

a. In $D(n)$, a path from $1$ to $n$ is described by a sequence of vertices $v1,v2,...,v_k$ where $v_1= 1$, $v_i< v_{i+1}$ for $i = 1,\dots,k − 1$, and $v_k= n$. For $D(5)$ above, please list all the paths from $1$ to $5$. (There should be $8$ of them.)
b. Suppose $P = v_1,v_2,\dots,v_k$ is a $1$-to-$n$ path in $D(n)$. Let $f(P) = \{v2,\dots,v_{k−1}\}$. For example, for $D(5)$, $f(1,2,4,5) = \{2,4\}$. Please explain why $f$ is one-to-one.
c. Next, explain why $f$ is onto.
d. From b and c, we conclude that $f$ is a bijection. What then does this imply about the number of $1$-to-$n$ paths in $D(n)$? (Note: your answer here should be a generalization of your answer in (a).)

Any ideas or hint or ... ?

A: The map $f$ that you need for (b)-(d) is poorly explained, since the problem does not say what its codomain is. I'll expand on the definition a bit.

Let $P$ be the set of paths from $1$ to $n$ in $D_n$. Let $Q$ be the set of all paths, including the empty path, in the subgraph of $D_n$ induced by the vertices $\{2,\dots,n-1\}$. For any path $$\langle 1=v_1,v_2,\dots,v_{k-1},v_k=n\rangle\in P$$ let $f\big(\langle 1,v_2,\dots,v_{k-1},n\rangle\big)=\langle v_2,\dots,v_{k-1}\rangle\in Q$.

Example: In $D_5$ the sets $P$ and $Q$ contain the following paths:
$$\begin{array}{l|l}
P&Q\\ \hline
\langle 1,5\rangle&\varnothing\\
\langle 1,2,5\rangle&\langle 2\rangle\\
\langle 1,3,5\rangle&\langle 3\rangle\\
\langle 1,4,5\rangle&\langle 4\rangle\\
\langle 1,2,3,5\rangle&\langle 2,3\rangle\\
\langle 1,2,4,5\rangle&\langle 2,4\rangle\\
\langle 1,3,4,5\rangle&\langle 3,4\rangle\\
\langle 1,2,3,4,5\rangle&\langle 2,3,4\rangle
\end{array}$$
The first column of this table actually answers (a). Parts (b) and (c) are very straightforward, especially if you realize that a path in $D_n$ is completely determined by the set of vertices: if we have the set, we can always order it correctly. Thus, $P$ corresponds in a straightforward way to the subsets of $\{1,\dots,n\}$ that contain both $1$ and $n$, and $Q$ corresponds in an equally straightforward way to the subsets of $\{1,\dots,n\}$ that contain neither of $1$ and $n$.
For (d) they want you to use to use the fact that $P$ and $Q$ have the same cardinality, since there is a bijection between them, and to notice that $|Q|$ is very easy to calculate. If you have trouble here, try counting by hand the paths from $1$ to $n$ in $D_n$ for $n=1,2,3,4,5$; if you do it right, you'll see a pretty obvious pattern.

A: I'll leave (a) to you.
For (b) and (c), note that a path from $1$ to $n$ will always start at $1$ and end at $n$, so paths determine, and are uniquely determined by, the set of intermediate vertices on the path. Note that in (c), I'm assuming the codomain is the set of all subsets of $\{2,...,n-1\}$.
For (d), since a path is uniquely determined by the set of intermediate vertices on the path, of which there are $n-2$ (for $n\geq 2$), then there are $2^{n-2}$ possible paths from $1$ to $n$ for $n\ge2$. Of course, for $n=1$, there's only one path, but that's the only one that doesn't really fit the pattern. I suppose that you could say that there are $\left\lceil 2^{n-2}\right\rceil$ paths from $1$ to $n$ possible, if you wanted it to hold for all $n$.


text:
Q: online database for C# window application I'm going to develop a POS system for medium scale company
and the requirement for me is to make all data on time for all of their branches
while in my mind, move the server from local to web would solve this problem
but, i never done any online server for window application
may i know what is the best option for use as secure database ?
such as SQL can handle this well ?
i tried to google but all of the result return is not what i want
may i know what will you do when you facing this problem ?
my knowledge on coding is just VB and CS
also SQL for database
i would like to learn new if there is better option
i hope it is impossible to access by anonymous and it is store secure at back-end only

A: What you probably want to do is create a series of services exposed on the internet and accessed by your application.  All database access would be mediated by these services.  For security you would probably want to build them in WCF and expose them through IIS.  Then your Windows application would just call these services for most of its processing.
If you design it properly you could also have it work with a local database as well so that it could work in a disconnected manner if, for example, your servers go down.

A: Typically you don't move the server off of the site premises.
The problem is that they will go completely down in the event your remote server is inaccessible.  Things that can cause this are internet service interruption (pretty common), remote server overloaded (common enough), basically anything that can stop the traffic between the store location and your remove server will bring them to their knees.  The first time this happens they'll scream.  The second time and they'll want your head due to the lost sales.
Instead, leave a sql server at each location.  Set up a master sql server somewhere.  Then set up a VPN connection between the stores and this central office.  Finally, have the store sql boxes do merge replication with the central office.  Incidentally, don't use the built in replication, but an off the shelf product which specializes in replicating sql server.  The built in one can be difficult to learn.
In the event their internet connection goes dark the individual stores will still be able to function.  It will also remain performant as all of the desktop app traffic is purely to the local sql box.
Solving replication errors is much easier than dealing with a flaky ISP.

A: I would recommend you to check Viravis Platform out.
It is an application platform that also can be used just as an online database for any .NET client with the provided SDK. It has its own generic windows and web clients and some custom web solutions for some specific applications.
You may be using it as a complete solution or as a secure online database backend.


text:
Q: Resizing colorbox after loading HTML content into a DIV I've ventured to any and all of the posts here about colorbox resizing issues, div properties and numerous other things!  Anyway, this very VERY simple piece of code is driving me up a wall and I wonder if it couldn't be answered?

Above is the code (which, I would imagine - should work like a charm).  I've tried using a $.get and putting the resize in a callback, using timeouts and separating things with functions.
I've also verified that nothing is broken, the text is being loaded (doing an alert with $("#text") as the message shows me the loaded text.  Also I can specify widths and/or heights for the resize function and they work find, however, I can't do this based on the loaded content.
Sorry for the long-winded post... any ideas why in the world this thing will not resize?

A: Try waiting until the content is actually loaded.

A: Thanks to anyone who read and tried to come up with a reason to why this didn't work, however, I finally found a work-around.
It appears that for some reason, even putting the resize() in a success callback, it was still getting called too early.  I was able to open firebug and manually enter the colorbox.resize() function in the command line and it worked just fine after loading, even though the callback failed.
So what I did was this
$(document).ready(function () {
        jQuery.ajaxSettings.async = false;

        $('#text').load('<%= Model.FileLocation %>');
        $.fn.colorbox.resize();
});

Setting the async in ajax to false forced it to be called in turn, and now it works great and is loading very quickly.


text:
Q: Extract value from R output I am wondering how to write the Out of Bag Error (OOB) values below to a csv. They are not included when I type summary(rf). Extracting values from an object summary is the only other approach I have tried and I am out of ideas now. I have also included my write to table function which works with objects.
Code:
rf <- tuneRF(x = Pdata[, Imppredictors], y = Pdata[, Response], mtryStart = 1,
             doBest = TRUE)
mtry = 1  OOB error = 0.6832447
Searching left ...
Searching right ...
mtry = 2    OOB error = 0.6329592
0.07359804 0.05
mtry = 4    OOB error = 0.7310359
-0.1549495 0.05

csv function:
write.table(Mse, file = "test1.txt", sep = " ", quote = FALSE, append = FALSE)

A: From the tuneRF documentation:

If doBest=FALSE (default), it returns a matrix whose first column contains the mtry values searched, and the second column the corresponding OOB error.

So:
rf <- tuneRF(x = Pdata[, Imppredictors], y = Pdata[, Response], mtryStart = 1)

And then you can write.table(rf, ...)


text:
Q: My HyperV Virtual Server stops with critical error I on microsoft hyper v create a server, i installing on it linux debian, but while installation this server stopped with critical error and if I start it, he stops after approximaly 1 minute.
How to debug it?
Where i can find information about this critical error because in a events viewer I can't find any information about it.

A: What version of Hyper-V (RTM or R2), do you have all the latest hotfixes installed?
I assume the VM is server that is experiencing the critical error?
Debian isn't supported on Hyper-V (see supported guest list - http://www.microsoft.com/windowsserver2008/en/us/hyperv-supported-guest-os.aspx).. saying that people have successfully got this up and running (see http://wiki.debian.org/WindowsServerHyperV)
I suggest checking that your VM has only one v.CPU and you are using the legacy network adapter.
Good luck, please post your results, I am interested to see if you can get it working.

A: I need more info (like what system is on your virtual server). Assuming that is not linux -

*

*Enable bootlog at startup by going to safe mode with F8

*Mount / install the disk somewhere else and analyse the log in %SystemRoot%\Ntbtlog.txt


text:
Q: Porting current number and forwarding to new phone number So, a little context for you first: Our app only has forwarding and text messaging capabilities for our clients. Basically, we just set up a forwarding number in twilio for our client and they use that as their public number (on websites, advertisements, Google, etc.). Then when their customers call that number we ask them a quick question using the phone menu before forwarding the call onto their regular land line and sending them a text message later.
What do you suggest we do when someone wants to keep their current number (land line or otherwise) as the main phone number (online, website, ads, etc.) instead of using a new forwarding number?
Would they port their current number over to twilio, and then just get a new number with their main phone provider that we'd forward the ported number to?
I'm sure this is a common problem, so wondering what the best way approach it would be.
Thanks!

A: Twilio evangelist here.
If they want to continue using their POTS equipment then what you described is  the only option.  If they were able to move over to a pure VoIP system then there are more options.
You could use Twilio Client to build web and/or mobile VoIP apps for them.  Or you could stand to a VoIP server (like Astrisk or FreeSWITCH) for them to connect VoIP phones to.
Of course they would still have to have an internet connection with for either of the VoIP options.
Hope that helps

A: This is an old question but it was at the top of my search for questions about porting for sms capabilities. Having worked 20 years in B2B telecom I can answer the last part of this in case anyone else needs to know.
If you go to any provider and request a number to be ported from the existing provider, the "losing carrier" cannot refuse to port the number as long as the number is active. I stress this point because if they are past-due, they still have to port it. But if the service is temporarily or permanently disconnected they don't and usually won't port it. The port has to come from the company winning the business. Don't contact the existing carrier about it because they can't "push" the number out. Instead, the new carrier will have you fill out a Letter of Authorization (LOA) to port it that gets submitted with the port request. Its very important that all of the details on this form match the billing record or it will get declined. So normally you would provide a copy of the current bill with the LOA.


text:
Q: explanation of List how it is being used in the code public static void main(String a[]){
        String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
        List<String> strList = Arrays.asList(strArr);
        System.out.println("Created List Size: "+strList.size());
        System.out.println(strList);

I was looking for the explanation of the code
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};

this line means that we are declaring a variable strArr of string type  and in the array we are declaring 5 variables is that correct
Then I am unable to clearly understand second line
List<String> strList = Arrays.asList(strArr);

is strList an object of List<String>?

A: With the below code you are converting your String array to a fixed size list.
List<String> strList = Arrays.asList(strArr);
While converting an Array to a List. You can perform all operation of List to your newly created fixed size list. Exmaple Sorting a List as below.
Collection.sort(strList);
But with the above code you cannot add element into your list. While adding element in list it will throw you an exception. Sample code as below.
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
strList.add("Spring"); // This line will throw exception
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);

If you want to add element to your list you have to convert your String Array to List as below.
List<String> strList = new ArrayList<String>(Arrays.asList(strArr));
Hope this will help you to understand it

A: Arrays.asList() is a static util for java. It creates a List copying the values from your array of strings (or any kind of primitive/object).
You can check the documentation on docs.oracle. The benefit of a List is that the size is variable, so you can add or remove elements (in short, it has no fixed size) while an array has a fixed size. This is true for List(Mutable list by default) unless you use an Immutable List which has a fixed size like an array.

A: Arrays.asList(T... arr) is a static method, sort of a utility, that takes an array as input and returns a List<T> backed by the input array. So, yes strList is a List.
To answer your question in the comments about "backed by":
From the Javadoc: "Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)".
So, the list is backed by the array in the sense that all changes made to the contents of the list will be reflected in the array. Example:
    String[] a = new String[] {"1", "2", "3"};

    List<String> l = Arrays.asList(a);
    l.set(0, "0");

    assert a[0] == "0";


text:
Q: How to create json object for mongodb I'm building json object which I want to insert to an already existing collection in mongoldb with data using pymongo. The data looks like this:
[
 {
    "title": "PyMongo",

    "publication_date": "2015-09-07 10:00:00",
    "tags": ["python", "mongodb", "nosql"],
    "author": {
        "name": "David",
        "author_info": {
        "$oid": "1870981708ddb1a352189e25w"
        },
    },
    "date": {
             "$date": 1484071215000 },
   }
]

I noticed author has objectid and date is a timestamp, how can I create values for author_info and date and insert into mongodb?
I have a function that builds the values like this:
def build_json(title, pubctndate,taglist,author):
    json_ob = \
    [ {
       "title": title,
       "publication_date": pubctndate,
       "tags": tablets,
       "author": {
         "name": author,
         "author_info": {
         "$oid": " "
        },
       },
      "date": {"$date": },
     }]

   return json_ob

which I intend to call this way json.dumps(build_json(title, pubctndate,taglist,author))
Please bear with me, I'm a complete beginner.


text: Q: Applying some edit distance function in pyspark I have a question for you.. Which is the best way to make the comparisons between a recognized word and a set of possible words saved in my dataset, I tried to find the word that is similar through a score based on a weighted average between: Levenshtein, Edit and Jako distances. But, I have a lot of data to make the comparisons around 75 milions of comparison data.. What you can suggest to me??


text:
Q: How to handle exceptions inside async block java I am making 2 https requests one after the other. I want to return with error state in case 1st request fails before making another request.
private CompletionStage<WSResponse> reverseGeocode(Double latitude, Double longitude) throws AuthenticationException {
    WSRequest complexRequest = ws.url(SECO_URL);

    return complexRequest.post(GRANT_TYPE + "=" + PASSWORD + "&" + USERNAME + "=" + SECO_USERNAME + "&" + PASSWORD
            + "=" + SECO_PASSWORD)
            .thenCompose(res -> {
                String authToken;
                try {
                    authToken = res.asJson().findValue("access_token").toString().replace("\"", "");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    LOG.error(e.getMessage() + e.toString());
                    throw new AuthenticationException("Not able to authenticate user");
                }
                String url = configuration.getString("host.lbsUrl") + "/rgc/json?lat="
                        + latitude + "&lon=" + longitude;
                WSRequest requestToReverseGeocode = ws.url(url)
                        .setHeader(API_KEY, ST_SECO_X_API_KEY)
                        .setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE)
                        .setHeader(AUTHORIZATION, "Bearer " + authToken);
                return requestToReverseGeocode.get();
            });

}

Above function gives me error that authentication error is unhandled. How do I return the error in this case?
Above code doesnt compile and the error is
play.sbt.PlayExceptions$CompilationException: Compilation error[unreported exception org.apache.http.auth.AuthenticationException; must be caught or declared to be thrown]
    at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
    at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
    at scala.Option.map(Option.scala:145)
    at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:49)
    at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:44)
    at scala.Option.map(Option.scala:145)
    at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:44)
    at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:40)
    at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
    at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
    at scala.util.Either$LeftProjection.map(Either.scala:377)
    at play.sbt.run.PlayReload$.compile(PlayReload.scala:17)
    at play.sbt.run.PlayRun$$anonfun$playRunTask$1$$anonfun$apply$2$$anonfun$apply$3$$anonfun$2.apply(PlayRun.scala:61)
    at play.sbt.run.PlayRun$$anonfun$playRunTask$1$$anonfun$apply$2$$anonfun$apply$3$$anonfun$2.apply(PlayRun.scala:61)
    at play.runsupport.Reloader$$anonfun$reload$1.apply(Reloader.scala:339)
    at play.runsupport.Reloader$$anon$3.run(Reloader.scala:44)
    at java.security.AccessController.doPrivileged(Native Method)
    at play.runsupport.Reloader$.play$runsupport$Reloader$$withReloaderContextClassLoader(Reloader.scala:40)
    at play.runsupport.Reloader.reload(Reloader.scala:337)
    at play.core.server.DevServerStart$$anonfun$mainDev$1$$anon$1$$anonfun$get$1.apply(DevServerStart.scala:118)
    at play.core.server.DevServerStart$$anonfun$mainDev$1$$anon$1$$anonfun$get$1.apply(DevServerStart.scala:116)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:405)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)

A: You can use exceptionally to catch any errors that may arise.
return complexRequest.post()
    .thenCompose(res -> {
        if (someCondition) throw new Step1Exception("Step 1 failed");
        // (...)
    }).thenCompose(res -> {
        if (someAnotherCondition) throw new StepNException("Step N failed");
        // (...)
    }).exceptionally(e -> ok("Got an error: " + e.getMessage()));

Notice that if someCondition is true, the second thenCompose is not executed.


text:
Q: How to derive hyperbolic tangent from SIR model's Recovered with Partial fraction decomposition approach There are follow SIR model's ODE:
\begin{eqnarray}
\begin{array}{ll}
\frac{dS}{dt} &=& -rSI & (1)\\
\frac{dI}{dt} &=& rSI - \gamma I & (2)\\
\frac{dR}{dt} &=& \gamma I & (3)\\
I + S + R &=& N, \text{ constant} & (4)
\end{array}
\end{eqnarray}

*

*infectives, say $I$,

*susceptibles, say $S$

*removals(recovered), say $R$.

determine $dR/dt$ as a function of time, $t$ .
from (3) and (4)
$$
\frac{dR}{dt}
= \gamma (N - R - S), (5)
$$
we can determine $S$ as a function of $R$ from
$$
\frac{dS}{dR}
= \frac{dS/dt}{dR/dt}
= -\frac{rSI}{\gamma I}
= -\frac{S}{\rho}
$$
Solving for $S$ gives $S = S_0 e^{-R/\rho}, \rho=\gamma/r$, and substituting in (5) gives
\begin{eqnarray}
\frac{dR}{dt} = \gamma(N - R - S_0e^{-R/\rho}), (6)
\end{eqnarray}
assuming $R / \rho$ is reasonably small, from 2nd order taylor
$$
e^{-R / \rho} \simeq 1 - R/\rho + (R / \rho)^2 / 2 - \cdots
$$
$$
\frac{dR}{dt} = \gamma[ N - R - S_0(1 - R/\rho + R^2 / 2\rho^2) ]\\
$$
i.e.
\begin{eqnarray}
\frac{dR}{dt}
= \gamma [ N - S_0 + (S_0 / \rho - 1)R - S_0R^2/2\rho^2 ], (7)
\end{eqnarray}
It can be verified that this equation has solution,
$$
\frac{dR}{S_0/(2\rho^2)R^2 +(1 - S_0 / \rho)R + (S_0-N)} = -\gamma dt\\
\frac{2\rho^2}{S_0}\frac{dR}{R^2 + \frac{2\rho^2}{S_0}(1 - S_0 / \rho)R + \frac{2\rho^2}{S_0}(S_0-N)} = -\gamma dt\\
$$
calc roots for Partial fraction decomposition.
\begin{eqnarray*}
r
&=& \frac{- \frac{2\rho^2}{S_0}(1 - S_0 / \rho) \pm \sqrt{\frac{4\rho^4}{S_0^2}(1 - S_0 / \rho)^2 - 4\frac{2\rho^2}{S_0}(S_0-N)}}{2}\\
&=& \frac{- \frac{2\rho^2}{S_0}(1 - S_0 / \rho) \pm
\sqrt{\frac{4\rho^4}{S_0^2}\{(1 - S_0 / \rho)^2 - 2\frac{S_0}{\rho^2}(S_0 - N ) \}}  }{2}\\
&=& \frac{\rho^2}{S_0}\{ (S_0 / \rho - 1) \pm
\sqrt{(1 - S_0 / \rho)^2 - 2\frac{S_0}{\rho^2}(S_0 - N ) } \}\\
&=& \frac{\rho^2}{S_0}\{ (S_0 / \rho - 1) \pm
\sqrt{(1 - S_0 / \rho)^2 + 2\frac{S_0}{\rho^2}( N - S_0) } \}\\
&=& \frac{\rho^2}{S_0}( \pm \alpha + \beta )\\
\end{eqnarray*}
where
$$
\alpha = \sqrt{(1 - S_0 / \rho)^2 + 2\frac{S_0}{\rho^2}( N - S_0) } \\
\beta = (S_0 / \rho - 1)\\
$$
roots are:
$$
r_1 = \frac{\rho^2}{S_0}( +\alpha + \beta )\\
r_2 = \frac{\rho^2}{S_0}( -\alpha + \beta )\\
$$
do Partial fraction decomposition,
$$
\frac{2\rho^2}{S_0}\frac{dR}{(R-r_1)(R-r_2)} = -\gamma dt\\
\frac{2\rho^2}{S_0} \int \frac{1}{r_1-r_2} (\frac{1}{(R-r_1)} - \frac{1}{(R-r_2)}) dR = - \int \gamma dt\\
$$
from $r_1 - r_2 = \frac{\rho^2}{S_0}2\alpha$,
$$
\frac{1}{\alpha} \int (\frac{1}{(R-r_1)} - \frac{1}{(R-r_2)}) dR = -\int \gamma dt\\
\ln{(R-r_1)} - \ln{(R-r_2)} = - \alpha \gamma t + \phi\\
\ln{\frac{R-r_1}{R-r_2}} = - \alpha \gamma t + \phi\\
\frac{R - r_1}{R - r_2} = e^{-\alpha \gamma t + \phi}\\
R - r_1 = (R - r_2)e^{-\alpha \gamma t + \phi}\\
(1-e^{-\alpha \gamma t + \phi})R = r_1  - r_2 e^{-\alpha \gamma t + \phi}\\
R = \frac{ r_1  - r_2 e^{-\alpha \gamma t + \phi}}{1-e^{-\alpha \gamma t + \phi}}\\
$$
substituting $r_1, r_2$,
\begin{eqnarray*}
R
&=& \frac{ \frac{\rho^2}{S_0}(\alpha + \beta)  - \frac{\rho^2}{S_0}(-\alpha + \beta) e^{ -\alpha \gamma t + \phi}}{1-e^{-\alpha \gamma t + \phi}}\\
&=& \frac{\rho^2}{S_0}\frac{ \alpha(1 + e^{ - \alpha \gamma t + \phi}) + \beta(1-e^{ \alpha \gamma t + \phi}) }{1-e^{- \alpha \gamma t + \phi}}\\
&=& \frac{\rho^2}{S_0}\left( \beta + \frac{ \alpha(1+e^{- (\alpha \gamma t - \phi)})}{1-e^{- (\alpha \gamma t - \phi)}}\right)
\end{eqnarray*}
from
$$
\tanh{x/2} = \frac{1-e^{-x}}{1+e^{-x}}\\
$$
\begin{eqnarray*}
R
&=& \frac{\rho^2}{S_0}\left( \beta + \frac{ \alpha}{\tanh{(\frac{\alpha \gamma t}{2} - \phi')}}\right)
\end{eqnarray*}
actually, should be hyperperbolic tangnt (not Reciprocal),
how to derive hyperperbolic tangnt?

original paper:

*

*https://royalsocietypublishing.org/doi/pdf/10.1098/rspa.1927.0118