Programs & Examples On #Latex

LaTeX is a macro package implemented on Donald Knuth's TeX programming language and is used primarily for creating high quality written documents. The "TeX - LaTeX" community in StackExchange (https://tex.stackexchange.com) is specifically dedicated to questions about LaTeX, TeX and other related technologies.

Making LaTeX tables smaller?

http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.

I used:

\scalebox{0.7}{
  \begin{tabular}
    ...
  \end{tabular}
}

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

How to create a timeline with LaTeX?

Just an update.

The present TiKZ package will issue: Package tikz Warning: Snakes have been superseded by decorations. Please use the decoration libraries instead of the snakes library on input line. . .

So the pertaining part of code has to be changed to:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations}
\begin{document}
\begin{tikzpicture}
%draw horizontal line
\draw (0,0) -- (2,0);
\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (2,0) -- (4,0);
\draw (4,0) -- (5,0);
\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (5,0) -- (7,0);

%draw vertical lines
\foreach \x in {0,1,2,4,5,7}
\draw (\x cm,3pt) -- (\x cm,-3pt);

%draw nodes
\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$   $};
\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
\draw (3,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
\draw (6,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
\end{tikzpicture}

\end{document}

HTH

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

Footnotes for tables in LaTeX

The best way to do it without any headache is to use the \tablefootnote command from the tablefootnote package. Add the following to your preamble:

\usepackage{tablefootnote}

It just works without the need of additional tricks.

How to order citations by appearance using BibTeX?

You answered your own question---unsrt is to be used when you want references to ne listed in the order of appeareance.

But you might also want to have a look at natbib, an extremely flexible citation package. I can not imagine living without it.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How to force two figures to stay on the same page in LaTeX?

try [h!] first but else you can do it the ugly way.

LateX is a bit hard in placing images with such constraints as it manages placing itself. What I usually do if I want a figure right in that spot is do something like|:

text in front of image here

 \newpage 
 \figure1 
 \figure2

text after images here

I know it may not be the correct way to do it but it works like a charm :).

//edit

You can do the same if you want a little text at top of the page but then just use /clearpage. Of course you can also scale them a bit smaller so it does not happen anymore. Maybe the non-seen whitespace is a bit larger than you suspect, I always try to scale down my image until they do appear on the same page, just to know for sure there is not like 1% overlap only making all of this not needed.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How can I compile LaTeX in UTF8?

I have success with using the Chrome addon "Sharelatex". This online editor has great compability with most latex files, but it somewhat lacks configuration possibilities. www.sharelatex.com

Eliminate space before \begin{itemize}

The cleanest way for you to accomplish this is to use the enumitem package (https://ctan.org/pkg/enumitem). For example,

enter image description here

\documentclass{article}
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\begin{document}
\noindent Here is some text and I want to make sure
there is no spacing the different items. 
\begin{itemize}[noitemsep]
  \item Item 1
  \item Item 2
  \item Item 3
\end{itemize}
\noindent Here is some text and I want to make sure
there is no spacing between this line and the item
list below it.
\begin{itemize}[noitemsep,topsep=0pt]
  \item Item 1
  \item Item 2
  \item Item 3
\end{itemize}
\end{document}

Furthermore, if you want to use this setting globally across lists, you can use

\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\setlist[itemize]{noitemsep, topsep=0pt}

However, note that this package does not work well with the beamer package which is used to make presentations in Latex.

Get started with Latex on Linux

LaTeX comes with most Linux distributions in the form of the teTeX distribution. Find all packages with 'teTeX' in the name and install them.

  • Most editors such as vim or emacs come with TeX editing modes. You can also get WYSIWIG-ish front-ends (technically WYSIWYM), of which perhaps the best known is LyX.

  • The best quick intro to LaTeX is Oetiker's 'The not so short intro to LaTeX'

  • LaTeX works like a compiler. You compile the LaTeX document (which can include other files), which generates a file called a .dvi (device independent). This can be post-processed to various formats (including PDF) with various post-processors.

  • To do PDF, use dvips and use the flag -PPDF (IIRC - I don't have a makefile to hand) to produce a PS with font rendering set up for conversion to pdf. PDF conversion can then be done with ps2pdf or distiller (if you have this).

  • The best format for including graphics in this environment is eps (Encapsulated Postscript) although not all software produces well-behaved postscript. Photographs in jpeg or other formats can be included using various mechanisms.

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

How do I remove blank pages coming between two chapters in Appendix?

You can also use \openany, \openright and \openleft commands:

\documentclass{memoir}
\begin{document}

\openany
\appendix

\openright
\appendixpage
This is the appendix.

\end{document}

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

How to change font size on part of the page in LaTeX?

The use of the package \usepackage{fancyvrb} allows the definition of the fontsize argument inside Verbatim:

\begin{Verbatim}[fontsize=\small]
print "Hello, World"
\end{Verbatim}

The fontsize that you can specify are the common

\tiny 
\scriptsize  
\footnotesize 
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:

\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}

LaTeX: remove blank page after a \part or \chapter

I think you can simply add the oneside option the book class?

i.e.

\documentclass[oneside]{book}

Although I didn't test it :)

Error including image in Latex

On a Mac (pdftex) I managed to include a png file simply with \includegraphics[width=1.2\textwidth]{filename.png}. But in order for that to work I had to comment out the following 2 packages:

%\usepackage[dvips]{epsfig}

%\usepackage[dvips]{graphicx}

...and simply use package graphicx:

\usepackage{graphicx}

It seems [dvips] is problematic when used with pdftex.

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

LaTeX table too wide. How to make it fit?

You can use these options as well, either use \footnotesize or \tiny. This would really help in fitting big tables.

\begin{table}[htbp]
\footnotesize
\caption{Information on making the table size small}
\label{table:table1}
\begin{tabular}{ll}
    \toprule
    S.No       & HMD           \\
    \midrule
    1          & HTC Vive \\
    2          & HTC Vive Pro   \\
    \bottomrule
\end{tabular}
\end{table}

Inserting code in this LaTeX document with indentation

Use Minted.

It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.

It's much more evolved and customizable than any other package!

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

How to label each equation in align environment?

like this

\begin{align} 

x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\

y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber

\end{align}

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

What LaTeX Editor do you suggest for Linux?

There is a pretty good list at linuxappfinder.com.

My personal preference for LaTeX on Linux has been the KDE-based editor Kile.

Two statements next to curly brace in an equation

That can be achieve in plain LaTeX without any specific package.

\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
  \left\{
    \begin{array}{l}
      0\\
      1
    \end{array}
  \right.
\end{math}
\end{document}

This code produces something which looks what you seems to need.

curly braces in front of two lines

The same example as in the @Tombart can be obtained with similar code.

\documentclass{article}

\begin{document}

\begin{math}
  f(x)=\left\{
    \begin{array}{ll}
      1, & \mbox{if $x<0$}.\\
      0, & \mbox{otherwise}.
    \end{array}
  \right.
\end{math}

\end{document}

This code produces very similar results.

enter image description here

multiple figure in latex with captions

Below is an example of multiple figures that I used recently in Latex. You need to call these packages

\usepackage{graphicx}
\usepackage{subfig})


\begin{figure}[H]%

    \centering

    \subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%

    \subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%

    \subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
    \hfill
    \subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%

    \subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%

    \caption{Multiple figures in latex.}%

    \label{fig:MFL}%

\end{figure}

How to display a content in two-column layout in LaTeX?

You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

How do I determine file encoding in OS X?

The @ sign means the file has extended attributes. xattr file shows what attributes it has, xattr -l file shows the attribute values too (which can be large sometimes — try e.g. xattr /System/Library/Fonts/HelveLTMM to see an old-style font that exists in the resource fork).

Inserting a PDF file in LaTeX

Use the pdfpages package.

\usepackage{pdfpages}

To include all the pages in the PDF file:

\includepdf[pages=-]{myfile.pdf}

To include just the first page of a PDF:

\includepdf[pages={1}]{myfile.pdf}

Run texdoc pdfpages in a shell to see the complete manual for pdfpages.

Tools for making latex tables in R

Thanks Joris for creating this question. Hopefully, it will be made into a community wiki.

The booktabs packages in latex produces nice looking tables. Here is a blog post on how to use xtable to create latex tables that use booktabs

I would also add the apsrtable package to the mix as it produces nice looking regression tables.

Another Idea: Some of these packages (esp. memisc and apsrtable) allow easy extensions of the code to produce tables for different regression objects. One such example is the lme4 memisc code shown in the question. It might make sense to start a github repository to collect such code snippets, and over time maybe even add it to the memisc package. Any takers?

How do you change the document font in LaTeX?

I found the solution thanks to the link in Vincent's answer.

 \renewcommand{\familydefault}{\sfdefault}

This changes the default font family to sans-serif.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

LaTeX table positioning

At the beginning with the usepackage definitions include:

\usepackage{placeins}

And before and after add:

\FloatBarrier
\begin{table}[h]
    \begin{tabular}{llll}
      .... 
    \end{tabular}
\end{table}
\FloatBarrier

This places the table exactly where you want in the text.

In LaTeX, how can one add a header/footer in the document class Letter?

Just before your "Content of the letter" line, add \thispagestyle{fancy} and it should show the headers you defined. (It worked for me.)

Here's the full document that I used to test:

\documentclass[12pt]{letter}

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

% page counting, header/footer
\usepackage{fancyhdr}
\usepackage{lastpage}

\pagestyle{fancy}
\lhead{\footnotesize \parbox{11cm}{Draft 1} }
\lfoot{\footnotesize \parbox{11cm}{\textit{2}}}
\cfoot{}
\rhead{\footnotesize 3}
\rfoot{\footnotesize Page \thepage\ of \pageref{LastPage}}
\renewcommand{\headheight}{24pt}
\renewcommand{\footrulewidth}{0.4pt}

\usepackage{lipsum}% provides filler text

\begin{document}
\name{ Joe Laroo }
\signature{ Joe Laroo }
\begin{letter}{ To-Address }
\renewcommand{\today}{ February 16, 2009 }
\opening{ Opening }

\thispagestyle{fancy}% sets the current page style to 'fancy' -- must occur *after* \opening
\lipsum[1-10]% just dumps ten paragraphs of filler text

\closing{ Yours truly, }
\end{letter}
\end{document}

The \opening command sets the page style to firstpage or empty, so you have to use \thispagestyle after that command.

Left align block of equations

Try to use the fleqn document class option.

\documentclass[fleqn]{article}

(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)

LaTeX Optional Arguments

All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)

well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with

\usepackage{ifthen}  % provides conditonals...

Start the command, with the "optional" command set blank by default:

\newcommand {\figHoriz} [4] []  {

I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank. This could be extended to any passed argument.

\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

Then I run the macro using the \temp{} variable for the two cases. (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).

\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.

\MyCommand {first arg} {} {} {}

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...

LaTeX package for syntax highlighting of code in various languages

You can use the listings package. It supports many different languages and there are lots of options for customising the output.

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

How to wrap text in LaTeX tables?

Use p{width} for your column specifiers instead of l/r/c.

\begin{tabular}{|p{1cm}|p{3cm}|}
  This text will be wrapped & Some more text \\
\end{tabular}

EDIT: (based on the comments)

\begin{table}[ht]
    \centering
    \begin{tabular}{p{0.35\linewidth} | p{0.6\linewidth}}
      Column 1  & Column2 \\ \hline
      This text will be wrapped & Some more text \\
      Some text here & This text maybe wrapped here if its tooooo long \\
    \end{tabular}
    \caption{Caption}
    \label{tab:my_label}
\end{table}

we get:

enter image description here

LaTeX beamer: way to change the bullet indentation?

Setting \itemindent for a new itemize environment solves the problem:

\newenvironment{beameritemize}
{ \begin{itemize}
  \setlength{\itemsep}{1.5ex}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}   
  \addtolength{\itemindent}{-2em}  }
{ \end{itemize} } 

How to write LaTeX in IPython Notebook?

I wrote how to write LaTeX in Jupyter Notebook in this article.

You need to enclose them in dollar($) signs.

  • To align to the left use a single dollar($) sign.

$P(A)=\frac{n(A)}{n(U)}$

  • To align to the center use double dollar($$) signs.

$$P(A)=\frac{n(A)}{n(U)}$$

  • Use \limits for \lim, \sum and \int to add limits to the top and the bottom of each sign.

  • Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.

enter image description here

Try this one.

$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i  $$
  • Matrices

enter image description here

  • Piecewise functions
$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$

The above code will create this.

enter image description here

If you want to know how to add numbering to equations and align equations, please read this article for details.

How can I start pagenumbers, where the first section occurs in LaTex?

You can also reset page number counter:

\setcounter{page}{1}

However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:

\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...

Breaking a list into multiple columns in Latex

Using the multicol package and embedding your list in a multicols environment does what you want:

\documentclass{article}
\usepackage{multicol}

\begin{document}
\begin{multicols}{2}
\begin{enumerate}
    \item a
    \item b
    \item c
    \item d
    \item e
    \item f
\end{enumerate}
\end{multicols}
\end{document}

Latex - Change margins of only a few pages

I could not find a easy way to set the margin for a single page.

My solution was to use vspace with the number of centimeters of empty space I wanted:

 \vspace*{5cm}                                                             

I put this command at the beginning of the pages that I wanted to have +5cm of margin.

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

QED symbol in latex

The question specifically mentions a full box and not an empty box and not using proof environment from amsthm package. Hence, an option may be to use the command \QED from the package stix. It reproduces the character U+220E (end of proof, ?).

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

How do I get LaTeX to hyphenate a word that contains a dash?

multi-disciplinary will not be hyphenated, as explained by kennytm. But multi-\-disciplinary has the same hyphenation opportunities that multidisciplinary has.

I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):

The command \- inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

Yes, include float package into the top of your document and H (capital H) as a figure specifier:

\usepackage{float}

\begin{figure}[H]
.
.
.
\end{figure}

LaTeX source code listing like in professional books

Have a try on the listings package. Here is an example of what I used some time ago to have a coloured Java listing:

\usepackage{listings}

[...]

\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}

