text:
\documentclass[]{article}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
\else % if luatex or xelatex
  \ifxetex
    \usepackage{mathspec}
  \else
    \usepackage{fontspec}
  \fi
  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\usepackage[margin=1in]{geometry}
\usepackage{hyperref}
\hypersetup{unicode=true,
            pdftitle={Visualización en ggplot2},
            pdfborder={0 0 0},
            breaklinks=true}
\urlstyle{same}  % don't use monospace font for urls
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\usepackage{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{0}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi

%%% Use protect on footnotes to avoid problems with footnotes in titles
\let\rmarkdownfootnote\footnote%
\def\footnote{\protect\rmarkdownfootnote}

%%% Change title format to be more compact
\usepackage{titling}

% Create subtitle command for use in maketitle
\newcommand{\subtitle}[1]{
  \posttitle{
    \begin{center}\large#1\end{center}
    }
}

\setlength{\droptitle}{-2em}
  \title{Visualización en ggplot2}
  \pretitle{\vspace{\droptitle}\centering\huge}
  \posttitle{\par}
  \author{}
  \preauthor{}\postauthor{}
  \date{}
  \predate{}\postdate{}

\usepackage[
  backend=biber,
  style=alphabetic,
  sorting=ynt,
  citestyle=authoryear
  ]{biblatex}
\addbibresource{../lit/bib.bib}

\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}

%%%% Frames
\ifxetex
    \makeatletter % undo the wrong changes made by mathspec
    \let\RequirePackage\original@RequirePackage
    \let\usepackage\RequirePackage
    \makeatother
\fi

\usepackage{xcolor}
\usepackage[tikz]{bclogo}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{lipsum}
\usepackage[many]{tcolorbox}

\definecolor{bgblue}{RGB}{245,243,253}
\definecolor{ttblue}{RGB}{91,194,224}
\definecolor{llred}{RGB}{255,228,225}
\definecolor{bbblack}{RGB}{0,0,0}

\mdfdefinestyle{mystyle}{%
  rightline=true,
  innerleftmargin=10,
  innerrightmargin=10,
  outerlinewidth=3pt,
  topline=false,
  rightline=true,
  bottomline=false,
  skipabove=\topsep,
  skipbelow=\topsep
}

\newtcolorbox{curiosidad}[1][]{
  breakable,
  title=#1,
  colback=white,
  colbacktitle=white,
  coltitle=black,
  fonttitle=\bfseries,
  bottomrule=0pt,
  toprule=0pt,
  leftrule=3pt,
  rightrule=3pt,
  titlerule=0pt,
  arc=0pt,
  outer arc=0pt,
  colframe=black,
}

\newtcolorbox{nota}[1][]{
  breakable,
  freelance,
  title=#1,
  colback=white,
  colbacktitle=white,
  coltitle=black,
  fonttitle=\bfseries,
  bottomrule=0pt,
  boxrule=0pt,
  colframe=white,
  overlay unbroken and first={
  \draw[red!75!black,line width=3pt]
    ([xshift=5pt]frame.north west) --
    (frame.north west) --
    (frame.south west);
  \draw[red!75!black,line width=3pt]
    ([xshift=-5pt]frame.north east) --
    (frame.north east) --
    (frame.south east);
  },
  overlay unbroken app={
  \draw[red!75!black,line width=3pt,line cap=rect]
    (frame.south west) --
    ([xshift=5pt]frame.south west);
  \draw[red!75!black,line width=3pt,line cap=rect]
    (frame.south east) --
    ([xshift=-5pt]frame.south east);
  },
  overlay middle and last={
  \draw[red!75!black,line width=3pt]
    (frame.north west) --
    (frame.south west);
  \draw[red!75!black,line width=3pt]
    (frame.north east) --
    (frame.south east);
  },
  overlay last app={
  \draw[red!75!black,line width=3pt,line cap=rect]
    (frame.south west) --
    ([xshift=5pt]frame.south west);
  \draw[red!75!black,line width=3pt,line cap=rect]
    (frame.south east) --
    ([xshift=-5pt]frame.south east);
  },
}

\begin{document}

\section{Visualización}\label{visualizacion}

La graficación es una manera eficiente de resumir, y mostrar
información. Es fundamental entender el contexto de negocio y de la
generación de los datos para tener más información con respecto a lo que
se está graficando.

Aunqu eno hay mucha teoría alrededor de gráficos estadísticos, muchos se
describen en distintos libros de texto de estadística
\parencite[][Introducción]{unwin2015}.

\textcite[][citando a John Tukey]{unwin2015} resume el propósito de la
visualización de datos en cuatro frases:

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
  Las gráficas son para análsisis cualitativos o descriptivos y quizá
  semi cuantitativos, nunca para análisis profundo cuantitativo (las
  tablas son mejores para esta tarea).
\item
  Las gráficas son para realizar comparaciones (en el tiempo, entre
  grupos), no para describir cantidades particulares.
\item
  Las gráficas son para impactar (visualmente, para sorprender, para
  transmitir información), pero casi nunca sirven para reflejar patrones
  escondidos en los datos.
\item
  Las gráficas deberían de reportar un análisis de datos trabajado, fino
  y cuidadoso. Jamás deben de reemplazar el análisis. Las gráficas están
  para fortalecer el análisis, no para fundamentarlo y los gráficos
  finales en un análisis deben reflejar el análisis realizado.
\end{enumerate}

Esta sección resume algunas de las funciones implementadas para
\textbf{visualizar} datos implementados en el paquete \texttt{ggplot2}
de \texttt{R}. Está fuera de la alcance de este apartado las
consideraciones estadísticas que deben de realizarse en un análisis de
datos pues el enfoque es mostrar cómo realizar esta tarea en \texttt{R}.
En la figura \ref{fig:ciclo4} podemos ver la etapa del análisis de datos
correspondiente.

\begin{figure}[h]
    \centering
    \includegraphics[width=0.75\textwidth]{../img/02_ciclo_4.png}
    \caption{Visualización en el análisis de datos \textcite[Introducción]{grolemund2016r}.}
    \label{fig:ciclo4}
\end{figure}

En \texttt{R} hay muchas maneras de realizar una tarea, esto es
particularmente cierto en lo que se refiere a visualización de datos
\parencite{basevggplot}. A fin de cuentas, lo más importante de la
visualización de datos es cuán útil es esta herramienta para el análisis
de datos y la forma en la que se le indica a la máquina como realizar la
tarea es un elemento importante solo en la medida en la que facilite el
trabajo del estadístico.

Aunque posiblemente cualquiera de los gráficos que se pueden hacer con
\texttt{ggplot2} pueden hacerse también con los gráficos implementados
en el \texttt{base\ graphics} de \texttt{R} \parencite{basevggplot},
aquí se cubre visualización en \texttt{ggplot2} principalmente debido a
que:

\begin{itemize}
\tightlist
\item
  El patrón de programación está definido formalmente mientras que en el
  \texttt{base} no lo está. Esto significa que cuando entiendes cómo
  hacer una gráfica en \texttt{ggplot2}, puedes hacer una gran cantidad
  de gráficos \parencite{basevggplot}.
\item
  \texttt{ggplot2} tiene una gran cantidad de \emph{defaults}
  predefinidos que facilitan realizar gráficos ilustrativos y estéticos
  muy rápidamente \parencite{reasonsggplot}.
\item
  \texttt{ggplot2} es compatible con
  \emph{piping}\footnote{Se introdujo el operador \textit{pipe} de \texttt{R} en la sección de transformación en este capítulo y se mencionó como ayuda en la lectura y escritura de código. Un\textit{pipeline} en programación consiste en un arreglo de elementos de procesamiento en donde la salida de cada elemento es la entrada del siguiente elemento. Este concepto fue concebido por Douglas Mcllroy \parencite{unixpipes}.}
  \parencite{notggplot}.
\item
  Muchas veces, resulta necesario realizar un mismo gráfico para varios
  subconjuntos de datos. Esta tarea se puede hacer en forma directa en
  \texttt{ggplot2} y no en el \texttt{base} a través de facetas.
\end{itemize}

Primero, se cubrirá el concepto detrás de \texttt{ggplot2}, la gramática
de las gráficas. Posteriormente, se describen los componentes de una
gráfica en \texttt{ggplot2}, las capas y sus componentes proporcionando
ejemplos en cada caso.

\subsection{La gramática de las
gráficas}\label{la-gramatica-de-las-graficas}

Es una herramienta que nos permite \parencite{wickham2010layered}:

\begin{itemize}
\tightlist
\item
  Describir los componentes de una gráfica en forma concisa
\item
  Ir más allá de los nombres de la gráfica (e.g.~scatterplot, boxplot,
  etc.)
\item
  Entender la estructura detrás de los gráficos estadísticos
\end{itemize}

\subsection{¿Qué es?}\label{que-es}

La gramática le da reglas al lenguaje y es un sistema formal para
generar enunciados \parencite{wilkinson2006grammar}.
\textcite{wilkinson2006grammar} proporciona una gramática para gráficos
que permite describir y construir una gran cantidad de gráficos
estadísticos. \parencite{wickham2010layered} implementa esta gramática
en el paquete \texttt{ggplot2} de \texttt{R} \parencite{ggplot2}.

