text:
Q: How to use the same colorbar for seaborn heatmaps? I have three subplots which have slightly different colorbars when plotted individually
I plotted the heatmaps as follows:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize = (20,10),sharey=True)

sns.heatmap(df,cmap=colormap,ax = axes[0])
sns.heatmap(df2,cmap=colormap,ax = axes[1])
sns.heatmap(df3,cmap=colormap,ax = axes[2])

I know that I can just set cbar = False for the first two plots, however as they are slightly different colorbars, the third colour bar will not represent all subplots. My first subplot ranges from 0-35, the second 0-36 and the third 0-37. I want a colorbar that encompasses the 0-37 range but obviously the colors will correspond to the wrong values for the first two subplots if I just do cbar = False.
How would I set up my subplots to contain just one colorbar which applies to all subplots, instead of three? Sorry about the lack of figures, I am unable to share them at this stage.

A:
I want a colorbar that encompasses the 0-37 range but obviously the colors will correspond to the wrong values for the first two subplots if I just do cbar=False.

In addition to setting cbar=False on the first two heatmaps, anchor all the heatmaps to the same colormap range:

*

*Either set vmin and vmax on each heatmap:
sns.heatmap(df,  ax=axes[0], vmin=0, vmax=37, cbar=False)
sns.heatmap(df2, ax=axes[1], vmin=0, vmax=37, cbar=False)
sns.heatmap(df3, ax=axes[2], vmin=0, vmax=37)
#                            ^       ^

*Or create a min/max norm using matplotlib.colors.Normalize:
import matplotlib.colors as mcolors
norm = mcolors.Normalize(0, 37)

sns.heatmap(df,  ax=axes[0], norm=norm, cbar=False)
sns.heatmap(df2, ax=axes[1], norm=norm, cbar=False)
sns.heatmap(df3, ax=axes[2], norm=norm)
#                            ^

Note that if you want to extract vmin and vmax automatically, ravel and stack the data:
values = np.hstack([d.values.ravel() for d in [df, df2, df3]])
norm = mcolors.Normalize(values.min(), values.max())


text:
Q: Multiple Ajax Request when refetching Events from fullcalendar.io I have the problem: hen i refetch the events from fullcalendar after i did the ajax request for inserting the event, he executes the ajax request multiple times. So the same event is twice or more in the database. Why that? Thanks!
dayClick: function(date, jsEvent, view) {
....
                    //alert(date.format());
     $('#btnYesNew').click(function(){
                            var startTimeParam = 'startTime=' + date.format() + "%20" + $('#startTime').val();
                            var endTimeParam = 'endTime=' + date.format() + "%20" + $('#endTime').val();
                            var purposeParam = 'purpose='+ $('#zweck').val();
                            var carIdParam = 'carId=' + $('#auto').val();
                            var departmentIdParam = 'departmentId=' + $('#abteilung').val();

                            if (view.name != 'month'){
                                startTimeParam = 'startTime=' + date.format('YYYY-MM-DD') + "%20" + $('#startTime').val();
                                endTimeParam = 'endTime=' +date.format('YYYY-MM-DD') + "%20" + $('#endTime').val();

                            }

                            var uri = startTimeParam + "&" + endTimeParam + "&" + purposeParam + "&" + carIdParam + "&" + departmentIdParam;

                            // Add Event to database
                            $.get( "kfz-buchung-ajax-rent-add?" + uri, function( data ) {

                            })
                                    .done(function(data){
                                        $('#myModalNew').modal('hide');
                                    })

                            $('#calendar').fullCalendar( 'refetchEvents' );
                        });

}

A: Solved, just used .off() before .click()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple script with onclick event works fine in Chrome but fails in Firefox I try to create an userscript using jQuery and JavaScript, but I am having a strange problem. I would like to add a onclick event to an image. It runs fine when I use Chrome (with TamperMonkey), but nothing happens when I click if using Firefox (with GreaseMonkey). However, the script is very basic. Assuming you have previously loaded jQuery and colorbox, here is what it is:
ok = "It works."

my_table = "";

$.colorbox({html:my_table,width:'33%',height:'33%'});

Uppercase the 'c' does not change anything. I also tried adding a javascript method attribute to a tag  but it does not work neither.
I really do not see why it would work in Chrome but not in Firefox. Could someone help me please?

A: I would do it this way :
ok = "It works."

my_table = "";

$.colorbox({html:my_table,width:'33%',height:'33%'});

$('.clickableImg').on('click', function(){
alert(ok);
});


text:
Q: Navigate programmatically to viewcontroller inside navigationcontroller & tabbarcontroller on another storyboard I need to go programmatically to a viewcontroller from another Storyboard. From here easy. But the problem is: that viewController is embedded in a navigation controller, and this one into a tabBarController (see image)

I've tried:
    let storyboard = UIStoryboard(name: "Inside", bundle: nil)

    let viewcontroller = storyboard.instantiateViewController(withIdentifier: "controller_id")
    let navigationController = UINavigationController(rootViewController: viewcontroller)

    self.present(navigationController, animated: true, completion: nil)

What I get with this is: I go to the correct controller, with navigation controller working, but no tabbarcontroller
Another try:
    let storyboard = UIStoryboard(name: "Inside", bundle: nil)

    let tabbar = storyboard.instantiateViewController(withIdentifier: "tab_id")
    let navigationController = UINavigationController(rootViewController: tabbar)

    self.present(navigationController, animated: true, completion: nil)

In this case, tabbar is working, but no navigationcontroller.
And... try number 3:
    let storyboard = UIStoryboard(name: "Inside", bundle: nil)
    let tabbar = storyboard.instantiateViewController(withIdentifier: "tab_id")
    let viewcontroller = storyboard.instantiateViewController(withIdentifier: "race_id")

    let navigationController = UINavigationController(rootViewController: tabbar)

    navigationController.pushViewController(viewcontroller, animated: false)

    self.present(navigationController, animated: true, completion: nil)

In this case, the behaviour is so strange... I appear in the correct controller, but with a back button. If I click I go to the same correct controller... with the tabbarcontroller... and then navigationcontroller disappear... nice :S
Any way to go programmatically to the correct controller and get working the tabbar & navigation?

A: Try out below code:
var storyBoard = UIStoryboard(name: "SecondStoryboard", bundle: nil)
var tabbar: UITabBarController? = (storyBoard.instantiateViewController(withIdentifier: "tabbar") as? UITabBarController)
navigationController?.pushViewController(tabbar, animated: true)

I have less knowledge in swift. Objective-C code for the above is:
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:nil];
    UITabBarController *tabbar = (UITabBarController *)[storyBoard instantiateViewControllerWithIdentifier:@"tabbar"];
    [self.navigationController pushViewController:tabbar animated:YES];


text:
Q: Has anybody ever successfully downloaded the Cities project in netlogo As shown in the following link, the developer says that the whole project codes are included in the zip archive, but after I downloaded and decompressed it, I can't find the file of Cities.nlogo which is the main procedure for the entire simulation project. I don't know if there are someone else encounter the same problem as mine, how do you solve it ?
http://ccl.northwestern.edu/cities/citiesmodel.shtml#download

A: I tried this just now:
% curl -OsS 'http://ccl.northwestern.edu/cities/cities.zip'
% unzip -l cities.zip | grep Cities.nlogo
error [cities.zip]:  missing 2 bytes in zipfile
  (attempting to process anyway)
    36365  09-26-07 15:21   cities/Cities.nlogo

as you can see there is definitely a Cities.nlogo file in there, but is also appears that the zip file is slightly corrupted ("missing 2 bytes in zipfile"). You might try extracting the archive with a different program? It extracted successfully for me using Archive Utility on Mac OS X.


text:
Q: Laplace transform of $\frac{1}{\sqrt{{1-e^{-{\sqrt{t}}}}}}$ I want to evaluate the following Laplace transform:
$$\int_0^{\infty}\frac{e^{-st}}{\sqrt{{1-e^{-{\sqrt{t}}}}}}dt$$
I tried using the substitution method, but it led me nowhere. I think the problem is arising because of the square root function.
I even tried integrating the function
$$\int\frac{1}{\sqrt{{1-e^{-\sqrt{t}}}}}dt$$
but it was of no luck. I am not able to understand how to proceed with the problem.
I have been using Mathematica for awhile now, but it returns the same expression. I can get a numerical answer for it using Mathematica, but I was wondering if there exists a functional form of the Laplace transform.
Is it possible to get the expression in the Laplace domain for this particular function?
I was looking up for the conditions that make the Laplace transform exist. But, the conditions are satisfied by this particular function.

A: We may start with the formal power series of $\frac{1}{\sqrt{1-x}}$:
$$\frac{1}{\sqrt{1-x}}=\sum_{n\geq 0}\frac{1}{4^n}\binom{2n}{n}x^n$$
in order to get
$$\frac{1}{\sqrt{1-e^{-\sqrt{t}}}}=\sum_{n\geq 0}\frac{1}{4^n}\binom{2n}{n}e^{-n\sqrt{t}}$$
and
$$\mathcal{L}\left(\frac{1}{\sqrt{1-e^{-\sqrt{t}}}}\right)(s) = \sum_{n\geq 0}\frac{1}{4^n}\binom{2n}{n}\int_{0}^{+\infty}2u e^{-(nu+su^2)}\,du $$
which equals
$$\sum_{n\geq 0}\frac{1}{4^n}\binom{2n}{n}\left(    \frac{1}{s}-\frac{\sqrt{\pi } n e^{\frac{n^2}{4 s}} \text{erfc}\left(\frac{n}{2 \sqrt{s}}\right)}{2 s^{3/2}}\right)$$
with a similar behaviour on $\mathbb{R}^+$ to the one of $s^{-3/4}$.