[...]

\begin{lstlisting}
public void here() {
    goes().the().code()
}

[...]

\end{lstlisting}

You may want to customize that. There are several references of the listings package. Just google them.

Scale an equation to fit exact page width

I just had the situation that I wanted this only for lines exceeding \linewidth, that is: Squeezing long lines slightly. Since it took me hours to figure this out, I would like to add it here.

I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g. multline of the mathtools package). So use it conscious.

In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.

\usepackage{environ}         % provides \BODY
\usepackage{etoolbox}        % provides \ifdimcomp
\usepackage{graphicx}        % provides \resizebox

\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation

\RenewEnviron{equation}{
  \settowidth{\myl}{$\BODY$}                       % calculate width and save as \myl
  \origequation
  \ifdimcomp{\the\linewidth}{>}{\the\myl}
  {\ensuremath{\BODY}}                             % True
  {\resizebox{\linewidth}{!}{\ensuremath{\BODY}}}  % False
  \origendequation
}

Before before After after

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

Is there any way I can define a variable in LaTeX?

For variables describing distances, you would use \newlength (and manipulate the values with \setlength, \addlength, \settoheight, \settolength and \settodepth).

Similarly you have access to \newcounter for things like section and figure numbers which should increment throughout the document. I've used this one in the past to provide code samples that were numbered separatly of other figures...

Also of note is \makebox which allows you to store a bit of laid-out document for later re-use (and for use with \settolength...).

Getting the error "Missing $ inserted" in LaTeX

My first guess is that LaTeX chokes on | outside a math environment. Missing $ inserted is usually a symptom of something like that.

How to draw a graph in LaTeX?

I have used graphviz ( https://www.graphviz.org/gallery ) together with LaTeX using dot command to generate graphs in PDF and includegraphics to include those.

If graphviz produces what you are aiming at, this might be the best way to integrate: dot2tex: https://ctan.org/pkg/dot2tex?lang=en

Latex Remove Spaces Between Items in List

This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:

\newenvironment{myitemize}
{ \begin{itemize}
    \setlength{\itemsep}{0pt}
    \setlength{\parskip}{0pt}
    \setlength{\parsep}{0pt}     }
{ \end{itemize}                  } 

Which should be used like this:

\begin{myitemize} 
  \item one 
  \item two 
  \item three 
\end{myitemize}

Source: https://tex.stackexchange.com/a/136050/12065

Latex Multiple Linebreaks

Insert some vertical space

blah blah blah \\
\vspace{1cm}

to scale to the font, use ex (the height of a lowercase "x") as the unit, and there are various predefined lengths related to the line spacing available, you might be particularly interested in baselineskip.

How can I have linebreaks in my long LaTeX equations?

There are a couple ways you can deal with this. First, and perhaps best, is to rework your equation so that it is not so long; it is likely unreadable if it is that long.

If it must be so, check out the AMS Short Math Guide for some ways to handle it. (on the second page)

Personally, I'd use an align environment, so that the breaking and alignment can be precisely controlled. e.g.

\begin{align*}
   x&+y+\dots+\dots+x_100000000\\
   &+x_100000001+\dots+\dots
\end{align*}

which would line up the first plus signs of each line... but obviously, you can set the alignments wherever you like.

References with text in LaTeX

Using the hyperref package, you could also declare a new command by using \newcommand{\secref}[1]{\autoref{#1}. \nameref{#1}} in the pre-amble. Placing \secref{section:my} in the text generates: 1. My section.

How to use Visual Studio Code as Default Editor for Git

Im not sure you can do this, however you can try these additions in your gitconfig file.

Try to replace the kdiff3 from these values to point to visual studio code executable.

[merge] tool = kdiff3 [mergetool "kdiff3"] path = C:/Program Files/KDiff3/kdiff3.exe keepBackup = false trustExitCode = false

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Python loop to run for certain amount of seconds

If I understand you, you can do it with a datetime.timedelta -

import datetime

endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
  if datetime.datetime.now() >= endTime:
    break
  # Blah
  # Blah

OpenCV in Android Studio

This worked for me and was as easy as adding a gradle dependancy:

https://bintray.com/seesaa/maven/opencv#

https://github.com/seesaa/opencv-android

The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.

It seems to build and the suggested test:

static {
    OpenCVLoader.initDebug();
}

spits out a bunch of output that looks about right to me.

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

When to use 'npm start' and when to use 'ng serve'?

npm start will run whatever you have defined for the start command of the scripts object in your package.json file.

So if it looks like this:

"scripts": {
  "start": "ng serve"
}

Then npm start will run ng serve.

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

When I used --allow-unrelated-histories, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories", I used following rebase command:

git pull --rebase=preserve --allow-unrelated-histories

After this commit the uncommitted changes with a commit message. Finally, run the following command:

git rebase --continue

After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.

How to print to console in pytest?

Using -s option will print output of all functions, which may be too much.

If you need particular output, the doc page you mentioned offers few suggestions:

  1. Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

  2. You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    

    You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.

That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

C# Error: Parent does not contain a constructor that takes 0 arguments

You can use a constructor with no parameters in your Parent class :

public parent() { } 

How to clear exisiting dropdownlist items when its content changes?

Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:

AppendDataBoundItems="True"

This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.

SOLUTION

Add AppendDataBoundItems="False" to your dropdownlist.

Now when data is rebound it will automatically clear all existing data beforehand.

Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
    ddl2.DataSource = sql2
    ddl2.DataBind()
End Sub

NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.


TOP TIP

Still want a default list item adding to your dropdown but need to rebind data?

Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.

ddl.Items.Insert(0, New ListItem("Select ...", ""))

Recommendations of Python REST (web services) framework?

I strongly recommend TurboGears or Bottle:

TurboGears:

  • less verbose than django
  • more flexible, less HTML-oriented
  • but: less famous

Bottle:

  • very fast
  • very easy to learn
  • but: minimalistic and not mature

How to convert a date String to a Date or Calendar object?

The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date / java.util.Calendar classes.

Joda's DateFormatter can parse a String to a Joda DateTime.

How to remove a build from itunes connect?

in itunes connect:

AppStore >> iosAPP >> Build (scroll down)

click the red icon as seen in the picture

delete build

Combating AngularJS executing controller twice

I've had this double initialisation happen for a different reason. For some route-transitions in my application I wanted to force scrolling to near the top of the page (e.g. in paginated search results... clicking next should take you to the top of page 2).

I did this by adding a listener to the $rootScope $on $viewContentLoaded which (based on certain conditions) executed

$location.hash('top');

Inadvertently this was causing my routes to be reevaluated and the controllers to be reinitialised

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

How do I run all Python unit tests in a directory?

In python 3, if you're using unittest.TestCase:

  • You must have an empty (or otherwise) __init__.py file in your test directory (must be named test/)
  • Your test files inside test/ match the pattern test_*.py. They can be inside a subdirectory under test/, and those subdirs can be named as anything.

Then, you can run all the tests with:

python -m unittest

Done! A solution less than 100 lines. Hopefully another python beginner saves time by finding this.

How to Specify Eclipse Proxy Authentication Credentials?

In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.

Eclipse screenshot

How can I find my Apple Developer Team id and Team Agent Apple ID?

Apple has changed the interface.

The team ID could be found via this link: https://developer.apple.com/account/#/membership

How to register multiple implementations of the same interface in Asp.Net Core?

How about a service for services?

If we had an INamedService interface (with .Name property), we could write an IServiceCollection extension for .GetService(string name), where the extension would take that string parameter, and do a .GetServices() on itself, and in each returned instance, find the instance whose INamedService.Name matches the given name.

Like this:

public interface INamedService
{
    string Name { get; }
}

public static T GetService<T>(this IServiceProvider provider, string serviceName)
    where T : INamedService
{
    var candidates = provider.GetServices<T>();
    return candidates.FirstOrDefault(s => s.Name == serviceName);
}

Therefore, your IMyService must implement INamedService, but you'll get the key-based resolution you want, right?

To be fair, having to even have this INamedService interface seems ugly, but if you wanted to go further and make things more elegant, then a [NamedServiceAttribute("A")] on the implementation/class could be found by the code in this extension, and it'd work just as well. To be even more fair, Reflection is slow, so an optimization may be in order, but honestly that's something the DI engine should've been helping with. Speed and simplicity are each grand contributors to TCO.

All in all, there's no need for an explicit factory, because "finding a named service" is such a reusable concept, and factory classes don't scale as a solution. And a Func<> seems fine, but a switch block is so bleh, and again, you'll be writing Funcs as often as you'd be writing Factories. Start simple, reusable, with less code, and if that turns out not to do it for ya, then go complex.

java SSL and cert keystore

First of all, there're two kinds of keystores.

Individual and General

The application will use the one indicated in the startup or the default of the system.

It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.

They are encrypted too

In short, the path will be like:

$JAVA_HOME/lib/security/cacerts for the "general one", who has all the CA for the Authorities and is quite important.

From ND to 1D arrays

Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.

def getVector(data_array,col):
    vector = []
    imax = len(data_array)
    for i in range(imax):
        vector.append(data_array[i][col])
    return ( vector )
a = ([1,2,3], [4,5,6])
b = getVector(a,1)
print(b)

Out>[2,5]

So if you need to transpose, you can do something like this:

def transposeArray(data_array):
    # need to test if this is a 1D array 
    # can't do a len(data_array[0]) if it's 1D
    two_d = True
    if isinstance(data_array[0], list):
        dimx = len(data_array[0])
    else:
        dimx = 1
        two_d = False
    dimy = len(data_array)
    # init output transposed array
    data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
    # fill output transposed array
    for i in range(dimx):
        for j in range(dimy):
            if two_d:
                data_array_t[j][i] = data_array[i][j]
            else:
                data_array_t[j][i] = data_array[j]
    return data_array_t

jquery function setInterval

try this declare the function outside the ready event.

    $(document).ready(function(){    
       setInterval(swapImages(),1000); 
    });


    function swapImages(){

    var active = $('.active'); 
    var next = ($('.active').next().length > 0) ? $('.active').next() :         $('#siteNewsHead img:first');
    active.removeClass('active');
    next.addClass('active');
}

Update a dataframe in pandas while iterating row by row

It's better to use lambda functions using df.apply() -

df["ifor"] = df.apply(lambda x: {value} if {condition} else x["ifor"], axis=1)

Java: print contents of text file to screen

Before Java 7:

 BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
 String line;
 while ((line = br.readLine()) != null) {
   System.out.println(line);
 }
  • add exception handling
  • add closing the stream

Since Java 7, there is no need to close the stream, because it implements autocloseable

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Argument list too long error for rm, cp, mv commands

i was facing same problem while copying form source directory to destination

source directory had files ~3 lakcs

i used cp with option -r and it's worked for me

cp -r abc/ def/

it will copy all files from abc to def without giving warning of Argument list too long

Binding a Button's visibility to a bool value in ViewModel

There's a third way that doesn't require a converter or a change to your view model: use a style:

<Style TargetType="Button">
   <Setter Property="Visibility" Value="Collapsed"/>
   <Style.Triggers>
      <DataTrigger Binding="{Binding IsVisible}" Value="True">
         <Setter Property="Visibility" Value="Visible"/>
      </DataTrigger>
   </Style.Triggers>
</Style>

I tend to prefer this technique because I use it in a lot of cases where what I'm binding to is not boolean - e.g. displaying an element only if its DataContext is not null, or implementing multi-state displays where different layouts appear based on the setting of an enum in the view model.

How to change Maven local repository in eclipse

location can be specified in Maven->Installation -> Global Settings: settings.xml

enter image description here

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

Embed website into my site

You can embed websites into another website using the <embed> tag, like so:

<embed src="http://www.example.com" style="width:500px; height: 300px;">

You can change the height, width, and URL to suit your needs.

The <embed> tag is the most up-to-date way to embed websites, as it was introduced with HTML5.

How to get name of dataframe column in pyspark?

The only way is to go an underlying level to the JVM.

df.col._jc.toString().encode('utf8')

This is also how it is converted to a str in the pyspark code itself.

From pyspark/sql/column.py:

def __repr__(self):
    return 'Column<%s>' % self._jc.toString().encode('utf8')

Interfaces with static fields in java for sharing 'constants'

It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.

But don't just take my word for it, Josh Bloch also says it's bad:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.

Manually highlight selected text in Notepad++

"Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

It should be default, but it might be hidden.

"It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

See this for more information

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

I would recommend using rgba(255,255,255,0) because broken (newest) safari thinks that if you are using transparent or rgba(0,0,0,0) in linear-gradent you really mean gray, For more info please head to - What happens in Safari with the transparent color?

Java method to swap primitives

I might do something like the following. Of course, with the wealth of Collection classes, i can't imagine ever needing to use this in any practical code.

public class Shift {
  public static <T> T[] left (final T... i) {
    if (1 >= i.length) {
      return i;
    }
    final T t = i[0];
    int x = 0;
    for (; x < i.length - 1; x++) {
      i[x] = i[x + 1];
    }
    i[x] = t;
    return i;
  }
}

Called with two arguments, it's a swap.

It can be used as follows:

int x = 1;
int y = 2;
Integer[] yx = Shift.left(x,y);

Alternatively:

Integer[] yx = {x,y};
Shift.left(yx);

Then

x = yx[0];
y = yx[1];

Note: it auto-boxes primitives.

Reading the selected value from asp:RadioButtonList using jQuery

The simple way to retrieve checked value of RadioButtonList1 is:

$('#RadioButtonList1 input:checked').val()

Edit by Tim:

where RadioButtonList1 must be the ClientID of the RadioButtonList

var rblSelectedValue = $("#<%= RadioButtonList1.ClientID %> input:checked"); 

Why does Maven have such a bad rep?

Maven is cool.


Stop listening to the alternatives, because right now, there aren't any - which aren't just toys.

Apart from the Microsoft development toolchain - it's best technology that money can't buy.

All these groups who are trying to push 'toolchain du jour' - it's just a cheap attempt to sow confusion and grab market-share.


Haters be hating.

  • SBT

Greatest misnomer in history of the earth. Can your Build pass a Turing test? Fucking ridiculous, a step 10 years back in time with it's ridiculous DSL. Uses IVY dependency management, Maven's middle sibling.

  • ANT

Great for that first project after you graduate from Shockwave development.

You understand XML, and are enthusiastic, but don't really understand build phases, restarting a project 6 months later, why Version Controlling binary artifacts is a false panacea or that someone other than oneself will one day try to work with your project.

  • MAKE

If the whole world runs in the same UNIX terminal, and speaks fluent Bash, then yeah. But why not just become a C/C++ programmer, it's much more fun than Java anyhow.

  • Ruby (Various)

Whatever. Niche, slow. Just develop Ruby then, stay away from Java development.

  • Python

People use Java where they don't trust Python (anywhere there's money involved). If your system is running Python anyway, you wont even be reading this, unless of course you want the Java money - but are stuck developing Python in some web shop.

  • Clojure (Various)

In honour of Stallman, I'll learn Lisp - but for Emacs, not so that I run it upon my VM. I feel that it cheapens the experience.

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

What does ellipsize mean in android?

You can find documentation here.

Based on your requirement you can try according option.

to ellipsize, a neologism, means to shorten text using an ellipsis, i.e. three dots ... or more commonly ligature , to stand in for the omitted bits.

Say original value pf text view is aaabbbccc and its fitting inside the view

start's output will be : ...bccc

end's output will be : aaab...

middle's output will be : aa...cc

marquee's output will be : aaabbbccc auto sliding from right to left

How to convert an array of key-value tuples into an object

Update 2020: As baao notes, Object.fromEntries(arr) now does this on all modern browsers.


You can use Object.assign, the spread operator, and destructuring assignment for an approach that uses map instead of @royhowie’s reduce, which may or may not be more intuitive:

Object.assign(...arr.map(([key, val]) => ({[key]: val})))

E.g.:

_x000D_
_x000D_
var arr = [ [ 'cardType', 'iDEBIT' ],
  [ 'txnAmount', '17.64' ],
  [ 'txnId', '20181' ],
  [ 'txnType', 'Purchase' ],
  [ 'txnDate', '2015/08/13 21:50:04' ],
  [ 'respCode', '0' ],
  [ 'isoCode', '0' ],
  [ 'authCode', '' ],
  [ 'acquirerInvoice', '0' ],
  [ 'message', '' ],
  [ 'isComplete', 'true' ],
  [ 'isTimeout', 'false' ] ]

var obj = Object.assign(...arr.map(([key, val]) => ({[key]: val})))

console.log(obj)
_x000D_
_x000D_
_x000D_

how to add button click event in android studio

package com.mani.helloworldapplication;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
    //Declaration
    TextView tvName;
    Button btnShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //Empty Window
        super.onCreate(savedInstanceState);
        //Load XML File
        setContentView(R.layout.activity_main);

        //Intilization
        tvName = (TextView) findViewById(R.id.tvName);
        btnShow = (Button) findViewById(R.id.btnShow);

        btnShow.setOnClickListener(this);

    }

    @Override
    public void onClick(View v)
    {
        String name = tvName.getText().toString();
        Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show();
    }
}