La gramática define un gráfico estadístico como un mapeo de datos a
atributos estéticos (un color, una forma) en objetos geométricos
(barras, líneas, puntos). Además, una gráfica puede implicar
transformaciones estadísticas de los datos y se dibuja sobre un sistema
de coordenadas específico. Por último, es posible generar el mismo
gráfico en diferentes subconjuntos de los datos (facetas). La
combinación de estos factores independientes conforman un gráfico
\parencite[][p. 5]{ggplot2}.

La implementación en capas, permite que los usuarios no se limiten
únicamente a los gráficos específicos que se implementan paquete a
paquete sino que puedan realizar tantos gráficos como este lenguaje de
gráficos permita.

\subsection{Base plotting vs.~ggplot}\label{base-plotting-vs.ggplot}

Observemos una gráfica utilizando la base \texttt{diamonds} en donde
graficamos en el eje \(x\) el carataje de diamantes y en el eje \(y\) su
precio:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{data}\NormalTok{(diamonds, }\DataTypeTok{package =} \StringTok{"ggplot2"}\NormalTok{)}
\KeywordTok{str}\NormalTok{(diamonds)}
\end{Highlighting}
\end{Shaded}

\begin{verbatim}
## Classes 'tbl_df', 'tbl' and 'data.frame':    53940 obs. of  10 variables:
##  $ carat  : num  0.23 0.21 0.23 0.29 0.31 0.24 0.24 0.26 0.22 0.23 ...
##  $ cut    : Ord.factor w/ 5 levels "Fair"<"Good"<..: 5 4 2 4 2 3 3 3 1 3 ...
##  $ color  : Ord.factor w/ 7 levels "D"<"E"<"F"<"G"<..: 2 2 2 6 7 7 6 5 2 5 ...
##  $ clarity: Ord.factor w/ 8 levels "I1"<"SI2"<"SI1"<..: 2 3 5 4 2 6 7 3 4 5 ...
##  $ depth  : num  61.5 59.8 56.9 62.4 63.3 62.8 62.3 61.9 65.1 59.4 ...
##  $ table  : num  55 61 65 58 58 57 57 55 61 61 ...
##  $ price  : int  326 326 327 334 335 336 336 337 337 338 ...
##  $ x      : num  3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...
##  $ y      : num  3.98 3.84 4.07 4.23 4.35 3.96 3.98 4.11 3.78 4.05 ...
##  $ z      : num  2.43 2.31 2.31 2.63 2.75 2.48 2.47 2.53 2.49 2.39 ...
\end{verbatim}

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{plot}\NormalTok{(diamonds}\OperatorTok{$}\NormalTok{carat, diamonds}\OperatorTok{$}\NormalTok{price)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-1-1.pdf}

Ese mismo gráfico, podemos realizarlo con la función \texttt{qplot} del
paquete\texttt{ggplot}:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{qplot}\NormalTok{(}\DataTypeTok{data =}\NormalTok{ diamonds, }\DataTypeTok{x =}\NormalTok{ carat, }\DataTypeTok{y =}\NormalTok{ price, }\DataTypeTok{geom =} \StringTok{"point"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-2-1.pdf}

En donde especificamos que la variable \texttt{carat} en la base
\texttt{diamonds} mapea al eje \(x\), la variable \texttt{price} en la
misma base al eje \(y\) y queremos que la geometría sea de puntos.

Observa que la estética de la gráfica generada con la función
\texttt{plot} es un poco distinta a la generada con \texttt{qplot}
(función que utiliza \texttt{ggplot}). Verifica la clase que tiene cada
objeto, en el primer caso no tiene y en el segundo tenemos un objeto de
clase \texttt{ggplot} que tiene atributos y que podemos guardar en un
objeto.

\subsection{ggplot}\label{ggplot}

Los componentes de la gramática de gráficas específica para
\texttt{ggplot} son:

\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
  Una o más capas donde cada cuál tiene:

  \begin{enumerate}
  \def\labelenumii{\alph{enumii}.}
  \tightlist
  \item
    Datos
  \item
    Mapeo estético de los datos (\emph{aesthetic mappings})
  \item
    Un objeto geométrico
  \item
    Una transformación estadística
  \item
    Ajustes en las posiciones de los objetos
  \end{enumerate}
\item
  Una escala para cada estética
\item
  Un sistema de coordenadas
\item
  Una especificación de facetas
\end{enumerate}

Al graficar en \texttt{ggplot} se tiene control sobre todos estos
elementos:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{() }\OperatorTok{+}
\StringTok{  }\KeywordTok{layer}\NormalTok{( }\CommentTok{# una capa}
    \DataTypeTok{data =}\NormalTok{ diamonds, }\CommentTok{# datos}
    \DataTypeTok{mapping =} \KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ carat, }\DataTypeTok{y =}\NormalTok{ price), }\CommentTok{# mapeo estético}
    \DataTypeTok{geom =} \StringTok{"point"}\NormalTok{, }\CommentTok{# geometría}
    \DataTypeTok{stat =} \StringTok{"identity"}\NormalTok{, }\CommentTok{# transformación estadística}
    \DataTypeTok{position =} \StringTok{"identity"} \CommentTok{# ajuste en posición de objetos}
\NormalTok{    ) }\OperatorTok{+}\StringTok{ }
\StringTok{  }\KeywordTok{scale_y_continuous}\NormalTok{() }\OperatorTok{+}\StringTok{ }\CommentTok{# Escala para estética continua en y}
\StringTok{  }\KeywordTok{scale_x_continuous}\NormalTok{() }\OperatorTok{+}\StringTok{ }\CommentTok{# Escala para estética continua en x}
\StringTok{  }\KeywordTok{coord_cartesian}\NormalTok{() }\CommentTok{# Sistema de coordenadas}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-3-1.pdf}

\texttt{ggplot} implementa también una serie de \texttt{defaults}
\parencite[][p. 3]{ggplot2} que facilitan la escritura de nuevas
gráficas pues no es necesario especificar cada uno de los detalles al
agregar una capa. Por tanto, es posible escribir el mismo gráfico
haciendo uso de esos \texttt{defaults}:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(diamonds, }\KeywordTok{aes}\NormalTok{(carat, price)) }\OperatorTok{+}\StringTok{ }\KeywordTok{geom_point}\NormalTok{()}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-4-1.pdf}

\subsection{Características
importantes}\label{caracteristicas-importantes}

Los componentes de una gráfica son ortogonales:

\begin{verbatim}
- Cambiar uno no debe romper los otros
- Una configuración distinta de componentes es válida
- Puedes construir mayor complejidad agregando capas
\end{verbatim}

\subsection{Las capas}\label{las-capas}

\texttt{ggplot} produce un objeto que se puede convertir en una gráfica.
Es decir, \texttt{R} sabe cómo convertirlo en una gráfica.

Este objeto está formado por capas, mismas que tienen sus entradas
(\emph{inputs}) particulares y que comparten argumentos del gráfico
\texttt{base} generado por la función \texttt{ggplot()}. Con el operador
\texttt{+} se van agregando las distintas capas al mismo objeto.

Así como en otros casos, el objeto en \texttt{R} puede ser guardado en
una variable, se le puede imprimir, se le puede guardar como imagen de
diferentes formatos, o se puede guardar en una lista o en un
\texttt{Rdata}.

\subsection{Componentes de una capa}\label{componentes-de-una-capa}

\subsubsection{Datos y mapa estético}\label{datos-y-mapa-estetico}

Permite mapear las columnas del \texttt{data.frame} de entrada a los
aspectos de la gráfica.

Es decir,

\begin{itemize}
\tightlist
\item
  las coordenadas \(x\), \(y\)
\item
  los grupos (definidos por otra variable)
\item
  el tamaño
\item
  el color
\item
  el relleno
\end{itemize}

Para ejemplificar, generamos una variable \(x\) que proviene de dos
distribuciones normales: mil realizaciones \(N(0, 1)\) y mil
\(N(3, 1)\). Asignamos un grupo a las primeras mil y otro a la segunda.

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{mix2norm <-}\StringTok{ }\KeywordTok{data.frame}\NormalTok{(}\DataTypeTok{x  =} \KeywordTok{c}\NormalTok{(}\KeywordTok{rnorm}\NormalTok{(}\DecValTok{1000}\NormalTok{), }\KeywordTok{rnorm}\NormalTok{(}\DecValTok{1000}\NormalTok{, }\DecValTok{3}\NormalTok{)), }
                       \DataTypeTok{grupo =} \KeywordTok{as.factor}\NormalTok{(}\KeywordTok{rep}\NormalTok{(}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{2}\NormalTok{),}\DataTypeTok{each=}\DecValTok{1000}\NormalTok{)))}

\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x=}\NormalTok{x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }\KeywordTok{geom_density}\NormalTok{()}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-5-1.pdf}

\subsubsection{Transformaciones
estadísticas}\label{transformaciones-estadisticas}

Ésta puede ser, por ejemplo, un resumen de la entrada (\emph{input})
recibido; se especifica vía el comando \texttt{stat}. Ejemplos:

\begin{itemize}
\tightlist
\item
  binning
\item
  smoothing
\item
  boxplot
\item
  identity
\end{itemize}

Utilizamos, por ejemplo, la transformación \emph{bin}, misma que se
especifica en el objeto geométrico:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x=}\NormalTok{x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }
\StringTok{  }\KeywordTok{geom_density}\NormalTok{(}\DataTypeTok{stat =} \StringTok{"bin"}\NormalTok{, }\DataTypeTok{binwidth =} \FloatTok{0.1}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-6-1.pdf}

La transformación utilizada tiene asociada parámetros como lo es el
tamaño en el que deben realizarse los colapsos de la variable categórica
(\emph{binwidth}).

\subsubsection{El objeto geométrico}\label{el-objeto-geometrico}

Esto permite especificar el tipo de gráfico a crear. Se especifica con
la \texttt{geom}. Se define de acuerdo a su dimensión, es decir,

\begin{itemize}
\tightlist
\item
  \texttt{0-dim}: puntos, texto
\item
  \texttt{1-dim}: líneas
\item
  \texttt{2-dim}: polígonos, intervalos
\end{itemize}

Otras geometrías incluyen:

\begin{itemize}
\tightlist
\item
  \texttt{geom\_hist}
\item
  \texttt{geom\_bar}
\item
  \texttt{geom\_contour}
\item
  \texttt{geom\_line}
\item
  \texttt{geom\_density}
\end{itemize}

Además, se puede cambiar la transformación estadística manteniendo la
geometría fijada. Al ejemplo anterior, le agregamos una transformación
estadística dentro del objeto geométrico con el parámetro
\texttt{adjust}.

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }\KeywordTok{geom_density}\NormalTok{(}\DataTypeTok{adjust =} \DecValTok{1}\OperatorTok{/}\DecValTok{2}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-7-1.pdf}

En este caso, estamos pidiendo la mitad del tamaño del bin que se
calcula en forma algorítmica por el paquete.

Viceversa, puede cambiarse la geometría pero mantener la transformación
estadística.

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }\KeywordTok{stat_density}\NormalTok{(}\DataTypeTok{adjust =} \DecValTok{1}\OperatorTok{/}\DecValTok{2}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-8-1.pdf}