text:
Q: Is it possible to join different unrelated query results? There is a project in which some samples are taken from the rows in the database and analyzed. A separate query is made for each column. (We are doing something outside of the normal use of the relational database. We are aware of this, but we need to somehow read this data here. There are several reasons for this.)
Due to the large number of queries, the need for optimization arose.
There are lots of queries as follow:
SELECT col1 FROM Table1 WHERE <some conditions>;

col1

content11

content12

...

SELECT col2 FROM Table2 WHERE <some conditions>;

col2

content21

content22

...

SELECT coln FROM Tablen WHERE <some conditions>;
...

coln

...

The results of these queries are input to an algorithm. I want to query queries as a single query without rules. The first thing that comes to my mind here is UNION ALL.
SELECT col1 FROM Table1 WHERE <some conditions>
UNION ALL
SELECT col2 FROM Table2 WHERE <some conditions>

But this query lists all results under one column.

col1

content11

content12

...

content21

content22

...

Is it possible to write a query that will result in the following?

col1
col2
col3
...
col n

content11
content21
...
...

content12
content22
...
...

...
...
...
...

Although it is not suitable for relational database use, I want to combine the results of more than one query for various reasons. The main goal is to reduce the number of queries (thousands of queries are dropped). Instead of making query attacks to the database, it will reduce both performance and time costs with a small number of queries. We have a specific need here. We know this. Even so, the answers to be given will be an example of what can be done in the database.

A: If there is no natural relation between the rows of the different tables, you could perhaps zip them up using a generated Row_Number() value.
SELECT T1.col1, T2.col2, T3.col3, T4.col4
FROM (
    SELECT col1, ROW_NUMBER() OVER(ORDER BY col1) AS rn FROM Table1
) T1
FULL OUTER JOIN (
    SELECT col2, ROW_NUMBER() OVER(ORDER BY col2) AS rn FROM Table2
) T2 ON T2.rn = T1.rn
FULL OUTER JOIN (
    SELECT col3, ROW_NUMBER() OVER(ORDER BY col3) AS rn FROM Table3
) T3 ON T3.rn = COALESCE(T1.rn, T2.rn)
FULL OUTER JOIN (
    SELECT col4, ROW_NUMBER() OVER(ORDER BY col4) AS rn FROM Table4
) T4 ON T4.rn = COALESCE(T1.rn, T2.rn, T3.rn)
ORDER BY COALESCE(T1.rn, T2.rn, T3.rn, T4.rn)

The above allows for columns of different types. Obviously, the COALESCE() functions get increasing long.
If the values are all of the same data type, you can union the results and then feed them to a PIVOT. Something like:
SELECT PVT.col1, PVT.col2, PVT.col3, PVT.col4
FROM (
    SELECT 'col1' AS name, col1 AS val, ROW_NUMBER() OVER(ORDER BY col1) AS rn FROM Table1
    UNION ALL
    SELECT 'col2' AS name, col2 AS val, ROW_NUMBER() OVER(ORDER BY col2) AS rn FROM Table2
    UNION ALL
    SELECT 'col3' AS name, col3 AS val, ROW_NUMBER() OVER(ORDER BY col3) AS rn FROM Table3
    UNION ALL
    SELECT 'col4' AS name, col4 AS val, ROW_NUMBER() OVER(ORDER BY col4) AS rn FROM Table4
) T
PIVOT (
    MAX(val)
    FOR name IN (col1, col2, col3, col4)
) PVT
ORDER BY PVT.rn

See this db<>fiddle for a demo.
I expect you will also need to look into using dynamic SQL to generate your actual queries.


text:
Q: Type text without displaying text I need something like raw_input, but without displaying the text you are typing.
Also I tried getpass, but it still displays what I just typed.

A: getpass() doesn't work in IDLE. Try it in command prompt or on the terminal.

A: getpass work very well either in command prompt or in python script.
import getpass
x = getpass.getpass("Input something: ")
print x


text:
Q: How to refer to indexed words Given a text with an indexed word, say minimum, is it possible to have a command, call it \DEX{}, that would print a later occurrence of that word and link it to the original occurrence? For an on-screen pdf, this would allow the reader to bypass the index by just clicking on the word s/he wants to check while \Cpageref{minimum}(\Cpageref{index:minimum}?) would allow the reader similarly to bypass the index on a printed copy.
Could this work with a word defined in a tcolorbox? In my case, though, this would be icing on the cake because, the magnum opus being written for raw beginners, most words are not formally defined, only a very few are. Besides, I already use cleveref for that. So, just asking.
Here is a MWE (Not quite minimum because I need the ``quick and dirty hack'' due to Heiko Oberdiek which loads showidx and I included a tcolorbox just in case someone wants to try it.)
    \documentclass[11pt]{book}
    \usepackage{makeidx}
    \makeindex
    \usepackage{tcolorbox}
%==================Begin HYPERREF
    \usepackage[hyperfootnotes=false]{hyperref}%[pdfborder={0 0 0}]