How do I see active SQL Server connections?

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame
;

See also the Microsoft documentation for sys.sysprocesses.

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

How do I clear only a few specific objects from the workspace?

Use the following command

remove(list=c("data_1", "data_2", "data_3"))

MySQL/SQL: Group by date only on a Datetime column

SELECT SUM(No), HOUR(dateofissue) 
FROM tablename 
WHERE dateofissue>='2011-07-30' 
GROUP BY HOUR(dateofissue)

It will give the hour by sum from a particular day!

How to pull specific directory with git

Tried and tested this works !

mkdir <directory name> ;  //Same directory name as the one you want to pull
cd <directory name>;
git remote add origin <GIT_URL>;
git checkout -b '<branch name>';
git config core.sparsecheckout true;
echo <directory name>/ >> .git/info/sparse-checkout;
git pull origin <pull branch name>

Hope this was helpful!

Changing column names of a data frame

In case we have 2 dataframes the following works

 DF1<-data.frame('a', 'b')
 DF2<-data.frame('c','d')

We change names of DF1 as follows

 colnames(DF1)<- colnames(DF2)

Split Div Into 2 Columns Using CSS

This works good for me. I have divided the screen into two halfs: 20% and 80%:

<div style="width: 20%; float:left">
   #left content in here
</div>

<div style="width: 80%; float:right">
   #right content in there
</div>

Find the nth occurrence of substring in a string

For the special case where you search for the n'th occurence of a character (i.e. substring of length 1), the following function works by building a list of all positions of occurences of the given character:

def find_char_nth(string, char, n):
    """Find the n'th occurence of a character within a string."""
    return [i for i, c in enumerate(string) if c == char][n-1]

If there are fewer than n occurences of the given character, it will give IndexError: list index out of range.

This is derived from @Zv_oDD's answer and simplified for the case of a single character.

Angular ui-grid dynamically calculate height of the grid

.ui-grid, .ui-grid-viewport,.ui-grid-contents-wrapper, .ui-grid-canvas { height: auto !important; }

AngularJS - How to use $routeParams in generating the templateUrl?

Alright, think I got it...

Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.

So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...

When you set up your module, save the $routeProvider globally:

// app.js:
var routeProvider
    , app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){

        routeProvider = $routeProvider;
        $routeProvider
            .when('/', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/home', {templateUrl: '/', controller: 'AppCtrl'})
            .when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
            .when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
            .when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
            .when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
            .when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
            .when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
            .when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
            .when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
            .when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
            .when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
        .otherwise({redirectTo: '/login'});

});

// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){

    var idParam = $routeParams.id;
    routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
    $location.path('/tasks/' + idParam + '/edit/');

});
...

That may be more info than what was needed...

  • Basically, you'll wanna store your Module's $routeProvider var globally, eg as routeProvider so that it can be accessed by your Controllers.

  • Then you can just use routeProvider and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.

  • Then (inside your Controller), set the templateUrl to the view you want to hit.

  • Take out the controller property of the .when() object, lest you get an infinite request loop.

  • And finally (still inside the Controller), use $location.path() to redirect to the route that was just created.

If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.

And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}.

If you clone this at this time, you'll need mongoDB on your machine to run it.

Hope this solves this issue!

Cody

Don't drink your bathwater.

Finding local IP addresses using Python's stdlib

Note: This is not using the standard library, but quite simple.

$ pip install pif

from pif import get_public_ip
get_public_ip()

How to get current moment in ISO 8601 format with date, hour, and minute?

For systems where the default Time Zone is not UTC:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());

The SimpleDateFormat instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.

EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone does not accept a String (corrected by Paul)

Why doesn't Python have multiline comments?

Multiline comments using IDLE on:

  • Mac OS X, after code selection, comment a block of code with Ctrl+3 and uncomment using Ctrl+4.

  • Windows, after code selection, comment a block of code with Ctrl+Alt+3 and uncomment using Ctrl+At+4.

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

What does template <unsigned int N> mean?

A template class is like a macro, only a whole lot less evil.

Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.

The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.

You can also use the "class" or "typename" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.

Consider this template class example code:

#include <cstdio>
template <int I>
class foo
{
  void print()
  {
    printf("%i", I);
  }
};

int main()
{
  foo<26> f;
  f.print();
  return 0;
}

It's functionally the same as this macro-using code:

#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
  void print() \
  { \
    printf("%i", I); \
  } \
};

MAKE_A_FOO(26)

int main()
{
  foo_26 f;
  f.print();
  return 0;
}

Of course, the template version is a billion times safer and more flexible.

CSS selector for first element with class

For some reason none of the above answers seemed to be addressing the case of the real first and only first child of the parent.

#element_id > .class_name:first-child

All the above answers will fail if you want to apply the style to only the first class child within this code.

<aside id="element_id">
  Content
  <div class="class_name">First content that need to be styled</div>
  <div class="class_name">
    Second content that don't need to be styled
    <div>
      <div>
        <div class="class_name">deep content - no style</div>
        <div class="class_name">deep content - no style</div>
        <div>
          <div class="class_name">deep content - no style</div>
        </div>
      </div>
    </div>
  </div>
</aside>

java.io.FileNotFoundException: (Access is denied)

  1. check the rsp's reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

Change :hover CSS properties with JavaScript

You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).

PHP Change Array Keys

No, there is not, for starters, it is impossible to have an array with elements sharing the same key

$x =array(); 
$x['foo'] = 'bar' ; 
$x['foo'] = 'baz' ; #replaces 'bar'

Secondarily, if you wish to merely prefix the numbers so that

$x[0] --> $x['foo_0']  

That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract" which will prefix numeric keys prior to making them variables.

The very simplest way is this:

function rekey( $input , $prefix ) { 
    $out = array(); 
    foreach( $input as $i => $v ) { 
        if ( is_numeric( $i ) ) { 
            $out[$prefix . $i] = $v; 
            continue; 
        }
        $out[$i] = $v;
    }
    return $out;
}

Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.

<section> 
    <foo_0></foo_0>
   <foo_1></foo_1>
   <bar></bar>
   <foo_2></foo_2>
</section>

Is not good XML.

<section> 
   <foo></foo>
   <foo></foo>
   <bar></bar>
   <foo></foo>
</section>

Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:

section => { 
    0 => [ foo , {} ]
    1 => [ foo , {} ]
    2 => [ bar , {} ]
    3 => [ foo , {} ] 
}

Writelines writes lines without newline, Just fills the file

As others have mentioned, and counter to what the method name would imply, writelines does not add line separators. This is a textbook case for a generator. Here is a contrived example:

def item_generator(things):
    for item in things:
        yield item
        yield '\n'