Revisa el comando \texttt{position} y \texttt{geometry}. Revisa sus
defaults y copia algunos de los ejemplos en la documentación.

\texttt{geom\_density} por ejemplo utiliza \texttt{ribbon} o una cosa
que a veces encontrarán en español como violín.

\renewcommand\bcStyleTitre[1]{\large\textcolor{bbblack}{#1}}

\begin{bclogo}[
  couleur=llred,
  arrondi=0,
  logo=\bcstop,
  barre=none,
  noborder=true]{Ejercicios}
\begin{enumerate}
\item Genera una gráfica con la función \texttt{ggplot} en donde los datos sea
la base \texttt{diamonds} y la estética sea $x = price$. Especifica como geometría
una densidad.
\item Cambia el color y el relleno de la geometría a gris (\texttt{grey50})
\item Cambia la geometría a \texttt{ribbon}, cambia los parámetros necesarios
para que funcione.
\item Agrega una faceta para que se haga un gráfico para cada uno de los subconjuntos
definidos por la variable \texttt{cut}.
\item Agrega a la gráfica el comando \texttt{coord\_flip} para que el precio este
en el eje $y$.
\end{enumerate}

\end{bclogo}

\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Respuestas}
\CommentTok{# 1}
\NormalTok{g <-}\StringTok{ }\KeywordTok{ggplot}\NormalTok{(diamonds, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ price)) }\OperatorTok{+}\StringTok{ }\KeywordTok{stat_density}\NormalTok{()}
\NormalTok{g}
\CommentTok{# 2}
\NormalTok{g }\OperatorTok{+}
\StringTok{  }\KeywordTok{stat_density}\NormalTok{(}\DataTypeTok{fill =} \StringTok{"grey50"}\NormalTok{, }\DataTypeTok{colour =} \StringTok{"grey50"}\NormalTok{) }
\CommentTok{# 3}
\NormalTok{g <-}\StringTok{ }\NormalTok{g }\OperatorTok{+}
\StringTok{  }\KeywordTok{stat_density}\NormalTok{(}\KeywordTok{aes}\NormalTok{(}\DataTypeTok{ymax =}\NormalTok{ ..density..,  }\DataTypeTok{ymin =} \OperatorTok{-}\NormalTok{..density..),}
    \DataTypeTok{fill =} \StringTok{"grey50"}\NormalTok{, }\DataTypeTok{colour =} \StringTok{"grey50"}\NormalTok{,}
    \DataTypeTok{geom =} \StringTok{"ribbon"}\NormalTok{, }\DataTypeTok{position =} \StringTok{"identity"}\NormalTok{)}
\NormalTok{g}
\CommentTok{# 4}
\NormalTok{g <-}\StringTok{ }\NormalTok{g  }\OperatorTok{+}
\StringTok{  }\KeywordTok{facet_grid}\NormalTok{(. }\OperatorTok{~}\StringTok{ }\NormalTok{cut) }
\NormalTok{g}
\CommentTok{# 5}
\NormalTok{g }\OperatorTok{+}\StringTok{ }\KeywordTok{coord_flip}\NormalTok{()}
\end{Highlighting}
\end{Shaded}

\subsubsection{Posición}\label{posicion}

Es posible especificar la posición de cada una de las capas en relación
a otras. Ejemplos:

\begin{itemize}
\tightlist
\item
  \texttt{dodge}
\item
  \texttt{identity}
\item
  \texttt{jitter}
\end{itemize}

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x=}\NormalTok{x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }
\StringTok{  }\KeywordTok{stat_density}\NormalTok{(}\DataTypeTok{adjust=}\DecValTok{1}\OperatorTok{/}\DecValTok{2}\NormalTok{, }\DataTypeTok{size=}\DecValTok{2}\NormalTok{, }\DataTypeTok{position =} \StringTok{"identity"}\NormalTok{, }\DataTypeTok{geom =} \StringTok{"line"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-10-1.pdf}

\subsubsection{Escalas}\label{escalas}

Determina cuál valor de entrada mapea a qué estética específica. Se
escribe usando \texttt{scale}. Hay de todo:

\begin{itemize}
\tightlist
\item
  \texttt{continous}
\item
  \texttt{logarithmic}
\item
  \texttt{values\ to\ shapes}
\item
  \texttt{what\ limits}
\item
  \texttt{what\ labels}
\item
  \texttt{what\ marks}
\end{itemize}

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x=}\NormalTok{x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }
\StringTok{  }\KeywordTok{stat_density}\NormalTok{(}\DataTypeTok{adjust=}\DecValTok{1}\OperatorTok{/}\DecValTok{2}\NormalTok{, }\DataTypeTok{size=}\DecValTok{2}\NormalTok{, }\DataTypeTok{position =}\StringTok{"identity"}\NormalTok{, }\DataTypeTok{geom =}\StringTok{"line"}\NormalTok{) }\OperatorTok{+}
\StringTok{  }\KeywordTok{scale_y_log10}\NormalTok{(}\DataTypeTok{limits =} \KeywordTok{c}\NormalTok{(}\FloatTok{1e-5}\NormalTok{,}\DecValTok{1}\NormalTok{))}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-11-1.pdf}

\subsubsection{Coordenadas}\label{coordenadas}

Te permite especificar las posiciones de las cosas y cómo mapean a las
posiciones en la pantalla. Antes todo era entorno a cómo le dices las
cosas a \texttt{R} pero también importa cómo las ves. Coordenadas
distintas pueden afectar a los objetos geométricos. Ejemplos:

\begin{itemize}
\tightlist
\item
  \texttt{cartesian}
\item
  \texttt{polar}
\item
  \texttt{map-projection}
\end{itemize}

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }
\StringTok{  }\KeywordTok{stat_density}\NormalTok{(}\DataTypeTok{adjust =} \DecValTok{1}\OperatorTok{/}\DecValTok{2}\NormalTok{, }\DataTypeTok{size =} \DecValTok{2}\NormalTok{, }\DataTypeTok{position =} \StringTok{"identity"}\NormalTok{, }\DataTypeTok{geom =} \StringTok{"line"}\NormalTok{) }\OperatorTok{+}
\StringTok{  }\KeywordTok{coord_polar}\NormalTok{()}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-12-1.pdf}

\subsubsection{Facetas}\label{facetas}

Permite arreglar diferentes gráficas en un grid o panel.

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{ggplot}\NormalTok{(mix2norm, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ x, }\DataTypeTok{color =}\NormalTok{ grupo)) }\OperatorTok{+}\StringTok{ }
\StringTok{  }\KeywordTok{stat_density}\NormalTok{(}\DataTypeTok{adjust =} \DecValTok{1}\OperatorTok{/}\DecValTok{2}\NormalTok{, }\DataTypeTok{size =} \DecValTok{2}\NormalTok{, }\DataTypeTok{position =} \StringTok{"identity"}\NormalTok{, }\DataTypeTok{geom =} \StringTok{"line"}\NormalTok{) }\OperatorTok{+}
\StringTok{  }\KeywordTok{facet_grid}\NormalTok{(grupo }\OperatorTok{~}\StringTok{ }\NormalTok{.)}
\end{Highlighting}
\end{Shaded}

\includegraphics{ggplot2_files/figure-latex/unnamed-chunk-13-1.pdf}

Ve el help de \texttt{facet\_wrap}

\section{Material adicional}\label{material-adicional}

\begin{itemize}
\tightlist
\item
  Importación

  \begin{itemize}
  \tightlist
  \item
    Curso \textbf{Importing Data in R (Part 1)} de
    \href{https://www.datacamp.com/courses/importing-data-in-r-part-1}{Data
    Camp}.
  \item
    Curso \textbf{Importing Data in R (Part 2)} de
    \href{https://www.datacamp.com/courses/importing-data-in-r-part-2}{Data
    Camp}.
  \end{itemize}