%Begin the ``quick and dirty hack'' due to Heiko Oberdiek which loads showidx
\makeatletter
\ifHy@hyperindex
  \def\HyInd@ParenLeft{(}%
% Hook in \HyInd@@wrindex
  \let\HyInd@showidx\@empty
% Hook in \HyInd@@wrindex for package showidx
  \def\HyInd@showidx#1{%
    \@showidx{#1}%
    \if@nobreak
      \ifvmode
        \nobrak
      \fi
    \fi
  }%
% Load package showidx
  \let\siOrg@makeindex\makeindex
  \let\siOrg@@index\@index
  \let\siOrg@@wrindex\@wrindex
  \let\siOrg@index\index
  \RequirePackage{showidx}
  \let\makeindex\siOrg@makeindex
  \let\@index\siOrg@@index
  \let\@wrindex\siOrg@@wrindex
  \let\index\siOrg@index
% rest of hyperref part
  \@ifpackageloaded{multind}{%
    \let\HyInd@org@wrindex\@wrindex
    \def\@wrindex#1#2{\HyInd@@wrindex{#1}#2||\\}%
    \def\HyInd@@wrindex#1#2|#3|#4\\{%
      \ifx\\#3\\%
        \HyInd@org@wrindex{#1}{#2|hyperpage}%
      \else
        \def\Hy@temp@A{#3}%
        \ifx\Hy@temp@A\HyInd@ParenLeft
          HyInd@org@wrindex{#1}{#2|#3hyperpage}%
        \else
          \HyInd@org@wrindex{#1}{#2|#3}%
        \fi
      \fi
    }%
  }{%
    \def\@wrindex#1{\@@wrindex#1||\\}
    \def\@@wrindex#1|#2|#3\\{%
      \ifx\\#2\\%
        \protected@write\@indexfile{}{%
          \string\indexentry{#1|hyperpage}{\thepage}%
        }%
      \else
        \def\Hy@temp@A{#2}%
        \ifx\Hy@temp@A\HyInd@ParenLeft
          \protected@write\@indexfile{}{%
             \string\indexentry{#1|#2hyperpage}{\thepage}%
          }%
        \else
          \protected@write\@indexfile{}{%
            \string\indexentry{#1|#2}{\thepage}%
          }%
        \fi
      \fi
      \endgroup
      \HyInd@showidx{#1}%
      \@esphack
    }%
  }%
\fi
\makeatother
%End the ``quick and dirty hack'' due to Heiko Oberdiek which loads showidx

    \usepackage{cleveref}
%Begin the Sharpe code as modified by Schulz (2016-02-1)
\let\oldopenparen\(
\let\oldcloseparen\)
\def\({\protect\oldopenparen}
\def\){\protect\oldcloseparen}
\newcommand{\INDEX}[1]{\index{#1}}
%End the Sharpe code as modified by Schulz (2016-02-1)

\newcounter{abc}%
\newtcolorbox%
[%beginForReferences
use counter= abc,
number within=chapter,
number freestyle={\noexpand\thechapter.\noexpand\arabic{\tcbcounter}~\noexpand\mytitleagree},%Used to make for LONG titles in the references.
crefname={definition}{definitions},
Crefname={Definition}{Definitions},
]%endForReferences
{greement}
[2][]%
{%
detach title,
coltitle=black,
nameref={#2},%
before upper={\tcbtitle\quad},
code={\gdef\mytitleagree{#2}},%Used to make for LONG titles in the references.
title=DEFINITION \thetcbcounter,%
#1,%Required for references.
}%

    \begin{document}

A \textbf{minimum}\INDEX{minimum} of a function is blah blah.

\begin{greement}[label={abc:3-1}]{Maximum}
  An input whose output is larger than the outputs of nearby inputs
\end{greement}

\newpage

A function can have more than one $\backslash$DEX\{minimum\} ($\backslash$Cpageref\{minimum\}.)

(The command $\backslash$DEX would print  the word minimum and link it to the above occurrence. Hopefully, $\backslash$Cpageref would still work too.)

\printindex
    \end{document}

and here is the pdf (without \newpage and without the index page). Note the swhowidx on the upper right:

A: Perhaps I don't understand what you want to do but it seems to me that all you need to do is to make your \INDEX command add a \label{...} for your index entry and then your \DEX command refers back to it. As you want to make a link in the PDF file you should use \hyperref from the hyperref package to create this link, rather than \ref. For good measure, the \DEX should also insert the \Cpageref command.
Putting this together, your \INDEX and \DEX commands become:
\newcommand{\INDEX}[1]{\index{#1}\label{ind:#1}}
\newcommand\DEX[1]{\hyperref[ind:#1]{#1} (\Cpageref{ind:#1})}

I have made the automatically generated index \label's of the form ind:... so that they are less likely to conflict with other labels.
With this is place, here is the output on page 2, showing the mouse-over that's over the word minimum:

(I use skim to view PDFs and one of its many great features is this mouse-over. Acrobat, for example, doesn't do this.)
EDIT
As noted in the comments, this approach goes wrong when indexing mathematics, such as \INDEX{$\pm$}. This really isn't surprising because having mathematics inside an index or label key is almost certain to cause problems but this means that to cope with cases like these we need to be able to manually override the label that is being used. This is most easily done using the xparse package that allows use to define \INDEX and \DEX as
\NewDocumentCommand\INDEX{ O{#2} m}{\index{#2}\label{ind:#1}}
\NewDocumentCommand\DEX{ O{#2} m }{\hyperref[ind:#1]{#2} (\Cpageref{ind:#1})}

What this means is that \INDEX now has an optional argument, which defaults to the value of the second argument, that is used in the labels. So, to index $\pm$ we can now type
\INDEX[pm]{$\pm$}

Similarly, the \DEX also accepts an optional argument, so to refer to $\pm$ we would use \DEX[pm]{$\pm$}. We only need top use the optional arguments to \INDEX and \DEX if what we are indexing is "complicated" in some way, such as in mathematics mode, and otherwise we use these two macros as before.
[Incidentally, \newcommand also caters for optional arguments (see Defining macros with arguments). The only reason that  have used \NewDocumentCommand is that is has an easier mechanism for dealing with default values.]
Here is the full code:
\documentclass[11pt]{book}
    \usepackage{makeidx}
    \makeindex
    \usepackage{tcolorbox}
%==================Begin HYPERREF
    \usepackage[hyperfootnotes=false]{hyperref}%[pdfborder={0 0 0}]

%Begin the ``quick and dirty hack'' due to Heiko Oberdiek which loads showidx
\makeatletter
\ifHy@hyperindex
  \def\HyInd@ParenLeft{(}%
% Hook in \HyInd@@wrindex
  \let\HyInd@showidx\@empty
% Hook in \HyInd@@wrindex for package showidx
  \def\HyInd@showidx#1{%
    \@showidx{#1}%
    \if@nobreak
      \ifvmode
        \nobrak
      \fi
    \fi
  }%
% Load package showidx
  \let\siOrg@makeindex\makeindex
  \let\siOrg@@index\@index
  \let\siOrg@@wrindex\@wrindex
  \let\siOrg@index\index
  \RequirePackage{showidx}
  \let\makeindex\siOrg@makeindex
  \let\@index\siOrg@@index
  \let\@wrindex\siOrg@@wrindex
  \let\index\siOrg@index
% rest of hyperref part
  \@ifpackageloaded{multind}{%
    \let\HyInd@org@wrindex\@wrindex
    \def\@wrindex#1#2{\HyInd@@wrindex{#1}#2||\\}%
    \def\HyInd@@wrindex#1#2|#3|#4\\{%
      \ifx\\#3\\%
        \HyInd@org@wrindex{#1}{#2|hyperpage}%
      \else
        \def\Hy@temp@A{#3}%
        \ifx\Hy@temp@A\HyInd@ParenLeft
          HyInd@org@wrindex{#1}{#2|#3hyperpage}%
        \else
          \HyInd@org@wrindex{#1}{#2|#3}%
        \fi
      \fi
    }%
  }{%
    \def\@wrindex#1{\@@wrindex#1||\\}
    \def\@@wrindex#1|#2|#3\\{%
      \ifx\\#2\\%
        \protected@write\@indexfile{}{%
          \string\indexentry{#1|hyperpage}{\thepage}%
        }%
      \else
        \def\Hy@temp@A{#2}%
        \ifx\Hy@temp@A\HyInd@ParenLeft
          \protected@write\@indexfile{}{%
             \string\indexentry{#1|#2hyperpage}{\thepage}%
          }%
        \else
          \protected@write\@indexfile{}{%
            \string\indexentry{#1|#2}{\thepage}%
          }%
        \fi
      \fi
      \endgroup
      \HyInd@showidx{#1}%
      \@esphack
    }%
  }%
\fi
\makeatother
%End the ``quick and dirty hack'' due to Heiko Oberdiek which loads showidx

    \usepackage{cleveref}
%Begin the Sharpe code as modified by Schulz (2016-02-1)
\let\oldopenparen\(
\let\oldcloseparen\)
\def\({\protect\oldopenparen}
\def\){\protect\oldcloseparen}
%End the Sharpe code as modified by Schulz (2016-02-1)

\newcommand{\INDEX}[2][]{%
\if\relax\detokenize{#1}\relax\index{#2}\label{ind:#2}%
   \else\index{#2}\label{ind:#1}\fi%
}
\newcommand{\DEX}[2][]{%
   \if\relax\detokenize{#1}\relax\hyperref[ind:#2]{#2} (\Cpageref{ind:#2})%
   \else\hyperref[ind:#1]{#2} (\Cpageref{ind:#1})\fi%
}

\newcounter{abc}%
\newtcolorbox%
[%beginForReferences
use counter= abc,
number within=chapter,
number freestyle={\noexpand\thechapter.\noexpand\arabic{\tcbcounter}~\noexpand\mytitleagree},%Used to make for LONG titles in the references.
crefname={definition}{definitions},
Crefname={Definition}{Definitions},
]%endForReferences
{greement}
[2][]%
{%
detach title,
coltitle=black,
nameref={#2},%
before upper={\tcbtitle\quad},
code={\gdef\mytitleagree{#2}},%Used to make for LONG titles in the references.
title=DEFINITION \thetcbcounter,%
#1,%Required for references.
}%

    \begin{document}

A \textbf{minimum}\INDEX{minimum} of a function is blah blah.

\begin{greement}[label={abc:3-1}]{Maximum}
  An input whose output is larger than the outputs of nearby inputs
\end{greement}

\INDEX[pm]{$\pm$}
\newpage

A function can have more than one \DEX{minimum}.

A function can have more than one \DEX{minimum}.

\chapter{one} \textbf{Andy}\INDEX[]{Andy} \chapter{two} \textbf{Beth}\INDEX[]{Beth} \chapter{three} \textbf{Carla}\INDEX[]{Carla} \chapter`{four}` \DEX[]{Andy} \DEX[]{Beth} \DEX[]{Carla}.

\printindex

    \end{document}


text:
Q: Need help on trigger We have two object say A and B.
A has a lookup on B.
A has two text field Type and year.
B has one text field Type and year
I want to populate the lookup field of A by matching Type and Year field of A with type and Year field of B. Trigger code should be bulkified. Need help, its urgent. Thank you

A: Although you can do implement literally what you asked for, the better way is to create a third field on the objects which will be concatenation of type and year fields (if needed, you can also have them as unique/external Ids). This field can be populated using workflow. And your trigger and any other code can do the comparison using this new field.
Note: you also use a formula field for the third field if you're ok with some drawbacks, like this field not being indexed or potential of using this field as external Ids for data migrations.

A: Best approach is to keep the bulkified logic out of the trigger and put it in a class. Use the trigger events to call the class and you already know, you can put different operations into different methods based on your needs.


text:
Q: Update widget every 5 seconds I need to do the widget with Flutter like "N users watch on it now", where N comes from the backend, and I need to update it every 5 seconds if the widget is visible.
I tried a few approaches with Future.delayed and Timer like this ones:
            _timer = Timer(
              const Duration(seconds: 5),
              () {
                if (isCounterVisible) {
                  // load data
                }
              },
            );

  @override
  void dispose() async {
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
  }

But facing an issue that requests still sending after I go away from this screen, and unit tests failed for the reason A Timer is still pending even after the widget tree was disposed
Also, I have problems with determining is widget visible or not. I used library visibility_detector but seems it does not work with modal windows - the listener does not trigger when the modal window showed.

A: Timer.periodic will do the job, Also you can use cancelable future. You are missing  super.dispose();.
Timer? timer;

void initTimer() {
  if (timer != null && timer!.isActive) return;

  timer = Timer.periodic(const Duration(seconds: 5), (timer) {
    //job
    setState(() {});
  });
}

@override
void dispose() {
  timer?.cancel();
  super.dispose();
}

Now use initTimer() to start woker.

A: You could use a RiverPod StreamProvider.autoDispose wrapped around a Timer.periodic to wake up a Consumer Widget at regular intervals.  It will automatically go away when no longer referenced.


text:
Q: Get additional user details with PHP and mail() function I have a simple PHP script that sends a message to a specified email address with content from a HTML form using the mail() function (which I am aware is prone to spam).
I was wondering if it's possible to obtain additional information about the user's settings and input them in the sent mail.
Additional information could contain:

*

*Browser type and version Whether

*Javascript is enabled or disabled

*Operating system Resolution

If any of those are possible, that would be awesome.
Thanks,
Amit
EDIT: Thanks to @Stephen, I was able to use the $_SERVER['HTTP_USER_AGENT'] to get more info regarding the browser. However, when using the get_browser, it did not work. This is my code:
$browser = get_browser(null, true);

$message = 'From: ' . "\n\n" .
'Name: ' . $_REQUEST['name'] . "\n\n" .
'E-mail: ' . $_REQUEST['email'] . "\n\n" .
'Comments: ' . $_REQUEST['comments'] . "\n\n" .
'Details: ' . $_SERVER['HTTP_USER_AGENT'] . "\n\n" .
'Further: ' . echo ($browser);

Anyone knows the reason why?
Thanks!

A: Many details can be found by parsing the $_SERVER['HTTP_USER_AGENT'] variable. Example for my current computer is:
echo $_SERVER['HTTP_USER_AGENT']
// Output: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"

Remember that the contents of this are not a definite sign - browsers can and do (sometimes deliberately, sometimes accidentally) lie about their origins.
Note there are some functions like get_browser which wrap the HTTP_USER_AGENT to return some useful information too.


text:
Q: How to tunnel an outgoing connection via an incoming connection I guess the following will be considred a hack, but here goes:
I have machines A and B, and C.
B can open a connection to A, but A cannot open a connection to B (due to FW).
Work: A <--- B
Doesn't work: A ---> B
I want to be able to open a connection from A to B.
Is there a way (tool, preferably an OS tool) to allow a seamless connection initiation from A to B, quite possibly by tunneling on top of an existing connection from B to A?
At the end of the day I want to be able to successfully telnet from A to B:
telnet B [port number]

Or even to machine C, that B has access to, but A doesn't. From A:
telnet C [port number]

Later edit:
I've been offered with "static" tunneling. But, I would to have seamless solution.
For example, configure that a connection attempt to a certain range of destination IPs will be tunneled through B, where C is the dynamically varying destination. So telnet  80, will connect to the target passing through B

A: You haven't given any indication of what OS these boxes are running, so I'll assume unix.  If that's wrong, please retag your question.  That said:
B% ssh A -R 2200:B:22

will log you into A, while making a tunnel from A to B such that when on A you connect to port 2200, ssh tunnels your packets to port 22 on B.
B% ssh A -R 2200:C:22

will also work, provided that B has an uninterrupted network path to C; when on A you connect to port 2200, ssh tunnels you to port 22 on C.

A: If you are running UNIX or UNIX-like systems, look into OpenSSH and its Tunnel, TunnelDevice, and PermitTunnel config directives. If your systems support tun devices, it should be possible to configure ssh and sshd to create a point-to-point (layer 3, the default) or an ethernet (layer 2) tunnel between hosts A and B.
In either case, you will then have to configure the tun devices on A and B as you would any other network device (i.e. assign IP addresses, add routes).
And finally, if you want to allow connections from A to C through the A-B tunnel, you will need to ensure that host B allows IP packet forwarding.


text:
Q: making a custom css rule Is it possible to make a custom rule in Css as @media
I have a parent class and need to make  changes depended on this class as

1

2

1

2

so when i change the parentGreen the items inside their css changes too
@parentGreen{
    ul{
direction: ltr
}
}

@parentYellow{
  ul{
direction: rtl;
margin:10px;
}
}

A: Compiled version on this link is what you want.
Do you hear about less? Try searching about it. Less is better choice for creating nested css. You can write like this:
.parent {
    .child1 {
      color: blue;
    }
    .child2 {
      color: blue;
    }
}

Look this link.

A: This should work...
.parentGreen ul {
    direction: ltr
}

.parentYellow ul {
    direction: rtl;
    margin:10px;
}


text:
Q: Fatou's lemma equality
I found a sequence of functions that makes Fatou's lemma be a strict unequality, but I'm not able to find one that makes it be an equality.
Can you help me to find one?
Thank you

A: $S=[0,1]$ , $\mu=$ Lebesgue measure and $f_n=1$ on $S$ for all $n$


text:
Q: Как в QSettings прописать сохранение и загрузку состояния RadioBatton'ов Имеется 4 RadioButton кнопки. Расположены в GroupBox'е. Работают зависимо друг от друга. Каким образом прописать функции загрузки и сохранения настроек, чтобы отмеченная ранее кнопка при запуске программы уже была включена. Для примера привожу отлично работающий код, в котором прописаны настройки для 2-ух CheckBox'ов. Попытка по аналогии с ними прописать RadioButton'ы не увенчалась успехом.
void MainWindow::saveSettings()

{
settings->beginGroup("CheckBoxState");
settings->setValue("CheckBoxState", ui->checkBox->isChecked());
settings->setValue("CheckBoxState_2", ui->checkBox_2->isChecked());
settings->endGroup();

settings->setValue("RadioButton_1", ui->radioButton_1->isChecked());
settings->setValue("RadioButton_2", ui->radioButton_2->isChecked());
settings->setValue("RadioButton_3", ui->radioButton_3->isChecked());
settings->setValue("RadioButton_4", ui->radioButton_4->isChecked());
settings->endGroup();

}
void MainWindow::loadSettings()
{
settings->beginGroup("CheckBoxState");
ui->checkBox->setChecked(settings->value("CheckBoxState").toBool());
ui->checkBox_2->setChecked(settings->value("CheckBoxState_2").toBool());
settings->endGroup();

settings->beginGroup("RadioButtons");
ui->radioButton_1->setChecked(settings->value("RadioButton_1").toBool());
ui->radioButton_2->setChecked(settings->value("RadioButton_2").toBool());
ui->radioButton_3->setChecked(settings->value("RadioButton_3").toBool());
ui->radioButton_4->setChecked(settings->value("RadioButton_4").toBool());
settings->endGroup();

}

A: В функции void MainWindow::saveSettings(), в группе с RadioButton кнопками, нет строчки, которая открывала бы эту группу: settings->beginGroup("RadioButtons");.
После того как начало группы было обозначено, сохранение состояния кнопок заработало.


text:
Q: React & CSS Modules: how to style components without assuming their content This challenge is best illustrated with a little example:
import React from 'react'
import styles from './styles.pcss'

const Spinner = () => (

    {/*
 elements here*/}

)

export default Spinner

I'd like to change the position of the spinner component so this has to be done by the parent of the spinner. I see 3 solutions:

*

*Use a CSS rule targeting the
 tag (the root element of the spinner). I don't like this as the parent component is making assumptions about the internal structure of the spinner. If this tag changes, then all styles targeting it will break. I must be able to change the internal structure of my components without worrying about breaking many areas of my app.

*Pass a className down to the spinner component. It's much better as no assumption is made regarding the internals of the spinner. But as potentially every component could be positioned by their parent (a very common CSS task), I would have then to implement the className being passed down (incl. prop types validation, etc) for every component that would need custom styling. There must be a better solution.
import React, { PropTypes } from 'react'
import classNames from 'classnames'
import styles from './styles.pcss'

const Spinner = ({ className }) => (

    {/*
 elements here*/}

)

Spinner.propTypes = {
  className: PropTypes.string
}

export default Spinner

*Use a containing
 around the component I want to style:

<Spinner />

But this leads to bloated markup with unnecessary
s in situations where many elements have to be styled (like setting their positions).
What are your recommendations?
Thx

A: I'm leaning towards solution 3. This way, the styled component (spinner) stays clean and doesn't have to implement additional logic for getting a className, validating it and merging it with its own classes.
I wanted to see how 3rd party libraries implemented this scenario, and they favor solution 3 as well. Here's the related discussion about styling <FormattedMessage> of react-intl.
Furthermore, the wrapping
 would only be used when styling the container itself (typically, the position), not the contents of the component. And if many components have to be positionned, it's very likely that they are subcomponents, ex: <TodoItemList> and in this case the <TodoList> parent component would pass down the className to them as they won't exist outside this particular context.


text:
Q: Send Email PHP script cannot receive help!
i want to send email with php
this is the script
<?php
if (isset($_POST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_POST['email'] ;
$subject = $_POST['subject'] ;
$message = $_POST['message'] ;
mail("faimaknyus@gmail.com", $subject,
$message, "From:" . $email);
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='email.php'>
Email: <input name='email' type='text'>

Subject: <input name='subject' type='text'>

Message:

<textarea name='message' rows='15' cols='40'>
</textarea>

<input type='submit'>
</form>";
}
?>

when i send im not receive that message link to my experiment --> http://goo.gl/2bDcLL

A: This code is working. have tested it. Make sure your website SMTP configuration setting are set correctly. For that you can contact your hosting provider.


text:
Q: Create a snapshot of Mac that I can restore from What is the easiest way to create a snapshot of my Mac at its current state that I can use to do future re-installs from.
I want to be able to get my Mac back to a state where all my required apps are set up with their required settings and plugins and all my system settings are set to a state I'm happy with.

A: You can indeed go into recovery mode and use Disk Utility to image your drive to another location (like an attached USB drive or the like.
There are also 3rd party programs (SuperDuper, Carbon Copy Cloner, and others) that will make a bootable image of your drive to either a DISK image (think multiple copies) or directly to another drive so that drive is bootable. The advantage of these is that they can do it on a live system without booting into recovery mode. The only downside is that you'll have to pay for them.


text:
Q: Eclipse PHP (PDT): App::make(Filesystem::class) = Syntax Error unexpected class I use the following Statement quite a lot:
App::make(Filesystem::class)

and Eclipse PHP-Edition (PDT) underlines the class with red and marks this as an Error (on the left border): "Syntax Error, unexcpected class".
How can I fix this, that this is either eignored or even better, correctly recognized as correct syntax.
Thanks

A: Your project (or entire workspace), have interpreter set to PHP < 5.5.
For PHP >= 5.5 everything is ok on current snapshot (will be released in next week). See also PDT help: http://help.eclipse.org/mars/topic/org.eclipse.php.help/html/reference/preferences/php_interpreter.html
If error still exist you should report bug on PDT bugzilla: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=PDT


text:
Q: Datastructure : Many (A) to many (B) relationship, each link also has its own data (C) What is a datastructure that is suitable to keep many-to-many relationships (A-B), each link of relation has its own user-data (C)?
I care most about performance.
Example 1
There are many 2D circles in a scene.
They can grow and overlap each other (circle A & circle B).
I have to keep track the overlap zones (C), e.g. color.
Example 2
There are many investors (A), and stocks (B).
Each investor (A) has %ownership/occupation (C) for a company (B).
Example 3
This is a real situation.  I don't thing you need to read it.
 I provide it just in case.
I am using entity-component-based architecture.
There are many joysticks (A), each joystick can click buttons (B).
Note that the buttons (B) are those on the game screen. (not the Joystick hardware buttons)
I have to keep track (using C) whether a button is "hovered" by a joystick, and execute callback.
One of the reasons that I have to keep track is : there are criteria whether it should callback.
It is same as standard Windows button :-

*

*The button is released while hovered ... and ...

*The same button is hovered when start clicking.

One of other reasons is : a mouse can hover many buttons at once.  I have to record duration of hovering too. (for graphic)
A,B and C are all components.
Amount of A and B are not known at compile time.
My poor solutions
The 1st solution :
HashMap<A*,HashMap<B*,C*>> database;

It is a bit not symmetry. (query A before B)
The 2nd solution :
class CustomStruct{  A* a; B* b; }
HashMap<CustomStruct,C*> database;

Cannot query C from A efficiently.
The 3rd solution :
HashMap<A*,C*> databaseAC;
HashMap<B*,C*> databaseBC;

Split it into two HashMap, and query (A,B)->C by expensive intersecting two tables.
The 4th solution :
class A{HashMap<B*,C*> databaseBC;};
class B{HashMap<A*,C*> databaseAC;};

might be good?
Other thought:
Should I use HashMap at all?  Should I try something more out of the box?
Are some of my solution promising?     (Which one experts will pick?)
Is the best solution "depend" on the access/query pattern?

A: A many-to-many relation with link attributes is an undirected graph. All of the options for graph implementation apply. The graph terminology for the object is "node." The relation pairs are "edges."

*

*Matrix:  Map your objects from indices. E.g. use an array of pointers or references to take an index to an object, then pass the indices around in your program to refer to objects. Represent edges as a square matrix of attribute records. Since your graph is undirected, the matrix can be triangular.  There is a fairly cool way of addressing elements of a triangular matrix stored in a 1d vector, though changing the node count with this method is expensive. The other method is to use an array of pointers to rows of different length.

*Adjacency list: Use the same index->object mapping array as above. Represent adjacencies as an array of sets of indices. Again since your graph is undirected, you only need to store adjacency pairs i -> j where i <= j.
There are other options for adjacency lists, but arrays and indices are handy (indices are nicer to debug than pointers), memory efficient (a 32-bit index allows 4 billion nodes; 64-bit pointers allow a lot more, but waste a factor of 2 in space in most applications), and very fast (compared to hashmap-based solutions).
The choice between the two is all about density if edges. The matrix is very fast, but if density is low, most of the matrix is empty. Just initializing it can become expensive.  So if nearly all node pairs have edges, use a matrix. If connections are sparse, the adjacency list wins.


text:
Q: Intuitively, why does the dot product of any point in the plane with the normal vector always give the same answer? A few days ago I asked: Help with Proposition $2.3.3$ from Elem. Differential Geometry by Pressley
But now I have a similar question:

If $\alpha$ and $\beta$ are points on the plane, why does $\alpha \cdot \mathbf N= \beta \cdot \mathbf N$.  I know one answer is because $$(\alpha - \beta) \cdot \mathbf N=0$$
$$\alpha \cdot N = \beta \cdot N$$
But looking at it this way: $$\| \alpha\|\|\mathbf N\|\cos\theta_1 = \| \beta\|\|\mathbf N\|\cos\theta_2$$
$$\| \alpha\|\cos\theta_1=\| \beta\|\cos\theta_2$$
Why does the dot product of any point in the plane (not vector ON the plane) with the normal vector always give the same answer?

A: Here is a picture.

$A$ and $B$ are points in the plane $P$, while $N$ is the subspace normal to $P$. Cleverly, I've called the origin $O$.
Recall that the dot product $A \cdot N$ is merely the length of the projection of $A$ onto $N$.
The green lines from $A$ and $B$ meet at the projection $\operatorname{proj}_N(A)$ of $A$ onto $N$ which just so happens to be the projection $\operatorname{proj}_N(B)$ of $B$ onto $N$.
The projections are the same, and hence have equal lengths. In other words, the dot products are equal.

A: Drop a perpendicular $d$  from the origin to the plane in question (it will be parallel to the normal). Then $$\| \alpha\|\cos\theta_1=\|d\|$$
for any $\alpha.$

A: If the vector is IN the plane then it will always be orthogonal with the normal vector. That is how it is defined. So we can pick whatever vectors sitting in the plane we like and the normal vector will always pass through them perpindicularly so the angle between any vectors and the normal vector will be equal.


text:
Q: The speed of 'extract(year from sysdate)' I have two queries:
with tmp as (
select asy.aim_student_id, ast.aim_test, asq.response
  from aim_student_test ast
  join aim_student_qst asq on (asq.aps_yr = ast.aps_yr and asq.aim_test = ast.aim_test and asq.aim_id = ast.aim_id)
  join aim_student_yr asy on (asy.aps_yr = ast.aps_yr and asy.aim_student_yr_id = ast.aim_student_yr_id)
    where asq.aps_yr = '2012'
    and asq.qst_num = 1)
select aim_student_id, aim_test, response
  from tmp
  where response is null
  -- execution-time: 0.032 seconds

define this_year = extract(year from sysdate)
with tmp as (
select asy.aim_student_id, ast.aim_test, asq.response
  from aim_student_test ast
  join aim_student_qst asq on (asq.aps_yr = ast.aps_yr and asq.aim_test = ast.aim_test and asq.aim_id = ast.aim_id)
  join aim_student_yr asy on (asy.aps_yr = ast.aps_yr and asy.aim_student_yr_id = ast.aim_student_yr_id)
    where asq.aps_yr = &this_year
    and asq.qst_num = 1)
select aim_student_id, aim_test, response
  from tmp
  where response is null
  -- execution-time: 82.202 seconds

The only difference is that in one I use '2012' and the other I implement extract(year from sysdate).
I can only imagine that Oracle is computing extract(year from sysdate) for EVERY record it checks, and that I just can't figure out how to make it compute this once and use it as a variable. Searching has not returned me the answers I seek... so I come to the magicians of SO.com. HOW do I properly use
extract(year from sysdate)

as a variable?

A: Using &this_year in the query causes a substitution of the string extract(year from sysdate), so the second query actually has:
where asq.aps_yr = extract(year from sysdate)

which you can see from the second explain plan. That in itself probably isn't the problem; what's possibly slowing it down is that doing this is changing the plan from an index range scan to an index skip scan against aim_student_qstp1. The real difference is that in the fast version you're comparing asq.aps_yr to a string ('2012'), in the second it's a number (2012), and - as also shown in the explain plan - this is causing it to do to_number(asq.aps_yr) which is stopping the index being used as you expect.
You could fix this in your code by making it:
where asq.aps_yr = to_char(&this_year)

If you want to calculate it once before the query runs and then use it as a variable, there are at least two ways (in SQL*Plus/SQL Developer). Sticking with substitution variables you can use the column commands instead of the define:
column tmp_this_year new_value this_year
set termout off
select extract(year from sysdate) as tmp_this_year from dual;
set termout on
set verify off

... which makes &this_year=2012 (the termout changes just make the actual retrieval invisible, and the verify stops it telling you when it uses the substitution; both so you don't get extra output in your script), and change your query to have:
where asq.aps_yr = '&this_year'

... so the value is treated as a string, making a to_char() unnecessary.
Or you can use bind variables:
var this_year varchar2(4);
set feedback off;
exec :this_year := extract(year from sysdate);

... and then your query has:
where asq.aps_yr = :this_year

Note that in this case you don't need the quotes because the bind variable is defined as a string already - there's an implicit conversion in the exec that sets it.

A: I doubt the difference is due to extracting the year from the date.  I'm pretty sure Oracle would only be extracting the year once, since it is using a variable in the second case.
The difference is due to the execution path used by the query.  You would need to post the execution plans to really see the difference.  Using an explicit constant gives the optimizer more information for choosing an optimal query plan.
For instance, if the data is partitioned by year, then with a constant year, Oracle can determine which partition has the data.  In the second case, Oracle might not recognize the value as a constant, and require reading all data partitions.  This is just an example of what might happen -- I'm not sure what Oracle does in this case.


text:
Q: How would I go about in drawing an NFPA 704 chart in LaTeX/TikZ? Our robotics team decided to re-write all of our documentation in LaTeX and combine it into a single manual. In our Safety manual, we have several NFPA 704 symbols to show how hazardous an item is. Unfortunately, I cannot find how to draw these in LaTeX or TikZ. Would someone be able to guide me in creating one of these symbols in a document?
An image of the standard is attached below. We do not need the special hazards.

edit: Here is a symbol showing an extremely hazardous material that cannot be exposed to water or oxygen:

(source: earlham.edu)

A:
\documentclass{article}
\usepackage{lmodern}
\usepackage{color,graphicx}

\begin{document}

\newcommand\foo[4]
{%
\setlength\unitlength{2pt}%
\setlength\fboxsep{0pt}\setlength\fboxrule{\unitlength}%
\rotatebox{45}{%
\begin{picture}(52,52)
\put(0,27){\fcolorbox{black}{blue}{\makebox(25,25){}}}%
\put(27,27){\fcolorbox{black}{red}{\makebox(25,25){}}}%
\put(0,0){\fcolorbox{black}{white}{\makebox(25,25){}}}%
\put(27,0){\fcolorbox{black}{yellow}{\makebox(25,25){}}}%
\end{picture}}%
\begin{picture}(0,0)
\fontsize{40pt}{45pt}\sffamily\bfseries
\put(-42,50){#1}
\put(-60,30){#2}
\put(-22,30){#3}
\fontsize{22pt}{23pt}\sffamily\bfseries
\put(-44,14){\begin{tabular}{@{}c@{}}#4\end{tabular}}
\end{picture}%
}

\fbox{\foo{4}{4}{4}{\rlap{---}W\\OX}}

\end{document}

A: Just for fun, an alternative with TiKZ.
I've had to use a regular polygon because I didn't find how to adjust diamond size.
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{shapes.geometric}
\usepackage{lmodern}

\begin{document}
\begin{tikzpicture}[box/.style={shape=regular polygon, regular polygon sides=4,
   shape border rotate=45, draw, fill=#1,
   font=\fontsize{40pt}{45pt}\sffamily\bfseries,
   text width=1.5cm, align=center, inner sep=1pt}]
\node[box=red, anchor=south] (1) {1};
\node[box=blue, anchor=east] (2) {2};
\node[box=yellow, anchor=west] (3) {3};
\node[box=white,font=\fontsize{22pt}{23pt}\sffamily\bfseries, anchor=north] (4) {ALK};
\end{tikzpicture}
\end{document}


text:
Q: ping local network with netduino (C#) I need to ping different objects on my network with an netduino plus
any suggestions on what code would work best
Im trying to use using System.Net.NetworkInformation; but I don't have that library available to me (constraint of netduino framework?)
suggestions?

A: This is an issue in Netduino project, but meanwhile someone created a library for Netduino which pings host. You can download ICMP library for Netduino here:
http://www.blake-foster.com/projects/ICMPPing.zip
More information on this code is here:
http://www.blake-foster.com/project.php?p=44

A: I might have the solution for you:
http://forums.netduino.com/index.php?/topic/2208-ping-a-host-on-the-network/page-2
I've started fiddling with the code to make it do what I want, but the work done by the others actually does ping resources on the network.


text:
Q: How to change EditText cursor height? I want to change the EditText cursor height, does anyone know how?

A: Paddings can be used to control cursor height
cursor.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:width="2dp" />
    <solid android:color="@color/black" />
</shape>

cursor_with_padding.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="7dp"
        android:drawable="@drawable/cursor"
        android:top="8dp" />
</layer-list>

layout
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textCursorDrawable="@drawable/cursor_with_padding"/>

A: I had to dig far into the Android source to find the answer to this, but you essentially have to use padding on a custom shape drawable.
note: only works on API 12 and greater due to support for textCursorDrawable
Use positive top padding to move the top of your cursor higher
User positive bottom padding to move the bottom of your cursor lower
I usually end up using negative bottom padding to shorten the cursor because the it drops too low below baseline when you increase the line height with lineSpacingMultiplier or lineSpacingExtra.
example cursor_red.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <size
        android:width="2dip" />
    <solid
        android:color="@color/red" />
    <padding
        android:top="2sp"
        android:bottom="-11sp" />
</shape>

This will make a 2dip wide red cursor that is

*

*2sp higher (longer) at the top

*11sp higher (shorter) on the bottom.

Then in your edittext, just specify android:textCursorDrawable:
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textCursorDrawable="@drawable/cursor_red" />

Relevant Android source code inside Editor.java from which I figured out the solution:
private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
    ...

    mCursorDrawable[cursorIndex].getPadding(mTempRect);

    ...

    mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
            bottom + mTempRect.bottom);
}

A: change the editText style to a custom style
<item name="android:editTextStyle">@style/myEditText</item>

then use a drawable to set the cursor:
<style name="myEditText" parent="@android:parentdetails">
<item name="android:textCursorDrawable">@android:drawable/my_cursor_drawable</item>
<item name="android:height">Height here e.g. 50sp</item>
</style>


text:
Q: Vector space base and dimension I have to determine the dimension and base of this vector space:
$\langle 2,t,\sin^2(t),\cos^2(t)\rangle $
I did this:
$\langle 2,t,\sin^2(t),\cos^2(t)\rangle =\langle 2,t,\sin^2(t)+\cos^2(t),\cos^2(t)\rangle =\langle 2,t,1,\cos^2(t)\rangle =\langle 1,t,\cos^2(t)\rangle $
So this is the base and the dimension is $3$. Am I right? How can I prove those 3 are independent of each other?
Regards,
Kevin

A: You are on the right track. It remains to show that $\cos^2$ is not an affine function. There are many ways of doing this.
For instance, notice that an affine function is uniquely determined by its output for two different values of the input variable $t$.
If $\cos^2$ was an affine function then $\cos^2(\pi/2)=0$ and $\cos^2(3\pi/2)=0$ would imply $\cos^2(t)=0$ for every $t\in\mathbb R$. But $\cos^2(0)=1$.

A: Implicit in this answer is the assumption that $t \in \mathbb R$
To prove linear independence, you need to prove that,

$$\lambda +\mu t+\nu \cos^2 t=0 \implies \lambda=\mu=\nu=0$$
  But note that, the equation is true for all values of $t$. Take $t=0$ and $t=2\pi$. You'll have $$\lambda+\nu=0$$ $$\lambda+2\pi \mu+\nu=0$$ This proves that $\boxed{\mu=0}$. Nextly, set $t=\dfrac{\pi}{2}$ and you'll have that, $\boxed{\lambda=0}$ and hence, $\boxed{\nu=0}$.

This completes the picture.
I posted a completely idiotic answer. Thanks are due to OP for pointing out, I have bluffed!


text:
Q: Replace UR battery by IMR with lower mAh I am replacing a shaver's battery, a Braun Silk Epil 5.
It uses a Li-Ion battery manufactured by Sanyo for Braun.
According to my research it must be a UR Battery like the UR18500L :
Size : 18500
Volts: 3.7V
Capacity : 1300mAh/4.8Wh

My question is pretty simple (and maybe dumb), the UR Batteries are pretty expressive.
Is it possible to replace it by an IMR Battery that has the same voltage but less mAh (Usually used for e-cigs)?
If it is, what would be the consequences ?

A: The only other battery on the IMR website that can fit in terms of dimensions, would be the 16340 Lithium-Ion cell. Though this battery would have only mostly 600-700mAh. Which means you get only half the original runtime.
https://www.imrbatteries.com/imren-16340-700mah-button-top-battery/


text:
Q: Change elements in 2d ndarray into arrays In numpy, I have a 2d array like:
[
 [1 2 3 4 5]
 [2 3 1 4 5]
 .....
 [3 5 2 3 5]
]

I want to replace each element in this array into a 1d array, e.g.
1 -> [0 0 0 0 1]
2 -> [0 0 0 1 0]

etc.
This will convert elements into arrays, and the whole 2d array into a 3d array.
I tried few things, but nothing worked. What should be the right way to do so?
Thanks.

A: Suppose this is your 2d array:
x=np.random.randint(1,3,size=(3,2))
print(x)

# [[2 2]
#  [1 2]
#  [2 1]]

Create the array:
y=np.array([[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]])

You can look upon this array as a mapping:
0 --> [0,0,0,0,0]   # y[0] is mapped to [0,0,0,0,0]
1 --> [0,0,0,0,1]   # y[1]      ...     [0,0,0,0,1]
2 --> [0,0,0,1,0]   # y[2]      ...     [0,0,0,1,0]

Then the array you desire is given by y[x]
print(y[x])

# [[[0 0 0 1 0]
#   [0 0 0 1 0]]

#  [[0 0 0 0 1]
#   [0 0 0 1 0]]

#  [[0 0 0 1 0]
#   [0 0 0 0 1]]]


text:
Q: How to better implement recurrence relations in code? I've been struggling with this problem for a couple days now, I'm still new to Python and more math intensive coding so any help would be appreciated, just point me in the right direction :)
So the question was something like:

You have a movie pass which is valid for N days. You can use it in any way you want except for 3 consecutive days or more.
So basically, you can either use your pass on a given day or choose to not, meaning 2 raised to N total possibilities. The valid ways for claiming the pass are then 2 raised to N - invalidCases
You have to find the number of valid cases % (10^9+7)

I found a recurrence relation for the invalid cases which looked like

invalidCases(at_N) = 2^(n-4) + 2*invalidCases(at_N-1) - invalidCases(at_n-4)

So my first impulse was to simply use recursion:
def invalidCases(n):
    if(n<3):
        return 0;
    elif(n==3):
        return 1;
    else:
        return 2**(n-4)+ 2*invalidCases(n-1)- invalidCases(n-4)

Very inefficient, but my equation seemed correct.
My next attempt, I tried memoization, but I kept running into an error at N=1006.
So I changed the recursion limit.
My present attempt(with memoization and increased recursion limit)
import sys
sys.setrecursionlimit(10**6)
T=int(input());
#2**(n-4) + 2*ans(n-1)-ans(n-4)
memo={0:0,1:0,2:0,3:1,4:3,5:8,6:20,7:47} #
def ans(n):
    #complete this function
    if n not in memo:

        memo[n]=(2**(n-4) + 2*ans(n-1)-ans(n-4));

    return memo[n];

modulo = 10**9 + 7;
print((2**n-ans(n))%modulo);

Finally, my problem.
I need this code to work for n = 999999.
How do I bring its worst case down to minimum?
Any pointers or tips would be great.

A: Here's a complete solution which is based on the observation that a valid solution for three or more days must begin with one of the following:
0
10
110

where 1 indicates the pass is used on that day, and 0 indicates it is not.
There are valid(n-1) possibilities for the first form, valid(n-2) possibilities for the second form, and valid(n-3) possibilities for the third form.
The recurrence is then:

valid(n) = valid(n-1) + valid(n-2) + valid(n-3)

The basis cases are valid(0) = 1, valid(1) = 2, and valid(2) = 4.  It is important to note that valid(0) is 1, not zero. That's because there is exactly one solution when n=0, namely, the empty sequence. This is not only mathematically correct, but is also needed for the recurrence to work correctly.
The code does three things to make it run fast:

*

*It uses a cache to cache results (memoization), as you had done.

*It doesn't store the full results, but instead first applies the modulus, greatly reducing the value ranges.

*It preloads the cache, starting with 0 and going up to the desired value.  This reduces the maximum recursion depth to one.

Here's the code:
cache = {}
modulus = 10**9 + 7

def valid(n):
    if n in cache:
        return cache[n]

    if n == 0:
        v = 1
    elif n == 1:
        v = 2
    elif n == 2:
        v = 4
    else:
        v = valid(n-1) + valid(n-2) + valid(n-3)

    v %= modulus

    cache[n] = v
    return v

def main():
    # Preload the cache
    for n in range(1000000):
        valid(n)

    print(valid(999999))

main()

Here's the output:
746580045

It runs in under 2 seconds on my system.
Update:  Here's a minimal iterative solution, inspired by the approach used by MFisherKDX.  The seed values were constructed in a way that eliminates the need for special-casing (the intial v2 is valid(0)):
modulus = 10**9 + 7

def valid(n):
    v0, v1, v2 = 0, 1, 1

    for i in range(n):
        v0, v1, v2 = v1, v2, (v0 + v1 + v2) % modulus

    return v2

print(valid(999999))

This solution is probably as fast as you can get.  It discards the intermediate results after using them, which is fine if you're only calling the function once.

A: Here's my answer.  Bottom up solution.  Compare with Tom's answer which is top down and equally valid.  At each day j it keeps track of the number of possibilities that use the pass on day j as well as the number of possibilities that use the pass on both j and j-1.
def ans(n):

    total = 1
    tcd = 0 #total used at current day
    tcpd = 0 #total used at current and previous day
    m = 1000000007

    for j in range(0, n):

        next_tot = 2*total - tcpd
        next_tcd = total - tcpd
        next_tcpd = tcd - tcpd

        total = next_tot % m

        tcd = next_tcd % m
        tcpd = next_tcpd % m

    return total

print(ans(999999))

Result is 746580045 and takes 400ms on my system.


text:
Q: Ubuntu snap plugin 'autotools' default 'make install' to be skipped while building with snapcraft I am building a snap package for my project, I have a library which I want to only compile. ie only /configure && make not : /configure && make && make install
As I had searched for the doc for it in Ubuntu snap, I found : https://snapcraft.io/docs/reference/plugins/autotools
Also searched here : https://github.com/search?o=desc&q=filename%3Asnapcraft.yaml+%22plugin%3A+autotools%22+&s=indexed&type=Code&utf8=%E2%9C%93
But I couldn't find anything to skip the make install part. Can anyone suggest me how to do that ? A dirty way might be after the make install, I will add one shell script to recursively delete the make install generated files and then proceed further to application code compilation. But I think there should be a happy path of doing this nicely. So please let me know if there is any way to skip this make install when I run snapcraft to build snap package.

A: You can override what is done in the install stage with an install: stanza which you could leave empty or so nothing but echo a blank line, showing you're skipping that. Alternatively if the Makefile has no install stanza, then you can use the install stanza to do whatever is required e.g.
parts:
  foo:
    source: .
    plugin: autotools
    install: |
      cp -a somebinary $SNAPCRAFT_PART_INSTALL/bin
      cp -a somesupportfiles $SNAPCRAFT_PART_INSTALL/foo

This will just use the shell cp command to do the installation.


text:
Q: How to show the projection graphically? We need to find a formula for $T(a,b)$ , where T represents the projection on the y-axis along the line $L$ = { (s , s) for s belonging to $R$ } .
I got $T(a,b)$ as $T(a,b)$ = ($0$ , $b-a$) , but how to show this projection graphically ?
Please help !

A: See this picture:

The dashed lines are drawn from the end of the vector toward the two directions, each one parallel to the other direction. So you make a parallelogram with the two directions.


text:
Q: Dynamic CRM Plugin Registration Tool, Same GMT Difference I raise this topic out of curiosity, related to my question in: Dynamic CRM Plugin Registration Tool returns unsecured or incorrectly secured fault
In short I got error of:

An unsecured or incorrectly secured fault was received from the other
  party.
Inner Exception: System.ServiceModel.FaultException: An error occurred
  when verifying security for the message.

Following suggestion to check the date and time in my PC, I decided to see whether my local time and Dynamic CRM 2011 Online server time is in sync. My local time is Singapore GMT (+8) and the Dynamic CRM 2011 Online server time is Krasnoyarsk GMT (+8).
Since it is the same GMT I assume both time are the same, however I tried to change the server time to Singapore, Kuala Lumpur GMT (+8) and suddenly the tool is working again.
I double checked by changing the timezone again to Krasnoyarsk and the same problem happened (I'm able to replicate it) so I'm certain this is the thing that caused my error.
I now wonder, why the same GMT Setting (Krasnoyarsk and Singapore is +8) can have a different effect? Or maybe my problem is caused by other entirely unrelated thing?
PS: I'm using the latest Dynamic CRM 2011 SDK.

A: The different timezone code as suggest by Joris most likely have caused this behavior at the first place, this question is now closed.


text:
Q: JToken.explicit operator bool cannot call operator or accessor directly if (JToken.op_Explicit(apiConfig["finjVersion"]) < JToken.op_Explicit(latestData["finjVersion"]))
{
 ...
}

Error: JToken.explicit operator bool(JToken)': cannot call operator or accessor directly
I tried searching it in Newtonsoft's website or Microsoft and found nothing.

A: It looks like you are trying to invoke one of the explicit conversion operators of JToken to convert a JSON property value to a .NET primitive.  In order to use these operators, you must use the explicit conversion syntax of c# to cast the value to the required primitive type.  You must also choose an appropriate .NET primitive type to which to cast that corresponds to the JSON property value.
E.g. if the value of "finjVersion" is some integer such as "finjVersion" : 1 you should do:
if ((long)apiConfig["finjVersion"] < (long)latestData["finjVersion"])
{
    //...
}

Demo #1 here.
If the value of "finjVersion" does not correspond to a .NET primitive, rather than casting you must use ToObject<T>() to deserialize to the required type. E.g. if "finjVersion" looks like "finjVersion":"1.1.2.0", you could deserialize to System.Version like so:
if (apiConfig["finjVersion"].ToObject<Version>() < latestData["finjVersion"].ToObject<Version>())
{
    //...
}

Demo #2 here.


text:
Q: How to show two splash screen one by one in android? I want to show two splash screens one by one. First to be aways static second will be change every time when user login. I do my second splash screen to change every time, but I dont know how to set a first static splash screen.
This is my .java file
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.content.Intent;

public class SplashScreen extends DefaultActivity {

    int timeout = 2000; // Choose the delay (1000 = 1 second)

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        setFonts();
         // Randomise a background
        int[] yourListOfImages= {R.drawable.test, R.drawable.test1, R.drawable.test2, R.drawable.test3};

        Random random = new Random(System.currentTimeMillis());
        int posOfImage = random.nextInt(yourListOfImages.length);

        ImageView imageView= (ImageView) findViewById(R.id.imageView1);
        imageView.setBackgroundResource(yourListOfImages[posOfImage]);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                //Redirecting to the home page
                Intent redirect = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(redirect);
                finish();
            }
        }, timeout);
    }
}

and this is .xml fail
    <?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    tools:context=".SplashScreen" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:contentDescription="@string/contentDescription"
        android:background="@android:color/white" />

      <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:contentDescription="@string/contentDescription"
        android:background="@android:color/white" />

    <TextView
        android:id="@+id/textViewSplash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="45dp"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        android:tag="helvetica"
        android:text="@string/splash_intro" />

</RelativeLayout>


text:
Q: How vlookup between range values? I have this challenge!!
How can I solve the problem below (picture) using any formula?

A: Please try:
=INDEX(D$3:D$11,MATCH(A14&B14,A$3:A$11&C$3:C$11,1)+1)

in C14 and copied down. It is an array formula to be entered with Ctrl+Shift+Enter.
Note that when at a break point it is the higher % that would be returned.

A: Use this formula -1 (without year match)
=VLOOKUP(B14,$B$3:$D$11,3)

formula-2 (with year match)
=IF(MATCH(A14,$A$3:$A$11,0)>0,VLOOKUP(B14,$B$3:$D$11,3),"Not Matched")

Just copy and paste the above formula in C14 and C15. An easy method to get the answer.


text:
Q: Inner Join in stored procedure I have this stored procedure:
ALTER PROCEDURE [dbo].[Get_All_Items]
AS
BEGIN
    SELECT
        ItemID, ItemName, CategoryID, CountryID,
        ItemSize, ColorID, ProductionDate, ExpiryDate,
        UnitName, FirstUnitBarcode, FirstItemQuantity,
        FirstUnitDefult, FirstUnitLimit,
        UnitsTbl.SecondUnit, SecondUnitBarcode, SecondItemQuantity,
        SecondUnitDefult, SecondUnitLimit,
        ThirdUnit, ThirdUnitBarcode, ThirdItemQuantity,
        ThirdUnitDefult, ThirdUnitLimit, UnitDefult,
        ItemImage, ItemStatus, ItemsMainTbl.Nots,
        ItemsMainTbl.CreatedBy, ItemsMainTbl.CreatedDate,
        ItemsMainTbl.ModifiedBy, ItemsMainTbl.ModifiedDate
    FROM
        ItemsMainTbl
    INNER JOIN
        UnitsTbl ON ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
    INNER JOIN
        UnitsTbl ON ItemsMainTbl.SecondUnit = UnitsTbl.UnitID
END

Conditions:

*

*ItemsMainTbl.FirstUnit = UnitsTbl.UnitID

*ItemsMainTbl.SecondUnit = UnitsTbl.UnitID

*ItemsMainTbl.ThirdUnit = UnitsTbl.UnitID

How to join all three tables on that common column?
I got only the first one
ItemsMainTbl.FirstUnit = UnitsTbl.UnitID

Thanks

A: If you want to join the same table multiple times, you need to specify an alias for each instance of the joined table, like this:
SELECT *
FROM ItemsMainTbl
INNER JOIN UnitsTbl u1 ON ItemsMainTbl.FirstUnit = u1.UnitID
INNER JOIN UnitsTbl u2 ON ItemsMainTbl.SecondUnit = u2.UnitID
INNER JOIN UnitsTbl u3 ON ItemsMainTbl.ThirdUnit = u3.UnitID

Then in the select statement, you can differentiate between the joined instances, like this:
SELECT u1.Barcode, -- Barcode from FirstUnit
       u2.Barcode, -- Barcode from SecondUnit
       u3.Barcode  -- Barcode from ThirdUnit

A: You need to define reference for you UnitsTbl. Think of these references as new objects of same class, in terms of OOP. Also, it is a good habit to use references for whenever querying over a table.
SELECT *
FROM
    ItemsMainTbl t1
INNER JOIN
    UnitsTbl u1 ON t1.FirstUnit = u1.UnitID
INNER JOIN
    UnitsTbl u2 ON t1.SecondUnit = u2.UnitID
INNER JOIN
    UnitsTbl u3 ON t1.ThirdUnit = u3.UnitID


text:
Q: How to change database prefix when required. I've determined in my database.php:
$db['default']['dbprefix'] = 'm_';

Let say, if I want to use another prefix for example the table prefix started with c_ instead of default database prefix m_, how I can do that?
My current code was:
$data['username'] = 'test_username';
$this->db->insert('c_my_table`, $data);

Any solution?


text:
Q: Retrieving the LPARAM with an item in treectrl using CTreeCtrl I have to add a list of sub keys recursively to an item in a Tree control.
I am using InsertItem as shown below. I am attaching the path of this element so that i can retrieve when clicked on the tree control.I am able to add the value but not able to retrieve it.
void CMyDlg::FillTreeWithRegistryKeysEx(CString sPath, HTREEITEM hItem)
{
    CString sRegKey = sPath.Left(sPath.Find(_T("\\")));
    sPath = sPath.Mid((sPath.Find(_T("\\")) + 1));
    sPath = CleanRegistryKey(sPath);

    int nKeyCount;
    CString  sSubKey = _T("");
    HKEY handle = GetHkey(sRegKey);
    HTREEITEM hReItem = NULL;
    HKEY phkey;

    std::vector<CString> sSubFolders;

    if (RegOpenKeyEx(handle, sPath, 0, KEY_ALL_ACCESS, &phkey) == ERROR_SUCCESS)
        sSubFolders = EnumRegistryKey(phkey);

    nKeyCount = sSubFolders.size();

    for (int nIndex = 0; nIndex < nKeyCount; nIndex++)
    {
        sSubKey = sPath + _T("\\") +sSubFolders.at(nIndex);
        hReItem = m_cTreeCtrl.InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM | TVIF_STATE, sSubFolders.at(nIndex),
                                        icoClosedFolder, icoOpenFolder, 0, 0, (LPARAM)(LPCTSTR)sSubKey, hItem, TVI_LAST);

        FillTreeWithRegistryKeys(handle, sSubKey, hReItem);
    }
    RegCloseKey(phkey);
}

While retrieving the string is always blank.

void CMyDlg::OnTvnSelchangedTree(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);

    LPARAM lp = pNMTreeView->itemNew.lParam;
    CString sKey = (LPCTSTR)lp;
}

what is going wrong?

A: The application-defined LPARAM passed to InsertItem is a string object that goes out of scope once the function completes not to mention it is replaced with each loop iteration with a new string.  I don't think that is going to work.
The TreeView control however allocates its own copy of the text, so you are safe to fill in the pszText member with local buffers as it appears you are doing.

A: As pointed out in previous answer, you are using LPARAM to point to a string which is destroyed when the function exits. The solution is store the strings in permanent storage. There are many ways to do this. One option is to use CStringArray member data:
class CMyDlg : public CDialog
{
    CStringArray m_strings;
    ...
};

*

*Store the registry keys in m_strings.

*Add the tree item with InsertItem, this returns HTREEITEM.

*Use tree.SetItemData to match the tree item with an index in m_strings

*Use tree.GetItemData to retrieve that index

Example:
BOOL CMyDlg::OnInitDialog()
{
    CDialog::OnInitDialog();
    ...
    m_strings.RemoveAll();
    addKey(L"SOFTWARE\\Microsoft\\Internet Explorer", tree.GetRootItem());
    return TRUE;
}

void CMyDlg::addKey(CString path, HTREEITEM parent)
{
    CRegKey rg;
    if (ERROR_SUCCESS != rg.Open(HKEY_CURRENT_USER, path))
        return;
    for (int i = 0;; i++)
    {
        wchar_t buf[300];
        DWORD bufsize = 300;
        if (rg.EnumKey(i, buf, &bufsize) != ERROR_SUCCESS) break;
        HTREEITEM hitem = tree.InsertItem(buf, parent);
        CString subkey = path + L"\\" + buf;
        m_strings.Add(subkey);
        tree.SetItemData(hitem, m_strings.GetCount() - 1);
        addKey(subkey, hitem);
    }
}

void CMyDlg::OnTvnSelchangedTree(NMHDR *pNMHDR, LRESULT *pResult)
{
    HTREEITEM hitem = tree.GetSelectedItem();
    if (!hitem) return;
    int i = tree.GetItemData(hitem);
    if (i >= 0 && i < m_strings.GetCount())
        SetWindowText(m_strings[i]);
}


text:
Q: Checkbox is not checked in React Formik I developed a component for checkbox using React Formik Library.Below is my code
const CheckBoxGroup = (props) => {
 const { label,name,options,...rest } = props
  return (
  <React.Fragment>
 {label}

    <Field  name={name} id={name} {...rest} >
        {
            ({field}) => {
               return options.map( (option) => {

                    return ( <React.Fragment key={option.key}>

                        <input type="checkbox"
                        id={option.value}  {...field} value={option.value}
                        checked={field.value.includes(option.value)}
                       />
                        {option.key}
                    </React.Fragment>)
                })
            }

        }
    </Field>
    <ErrorMessage name={name} component={TextError} />

</React.Fragment>
 );
}

Interesting part is that when checked property is present the checkbox is not cheked but if i remove checked property it is checked.what is the reason?

A: In my case use value atribute as number but works only with string
<Field
                              className="form-check-input"
                              type="checkbox"
                              name="idsProfiles"
                              id={item.defaultText}
                              value={item.id.toString()}
                              aria-label={item.defaultText}
                            />

                              {item.defaultText}

A: you can check the docs on the formik web page, here is a local implementation to try the demo checkbox and it's running ok, i used the last formik lib version.
here is the example from formik site: formik checkboxex codesandbox demo
***i cannot replicate you code because you miss the inputs on the props
here is what i run on local:

import React from 'react';
import { Field, Formik ,Form } from 'formik';
import './App.css';

function App() {

  ///FORMIK DOCS:
  ///https://formik.org/docs/examples/checkboxes

const CheckBoxGroup = (props) => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

     return (
      <Formik
      initialValues={{
        toggle: false,
        checked: [],
      }}
      onSubmit={async (values) => {
        await sleep(500);
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ values }) => (
        <Form>

            <Field type="checkbox" name="toggle" />
            {`${values.toggle}`}

Checked

              <Field type="checkbox" name="checked" value="One" />
              One

              <Field type="checkbox" name="checked" value="Two" />
              Two

              <Field type="checkbox" name="checked" value="Three" />
              Three

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
    );
   }

  return (

      {CheckBoxGroup()}

  );
}

export default App;


text:
Q: how could i get both the final hidden state and sequence in a LSTM layer when using a bidirectional wrapper i have followed the steps in https://machinelearningmastery.com/return-sequences-and-return-states-for-lstms-in-keras/
But when it comes to the Bidirectional lstm, i tried this
lstm, state_h, state_c = Bidirectional(LSTM(128, return_sequences=True, return_state= True))(input)

but it won't work.
is there some approach to  get both the final hidden state and sequence in a  LSTM layer when using a bidirectional wrapper

A: The call Bidirectional(LSTM(128, return_sequences=True, return_state=True))(input) returns 5 tensors:

*

*The entire sequence of hidden states, by default it'll be the concatenation of forward and backward states.

*The last hidden state h for the forward LSTM

*The last cell state c for the forward LSTM

*The last hidden state h for the backward LSTM

*The last cell state c for the backward LSTM

The line you've posted would raise an error since you want to unpack the returned value into just three variables (lstm, state_h, state_c).
To correct it, simply unpack the returned value into 5 variables. If you want to merge the states, you can concatenate the forward and backward states with Concatenate layers.
lstm, forward_h, forward_c, backward_h, backward_c = Bidirectional(LSTM(128, return_sequences=True, return_state=True))(input)
state_h = Concatenate()([forward_h, backward_h])
state_c = Concatenate()([forward_c, backward_c])


text:
Q: RxJS Continuous HTTP polling in case it fails as well I am trying to implement HTTP-polling. The expectation is for every 5 minutes it should poll from HTTP or I could say sync on Server. In case if it fails, it shouldn't stop the subject but it should retry three times then again it should try after 5 mins. In case if it fails after 5 mins as well, it should retry 3 mins, and the scenario continuous to go on.
What I tried is something.
const checkTimeForRestart$ = Rx.Observable.timer(5 * 60 * 1000, 5000)
    .switchMap(() => Rx.Observable.of(axios.get(url)).retry(3));

// .map(response => console.log(`console here !! - ${response}`));
// .concatMap(val => of(`Delayed by: ${val}ms`).pipe(delay(val)));

checkTimeForRestart$.subscribe(
    x => console.log(x),
    error => console.error(`Error: ${error}`),
    () => console.log(`Complete: fires when the observable completes`)
);

If the server is not up or for connectivity issues it shouldn't complete the observable, but should try for 3 times then again 5 mins after it would redo the process.

A: So the problem is that when a it retries 3 times then the error notification is sent forward which disposes the chain and that's not what you want.
An easy solution is using catch (catchErrorin RxJS 6) to ignore the error after 3 retries:
const checkTimeForRestart$ = Rx.Observable.timer(5 * 60 * 1000, 5000)
  .switchMap(() => Rx.Observable.of(axios.get(url))
    .retry(3)
    .catch(err => Rx.Observable.empty())
  );