def write_things_to_file(things):
    with open('path_to_file.txt', 'wb') as f:
        f.writelines(item_generator(things))

Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!

How do you loop through each line in a text file using a windows batch file?

The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;

To read lines of any content, you need the delayed expansion toggling technic.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ text.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore.

DelayedExpansion needs to be disabled, when accessing the %%a parameter, else exclamation marks ! and carets ^ will be lost, as they have special meanings in that mode.

But to remove the line number from the line, the delayed expansion needs to be enabled.
set "var=!var:*:=!" removes all up to the first colon (using delims=: would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.

The only limitation is now the line length limit of ~8191, but there seems no way to overcome this.

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

How to use ImageBackground to set background image for screen in react-native

i achieved this by:

import { ImageBackground } from 'react-native';

<ImageBackground style={ styles.imgBackground } 
                 resizeMode='cover' 
                 source={require('./Your/Path.png')}>

   //place your now nested component JSX code here

</ImageBackground>

And then the Styles:

imgBackground: {
        width: '100%',
        height: '100%',
        flex: 1 
},

Using Jasmine to spy on a function without an object

TypeScript users:

I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.

In the test file, convert the import of the function from this:

import {foo} from '../foo_functions';

x = foo(y);

To this:

import * as FooFunctions from '../foo_functions';

x = FooFunctions.foo(y);

Then you can spy on FooFunctions.foo :)

spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();

ng-mouseover and leave to toggle item using mouse in angularjs

I'd probably change your example to look like this:

<ul ng-repeat="task in tasks">
  <li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
  <span ng-show="task.editable"><a>Edit</a></span>
</ul>

//js
$scope.enableEdit = function(item){
  item.editable = true;
};

$scope.disableEdit = function(item){
  item.editable = false;
};

I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.

Example jsFiddle.

Vertical (rotated) text in HTML table

After having tried for over two hours, I can safely say that all the method mentioned so far don't work across browsers, or for IE even across browser versions...

For example (top upvoted answer):

 filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */
     -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */

rotates twice in IE9, once for filter, and once for -ms-filter, so...

All other mentioned methods do not work either, at least not if you have to set no fixed height/width of the table header cell (with background color), where it should automatically adjust to size of the highest element.

So to elaborate on the server-side image generation proposed by Nathan Long, which is really the only universially working method, here my VB.NET code for a generic handler (*.ashx ):

Imports System.Web
Imports System.Web.Services