\item
  \texttt{dplyr} y \texttt{tidyr}

  \begin{itemize}
  \tightlist
  \item
    Curso de \texttt{swirl} \textbf{Getting and cleaning data}.
  \item
    Curso \textbf{Cleaning Data in R} de
    \href{https://www.datacamp.com/courses/cleaning-data-in-r}{Data
    Camp}.
  \item
    Curso \textbf{Data Manipulation in R with dplyr} de
    \href{https://www.datacamp.com/courses/dplyr-data-manipulation-r-tutorial}{Data
    Camp}.
  \item
    Curso \textbf{Joining data in R with dplyr} de
    \href{https://www.datacamp.com/courses/joining-data-in-r-with-dplyr}{Data
    Camp}.
  \end{itemize}
\item
  Gráficos del \texttt{base}

  \begin{itemize}
  \tightlist
  \item
    Curso de \texttt{swirl} \textbf{Overview of Statistics}.
  \end{itemize}
\item
  \texttt{ggplot2}

  \begin{itemize}
  \tightlist
  \item
    Curso de \texttt{swirl} \textbf{Exploratory data analysis}.
  \item
    Curso \textbf{Data Visualization in R} de
    \href{https://www.datacamp.com/courses/data-visualization-in-r}{Data
    Camp}.
  \item
    Curso \textbf{Data Visualization with ggplot2 (Part 1)} de
    \href{https://www.datacamp.com/courses/data-visualization-with-ggplot2-1}{Data
    Camp}.
  \item
    Curso \textbf{Data Visualization with ggplot2 (Part 2)} de
    \href{https://www.datacamp.com/courses/data-visualization-with-ggplot2-2}{Data
    Camp}.
  \item
    Curso \textbf{Data Visualization with ggplot2 (Part 3)} de
    \href{https://www.datacamp.com/courses/data-visualization-with-ggplot2-3}{Data
    Camp}.
  \end{itemize}
\end{itemize}

\end{document}


text:
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check, Match } from 'meteor/check';
import { Random } from 'meteor/random';
import { Notes } from './notes';
import { Slides } from './slides';

import AppState from '/imports/api/appState';

Meteor.methods({
  'drawing.insert' (drawing) {
    check(drawing, {
      type: String,
      data: {
        coords: [{
          x: Number,
          y: Number,
        }]
      },
      color: String,
      size: String,
      slide: Match.Maybe(String),
      _id: Match.Maybe(String),
    });
    drawing = Object.assign(drawing, {
      slide: drawing.slide || Slides.activeSlide('_id'),
      _id: drawing._id || Random.id(),
    });
    Meteor.call('recordings.insert', 'drawing.insert', Array.from(arguments) );
    return Notes.insert(drawing);
  },
});

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<serializer>
    <class name="Application\Sonata\ProductBundle\Entity\Travel" exclusion-policy="all" xml-root-name="product">

        <property name="travellers" type="integer"  expose="true" since-version="1.0" groups="sonata_api_read,sonata_api_write,sonata_search" />
        <property name="travelDate" type="DateTime" expose="true" since-version="1.0" groups="sonata_api_read,sonata_api_write,sonata_search" />
        <property name="travelDays" type="integer"  expose="true" since-version="1.0" groups="sonata_api_read,sonata_api_write,sonata_search" />

    </class>
</serializer>


text:
class Address < ActiveRecord::Base

  cache_records :store => :shared, :key => "add", :index => [:store_id]

  serialize :location, Hash

  belongs_to :store

end


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System.Collections;
using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.Commands.BaseCommandInterfaces;

namespace Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.GetAzureHDInsightClusters
{
    internal abstract class AzureHDInsightNewJobDefinitionCommandBase : AzureHDInsightCommandBase, INewAzureHDInsightJobConfigBase
    {
        public abstract Hashtable Defines { get; set; }

        public abstract string[] Files { get; set; }

        public abstract string StatusFolder { get; set; }
    }
}


text:
package com.develhack.lombok.eclipse.handlers.feature;

import lombok.core.AST.Kind;
import lombok.core.AnnotationValues;
import lombok.core.HandlerPriority;
import lombok.eclipse.EclipseAnnotationHandler;
import lombok.eclipse.EclipseNode;

import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.mangosdk.spi.ProviderFor;

import com.develhack.annotation.feature.Serializable;

@ProviderFor(EclipseAnnotationHandler.class)
@HandlerPriority(SerializableHandler.PRIORITY)
public class SerializableHandler extends AbstractFeatureHandler<Serializable> {

	public static final int PRIORITY = InitializeFieldsByConstructorHandler.PRIORITY + 1;

	public SerializableHandler() {
		super(Serializable.class);
	}