Public Class GenerateImage
    Implements System.Web.IHttpHandler


    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World!")
        context.Response.ContentType = "image/png"

        Dim strText As String = context.Request.QueryString("text")
        Dim strRotate As String = context.Request.QueryString("rotate")
        Dim strBGcolor As String = context.Request.QueryString("bgcolor")

        Dim bRotate As Boolean = True

        If String.IsNullOrEmpty(strText) Then
            strText = "No Text"
        End If


        Try
            If Not String.IsNullOrEmpty(strRotate) Then
                bRotate = System.Convert.ToBoolean(strRotate)
            End If
        Catch ex As Exception

        End Try


        'Dim img As System.Drawing.Image = GenerateImage(strText, "Arial", bRotate)
        'Dim img As System.Drawing.Image = CreateBitmapImage(strText, bRotate)

        ' Generic error in GDI+
        'img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

        'Dim bm As System.Drawing.Bitmap = New System.Drawing.Bitmap(img)
        'bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

        Using msTempOutputStream As New System.IO.MemoryStream
            'Dim img As System.Drawing.Image = GenerateImage(strText, "Arial", bRotate)
            Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)
                img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)
                msTempOutputStream.Flush()

                context.Response.Buffer = True
                context.Response.ContentType = "image/png"
                context.Response.BinaryWrite(msTempOutputStream.ToArray())
            End Using ' img

        End Using ' msTempOutputStream

    End Sub ' ProcessRequest


    Private Function CreateBitmapImage(strImageText As String) As System.Drawing.Image
        Return CreateBitmapImage(strImageText, True)
    End Function ' CreateBitmapImage


    Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean) As System.Drawing.Image
        Return CreateBitmapImage(strImageText, bRotate, Nothing)
    End Function


    Private Function InvertMeAColour(ColourToInvert As System.Drawing.Color) As System.Drawing.Color
        Const RGBMAX As Integer = 255
        Return System.Drawing.Color.FromArgb(RGBMAX - ColourToInvert.R, RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B)
    End Function



    Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean, strBackgroundColor As String) As System.Drawing.Image
        Dim bmpEndImage As System.Drawing.Bitmap = Nothing

        If String.IsNullOrEmpty(strBackgroundColor) Then
            strBackgroundColor = "#E0E0E0"
        End If

        Dim intWidth As Integer = 0
        Dim intHeight As Integer = 0


        Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray
        bgColor = System.Drawing.ColorTranslator.FromHtml(strBackgroundColor)

        Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black
        TextColor = InvertMeAColour(bgColor)

        'TextColor = Color.FromArgb(102, 102, 102)



        ' Create the Font object for the image text drawing.
        Using fntThisFont As New System.Drawing.Font("Arial", 11, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel)

            ' Create a graphics object to measure the text's width and height.
            Using bmpInitialImage As New System.Drawing.Bitmap(1, 1)

                Using gStringMeasureGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpInitialImage)
                    ' This is where the bitmap size is determined.
                    intWidth = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Width)
                    intHeight = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Height)

                    ' Create the bmpImage again with the correct size for the text and font.
                    bmpEndImage = New System.Drawing.Bitmap(bmpInitialImage, New System.Drawing.Size(intWidth, intHeight))

                    ' Add the colors to the new bitmap.
                    Using gNewGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpEndImage)
                        ' Set Background color
                        'gNewGraphics.Clear(Color.White)
                        gNewGraphics.Clear(bgColor)
                        gNewGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias
                        gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias


                        ''''

                        'gNewGraphics.TranslateTransform(bmpEndImage.Width, bmpEndImage.Height)
                        'gNewGraphics.RotateTransform(180)
                        'gNewGraphics.RotateTransform(0)
                        'gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault


                        gNewGraphics.DrawString(strImageText, fntThisFont, New System.Drawing.SolidBrush(TextColor), 0, 0)

                        gNewGraphics.Flush()

                        If bRotate Then
                            'bmpEndImage = rotateImage(bmpEndImage, 90)
                            'bmpEndImage = RotateImage(bmpEndImage, New PointF(0, 0), 90)
                            'bmpEndImage.RotateFlip(RotateFlipType.Rotate90FlipNone)
                            bmpEndImage.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone)
                        End If ' bRotate

                    End Using ' gNewGraphics

                End Using ' gStringMeasureGraphics

            End Using ' bmpInitialImage

        End Using ' fntThisFont

        Return bmpEndImage
    End Function ' CreateBitmapImage


    ' http://msdn.microsoft.com/en-us/library/3zxbwxch.aspx
    ' http://msdn.microsoft.com/en-us/library/7e1w5dhw.aspx
    ' http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=286
    ' http://road-blogs.blogspot.com/2011/01/rotate-text-in-ssrs.html
    Public Shared Function GenerateImage_CrappyOldReportingServiceVariant(ByVal strText As String, ByVal strFont As String, bRotate As Boolean) As System.Drawing.Image
        Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray
        bgColor = System.Drawing.ColorTranslator.FromHtml("#E0E0E0")


        Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black
        'TextColor = System.Drawing.Color.FromArgb(255, 0, 0, 255)

        If String.IsNullOrEmpty(strFont) Then
            strFont = "Arial"
        Else
            If strFont.Trim().Equals(String.Empty) Then
                strFont = "Arial"
            End If
        End If


        'Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Regular
        Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Bold
        Dim fontFamily As New System.Drawing.FontFamily(strFont)
        Dim iFontSize As Integer = 8 '//Change this as needed


        ' vice-versa, because 270° turn
        'Dim height As Double = 2.25
        Dim height As Double = 4
        Dim width As Double = 1

        ' width = 10
        ' height = 10

        Dim bmpImage As New System.Drawing.Bitmap(1, 1)
        Dim iHeight As Integer = CInt(height * 0.393700787 * bmpImage.VerticalResolution) 'y DPI
        Dim iWidth As Integer = CInt(width * 0.393700787 * bmpImage.HorizontalResolution) 'x DPI

        bmpImage = New System.Drawing.Bitmap(bmpImage, New System.Drawing.Size(iWidth, iHeight))



        '// Create the Font object for the image text drawing.
        'Dim MyFont As New System.Drawing.Font("Arial", iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)
        '// Create a graphics object to measure the text's width and height.
        Dim MyGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpImage)
        MyGraphics.Clear(bgColor)


        Dim stringFormat As New System.Drawing.StringFormat()
        stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical
        'stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical Or System.Drawing.StringFormatFlags.DirectionRightToLeft
        Dim solidBrush As New System.Drawing.SolidBrush(TextColor)
        Dim pointF As New System.Drawing.PointF(CSng(iWidth / 2 - iFontSize / 2 - 2), 5)
        Dim font As New System.Drawing.Font(fontFamily, iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)


        MyGraphics.TranslateTransform(bmpImage.Width, bmpImage.Height)
        MyGraphics.RotateTransform(180)
        MyGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault
        MyGraphics.DrawString(strText, font, solidBrush, pointF, stringFormat)
        MyGraphics.ResetTransform()

        MyGraphics.Flush()

        'If Not bRotate Then
        'bmpImage.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone)
        'End If

        Return bmpImage
    End Function ' GenerateImage



    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property ' IsReusable


End Class

Note that if you think that this part

        Using msTempOutputStream As New System.IO.MemoryStream
            'Dim img As System.Drawing.Image = GenerateImage(strText, "Arial", bRotate)
            Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)
                img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)
                msTempOutputStream.Flush()

                context.Response.Buffer = True
                context.Response.ContentType = "image/png"
                context.Response.BinaryWrite(msTempOutputStream.ToArray())
            End Using ' img

        End Using ' msTempOutputStream

can be replaced with

img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

because it works on the development server, then you are sorely mistaken to assume the very same code wouldn't throw a Generic GDI+ exception if you deploy it to a Windows 2003 IIS 6 server...

then use it like this:

<img alt="bla" src="GenerateImage.ashx?no_cache=123&text=Hello%20World&rotate=true" />

How to catch all exceptions in c# using try and catch?

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        throw new NotImplementedException();
    }

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

MySQL error 1449: The user specified as a definer does not exist

Fixed by running this following comments.

grant all on *.* to 'web2vi'@'%' identified by 'root' with grant option;
FLUSH PRIVILEGES;

if you are getting some_other instead of web2vi then you have to change the name accordingly.

Custom pagination view in Laravel 5

If you want to customize your pagination link using next and prev. You can see at Paginator.php Inside it, there's some method I'm using Laravel 7

<a href="{{ $paginator->previousPageUrl() }}" < </a>
<a href="{{ $paginator->nextPageUrl() }}" > </a>

To limit items, in controller using paginate()

$paginator = Model::paginate(int);

hasNext in Python iterators?

If you really need a has-next functionality (because you're just faithfully transcribing an algorithm from a reference implementation in Java, say, or because you're writing a prototype that will need to be easily transcribed to Java when it's finished), it's easy to obtain it with a little wrapper class. For example:

class hn_wrapper(object):
  def __init__(self, it):
    self.it = iter(it)
    self._hasnext = None
  def __iter__(self): return self
  def next(self):
    if self._hasnext:
      result = self._thenext
    else:
      result = next(self.it)
    self._hasnext = None
    return result
  def hasnext(self):
    if self._hasnext is None:
      try: self._thenext = next(self.it)
      except StopIteration: self._hasnext = False
      else: self._hasnext = True
    return self._hasnext

now something like

x = hn_wrapper('ciao')
while x.hasnext(): print next(x)

emits

c
i
a
o

as required.

Note that the use of next(sel.it) as a built-in requires Python 2.6 or better; if you're using an older version of Python, use self.it.next() instead (and similarly for next(x) in the example usage). [[You might reasonably think this note is redundant, since Python 2.6 has been around for over a year now -- but more often than not when I use Python 2.6 features in a response, some commenter or other feels duty-bound to point out that they are 2.6 features, thus I'm trying to forestall such comments for once;-)]]

How to define an empty object in PHP

Short answer

$myObj = new stdClass();

// OR 

$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

Long answer

I love how easy is to create objects of anonymous type in JavaScript:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: "Bar value"
};
console.log(myObj.foo); //Output: Foo value

So I always try to write this kind of objects in PHP like javascript does:

//PHP >= 5.4
$myObj = (object) [
    "foo" => "Foo value",
    "bar" => "Bar value"
];

//PHP < 5.4
$myObj = (object) array(
    "foo" => "Foo value",
    "bar" => "Bar value"
);

echo $myObj->foo; //Output: Foo value

But as this is basically an array you can't do things like assign anonymous functions to a property like js does:

//JavaScript
var myObj = {
    foo: "Foo value",
    bar: function(greeting) {
        return greeting + " bar";
    }
};
console.log(myObj.bar("Hello")); //Output: Hello bar

//PHP >= 5.4
$myObj = (object) [
    "foo" => "Foo value",
    "bar" => function($greeting) {
        return $greeting . " bar";
    }
];
var_dump($myObj->bar("Hello")); //Throw 'undefined function' error
var_dump($myObj->bar); //Output: "object(Closure)"

Well, you can do it, but IMO isn't practical / clean:

$barFunc = $myObj->bar;
echo $barFunc("Hello"); //Output: Hello bar

Also, using this synthax you can find some funny surprises, but works fine for most cases.

Does bootstrap have builtin padding and margin classes?

This is taken from the docs and it works very well. Here is the link

  • m - for classes that set margin
  • p - for classes that set padding

Where sides are one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • l - for classes that set margin-left or padding-left
  • r - for classes that set margin-right or padding-right

if you want to give margin to the left use mt-x where x stands for [1,2,3,4,5]

same for padding

example be like

<div class = "mt-5"></div>
<div class = "pt-5"></div>

Use only p-x or m-x for getting padding and margin of x from all sides.

Repeat a string in JavaScript a number of times

In a new ES6 harmony, you will have native way for doing this with repeat. Also ES6 right now only experimental, this feature is already available in Edge, FF, Chrome and Safari

"abc".repeat(3) // "abcabcabc"

And surely if repeat function is not available you can use old-good Array(n + 1).join("abc")

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

Real world use of JMS/message queues?

Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer by create a Message object, putting it on a particular Queue, and moving forward.
There would be a set of Consumers who would subscribe to the Queue in question, and would take care handling the Message sent across. Note that during the course of this transaction, the Producers are decoupled from the logic of how a given Message would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message transactions by providing MessageBrokers.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have posted a similar solution for the same problem,

visit How to use javascript to set attribute of selected web element using selenium Webdriver using java?

Here First we have find the element in my case I have found the element using xpath then we have traverse through the list of elements and then We have cast the driver object to the Executor object and create a script here the first argument is the element and second argument is the property and the third argument is the new value

List<WebElement> unselectableDiv = driver
                .findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));

        for (WebElement element : unselectableDiv) {

            // System.out.println( "**** Checking the size of div "+unselectableDiv.size());

            JavascriptExecutor js = (JavascriptExecutor) driver;

            String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";

            js.executeScript(scriptSetAttr, element, "unselectable", "off");

            System.out.println(" *****   check value of Div property " + element.getAttribute("unselectable"));

        }

Is it possible to set an object to null?

You want to check if an object is NULL/empty. Being NULL and empty are not the same. Like Justin and Brian have already mentioned, in C++ NULL is an assignment you'd typically associate with pointers. You can overload operator= perhaps, but think it through real well if you actually want to do this. Couple of other things:

  1. In C++ NULL pointer is very different to pointer pointing to an 'empty' object.
  2. Why not have a bool IsEmpty() method that returns true if an object's variables are reset to some default state? Guess that might bypass the NULL usage.
  3. Having something like A* p = new A; ... p = NULL; is bad (no delete p) unless you can ensure your code will be garbage collected. If anything, this'd lead to memory leaks and with several such leaks there's good chance you'd have slow code.
  4. You may want to do this class Null {}; Null _NULL; and then overload operator= and operator!= of other classes depending on your situation.

Perhaps you should post us some details about the context to help you better with option 4.

Arpan

Stacked Tabs in Bootstrap 3

To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.

https://github.com/dbtek/bootstrap-vertical-tabs

How to send email to multiple recipients with addresses stored in Excel?

ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

Are you using Git-Bash in Windows? I was getting the same error until I tried PowerShell and magically this error disappeared.

Delete keychain items when an app is uninstalled

There is no trigger to perform code when the app is deleted from the device. Access to the keychain is dependant on the provisioning profile that is used to sign the application. Therefore no other applications would be able to access this information in the keychain.

It does not help with you aim to remove the password in the keychain when the user deletes application from the device but it should give you some comfort that the password is not accessible (only from a re-install of the original application).

TypeError: Image data can not convert to float

From what I understand of the scikit-image docs (http://scikit-image.org/docs/dev/index.html), imshow() takes a ndarray as an argument, and not a dictionary:

http://scikit-image.org/docs/dev/api/skimage.io.html?highlight=imshow#skimage.io.imshow

Maybe if you post the whole stack trace, we could see that the TypeError comes somewhere deep from imshow().

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Like the docs say, think about it this way. If you were to do an application like a book reader, you will not want to load all the fragments into memory at once. You would like to load and destroy Fragments as the user reads. In this case you will use FragmentStatePagerAdapter. If you are just displaying 3 "tabs" that do not contain a lot of heavy data (like Bitmaps), then FragmentPagerAdapter might suit you well. Also, keep in mind that ViewPager by default will load 3 fragments into memory. The first Adapter you mention might destroy View hierarchy and re load it when needed, the second Adapter only saves the state of the Fragment and completely destroys it, if the user then comes back to that page, the state is retrieved.

MongoDB Show all contents from all collections

Once you are in terminal/command line, access the database/collection you want to use as follows:

show dbs
use <db name>
show collections

choose your collection and type the following to see all contents of that collection:

db.collectionName.find()

More info here on the MongoDB Quick Reference Guide.

convert streamed buffers to utf8-string

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

What is the convention for word separator in Java package names?

Underscores look ugly in package names. For what is worth, in case of names compound of three or more words I use initials (for example: com.company.app.ingresoegresofijo (ingreso/egreso fijo) -> com.company.app.iefijo) and then document the package purpose in package-info.java.

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

If you're running in a Linux environment, open the file /etc/hosts.allow add the following line

ALL

Wildcards

Also check the /etc/hostname and /etc/host to see if there might be something wrong there.

I had to change my / etc / host from

127.0.0.1 localhost
127.0.1.1 AMK

to

127.0.0.1 localhost
127.0.0.1 AMK

also wrote in ALL in the file /etc/hosts.allow which was previously completely empty

Now everything works

do not know how safe it is. you have to read more about possible options for /etc/hosts.allow to do something that requires a touch of security.

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

Use chrome as browser in C#?

Update for 2014:

I use geckofx, a healthy open source project that (as of this writing) keeps up to date pretty well with the latest Firefox releases.

To embed Chrome, you might consider another healthy looking open source project, Xilium.cefGlue, based on The Chromium Embedded Framework (CEF).

Both of these support WPF and Winforms, and both projects have support for .net and mono.

How do I parse JSON with Ruby on Rails?

require 'json'

hash = JSON.parse string

work with the hash and do what you want to do.

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

PHP - Get array value with a numeric index

I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function. In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.

So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].

function array_get_by_index($index, $array) {

    $i=0;
    foreach ($array as $value) {
        if($i==$index) {
            return $value;
        }
        $i++;
    }
    // may be $index exceedes size of $array. In this case NULL is returned.
    return NULL;
}

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

removeEventListener on anonymous functions in JavaScript

A not so anonymous option

element.funky = function() {
    console.log("Click!");
};
element.funky.type = "click";
element.funky.capt = false;
element.addEventListener(element.funky.type, element.funky, element.funky.capt);
// blah blah blah
element.removeEventListener(element.funky.type, element.funky, element.funky.capt);

Since receiving feedback from Andy (quite right, but as with many examples, I wished to show a contextual expansion of the idea), here's a less complicated exposition:

<script id="konami" type="text/javascript" async>
    var konami = {
        ptrn: "38,38,40,40,37,39,37,39,66,65",
        kl: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
    };
    document.body.addEventListener( "keyup", function knm ( evt ) {
        konami.kl = konami.kl.slice( -9 );
        konami.kl.push( evt.keyCode );
        if ( konami.ptrn === konami.kl.join() ) {
            evt.target.removeEventListener( "keyup", knm, false );

            /* Although at this point we wish to remove a listener
               we could easily have had multiple "keyup" listeners
               each triggering different functions, so we MUST
               say which function we no longer wish to trigger
               rather than which listener we wish to remove.

               Normal scoping will apply to where we can mention this function
               and thus, where we can remove the listener set to trigger it. */

            document.body.classList.add( "konami" );
        }
    }, false );
    document.body.removeChild( document.getElementById( "konami" ) );
</script>

This allows an effectively anonymous function structure, avoids the use of the practically deprecated callee, and allows easy removal.

Incidentally: The removal of the script element immediately after setting the listener is a cute trick for hiding code one would prefer wasn't starkly obvious to prying eyes (would spoil the surprise ;-)

So the method (more simply) is:

element.addEventListener( action, function name () {
    doSomething();
    element.removeEventListener( action, name, capture );
}, capture );

Limiting floats to two decimal points

orig_float = 232569 / 16000.0

14.5355625

short_float = float("{:.2f}".format(orig_float)) 

14.54

How to effectively work with multiple files in Vim

Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say :tabe [filename] to open a file in a new tab. Cycling between tabs is done by clicking on the tab or by the key combinations [n]gt and gT. Graphical Vim even has graphical tabs.

cannot load such file -- bundler/setup (LoadError)

This was happening in the production environment for me.

rm /vendor/bundle

then bundle install --deployment

resolved the issue.

Difference between subprocess.Popen and os.system

When running python (cpython) on windows the <built-in function system> os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.

On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.

That said, an important piece of advice comes from os.system docs, which says:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

Check if an object belongs to a class in Java

If you ever need to do this dynamically, you can use the following:

boolean isInstance(Object object, Class<?> type) {
    return type.isInstance(object);
}

You can get an instance of java.lang.Class by calling the instance method Object::getClass on any object (returns the Class which that object is an instance of), or you can do class literals (for example, String.class, List.class, int[].class). There are other ways as well, through the reflection API (which Class itself is the entry point for).

how to get GET and POST variables with JQuery?

simple, but yet usefull to get vars/values from URL:

function getUrlVars() {
    var vars = [], hash, hashes = null;
    if (window.location.href.indexOf("?") && window.location.href.indexOf("&")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    } else if (window.location.href.indexOf("?")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
    }
    if (hashes != null) {
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}

I found it somewhere on the internet, just fixed few bugs

How is TeamViewer so fast?

A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP

ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.

Full source (it's huge!) is provided. It implements the RTP protocol.

How to check if a string contains an element from a list in Python

Check if it matches this regex:

'(\.pdf$|\.doc$|\.xls$)'

Note: if you extensions are not at the end of the url, remove the $ characters, but it does weaken it slightly

Count all values in a matrix greater than a value

There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):

>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[  123, 24123, 32432],
       [  234,    24,    23]])
>>> b = y > 200
>>> b
array([[False,  True,  True],
       [ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432,   234])
>>> len(y[b])
3
>>>> y[b].sum()
56789

Update:

As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:

>>>> (y>200).sum()
3

which is a simpler solution.


Speed comparison with filter:

### use boolean/mask array ###

b = y > 200

%timeit y[b]
100000 loops, best of 3: 3.31 us per loop

%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop

### use filter ###

x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop

%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop

%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop

%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop

*** use numpy.where ***

nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop

%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop

List of zeros in python

$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]

Loading an image to a <img> from <input file>

_x000D_
_x000D_
var outImage ="imagenFondo";_x000D_
function preview_2(obj)_x000D_
{_x000D_
 if (FileReader)_x000D_
 {_x000D_
  var reader = new FileReader();_x000D_
  reader.readAsDataURL(obj.files[0]);_x000D_
  reader.onload = function (e) {_x000D_
  var image=new Image();_x000D_
  image.src=e.target.result;_x000D_
  image.onload = function () {_x000D_
   document.getElementById(outImage).src=image.src;_x000D_
  };_x000D_
  }_x000D_
 }_x000D_
 else_x000D_
 {_x000D_
      // Not supported_x000D_
 }_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>preview photo</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<form>_x000D_
 <input type="file" onChange="preview_2(this);"><br>_x000D_
 <img id="imagenFondo" style="height: 300px;width: 300px;">_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

private async Task<DateTime> CountToAsync(int num = 1000)
{
    await Task.Yield();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("#{0}", i);
    }
    return DateTime.Now;
}

Update Row if it Exists Else Insert Logic with Entity Framework

If you know that you're using the same context and not detaching any entities, you can make a generic version like this:

public void InsertOrUpdate<T>(T entity, DbContext db) where T : class
{
    if (db.Entry(entity).State == EntityState.Detached)
        db.Set<T>().Add(entity);

    // If an immediate save is needed, can be slow though
    // if iterating through many entities:
    db.SaveChanges(); 
}

db can of course be a class field, or the method can be made static and an extension, but this is the basics.

How do I make Git use the editor of my choice for commits?

Mvim as your git editor

Like all the other GUI applications, you have to launch mvim with the wait flag.

git config --global core.editor "mvim --remote-wait"

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

How can git be installed on CENTOS 5.5?

It looks like the repos for CentOS 5 are disappearing. Most of the ones mentioned in this question are no longer online, don't seem to have Git, or have a really old version of Git. Below is the script I use to build OpenSSL, IDN2, PCRE, cURL and Git from sources. Both the git:// and https:// protocols will be available for cloning.

Over time the names of the archives will need to be updates. For example, as of this writing, openssl-1.0.2k.tar.gz is the latest available in the 1.0.2 family.

Dale Anderson's answer using RHEL repos looks good at the moment, but its a fairly old version. Red Hat provides Git version 1.8, while the script below builds 2.12 from sources.


#!/usr/bin/env bash

# OpenSSL installs into lib64/, while cURL installs into lib/
INSTALL_ROOT=/usr/local
INSTALL_LIB32="$INSTALL_ROOT/lib"
INSTALL_LIB64="$INSTALL_ROOT/lib64"

OPENSSL_TAR=openssl-1.0.2k.tar.gz
OPENSSL_DIR=openssl-1.0.2k

ZLIB_TAR=zlib-1.2.11.tar.gz
ZLIB_DIR=zlib-1.2.11

UNISTR_TAR=libunistring-0.9.7.tar.gz
UNISTR_DIR=libunistring-0.9.7

IDN2_TAR=libidn2-0.16.tar.gz
IDN2_DIR=libidn2-0.16

PCRE_TAR=pcre2-10.23.tar.gz
PCRE_DIR=pcre2-10.23

CURL_TAR=curl-7.53.1.tar.gz
CURL_DIR=curl-7.53.1

GIT_TAR=v2.12.2.tar.gz
GIT_DIR=git-2.12.2

###############################################################################

# I don't like doing this, but...
read -s -p "Please enter password for sudo: " SUDO_PASSWWORD

###############################################################################

echo
echo "********** zLib **********"

wget "http://www.zlib.net/$ZLIB_TAR" -O "$ZLIB_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$ZLIB_DIR" &>/dev/null
tar -xzf "$ZLIB_TAR"
cd "$ZLIB_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build zLib"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** Unistring **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.gnu.org/gnu/libunistring/$UNISTR_TAR" --no-check-certificate -O "$UNISTR_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$UNISTR_DIR" &>/dev/null
tar -xzf "$UNISTR_TAR"
cd "$UNISTR_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** IDN **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://alpha.gnu.org/gnu/libidn/$IDN2_TAR" --no-check-certificate -O "$IDN2_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$IDN2_DIR" &>/dev/null
tar -xzf "$IDN2_TAR"
cd "$IDN2_DIR"

LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build IDN"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** OpenSSL **********"

wget "https://www.openssl.org/source/$OPENSSL_TAR" -O "$OPENSSL_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$OPENSSL_DIR" &>/dev/null
tar -xzf "$OPENSSL_TAR"
cd "$OPENSSL_DIR"

# OpenSSL and enable-ec_nistp_64_gcc_12 option
IS_X86_64=$(uname -m 2>&1 | egrep -i -c "(amd64|x86_64)")

CONFIG=./config
CONFIG_FLAGS=(no-ssl2 no-ssl3 no-comp shared "-Wl,-rpath,$INSTALL_LIB64" --prefix="$INSTALL_ROOT" --openssldir="$INSTALL_ROOT")
if [[ "$IS_X86_64" -eq "1" ]]; then
    CONFIG_FLAGS+=("enable-ec_nistp_64_gcc_128")
fi

"$CONFIG" "${CONFIG_FLAGS[@]}"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make depend
make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build OpenSSL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install_sw

cd ..

###############################################################################

echo
echo "********** PCRE **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.pcre.org/pub/pcre//$PCRE_TAR" --no-check-certificate -O "$PCRE_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$PCRE_DIR" &>/dev/null
tar -xzf "$PCRE_TAR"
cd "$PCRE_DIR"

make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
    LIBS="-lidn2 -lz -ldl -lpthread" ./configure --enable-shared --enable-pcre2-8 --enable-pcre2-16 --enable-pcre2-32 \
    --enable-unicode-properties --enable-pcregrep-libz --prefix="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make all -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build PCRE"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** cURL **********"

# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://curl.haxx.se/download/$CURL_TAR" --no-check-certificate -O "$CURL_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$CURL_DIR" &>/dev/null
tar -xzf "$CURL_TAR"
cd "$CURL_DIR"

CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
    LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" \
    ./configure --enable-shared --with-ssl="$INSTALL_ROOT" --with-libidn2="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build cURL"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

echo "$SUDO_PASSWWORD" | sudo -S make install

cd ..

###############################################################################

echo
echo "********** Git **********"

wget "https://github.com/git/git/archive/$GIT_TAR" -O "$GIT_TAR"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to download Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

rm -rf "$GIT_DIR" &>/dev/null
tar -xzf "$GIT_TAR"
cd "$GIT_DIR"

make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64,-rpath,$INSTALL_LIB32 -L$INSTALL_LIB64 -L$INSTALL_LIB32" \
    LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" ./configure --with-openssl --with-curl --with-libpcre --prefix="$INSTALL_ROOT"

if [[ "$?" -ne "0" ]]; then
    echo "Failed to configure Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

make all -j 4

if [ "$?" -ne "0" ]; then
    echo "Failed to build Git"
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

MAKE=make
MAKE_FLAGS=(install)
if [[ ! -z `which asciidoc 2>/dev/null | grep -v 'no asciidoc'` ]]; then
    if [[ ! -z `which xmlto 2>/dev/null | grep -v 'no xmlto'` ]]; then
        MAKE_FLAGS+=("install-doc" "install-html" "install-info")
    fi
fi

echo "$SUDO_PASSWWORD" | sudo -S "$MAKE" "${MAKE_FLAGS[@]}"

cd ..

###############################################################################

echo
echo "********** Cleanup **********"

rm -rf "$OPENSSL_TAR  $OPENSSL_DIR  $UNISTR_TAR  $UNISTR_DIR  $CURL_TAR  $CURL_DIR"
rm -rf "$PCRE_TAR $PCRE_DIR $ZLIB_TAR $ZLIB_DIR $IDN2_TAR $IDN2_DIR $GIT_TAR $GIT_DIR"

[[ "$0" = "$BASH_SOURCE" ]] && exit 0 || return 0

Convert a Python list with strings all to lowercase or uppercase

For this sample the comprehension is fastest

$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]'
1000 loops, best of 3: 809 usec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)'
1000 loops, best of 3: 1.12 msec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)'
1000 loops, best of 3: 1.77 msec per loop

Converting bytes to megabytes

In general, it's wrong to use decimal SI prefixes (e.g. kilo, mega) when referring to binary data sizes (except in casual usage). It's ambiguous and causes confusion. To be precise you can use binary prefixes (e.g. 1 mebibyte = 1 MiB = 1024 kibibytes = 2^20 bytes). When someone else uses decimal SI prefixes for binary data you need to get more information before you can know what is meant.

ImportError: No module named request

from @Zzmilanzz's answer I used

try: #python3
    from urllib.request import urlopen
except: #python2
    from urllib2 import urlopen

Get counts of all tables in a schema

You have to use execute immediate (dynamic sql).

DECLARE 
v_owner varchar2(40); 
v_table_name varchar2(40); 
cursor get_tables is 
select distinct table_name,user 
from user_tables 
where lower(user) = 'schema_name'; 
begin 
open get_tables; 
loop
    fetch get_tables into v_table_name,v_owner; 
    EXIT WHEN get_tables%NOTFOUND;
    execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED) 
    SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'')     FROM ' || v_table_name; 
end loop;
CLOSE get_tables; 
END; 

Insert new item in array on any position in PHP

Based on @Halil great answer, here is simple function how to insert new element after a specific key, while preserving integer keys:

private function arrayInsertAfterKey($array, $afterKey, $key, $value){
    $pos   = array_search($afterKey, array_keys($array));

    return array_merge(
        array_slice($array, 0, $pos, $preserve_keys = true),
        array($key=>$value),
        array_slice($array, $pos, $preserve_keys = true)
    );
} 

How to get the selected item from ListView?

myList.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
      MyClass selItem = (MyClass) adapter.getItem(position);
   }
}

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

make div's height expand with its content

I added Bootstrap to a project with section tags that I had set to 100% of screen height. It worked well until I made the project responsive, at which point I borrowed part of jennyfofenny's answer so my section background matched background of the content when the screen size changed on smaller screens.

My new section CSS looks like this:

section {
    // min-height so it looks good on big screen
    // but resizes on a small-screen
    min-height: 100%;
    min-height: 100vh;
    width:100%;
    width:100vh;
}

Let's say you've got a section that's a certain color. By using min-height, if the width of the section shrinks because of a smaller-screen, the height of the section will expand, the content will stay within the section, and your background will stay the desired color.

Recommended method for escaping HTML in Java

org.apache.commons.lang3.StringEscapeUtils is now deprecated. You must now use org.apache.commons.text.StringEscapeUtils by

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>${commons.text.version}</version>
    </dependency>

Is there 'byte' data type in C++?

namespace std
{
  // define std::byte
  enum class byte : unsigned char {};

};

This if your C++ version does not have std::byte will define a byte type in namespace std. Normally you don't want to add things to std, but in this case it is a standard thing that is missing.

std::byte from the STL does much more operations.

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Python exit commands - why so many and when should each be used?

Different Means of Exiting

os._exit():

  • Exit the process without calling the cleanup handlers.

exit(0):

  • a clean exit without any errors / problems.

exit(1):

  • There was some issue / error / problem and that is why the program is exiting.

sys.exit():

  • When the system and python shuts down; it means less memory is being used after the program is run.

quit():

  • Closes the python file.

Summary

Basically they all do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

Otherwise mainly use exit() or quit().

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

Combine two (or more) PDF's

I had to solve a similar problem and what I ended up doing was creating a small pdfmerge utility that uses the PDFSharp project which is essentially MIT licensed.

The code is dead simple, I needed a cmdline utility so I have more code dedicated to parsing the arguments than I do for the PDF merging:

using (PdfDocument one = PdfReader.Open("file1.pdf", PdfDocumentOpenMode.Import))
using (PdfDocument two = PdfReader.Open("file2.pdf", PdfDocumentOpenMode.Import))
using (PdfDocument outPdf = new PdfDocument())
{                
    CopyPages(one, outPdf);
    CopyPages(two, outPdf);

    outPdf.Save("file1and2.pdf");
}

void CopyPages(PdfDocument from, PdfDocument to)
{
    for (int i = 0; i < from.PageCount; i++)
    {
        to.AddPage(from.Pages[i]);
    }
}

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

PHP Fatal error: Call to undefined function mssql_connect()

I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line

; On windows: extension_dir = "ext"

I changed it to:

; On windows: extension_dir = "C:\php\ext"

And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

... then, install

pip install matplotlib

From all the above, this could be a package management problem, and BTW, I use both conda and pip, whenever feasible.

Generate sql insert script from excel worksheet

This query i have generated for inserting the Excel file data into database In this id and price are numeric values and date field as well. This query summarized all the type which I require It may useful to you as well

="insert into  product (product_id,name,date,price) values("&A1&",'" &B1& "','" &C1& "'," &D1& ");"


    Id    Name           Date           price 
    7   Product 7   2017-01-05 15:28:37 200
    8   Product 8   2017-01-05 15:28:37 40
    9   Product 9   2017-01-05 15:32:31 500
    10  Product 10  2017-01-05 15:32:31 30
    11  Product 11  2017-01-05 15:32:31 99
    12  Product 12  2017-01-05 15:32:31 25

Best Timer for using in a Windows service

I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:

This will:

  • Reduce plumbing code that replicates scheduler behaviour
  • Provide greater flexibility in terms of scheduling behaviour (e.g. only run on weekends) with all scheduling logic abstracted from application code
  • Utilise the command line arguments for parameters without having to setup configuration values in config files etc
  • Far easier to debug/test during development
  • Allow a support user to execute by invoking the console application directly (e.g. useful during support situations)

SQL: How to properly check if a record exists

You can use:

SELECT COUNT(1) FROM MyTable WHERE ... 

or

WHERE [NOT] EXISTS 
( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

How to Call a JS function using OnClick event

I removed your document.getElementById("Save").onclick = before your functions, because it's an event already being called on your button. I also had to call the two functions separately by the onclick event.

     <!DOCTYPE html>
      <html>
      <head>
      <script>
       function fun()
        {
         alert("hello");
         //validation code to see State field is mandatory.  
        }   
        function f1()
        {
          alert("f1 called");
           //form validation that recalls the page showing with supplied inputs.    
        }
      </script>
      </head>
      <body>
      <form name="form1" id="form1" method="post">
                State: 
                <select id="state ID">
                   <option></option>
                   <option value="ap">ap</option>
                   <option value="bp">bp</option>
                </select>
       </form>

       <table><tr><td id="Save" onclick="f1(); fun();">click</td></tr></table>

   </body>
   </html>

Java Swing - how to show a panel on top of another panel?

There's another layout manager that may be of interest here: Overlay Layout Here's a simple tutorial: OverlayLayout: for layout management of components that lie on top of one another. Overlay Layout allows you to position panels on top of one another, and set a layout inside each panel. You are also able to set size and position of each panel separately.

(The reason I'm answering this question from years ago is because I have stumbled upon the same problem, and I have seen very few mentions of the Overlay Layout on StackOverflow, while it seems to be pretty well documented. Hopefully this may help someone else who keeps searching for it.)

Capturing browser logs with Selenium WebDriver using Java

Driver manager logs can be used to get console logs from browser and it will help to identify errors appears in console.

   import org.openqa.selenium.logging.LogEntries;
   import org.openqa.selenium.logging.LogEntry;

    public List<LogEntry> getBrowserConsoleLogs()
    {
    LogEntries log= driver.manage().logs().get("browser")
    List<LogEntry> logs=log.getAll();
    return logs;
    }

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

XMLHttpRequest (Ajax) Error

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

Find column whose name contains a specific string

This answer uses the DataFrame.filter method to do this without list comprehension:

import pandas as pd

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6]}
df = pd.DataFrame(data)

print(df.filter(like='spike').columns)

Will output just 'spike-2'. You can also use regex, as some people suggested in comments above:

print(df.filter(regex='spike|spke').columns)

Will output both columns: ['spike-2', 'hey spke']

Subdomain on different host

UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!

Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.

Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.

Thanks!

Auto-size dynamic text to fill fixed size container

As much as I love the occasional upvotes I get for this answer (thanks!), this is really not the greatest approach to this problem. Please check out some of the other wonderful answers here, especially the ones that have found solutions without looping.


Still, for the sake of reference, here's my original answer:

<html>
<head>
<style type="text/css">
    #dynamicDiv
    {
    background: #CCCCCC;
    width: 300px;
    height: 100px;
    font-size: 64px;
    overflow: hidden;
    }
</style>

<script type="text/javascript">
    function shrink()
    {
        var textSpan = document.getElementById("dynamicSpan");
        var textDiv = document.getElementById("dynamicDiv");

        textSpan.style.fontSize = 64;

        while(textSpan.offsetHeight > textDiv.offsetHeight)
        {
            textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
        }
    }
</script>

</head>
<body onload="shrink()">
    <div id="dynamicDiv"><span id="dynamicSpan">DYNAMIC FONT</span></div>
</body>
</html>

And here's a version with classes:

<html>
<head>
<style type="text/css">
.dynamicDiv
{
    background: #CCCCCC;
    width: 300px;
    height: 100px;
    font-size: 64px;
    overflow: hidden;
}
</style>

<script type="text/javascript">
    function shrink()
    {
        var textDivs = document.getElementsByClassName("dynamicDiv");
        var textDivsLength = textDivs.length;

        // Loop through all of the dynamic divs on the page
        for(var i=0; i<textDivsLength; i++) {

            var textDiv = textDivs[i];

            // Loop through all of the dynamic spans within the div
            var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0];

            // Use the same looping logic as before
            textSpan.style.fontSize = 64;

            while(textSpan.offsetHeight > textDiv.offsetHeight)
            {
                textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
            }

        }

    }
</script>

</head>
<body onload="shrink()">
    <div class="dynamicDiv"><span class="dynamicSpan">DYNAMIC FONT</span></div>
    <div class="dynamicDiv"><span class="dynamicSpan">ANOTHER DYNAMIC FONT</span></div>
    <div class="dynamicDiv"><span class="dynamicSpan">AND YET ANOTHER DYNAMIC FONT</span></div>
</body>
</html>

How to update an object in a List<> in C#

This was a new discovery today - after having learned the class/struct reference lesson!

You can use Linq and "Single" if you know the item will be found, because Single returns a variable...

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;

How to get the data-id attribute?

This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id

<a href="#" id="click-demo" data-id="a1">Click</a>

js:

$(this).data("id");

// get the value of the data-id -> a1

$(this).data("id", "a2");

// this will change the data-id -> a2

$(this).data("id");

// get the value of the data-id -> a2

How to load a controller from another controller in codeigniter?

you cannot call a controller method from another controller directly

my solution is to use inheritances and extend your controller from the library controller

class Controller1 extends CI_Controller {

    public function index() {
        // some codes here
    }

    public function methodA(){
        // code here
    }
}

in your controller we call it Mycontoller it will extends Controller1

include_once (dirname(__FILE__) . "/controller1.php");

class Mycontroller extends Controller1 {

    public function __construct() {
        parent::__construct();
    }

    public function methodB(){
        // codes....
    }
}

and you can call methodA from mycontroller

http://example.com/mycontroller/methodA

http://example.com/mycontroller/methodB

this solution worked for me

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

Deleting a file in VBA

An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).

Magento: Set LIMIT on collection

You can Implement this also:- setPage(1, n); where, n = any number.

$products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('*')
                ->addAttributeToSelect(array('name', 'price', 'small_image'))
                ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //visible only catalog & searchable product
                ->addAttributeToFilter('status', 1) // enabled
                ->setStoreId($storeId)
                ->setOrder('created_at', 'desc')
                ->setPage(1, 6);

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

How do I create a sequence in MySQL?

SEQUENCES like it works on firebird:

-- =======================================================

CREATE TABLE SEQUENCES  
(  
  NM_SEQUENCE VARCHAR(32) NOT NULL UNIQUE,  
  VR_SEQUENCE BIGINT      NOT NULL  
);  

-- =======================================================
-- Creates a sequence sSeqName and set its initial value.
-- =======================================================

DROP PROCEDURE IF EXISTS CreateSequence;  

DELIMITER :)  
CREATE PROCEDURE CreateSequence( sSeqName VARCHAR(32), iSeqValue BIGINT )  
BEGIN  
  IF NOT EXISTS ( SELECT * FROM SEQUENCES WHERE (NM_SEQUENCE = sSeqName) ) THEN  
    INSERT INTO SEQUENCES (NM_SEQUENCE, VR_SEQUENCE)  
    VALUES (sSeqName   , iSeqValue  );  
  END IF;  
END :)  
DELIMITER ;  

-- CALL CreateSequence( 'MySequence', 0 );  

-- =======================================================================
-- Increments the sequence value of sSeqName by iIncrement and returns it.
-- If iIncrement is zero, returns the current value of sSeqName.
-- =======================================================================

DROP FUNCTION IF EXISTS GetSequenceVal;  

DELIMITER :)  
CREATE FUNCTION GetSequenceVal( sSeqName VARCHAR(32), iIncrement INTEGER )  
RETURNS BIGINT  -- iIncrement can be negative  
BEGIN  
  DECLARE iSeqValue BIGINT;  

  SELECT VR_SEQUENCE FROM SEQUENCES  
  WHERE  ( NM_SEQUENCE = sSeqName )  
  INTO   @iSeqValue;  

  IF ( iIncrement <> 0 ) THEN  
    SET @iSeqValue = @iSeqValue + iIncrement;  

    UPDATE SEQUENCES SET VR_SEQUENCE = @iSeqValue  
    WHERE  ( NM_SEQUENCE = sSeqName );  
  END IF;

  RETURN @iSeqValue;
END :)  
DELIMITER ;  

-- SELECT GetSequenceVal('MySequence', 1);  -- Adds 1 to MySequence value and returns it.

-- ===================================================================

jQuery check if <input> exists and has a value

You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

var elHasValue = $("#name").is(":hasValue");

_x000D_
_x000D_
jQuery.expr[':'].hasValue = function(el) {_x000D_
  return el.value != "";_x000D_
};_x000D_
_x000D_
_x000D_
var data = $("form input:hasValue").serialize();_x000D_
console.log(data)_x000D_
_x000D_
_x000D_
var elHasValue = $("[name='LastName']").is(":hasValue");_x000D_
console.log(elHasValue)
_x000D_
label { display: block; margin-top:10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
  <label>_x000D_
    First Name:_x000D_
    <input type="text" name="FirstName" value="Frida" />_x000D_
  </label>_x000D_
_x000D_
  <label>_x000D_
    Last Name:_x000D_
    <input type="text" name="LastName" />_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Further Reading:

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You do realize this is the default behavior, right? if you add /something the results would be different.

you can do a number of things to prevent default behavior.

href="#":

Will do nothing but anchor - not the best solution since it may jump to page top.

<a href="#">

href="javascript:void(0);"

Will do nothing at all and is perfectly legit.

<a href="javascript:void(0);"></a>

href="your-actual-intended-link" (Best)

obviously the best.

<a href="<your-actual-intended-link>"></a>

If you don't want an a tag to go somewhere, why use an a tag at all?

MySQL - DATE_ADD month interval

BETWEEN ... AND

If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0.

The important part here is EQUAL to max., which 1st of July is.

What are Java command line options to set to allow JVM to be remotely debugged?

java

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8001,suspend=y -jar target/cxf-boot-simple-0.0.1-SNAPSHOT.jar

address specifies the port at which it will allow to debug

Maven

**Debug Spring Boot app with Maven:

mvn spring-boot:run -Drun.jvmArguments=**"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8001"

What is "entropy and information gain"?

To begin with, it would be best to understand the measure of information.

How do we measure the information?

When something unlikely happens, we say it's a big news. Also, when we say something predictable, it's not really interesting. So to quantify this interesting-ness, the function should satisfy

  • if the probability of the event is 1 (predictable), then the function gives 0
  • if the probability of the event is close to 0, then the function should give high number
  • if probability 0.5 events happens it give one bit of information.

One natural measure that satisfy the constraints is

I(X) = -log_2(p)

where p is the probability of the event X. And the unit is in bit, the same bit computer uses. 0 or 1.

Example 1

Fair coin flip :

How much information can we get from one coin flip?

Answer : -log(p) = -log(1/2) = 1 (bit)

Example 2

If a meteor strikes the Earth tomorrow, p=2^{-22} then we can get 22 bits of information.

If the Sun rises tomorrow, p ~ 1 then it is 0 bit of information.

Entropy

So if we take expectation on the interesting-ness of an event Y, then it is the entropy. i.e. entropy is an expected value of the interesting-ness of an event.

H(Y) = E[ I(Y)]

More formally, the entropy is the expected number of bits of an event.

Example

Y = 1 : an event X occurs with probability p

Y = 0 : an event X does not occur with probability 1-p

H(Y) = E[I(Y)] = p I(Y==1) + (1-p) I(Y==0) 
     = - p log p - (1-p) log (1-p)

Log base 2 for all log.

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

Use of for_each on map elements

Here is an example of how you can use for_each for a map.

std::map<int, int> map;

map.insert(std::pair<int, int>(1, 2));
map.insert(std::pair<int, int>(2, 4));
map.insert(std::pair<int, int>(3, 6));

auto f = [](std::pair<int,int> it) {std::cout << it.first + it.second << std::endl; };
std::for_each(map.begin(), map.end(), f);

Assign result of dynamic sql to variable

You could use sp_executesql instead of exec. That allows you to specify an output parameter.

declare @out_var varchar(max);
execute sp_executesql 
    N'select @out_var = ''hello world''', 
    N'@out_var varchar(max) OUTPUT', 
    @out_var = @out_var output;
select @out_var;

This prints "hello world".

When is del useful in Python?

del is often seen in __init__.py files. Any global variable that is defined in an __init__.py file is automatically "exported" (it will be included in a from module import *). One way to avoid this is to define __all__, but this can get messy and not everyone uses it.

For example, if you had code in __init__.py like

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

Then your module would export the sys name. You should instead write

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

del sys

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

Where does Android emulator store SQLite database?

I wrote a simple bash script, which pulls database from android device to your computer (Linux, Mac users)

filename:android_db_move.sh usage: android_db_move.sh com.example.app db_name.db

#!/bin/bash

REQUIRED_ARGS=2
ADB_PATH=/Users/Tadas/Library/sdk/platform-tools/adb
PULL_DIR="~/"

if [ $# -ne $REQUIRED_ARGS ]
    then
        echo ""
        echo "Usage:"
        echo "android_db_move.sh [package_name] [db_name]"
        echo "eg. android_db_move.sh lt.appcamp.impuls impuls.db"
        echo ""
    exit 1
fi;


echo""

cmd1="$ADB_PATH -d shell 'run-as $1 cat /data/data/$1/databases/$2 > /sdcard/$2' "
cmd2="$ADB_PATH pull /sdcard/$2 $PULL_DIR"

echo $cmd1
eval $cmd1
if [ $? -eq 0 ]
    then
    echo ".........OK"
fi;

echo $cmd2
eval $cmd2

if [ $? -eq 0 ]
    then
    echo ".........OK"
fi;

exit 0

Change the spacing of tick marks on the axis of a plot?

There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):

  1. Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)

  2. You can suppress the drawing of the axis altogether and add the tick marks later with axis().
    To suppress the drawing of the axis use plot(... , xaxt = "n").
    Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Why can't I initialize non-const static member or static array in class?