	@Override
	public void handle(AnnotationValues<Serializable> annotationValues, Annotation ast, EclipseNode annotationNode) {

		super.handle(annotationValues, ast, annotationNode);

		EclipseNode typeNode = annotationNode.up();

		if (typeNode.getKind() != Kind.TYPE) {
			annotationNode.addWarning(String.format("@%s is only applicable to the type.", getAnnotationName()));
			return;
		}

		supplementSuperInterface(java.io.Serializable.class);
		supplementSuppressWaring("serial");
	}
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const os = require("os");
// import * as shelljs from 'shelljs';
const utility_1 = require("../utility");
const unknown = 'unknown';
/**
 * There is no standard way on Linux to find the distribution name and version.
 * Recently, systemd has pushed to standardize the os-release file. This has
 * seen adoption in "recent" versions of all major distributions.
 * https://www.freedesktop.org/software/systemd/man/os-release.html
 */
class LinuxDistribution {
    constructor(name, version, idLike) {
        this.name = name;
        this.version = version;
        this.idLike = idLike;
    }
    static GetCurrent() {
        // Try /etc/os-release and fallback to /usr/lib/os-release per the synopsis
        // at https://www.freedesktop.org/software/systemd/man/os-release.html.
        return LinuxDistribution.FromFilePath('/etc/os-release')
            .catch(() => LinuxDistribution.FromFilePath('/usr/lib/os-release'))
            .catch(() => Promise.resolve(new LinuxDistribution(unknown, unknown)));
    }
    toString() {
        return `name=${this.name}, version=${this.version}`;
    }
    static FromFilePath(filePath) {
        return new Promise((resolve, reject) => {
            fs.readFile(filePath, 'utf8', (error, data) => {
                if (error) {
                    reject(error);
                }
                else {
                    resolve(LinuxDistribution.FromReleaseInfo(data));
                }
            });
        });
    }
    static FromReleaseInfo(releaseInfo, eol = os.EOL) {
        let name = unknown;
        let version = unknown;
        let idLike = null;
        const lines = releaseInfo.split(eol);
        for (let line of lines) {
            line = line.trim();
            let equalsIndex = line.indexOf('=');
            if (equalsIndex >= 0) {
                let key = line.substring(0, equalsIndex);
                let value = line.substring(equalsIndex + 1);
                // Strip double quotes if necessary
                if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) {
                    value = value.substring(1, value.length - 1);
                }
                if (key === 'ID') {
                    name = value;
                }
                else if (key === 'VERSION_ID') {
                    version = value;
                }
                else if (key === 'ID_LIKE') {
                    idLike = value.split(" ");
                }
                if (name !== unknown && version !== unknown && idLike !== null) {
                    break;
                }
            }
        }
        return new LinuxDistribution(name, version, idLike);
    }
}
exports.LinuxDistribution = LinuxDistribution;
class PlatformInformation {
    constructor(platform, architecture, distribution = null) {
        this.platform = platform;
        this.architecture = architecture;
        this.distribution = distribution;
        try {
            this.runtimeId = PlatformInformation.getRuntimeId(platform, architecture, distribution);
        }
        catch (err) {
            console.error(err);
            this.runtimeId = null;
        }
    }
    isWindows() {
        return this.platform === 'win32';
    }
    isMacOS() {
        return this.platform === 'darwin';
    }
    isLinux() {
        return this.platform === 'linux';
    }
    toString() {
        let result = this.platform;
        if (this.architecture) {
            if (result) {
                result += ', ';
            }
            result += this.architecture;
        }
        if (this.distribution) {
            if (result) {
                result += ', ';
            }
            result += this.distribution.toString();
        }
        return result;
    }
    static GetCurrent() {
        let platform = os.platform();
        let architecturePromise;
        let distributionPromise;
        switch (platform) {
            case 'win32':
                architecturePromise = PlatformInformation.GetWindowsArchitecture();
                distributionPromise = Promise.resolve(null);
                break;
            case 'darwin':
                architecturePromise = PlatformInformation.GetUnixArchitecture();
                distributionPromise = Promise.resolve(null);
                break;
            case 'linux':
                architecturePromise = PlatformInformation.GetUnixArchitecture();
                distributionPromise = LinuxDistribution.GetCurrent();
                break;
            default:
                throw new Error(`Unsupported platform: ${platform}`);
        }
        return Promise.all([architecturePromise, distributionPromise])
            .then(([arch, distro]) => {
            return new PlatformInformation(platform, arch, distro);
        });
    }
    static GetWindowsArchitecture() {
        return __awaiter(this, void 0, void 0, function* () {
            const process = yield utility_1.Utility.exec("wmic os get osarchitecture");
            if (process.exitCode == 0) {
                let archArray = process.stdout.split(os.EOL);
                if (archArray.length >= 2) {
                    let arch = archArray[1].trim();
                    // Note: This string can be localized. So, we'll just check to see if it contains 32 or 64.
                    if (arch.indexOf('64') >= 0) {
                        return "x86_64";
                    }
                    else if (arch.indexOf('32') >= 0) {
                        return "x86";
                    }
                }
            }
            return unknown;
        });
    }
    static GetUnixArchitecture() {
        return __awaiter(this, void 0, void 0, function* () {
            const process = yield utility_1.Utility.exec("uname -m");
            return process.exitCode == 0 ? process.stdout.trim() : unknown;
        });
    }
    /**
     * Returns a supported .NET Core Runtime ID (RID) for the current platform. The list of Runtime IDs
     * is available at https://github.com/dotnet/corefx/tree/master/pkg/Microsoft.NETCore.Platforms.
     */
    static getRuntimeId(platform, architecture, distribution) {
        // Note: We could do much better here. Currently, we only return a limited number of RIDs that
        // are officially supported.
        switch (platform) {
            case 'win32':
                switch (architecture) {
                    case 'x86': return 'win7-x86';
                    case 'x86_64': return 'win7-x64';
                }
                throw new Error(`Unsupported Windows architecture: ${architecture}`);
            case 'darwin':
                if (architecture === 'x86_64') {
                    // Note: We return the El Capitan RID for Sierra
                    return 'osx.10.11-x64';
                }
                throw new Error(`Unsupported macOS architecture: ${architecture}`);
            case 'linux':
                if (architecture === 'x86_64') {
                    const unknown_distribution = 'unknown_distribution';
                    const unknown_version = 'unknown_version';
                    // First try the distribution name
                    let runtimeId = PlatformInformation.getRuntimeIdHelper(distribution.name, distribution.version);
                    // If the distribution isn't one that we understand, but the 'ID_LIKE' field has something that we understand, use that
                    //
                    // NOTE: 'ID_LIKE' doesn't specify the version of the 'like' OS. So we will use the 'VERSION_ID' value. This will restrict
                    // how useful ID_LIKE will be since it requires the version numbers to match up, but it is the best we can do.
                    if (runtimeId === unknown_distribution && distribution.idLike && distribution.idLike.length > 0) {
                        for (let id of distribution.idLike) {
                            runtimeId = PlatformInformation.getRuntimeIdHelper(id, distribution.version);
                            if (runtimeId !== unknown_distribution) {
                                break;
                            }
                        }
                    }
                    if (runtimeId !== unknown_distribution && runtimeId !== unknown_version) {
                        return runtimeId;
                    }
                }
                // If we got here, this is not a Linux distro or architecture that we currently support.
                throw new Error(`Unsupported Linux distro: ${distribution.name}, ${distribution.version}, ${architecture}`);
        }
        // If we got here, we've ended up with a platform we don't support  like 'freebsd' or 'sunos'.
        // Chances are, VS Code doesn't support these platforms either.
        throw Error('Unsupported platform ' + platform);
    }
    static getRuntimeIdHelper(distributionName, distributionVersion) {
        const unknown_distribution = 'unknown_distribution';
        const unknown_version = 'unknown_version';
        const centos_7 = 'centos.7-x64';
        const debian_8 = 'debian.8-x64';
        const fedora_23 = 'fedora.23-x64';
        const fedora_24 = 'fedora.24-x64';
        const opensuse_13_2 = 'opensuse.13.2-x64';
        const opensuse_42_1 = 'opensuse.42.1-x64';
        const rhel_7 = 'rhel.7-x64';
        const ubuntu_14_04 = 'ubuntu.14.04-x64';
        const ubuntu_16_04 = 'ubuntu.16.04-x64';
        const ubuntu_16_10 = 'ubuntu.16.10-x64';
        switch (distributionName) {
            case 'ubuntu':
                if (distributionVersion === "14.04") {
                    // This also works for Linux Mint
                    return ubuntu_14_04;
                }
                else if (distributionVersion === "16.04") {
                    return ubuntu_16_04;
                }
                else if (distributionVersion === "16.10") {
                    return ubuntu_16_10;
                }
                break;
            case 'elementary':
            case 'elementary OS':
                if (distributionVersion.startsWith("0.3")) {
                    // Elementary OS 0.3 Freya is binary compatible with Ubuntu 14.04
                    return ubuntu_14_04;
                }
                else if (distributionVersion.startsWith("0.4")) {
                    // Elementary OS 0.4 Loki is binary compatible with Ubuntu 16.04
                    return ubuntu_16_04;
                }
                break;
            case 'linuxmint':
                if (distributionVersion.startsWith("18")) {
                    // Linux Mint 18 is binary compatible with Ubuntu 16.04
                    return ubuntu_16_04;
                }
                break;
            case 'centos':
            case 'ol':
                // Oracle Linux is binary compatible with CentOS
                return centos_7;
            case 'fedora':
                if (distributionVersion === "23") {
                    return fedora_23;
                }
                else if (distributionVersion === "24") {
                    return fedora_24;
                }
                break;
            case 'opensuse':
                if (distributionVersion.startsWith("13.")) {
                    return opensuse_13_2;
                }
                else if (distributionVersion.startsWith("42.")) {
                    return opensuse_42_1;
                }
                break;
            case 'rhel':
                return rhel_7;
            case 'debian':
                return debian_8;
            case 'galliumos':
                if (distributionVersion.startsWith("2.0")) {
                    return ubuntu_16_04;
                }
                break;
            case 'arch':
                // NOTE: currently Arch Linux seems to be compatible enough with Ubuntu 16 that this works,
                // though in the future this may need to change as Arch follows a rolling release model.
                return ubuntu_16_04;
            default:
                return unknown_distribution;
        }
        return unknown_version;
    }
}
exports.PlatformInformation = PlatformInformation;
//# sourceMappingURL=platform.js.map


text:
class ManabuWindow : public QMainWindow
{
    Q_OBJECT

public:
                            ManabuWindow(QWidget *parent = 0);
                            ~ManabuWindow();
public slots:
    void                    SubmitClicked();
    void                    Quit();
    void                    OpenDeck();
    void                    SaveDeck();
    void                    PileIndexChanged(int index);
    void                    DeckClicked(QModelIndex);
    void                    ToggleDisplay();
    void                    NewDeck();
    void                    EditDeck();
    void                    EditCard();
    void                    AddCard();
private:
    Ui::fMainWindow         fWindow;
    map<int,PileManager*>   fDecks;
    int                     fCurrentDeck;
    int                     fCurrentPile;
    int                     fPileSize;
    int                     fCurrentCard;
    bool                    fShowFront;
    list<Card*>*            fOnDeck;

    void                    _CreatePile(int pileNum);
    void                    _ShowCard();
    void                    _AddMenuItem(PileManager* deck);
};

#endif // MANABUWINDOW_H


text:
package org.elasticsearch.common.lucene.search;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.DocValuesFieldExistsQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.Version;
import org.elasticsearch.index.mapper.SeqNoFieldMapper;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;

public class QueriesTests extends ESTestCase {

    public void testNonNestedQuery() {
        for (Version version : VersionUtils.allVersions()) {
            // This is a custom query that extends AutomatonQuery and want to make sure the equals method works
            assertEquals(Queries.newNonNestedFilter(version), Queries.newNonNestedFilter(version));
            assertEquals(Queries.newNonNestedFilter(version).hashCode(), Queries.newNonNestedFilter(version).hashCode());
            if (version.onOrAfter(Version.V_6_1_0)) {
                assertEquals(Queries.newNonNestedFilter(version), new DocValuesFieldExistsQuery(SeqNoFieldMapper.PRIMARY_TERM_NAME));
            } else {
                assertEquals(Queries.newNonNestedFilter(version), new BooleanQuery.Builder()
                    .add(new MatchAllDocsQuery(), BooleanClause.Occur.FILTER)
                    .add(Queries.newNestedFilter(), BooleanClause.Occur.MUST_NOT)
                    .build());
            }
        }
    }

    public void testIsNegativeQuery() {
        assertFalse(Queries.isNegativeQuery(new MatchAllDocsQuery()));
        assertFalse(Queries.isNegativeQuery(new BooleanQuery.Builder().build()));
        assertFalse(Queries.isNegativeQuery(new BooleanQuery.Builder()
                .add(new TermQuery(new Term("foo", "bar")), Occur.MUST).build()));
        assertTrue(Queries.isNegativeQuery(new BooleanQuery.Builder()
                .add(new TermQuery(new Term("foo", "bar")), Occur.MUST_NOT).build()));
        assertFalse(Queries.isNegativeQuery(new BooleanQuery.Builder()
                .add(new MatchAllDocsQuery(), Occur.MUST)
                .add(new MatchAllDocsQuery(), Occur.MUST_NOT).build()));
    }

    public void testFixNegativeQuery() {
        assertEquals(new BooleanQuery.Builder()
                .add(new MatchAllDocsQuery(), Occur.FILTER)
                .add(new TermQuery(new Term("foo", "bar")), Occur.MUST_NOT).build(),
                Queries.fixNegativeQueryIfNeeded(
                        new BooleanQuery.Builder()
                        .add(new TermQuery(new Term("foo", "bar")), Occur.MUST_NOT)
                        .build()));
    }
}


text:
package com.maghi711.spring.springdeveloper.beanfactory;

public interface Oracle {

    String defineMeaningOfLife();

}


text:
/// <reference path="../../src/js/lib/classes/ScrollFire.d.ts" />
/// <reference types="element-measurer" />
/// <reference types="jest" />

import { resolve } from 'path';
import createPuppeteer from '../utils/createPuppeteer';

/** @type {puppeteer.Browser} */
let browser;
/** @type {puppeteer.Page} */
let page;

beforeEach(async (done) => {
  const p = await createPuppeteer(resolve(__dirname, './ScrollFire.html'));
  browser = p.browser;
  page = p.page;
  done();
}, 20e3);

afterEach(() => {
  browser.close();
});

describe('Puppeteer initialize test.', () => {
  it('should work.', async () => {
    const num = await page.evaluate(x => 5 * x, 5);
    expect(num).toEqual(25);
  });

  it('clientWidth: 800, clientHeight: 600', async () => {
    const [clientWidth, clientHeight] = await page.evaluate(() => {
      return [window.innerWidth, window.innerHeight];
    });
    expect(clientWidth).toEqual(800);
    expect(clientHeight).toEqual(600);
  });
});

describe('ScrollFire', () => {
  /** @type {typeof scrollFire.ScrollFire>} */
  let ScrollFire;

  it('should work.', async () => {
    const [minY, maxY] = await page.evaluate(() => {
      const scrollFire = new window.ScrollFire({ target: '.box.third' });
      return scrollFire.getTargetPosition();
    });
    expect(minY).toEqual(800);
    expect(maxY).toEqual(1200);
  });

  it('could set target as string when constructing.', async () => {
    const [minY, maxY] = await page.evaluate(() => {
      const scrollFire = new window.ScrollFire('.box.second');
      return scrollFire.getTargetPosition();
    });
    expect(minY).toEqual(400);
    expect(maxY).toEqual(800);
  });

  it('fire event test', async () => {
    const isActivated = await page.evaluate(async () => {
      const elm = document.querySelector('.box.second');
      const handler = () => elm.classList.add('active');

      ScrollFire = window.ScrollFire;
      new ScrollFire({
        target: '.box.second',
        actions: [
          { handler },
        ],
      });

      await window.autoScroll();
      return elm.classList.contains('active');
    });
    expect(isActivated).toBeTruthy();
  });

  it('addAction TEST', async () => {
    const [forwardResult, reverseResult] = await page.evaluate(async () => {
      ScrollFire = window.ScrollFire;
      const scrollFire = new ScrollFire({ target: '.box.second' });

      scrollFire.addAction({
        direction: 'reverse',
        handler: elm => elm.classList.add('active'),
      });
      // forward scrolling.
      await window.autoScroll();
      const elm = document.querySelector('.box.second');
      const forwardResult = elm.classList.contains('active'); // expect false.
      // reverse scrolling.
      await window.autoScroll(0);
      const reverseResult = elm.classList.contains('active'); // expect true.
      return [forwardResult, reverseResult];
    });

    expect(forwardResult).toBeFalsy();
    expect(reverseResult).toBeTruthy();
  });

  it('addAction TEST 2: could gives argument as ActionHandler.', async () => {
    const results = await page.evaluate(async () => {
      ScrollFire = window.ScrollFire;
      new ScrollFire('.box.second').addAction(elm => elm.classList.add('active'));

      const checkActive = () => document.querySelector('.box.second').classList.contains('active');

      const firstResult = checkActive();
      await window.autoScroll();
      const secondResult = checkActive();
      return [firstResult, secondResult];
    });

    expect(results[0]).toBeFalsy();
    expect(results[1]).toBeTruthy();
  });

  it('referencePoint TEST', async () => {
    const results = await page.evaluate(async () => {
      ScrollFire = window.ScrollFire;
      const scrollFire = new ScrollFire({
        target: '.box.second', // box height: 400 ~ 800
        referencePoint: 'center', // reference point: 600
      });
      scrollFire.addAction({
        direction: 'forward',
        handler: elm => elm.classList.add('active'),
      });
      const checkActive = () => document.querySelector('.box.second').classList.contains('active');

      const firstResult = checkActive(); // expect false.
      // scroll until 500.
      await window.autoScroll(500);
      const secondResult = checkActive(); // expect false.
      // scroll until 700.
      await window.autoScroll(700);
      const thirdResult = checkActive(); // expect true.
      return [firstResult, secondResult, thirdResult];
    });

    expect(results[0]).toBeFalsy();
    expect(results[1]).toBeFalsy();
    expect(results[2]).toBeTruthy();
  });

  it('offset TEST', async () => {
    const results = await page.evaluate(async () => {
      ScrollFire = window.ScrollFire;
      const scrollFire = new ScrollFire({
        target: '.box.second', // box height: 400 ~ 800
        offset: 200, // expected targetPosition: 200 ~ 1000
      });
      scrollFire.addAction({
        direction: 'forward',
        handler: elm => elm.classList.add('active'),
      });
      const checkActive = () => document.querySelector('.box.second').classList.contains('active');
      const firstResult = checkActive(); // expect false.
      // scroll until 300
      await window.autoScroll(300);
      const secondResult = checkActive(); // expect true.
      return [firstResult, secondResult];
    });

    expect(results[0]).toBeFalsy();
    expect(results[1]).toBeTruthy();
  });

  it('destroy TEST', async () => {
    const results = await page.evaluate(async () => {
      ScrollFire = window.ScrollFire;
      const scrollFire = new ScrollFire({ target: '.box.second' });
      scrollFire.addAction({
        handler: elm => elm.classList.add('active'),
      });
      const elm = document.querySelector('.box.second');
      const checkActive = () => elm.classList.contains('active');
      // scroll.
      await window.autoScroll();
      const firstResult = checkActive(); // expect true.
      // destroy and reset.
      scrollFire.destroy();
      elm.classList.remove('active');
      window.scrollTo(0, 0);
      // scroll again.
      await window.autoScroll();
      const secondResult = checkActive(); // expect false.
      return [firstResult, secondResult];
    });

    expect(results[0]).toBeTruthy();
    expect(results[1]).toBeFalsy();
  });
});


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { DateTimeInputModule } from '../../modules/datetimeinput.module';
import { PanelModule } from '../../modules/panel.module';