It's because there can only be one definition of A::a that all the translation units use.

If you performed static int a = 3; in a class in a header included in all a translation units then you'd get multiple definitions. Therefore, non out-of-line definition of a static is forcibly made a compiler error.

Using static inline or static const remedies this. static inline only concretises the symbol if it is used in the translation unit and ensures the linker only selects and leaves one copy if it's defined in multiple translation units due to it being in a comdat group. const at file scope makes the compiler never emit a symbol because it's always substituted immediately in the code unless extern is used, which is not permitted in a class.

One thing to note is static inline int b; is treated as a definition whereas static const int b or static const A b; are still treated as a declaration and must be defined out-of-line if you don't define it inside the class. Interestingly static constexpr A b; is treated as a definition, whereas static constexpr int b; is an error and must have an initialiser (this is because they now become definitions and like any const/constexpr definition at file scope, they require an initialiser which an int doesn't have but a class type does because it has an implicit = A() when it is a definition -- clang allows this but gcc requires you to explicitly initialise or it is an error. This is not a problem with inline instead). static const A b = A(); is not allowed and must be constexpr or inline in order to permit an initialiser for a static object with class type i.e to make a static member of class type more than a declaration. So yes in certain situations A a; is not the same as explicitly initialising A a = A(); (the former can be a declaration but if only a declaration is allowed for that type then the latter is an error. The latter can only be used on a definition. constexpr makes it a definition). If you use constexpr and specify a default constructor then the constructor will need to be constexpr