@NgModule({
  declarations: [
      AppComponent
  ],
  imports: [
      BrowserModule, CommonModule, FormsModule, DateTimeInputModule, PanelModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }


text:
import logging, sys, os, signal, time, errno
from socket import gethostname
from django.core.management.base import BaseCommand
import cherrypy

CPSERVER_HELP = r"""
  Run this project in a CherryPy webserver. To do this, CherryPy from
  http://www.cherrypy.org/ is required.

   runcpserver [options] [cpserver settings] [stop]

Optional CherryPy server settings: (setting=value)
  host=HOSTNAME         hostname to listen on
                        Defaults to localhost
  port=PORTNUM          port to listen on
                        Defaults to 8088
  server_name=STRING    CherryPy's SERVER_NAME environ entry
                        Defaults to localhost
  daemonize=BOOL        whether to detach from terminal
                        Defaults to False
  pidfile=FILE          write the spawned process-id to this file
  workdir=DIRECTORY     change to this directory when daemonizing
  threads=NUMBER        Number of threads for server to use
  timeout=NUMBER        Timeout (in seconds) for accepted connections
  ssl_certificate=FILE  SSL certificate file
  ssl_private_key=FILE  SSL private key file
  ssl_certificate_chain=FILE	SSL root CA certificate file
  server_user=STRING    user to run daemonized process
                        Defaults to www-data
  server_group=STRING   group to daemonized process
                        Defaults to www-data

Examples:
  Run a "standard" CherryPy server server
    $ manage.py runcpserver

  Run a CherryPy server on port 80
    $ manage.py runcpserver port=80

  Run a CherryPy server as a daemon and write the spawned PID in a file
    $ manage.py runcpserver daemonize=true pidfile=/var/run/django-cpserver.pid

"""

CPSERVER_OPTIONS = {
'host': 'localhost',
'port': 8088,
'server_name': 'localhost',
'threads': 10,
'timeout': 10,
'daemonize': False,
'workdir': None,
'pidfile': None,
'server_user': 'www-data',
'server_group': 'www-data',
'ssl_certificate': None,
'ssl_private_key': None,
'ssl_certificate_chain': None,
}

class Command(BaseCommand):
    help = "CherryPy Server for project. Requires CherryPy."
    args = "[various KEY=val options, use `runcpserver help` for help]"

    def handle(self, *args, **options):
        from django.conf import settings
        from django.utils import translation
        # Activate the current language, because it won't get activated later.
        try:
            translation.activate(settings.LANGUAGE_CODE)
        except AttributeError:
            pass
        runcpserver(args)

    def usage(self, subcommand):
        return CPSERVER_HELP

def change_uid_gid(uid, gid=None):
    """Try to change UID and GID to the provided values.
    UID and GID are given as names like 'nobody' not integer.

    Src: http://mail.mems-exchange.org/durusmail/quixote-users/4940/1/
    """
    if not os.geteuid() == 0:
        # Do not try to change the gid/uid if not root.
        return
    (uid, gid) = get_uid_gid(uid, gid)
    os.setgid(gid)
    os.setuid(uid)

def get_uid_gid(uid, gid=None):
    """Try to change UID and GID to the provided values.
    UID and GID are given as names like 'nobody' not integer.

    Src: http://mail.mems-exchange.org/durusmail/quixote-users/4940/1/
    """
    import pwd, grp
    uid, default_grp = pwd.getpwnam(uid)[2:4]
    if gid is None:
        gid = default_grp
    else:
        try:
            gid = grp.getgrnam(gid)[2]
        except KeyError:
            gid = default_grp
    return (uid, gid)

def poll_process(pid):
    """
    Poll for process with given pid up to 10 times waiting .25 seconds in between each poll.
    Returns False if the process no longer exists otherwise, True.
    """
    for n in range(10):
        time.sleep(0.25)
        try:
            # poll the process state
            os.kill(pid, 0)
        except OSError, e:
            if e[0] == errno.ESRCH:
                # process has died
                return False
            else:
                raise Exception
    return True

def stop_server(pidfile):
    """
    Stop process whose pid was written to supplied pidfile.
    First try SIGTERM and if it fails, SIGKILL. If process is still running, an exception is raised.
    """
    if os.path.exists(pidfile):
        pid = int(open(pidfile).read())
        try:
            os.kill(pid, signal.SIGTERM)
        except OSError: #process does not exist
            os.remove(pidfile)
            return
        if poll_process(pid):
            #process didn't exit cleanly, make one last effort to kill it
            os.kill(pid, signal.SIGKILL)
            if poll_process(pid):
                raise OSError, "Process %s did not stop."
        os.remove(pidfile)

def start_server(options):
    """
    Start CherryPy server
    """

    if options['daemonize'] and options['server_user'] and options['server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])

    from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    from django.core.handlers.wsgi import WSGIHandler
    server = Server(
        (options['host'], int(options['port'])),
        WSGIHandler(),
        int(options['threads']),
        options['server_name'],
        timeout=int(options['timeout'])
    )

    if cherrypy.__version__ >= '3.2.0':
        #3.2 and beyond usage of ssl_adapter
        try:
            #use the openssl adapter if available
            from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter as sslAdapter
        except ImportError:
            from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter as sslAdapter
        if options['ssl_certificate'] and options['ssl_private_key']:
            if options['ssl_certificate_chain']:
                chain = options['ssl_certificate_chain']
            else:
                chain = None
            server.ssl_adapter = sslAdapter(options['ssl_certificate'], options['ssl_private_key'], certificate_chain=chain)
    else:
        #legacy older ssl setup method
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']
        if options['ssl_certificate_chain']:
            server.ssl_certificate_chain = options['ssl_certificate_chain']

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

def runcpserver(argset=[], **kwargs):
    # Get the options
    options = CPSERVER_OPTIONS.copy()
    options.update(kwargs)
    for x in argset:
        if "=" in x:
            k, v = x.split('=', 1)
        else:
            k, v = x, True
        options[k.lower()] = v

    if "help" in options:
        print CPSERVER_HELP
        return

    if "stop" in options:
        stop_server(options['pidfile'])
        return True

    if options['daemonize']:
        if not options['pidfile']:
            options['pidfile'] = '/var/run/cpserver_%s.pid' % options['port']
        stop_server(options['pidfile'])

        from django.utils.daemonize import become_daemon
        if options['workdir']:
            become_daemon(our_home_dir=options['workdir'])
        else:
            become_daemon()

        fp = open(options['pidfile'], 'w')
        fp.write("%d\n" % os.getpid())
        fp.close()

    # Start the webserver
    print 'starting server with options %s' % options
    start_server(options)

if __name__ == '__main__':
    runcpserver(sys.argv[1:])


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/Filter.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /**
   *
Contains the parameters for DescribeAvailabilityZones.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API DescribeAvailabilityZonesRequest : public EC2Request
  {
  public:
    DescribeAvailabilityZonesRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeAvailabilityZones"; }

    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline const Aws::Vector<Filter>& GetFilters() const{ return m_filters; }

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline void SetFilters(const Aws::Vector<Filter>& value) { m_filtersHasBeenSet = true; m_filters = value; }

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline void SetFilters(Aws::Vector<Filter>&& value) { m_filtersHasBeenSet = true; m_filters = std::move(value); }

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline DescribeAvailabilityZonesRequest& WithFilters(const Aws::Vector<Filter>& value) { SetFilters(value); return *this;}

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline DescribeAvailabilityZonesRequest& WithFilters(Aws::Vector<Filter>&& value) { SetFilters(std::move(value)); return *this;}

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline DescribeAvailabilityZonesRequest& AddFilters(const Filter& value) { m_filtersHasBeenSet = true; m_filters.push_back(value); return *this; }

    /**
     *
One or more filters.

 message - Information
     * about the Availability Zone.

 region-name - The
     * name of the region for the Availability Zone (for example,
     * us-east-1).

 state - The state of
     * the Availability Zone (available | information |
     * impaired | unavailable).

     * zone-name - The name of the Availability Zone (for example,
     * us-east-1a).

     */
    inline DescribeAvailabilityZonesRequest& AddFilters(Filter&& value) { m_filtersHasBeenSet = true; m_filters.push_back(std::move(value)); return *this; }

    /**
     *
The names of one or more Availability Zones.

     */
    inline const Aws::Vector<Aws::String>& GetZoneNames() const{ return m_zoneNames; }

    /**
     *
The names of one or more Availability Zones.

     */
    inline void SetZoneNames(const Aws::Vector<Aws::String>& value) { m_zoneNamesHasBeenSet = true; m_zoneNames = value; }

    /**
     *
The names of one or more Availability Zones.

     */
    inline void SetZoneNames(Aws::Vector<Aws::String>&& value) { m_zoneNamesHasBeenSet = true; m_zoneNames = std::move(value); }

    /**
     *
The names of one or more Availability Zones.

     */
    inline DescribeAvailabilityZonesRequest& WithZoneNames(const Aws::Vector<Aws::String>& value) { SetZoneNames(value); return *this;}

    /**
     *
The names of one or more Availability Zones.

     */
    inline DescribeAvailabilityZonesRequest& WithZoneNames(Aws::Vector<Aws::String>&& value) { SetZoneNames(std::move(value)); return *this;}

    /**
     *
The names of one or more Availability Zones.

     */
    inline DescribeAvailabilityZonesRequest& AddZoneNames(const Aws::String& value) { m_zoneNamesHasBeenSet = true; m_zoneNames.push_back(value); return *this; }

    /**
     *
The names of one or more Availability Zones.

     */
    inline DescribeAvailabilityZonesRequest& AddZoneNames(Aws::String&& value) { m_zoneNamesHasBeenSet = true; m_zoneNames.push_back(std::move(value)); return *this; }

    /**
     *
The names of one or more Availability Zones.

     */
    inline DescribeAvailabilityZonesRequest& AddZoneNames(const char* value) { m_zoneNamesHasBeenSet = true; m_zoneNames.push_back(value); return *this; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline bool GetDryRun() const{ return m_dryRun; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline DescribeAvailabilityZonesRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}

  private:

    Aws::Vector<Filter> m_filters;
    bool m_filtersHasBeenSet;

    Aws::Vector<Aws::String> m_zoneNames;
    bool m_zoneNamesHasBeenSet;

    bool m_dryRun;
    bool m_dryRunHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
<module>
 <v-iptables
  name="Ipv4 Linux firewall, NAT and packet mangling tools"
  provides="iptables"
  after="^net">

  <execute id="prepare" code="touch ${configuration_services_iptables_rules_file} ;
           chmod 0600 ${configuration_services_iptables_rules_file}" />
  <execute id="enable" code="iptables-restore ${configuration_services_iptables_options} < ${configuration_services_iptables_rules_file}" />
  <execute id="prepare" code="if [ "${configuration_services_iptables_save_on_stop}" = "yes" ]; then
                iptables-save ${configuration_services_iptables_options} > ${configuration_services_iptables_rules_file} ;
           else
                true ;
           fi" />

  <variables s="configuration-services-iptables/.*" />
  <need-files s="iptables-save:iptables-restore" />
 </v-iptables>
</module>


text:
<?php
    require_once 'system/Templater.php';

    $form = new Templater();
    $form->load( "templates/browse.tpl.php" );
    $page = new Templater( "templates/main.tpl.php" );

    $page->title = "List/Remove Authors";
    $page->scripts = array( "browse.js" );
    $page->set( "body", $form->parse() );

    $page->publish();
?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
RDFEncoder
</TITLE>

<META NAME="date" CONTENT="2012-04-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cbiit.cmts.transform.artifact

Class RDFEncoder

java.lang.Object
  gov.nih.nci.cbiit.cmts.transform.artifact.RDFEncoder

public class RDFEncoder
extends java.lang.Object

Constructor Summary

RDFEncoder(java.lang.String xmlSource)

          Constructor with XML string

Method Summary

 java.lang.String
getFormatedRDF()

          Export formated XML document

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RDFEncoder

public RDFEncoder(java.lang.String xmlSource)

Constructor with XML string

Parameters:
xmlSource - String of source XML

Method Detail

getFormatedRDF

public java.lang.String getFormatedRDF()

Export formated XML document

Returns:
xmlString formated  XML document

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
const webpack = require('webpack');
const config = require('./base.config');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const clone = require('clone');
const newConfig = clone(config);

newConfig.devtool = false;
newConfig.module.loaders.push(
    // 编译sass 编译css并自动添加css前缀
    {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
            fallbackLoader: 'style-loader',
            loader: 'css-loader!sass-loader'
        })
    }
);
// 修改最终发布地址
newConfig.output.publicPath = "/assets/dist/";

newConfig.plugins = (config.plugins || []).concat([
    // this allows uglify to strip all warnings
    // from Vue.js source code.
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: '"production"'
        }
    }),
    // 压缩js css html
    // This minifies not only JavaScript, but also
    // the templates (with html-minifier) and CSS (with cssnano)!
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }),
    // new webpack.optimize.CommonsChunkPlugin({
    //     name: 'common',
    //     filename: 'common.js',
    //     async: true,
    //     minChunks: 2
    // }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new ExtractTextPlugin('css/[name].css'),
    new HtmlWebpackPlugin({
        title: 'vue chat',
        cache: true,
        template: './index.ejs'
    })
    // new webpack.optimize.DedupePlugin()

]);