#include<iostream>

struct A
{
    int b =2;
    mutable int c = 3; //if this member is included in the class then const A will have a full .data symbol emitted for it on -O0 and so will B because it contains A.
    static const int a = 3;
};

struct B {
    A b;
    static constexpr A c; //needs to be constexpr or inline and doesn't emit a symbol for A a mutable member on any optimisation level
};

const A a;
const B b;

int main()
{
    std::cout << a.b << b.b.b;
    return 0;
}

A static member is an outright file scope declaration extern int A::a; (which can only be made in the class and out of line definitions must refer to a static member in a class and must be definitions and cannot contain extern) whereas a non-static member is part of the complete type definition of a class and have the same rules as file scope declarations without extern. They are implicitly definitions. So int i[]; int i[5]; is a redefinition whereas static int i[]; int A::i[5]; isn't but unlike 2 externs, the compiler will still detect a duplicate member if you do static int i[]; static int i[5]; in the class.

Android device does not show up in adb list

I tried everything on this thread but nothing worked. My problem: my computer was charging the device when I was connecting the cable on, so I assumed the cable was working, but not. After I swap the cable, adb devices worked. The cable was the issue.

Beautiful Soup and extracting a div and its contents by ID

Beautiful Soup 4 supports most CSS selectors with the .select() method, therefore you can use an id selector such as:

soup.select('#articlebody')

If you need to specify the element's type, you can add a type selector before the id selector:

soup.select('div#articlebody')

The .select() method will return a collection of elements, which means that it would return the same results as the following .find_all() method example:

soup.find_all('div', id="articlebody")
# or
soup.find_all(id="articlebody")

If you only want to select a single element, then you could just use the .find() method:

soup.find('div', id="articlebody")
# or
soup.find(id="articlebody")

How to sign in kubernetes dashboard?

You need to follow these steps before the token authentication

  1. Create a Cluster Admin service account

    kubectl create serviceaccount dashboard -n default
    
  2. Add the cluster binding rules to your dashboard account

    kubectl create clusterrolebinding dashboard-admin -n default --clusterrole=cluster-admin --serviceaccount=default:dashboard
    
  3. Get the secret token with this command

    kubectl get secret $(kubectl get serviceaccount dashboard -o jsonpath="{.secrets[0].name}") -o jsonpath="{.data.token}" | base64 --decode
    
  4. Choose token authentication in the Kubernetes dashboard login page enter image description here

  5. Now you can able to login

Search and replace part of string in database

You can do it with an UPDATE statement setting the value with a REPLACE

UPDATE
    Table
SET
    Column = Replace(Column, 'find value', 'replacement value')
WHERE
    xxx

You will want to be extremely careful when doing this! I highly recommend doing a backup first.

How to embed images in html email

You have to encode your email as multipart mime and then you can attach emails as attachments basically. You reference them by cid in the email.

Alternatively you could not attach them to the email and use URLs directly but most mail programs will block this as spammers use the trick to detect the liveness of email addresses.

You don't say what language but here is one example.

How do I turn off Oracle password expiration?

To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:

select profile from DBA_USERS where username = '<username>';

Then you can change the limit to never expire using:

alter profile <profile_name> limit password_life_time UNLIMITED;

If you want to previously check the limit you may use:

select resource_name,limit from dba_profiles where profile='<profile_name>';

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

Spacing between elements

If you want vertical spacing between elements, use a margin.

Don't add extra elements if you don't need to.

Difference between Select Unique and Select Distinct

  1. Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.
  2. Unique creates a constraint that all values to be inserted must be different from the others. An error can be witnessed if one tries to enter a duplicate value. Distinct results in the removal of the duplicate rows while retrieving data.
  3. Example: SELECT DISTINCT names FROM student ;

    CREATE TABLE Persons ( Id varchar NOT NULL UNIQUE, Name varchar(20) );

Is it possible to display inline images from html in an Android TextView?

You could also write your own parser to pull the URL of all the images and then dynamically create new imageviews and pass in the urls.

How do I shut down a python simpleHTTPserver?

When you run a program as a background process (by adding an & after it), e.g.:

python -m SimpleHTTPServer 8888 &

If the terminal window is still open you can do:

jobs

To get a list of all background jobs within the running shell's process.

It could look like this:

$ jobs
[1]+  Running                 python -m SimpleHTTPServer 8888 &

To kill a job, you can either do kill %1 to kill job "[1]", or do fg %1 to put the job in the foreground (fg) and then use ctrl-c to kill it. (Simply entering fg will put the last backgrounded process in the foreground).

With respect to SimpleHTTPServer it seems kill %1 is better than fg + ctrl-c. At least it doesn't protest with the kill command.

The above has been tested in Mac OS, but as far as I can remember it works just the same in Linux.

Update: For this to work, the web server must be started directly from the command line (verbatim the first code snippet). Using a script to start it will put the process out of reach of jobs.

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

Getting each individual digit from a whole integer

RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).

day of the week to day number (Monday = 1, Tuesday = 2)

What about using idate()? idate()

$integer = idate('w', $timestamp);

Google Chrome redirecting localhost to https

I am facing the same problem but only in Chrome Canary and searching a solution I've found this post.

one of the next versions of Chrome is going to force all domains ending on .dev (and .foo) to be redirected to HTTPs via a preloaded HTTP Strict Transport Security (HSTS) header.

{ "name": "dev", "include_subdomains": true, "mode": "force-https" },
{ "name": "foo", "include_subdomains": true, "mode": "force-https" },

So, change your domains.

What are abstract classes and abstract methods?

With abstract classes you can have some kind of skeleton for other classes to extend.

You can't instantiate them but you can put some common implementation which you can use in the classes that extend them.

Groovy Shell warning "Could not open/create prefs root node ..."

This happened to me.

Apparently it is because Java does not have permission to create registry keys.

See: Java: java.util.Preferences Failing

jQuery fade out then fade in

After jQuery 1.6, using promise seems like a better option.

var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
  fadeoOutDone.then(function(){
    $div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
    $div1.fadeIn();
  });
});

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Go in xampp/apache/conf/httpd.conf and open it. Then just chang 2 lines

Listen 80
to
Listen 81

And

ServerName localhost:80
to
ServerName localhost:81

Then start using admin privileges.

As I am working in a corporate environment where developers faces firewall issues, none of the other answers resolved my issue.

As the port is not used by Skype, but by some other internal applications, I followed the below steps to resolve the issue:

Step 1 - From the XAMPP Control Panel, under Apache, click the Config button, and select the Apache (httpd.conf).

Inside the httpd.conf file, somehow I found a line that says:

Listen 80 And change the 80 into any number / port you want. In my scenario I’m using port 8080.

Listen 8080 Still from the httpd.conf file,

You should also do this in the same process Still from the httpd-ssl.conf file, find another line that says

ServerName localhost:443 And change 443 to 4433.

ServerName localhost:4433 Remember to save the httpd.conf and httpd-ssl.conf files after performing some changes. Then restart the Apache service.

Execute SQLite script

You want to feed the create.sql into sqlite3 from the shell, not from inside SQLite itself:

$ sqlite3 auction.db < create.sql

SQLite's version of SQL doesn't understand < for files, your shell does.

Simple check for SELECT query empty result

SELECT * FROM service s WHERE s.service_id = ?;
IF @@rowcount = 0
begin
select 'no data'
end

How to decode JWT Token?

new JwtSecurityTokenHandler().ReadToken("") will return a SecurityToken

new JwtSecurityTokenHandler().ReadJwtToken("") will return a JwtSecurityToken

If you just change the method you are using you can avoid the cast in the above answer

Android Studio does not show layout preview

In my case, Android Studio created project including support library which version is RC or beta. So I tried downgrade version of support library, then worked.
If your library version is RC or beta, try downgrade.

Downgrade this
implementation 'com.android.support:appcompat-v7:28.0.0-rc01'

to this
implementation 'com.android.support:appcompat-v7:27.1.1'

and downgrade also compileSdkVersion, targetSdkVersion if you need.

Sorting std::map using value

To build on Oli's solution (https://stackoverflow.com/a/5056797/2472351) using multimaps, you can replace the two template functions he used with the following:

template <typename A, typename B>
multimap<B, A> flip_map(map<A,B> & src) {

    multimap<B,A> dst;

    for(map<A, B>::const_iterator it = src.begin(); it != src.end(); ++it)
        dst.insert(pair<B, A>(it -> second, it -> first));

    return dst;
}

Here is an example program that shows all the key-value pairs being preserved after performing the flip.

#include <iostream>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

template <typename A, typename B>
multimap<B, A> flip_map(map<A,B> & src) {

    multimap<B,A> dst;

    for(typename map<A, B>::const_iterator it = src.begin(); it != src.end(); ++it)
        dst.insert(pair<B, A>(it -> second, it -> first));

    return dst;
}

int main() {

    map<string, int> test;
    test["word"] = 1;
    test["spark"] = 15;
    test["the"] = 2;
    test["mail"] = 3;
    test["info"] = 3;
    test["sandwich"] = 15;

    cout << "Contents of original map:\n" << endl;
    for(map<string, int>::const_iterator it = test.begin(); it != test.end(); ++it)
        cout << it -> first << " " << it -> second << endl; 

    multimap<int, string> reverseTest = flip_map(test);

    cout << "\nContents of flipped map in descending order:\n" << endl;
    for(multimap<int, string>::const_reverse_iterator it = reverseTest.rbegin(); it != reverseTest.rend(); ++it)
        cout << it -> first << " " << it -> second << endl; 

    cout << endl;
}

Result:

enter image description here

Moment js date time comparison

var startDate = moment(startDateVal, "DD.MM.YYYY");//Date format
var endDate = moment(endDateVal, "DD.MM.YYYY");

var isAfter = moment(startDate).isAfter(endDate);

if (isAfter) {
    window.showErrorMessage("Error Message");
    $(elements.endDate).focus();
    return false;
}