module.exports = newConfig;


text:
import Ember from "ember";

export default Ember.View.extend({
    classNameBindings: [":side-panel"],
    layoutName: "detail-views/side-panel-layout"
});


text:
<vars xmlns="http://www.idiominc.com/opentopic/vars">
  <variable id="blank_page">Deze bladzijde werd met opzet blanco gelaten</variable>
  <variable id="#table-continued">Table continued…</variable>
  <variable id="Figure">Figuur: <param ref-name="title"/></variable>
  <variable id="Table">Tabel: <param ref-name="title"/></variable>
  <variable id="Chapter with number"></variable>
  <variable id="Table of Contents Chapter"></variable>
  <variable id="Table of Contents Appendix">Bijlage: </variable>
</vars>


text:
1. What database models do you know?
-----

A database model is a type of data model that determines the logical structure of a database and fundamentally determines in which manner data can be stored, organized, and manipulated. The most popular example of a database model is the relational model, which uses a table-based format.
Common logical data models for databases include:

* [Hierarchical database model](https://en.wikipedia.org/wiki/Hierarchical_database_model)
* [Network model](https://en.wikipedia.org/wiki/Network_model)
* [Relational model](https://en.wikipedia.org/wiki/Relational_model)
* [Entity–relationship model](https://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model)
    * [Enhanced entity–relationship model](https://en.wikipedia.org/wiki/Enhanced_entity%E2%80%93relationship_model)
* [Object model](https://en.wikipedia.org/wiki/Object_database)
* [Document model](https://en.wikipedia.org/wiki/Document-oriented_database)
* [Entity–attribute–value model](https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model)
* [Star schema](https://en.wikipedia.org/wiki/Star_schema)

***

2. Which are the main functions performed by a Relational Database Management System (RDBMS)?
-----

A relational database management system (RDBMS) is a program that lets you create, update, and administer a relational database. Most commercial RDBMS's use the Structured Query Language (SQL) to access the database, although SQL was invented after the development of the relational model and is not necessary for its use.

Main functions performed by RDBMS:

* Creating / altering / deleting tables and relationships between them (database schema)

* Adding, changing, deleting, searching and retrieving of data stored in the tables

***

3. Define what is "table" in database terms.
-----

A table is a collection of related data held in a structured format within a database. It consists of fields (columns), and rows.

In [relational databases](https://en.wikipedia.org/wiki/Relational_database) and [flat file databases](https://en.wikipedia.org/wiki/Flat_file_database), a **table** is a set of data elements (values) using a model of vertical columns (identifiable by name) and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Each row is identified by one or more values appearing in a particular column subset. The columns subset which uniquely identifies a row is called the primary key.

"Table" is another term for "relation"; although there is the difference in that a table is usually a multiset (bag) of rows where a relation is a set and does not allow duplicates. Besides the actual data rows, tables generally have associated with them some metadata, such as constraints on the table or on the values within particular columns.

The data in a table does not have to be physically stored in the database. Views also function as relational tables, but their data are calculated at query time. External tables (in Informix or Oracle, for example) store data outside standard database structures but accessible to database commands.

***

4. Explain the difference between a primary and a foreign key.
-----

**Foreign keys** are used to reference unique columns in another table. So, for example, a foreign key can be defined on one table A, and it can reference some unique column(s) in another table B. Why would you want a foreign key? Well, whenever it makes sense to have a relationship between columns in two different tables.

A table can have multiple **unique** and **foreign keys**. However, a table can have only one **primary key**.

***

5. Explain the different kinds of relationships between tables in relational databases.
-----

Relationship types
You share many relationships with members of your family. For instance, you and your mother are related. You have only one mother, but she may have several children. You and your siblings are related—you may have many brothers and sisters and, of course, they'll have many brothers and sisters as well. If you're married, both you and your spouse have a spouse—each other—but only one at a time. Database relationships are very similar in that they're associations between tables. There are three types of relationships:

* __One-to-one__: Both tables can have only one record on either side of the relationship. Each primary key value relates to only one (or no) record in the related table. They're like spouses—you may or may not be married, but if you are, both you and your spouse have only one spouse. Most one-to-one relationships are forced by business rules and don't flow naturally from the data. In the absence of such a rule, you can usually combine both tables into one table without breaking any normalization rules.
* __One-to-many__: The primary key table contains only one record that relates to none, one, or many records in the related table. This relationship is similar to the one between you and a parent. You have only one mother, but your mother may have several children.
* __Many-to-many__: Each record in both tables can relate to any number of records (or no records) in the other table. For instance, if you have several siblings, so do your siblings (have many siblings). Many-to-many relationships require a third table, known as an associate or linking table, because relational systems can't directly accommodate the relationship.

***

6. When is a certain database schema normalized?
-----
    * What are the advantages of normalized databases?
------

Database normalization (or normalisation) is the process of organizing the columns (attributes) and tables (relations) of a relational database to minimize data redundancy.

Normalization involves decomposing a table into less redundant (and smaller) tables without losing information; defining foreign keys in the old table referencing the primary keys of the new ones. The objective is to isolate data so that additions, deletions, and modifications of an attribute can be made in just one table and then propagated through the rest of the database using the defined foreign keys.

***

7. What are database integrity constraints and when are they used?
-----

Integrity constraints provide a mechanism for ensuring that data conforms to guidelines specified by the database administrator. The most common types of constraints include:

* UNIQUE constraints

    To ensure that a given column is unique

* NOT NULL constraints

    To ensure that no null values are allowed

* FOREIGN KEY constraints

    To ensure that two keys share a primary key to foreign key relationship

Constraints can be used for these purposes in a data warehouse:

* Data cleanliness

    Constraints verify that the data in the data warehouse conforms to a basic level of data consistency and correctness, preventing the introduction of dirty data.

* Query optimization

    The Oracle Database utilizes constraints when optimizing SQL queries. Although constraints can be useful in many aspects of query optimization, constraints are particularly important for query rewrite of materialized views.

Unlike data in many relational database environments, data in a data warehouse is typically added or modified under controlled circumstances during the extraction, transformation, and loading (ETL) process. Multiple users normally do not update the data warehouse directly, as they do in an OLTP system.

***

8. Point out the pros and cons of using indexes in a database.
-----

**Advantages**: Use an index for quick access to a database table specific information. The index is a structure of the database table the value of one or more columns to sort
As a general rule, only when the data in the index column Frequent queries, only need to create an index on the table. The index take up disk space and reduce to add, delete, and update the line speed. In most cases, the speed advantages of indexes for data retrieval greatly exceeds it.

**Disadvantages**: Index will affect the speed of update and insert, because it requires the same update each index file. For a frequently updated and inserted into the table, there is no need for a rarely used where the words indexed separately, small table, the cost of sorting will not be great, there is no need to create additional indexes. In some cases, the indexing words may not be fast, for example, the index is placed in a contiguous memory space, which will increase the burden of disk read, which is optimal, it should be through the actual use of the environment to be tested.

[More about indexes](http://www.databaseskill.com/3082411/)

***

9. What's the main purpose of the SQL language?
-----

SQL language is originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language, data manipulation language, and a data control language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.

SQL was one of the first commercial languages for Edgar F. Codd's relational model, as described in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks."[10] Despite not entirely adhering to the relational model as described by Codd, it became the most widely used database language.

***

10. What are transactions used for?
-----
    * Give an example.
------

A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.

A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.

There are following commands used to control transactions:

* COMMIT: to save the changes.

* ROLLBACK: to rollback the changes.

* SAVEPOINT: creates points within groups of transactions in which to ROLLBACK

* SET TRANSACTION: Places a name on a transaction.

Transactional control commands are only used with the DML commands INSERT, UPDATE and DELETE only. They can not be used while creating tables or dropping them because these operations are automatically commited in the database.

11. What is a NoSQL database?
-----

NoSQL encompasses a wide variety of different database technologies that were developed in response to a rise in the volume of data stored about users, objects and products, the frequency in which this data is accessed, and performance and processing needs. Relational databases, on the other hand, were not designed to cope with the scale and agility challenges that face modern applications, nor were they built to take advantage of the cheap storage and processing power available today.

***


text:
module ReactOnRails
  module GitUtils
    def self.uncommitted_changes?(message_handler)
      return false if ENV["COVERAGE"]
      status = `git status --porcelain`
      return false if status.empty?
      error = "You have uncommitted code. Please commit or stash your changes before continuing"
      message_handler.add_error(error)
      true
    end
  end
end