text:
% Copyright (c)  2005  Luis Fernando Llana Díaz
% Se otorga permiso para copiar, distribuir y/o modificar este documento
% bajo los términos de la Licencia de Documentación Libre GNU, Versión 1.2
% o cualquier otra versión posterior publicada por la Free Software Foundation;
% sin partes invariantes, sin portadas ni contraportadas
% Una copia de la licencia es incluida en el fichero "LICENSE.txt"

% Permission is granted to copy, distribute and/or modify this document
% under the terms of the GNU Free Documentation License, Version 1.2
% or any later version published by the Free Software Foundation;
% with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
% A copy of the license is included in the file "LICENSE.txt"
% $Id: transparencias.tex,v 1.3 2008-10-08 20:56:41 luis Exp $

\title{Redes Border Gateway Protocol (BGP-4)}
\subtitle{Estudio y Simulación}

\maketitle

\begin{frame}
\frametitle{Índice}
\tableofcontents
\end{frame}

\section{Introducción a BGP-4}
\begin{frame}
\frametitle{Introducción a BGP-4}
\tableofcontents[currentsection]
\end{frame}
\subsection{Qué es BGP-4}
\begin{frame}
  \frametitle{Border Gateway Protocol (BGP-4)}
  \begin{itemize}
   \item BGP-4 es un Protocolo de encaminamiento externo.
   \item Comparte información de encaminamiento entre conjuntos de encaminadores denominados
   sistemas autónomos.
   \item Se complementa con protocolos de encaminamiento interno como OSPF y RIP.
  \end{itemize}
\end{frame}

\subsection{Estructura de BGP-4}
\begin{frame}[allowframebreaks]
  \frametitle{Estructura de BGP-4}
  \begin{itemize}
   \item BGP-4 se organiza en sistemas autónomos.
   \item La comunicación en BGP-4 se realiza únicamente entre pares de encaminadores.
   \item Las sesiones BGP entre encaminadores pueden ser:
   \begin{itemize}
    \item \textbf{Internas}: los encaminadores pertenecen al mismo sistema autónomo.
    \item \textbf{Externas}: los encaminadores no pertenecen al mismo sistema autónomo.
   \end{itemize}
   \item La información compartida contiene rutas de encaminamiento y un conjunto atributos que
   determina si la ruta es utilizada y publicada.
  \end{itemize}
  \begin{figure}
   \centering
   \includegraphics[width=.80\hsize]{Imagenes/redBGP}
   \caption{Ejemplo de topología BGP-4}
  \end{figure}

\end{frame}

\subsection{Importancia de BGP-4}
\begin{frame}
  \frametitle{Importancia de BGP-4}
  \begin{itemize}
   \item Optimiza el intercambio de información en redes de gran tamaño.
   \item Es usado por la mayoría de los proveedores de Internet para publicar sus contenidos.
   \item Es el responsable de garantizar a los usuarios de Internet el acceso a gran parte de los
   contenidos
  \end{itemize}

\end{frame}

\section{Herramientas para su estudio}
\begin{frame}
\frametitle{Herramientas para su estudio}
\tableofcontents[currentsection]
\end{frame}
\subsection{Estudio de BGP-4}
\begin{frame}
  \frametitle{Estudio de BGP-4}
  \begin{itemize}
   \item BGP-4 es un protocolo fundamental para el correcto funcionamiento de Internet.
   \item Analizar la respuesta del protocolo en redes de poco tamaño es sencillo.
   \item Predecir el comportamiento de grandes redes como Internet es prácticamente imposible.
   \item Herramientas existentes para estudiar BGP-4 son:
   \begin{itemize}
    \item \textbf{Registros Regionales de Internet}: Organizaciones como Réseaux IP Européens (RIPE)
    registran todo el tráfico de BGP-4 de su zona.
    \item \textbf{Simulación}: Imita el comportamiento de una red mediante implementaciones
    teóricas de los elementos que componen la misma.
    \item \textbf{Emulación}: Realiza una simulación imitando cada uno de los elementos de una red.
   \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Simulación frente a Emulación}
  \begin{itemize}
   \item \textbf{Emulación}:
     \begin{itemize}
      \item Imita los elementos de la red.
      \item Resultados muy fieles a lo que ocurriría en la realidad.
      \item Sistemas poco flexibles.
      \item Necesita muchos recursos.
     \end{itemize}
   \item \textbf{Simulación}:
     \begin{itemize}
      \item Usa implementaciones de los elementos de la red.
      \item Sistemas muy flexibles.
      \item Dependiendo del simulador utilizado, el sistema puede ser muy escalable.
      \item Consume menos recursos que una emulación.
      \item Resultados menos fieles que los obtenidos en una emulación.
     \end{itemize}
   \item Existen herramientas que utilizan elementos simulados y emulados.
  \end{itemize}
\end{frame}

\subsection{J-Sim}

\begin{frame}
\frametitle{J-Sim}
  \begin{itemize}
   \item Está implementado en Java e integra el lenguaje de script TCL para sus simulaciones.
   \item Se basa en una arquitectura de capas y componentes anidados.
   \item El programa está licenciado bajo BSD.
   \item Existe una implementación BGP-4 pero está incompleta.
   \item Proyecto está abandonado.
  \end{itemize}
\end{frame}

\begin{frame}
\frametitle{Arquitectura del simulador}
  \begin{figure}
   \centering
   \includegraphics[width=.80\hsize]{Imagenes/arqCapas}
  \end{figure}
\end{frame}

\begin{frame}
  \frametitle{Desarrollo sobre el simulador}
  \begin{itemize}
   \item Labores de mantenimiento del software.
   \item Soporte de interfaces virtuales.
   \item Capacidad de realizar simulaciones a partir de ficheros XML sin necesidad de usar
   scripts TCL.
   \item Implementación de una utilidad que permite conocer el camino que sigue un paquete hasta
   llegar a su destino (\texttt{traceroute}).
   \item Implementación de la especificación de un nuevo protocolo GP-BGP como soporte para el
   proyecto 4Ward.
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Simular BGP-4 en J-Sim}
  \begin{itemize}
   \item Existe una adaptación de la implementación realizada por SSFNet realizada por Infonet de
   la Universidad de Illinois.
   \item Contiene fallos en la implementación.
   \item Carece las características avanzadas de BGP-4.
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Desarrollo sobre BGP-4}
  \begin{itemize}
   \item Labores de mantenimiento de la implementación del protocolo.
   \item Implementación de características avanzadas del protocolo: uso de reflexión de rutas,
   configuración de atributos y aplicación de políticas.
   \item Implementación de características experimentales: Soporte multipath y proceso de selección
   selectivo.
   \item Adaptación del protocolo a las simulaciones desde ficheros XML.
  \end{itemize}
\end{frame}

\section{Estudio del protocolo}
\begin{frame}
\tableofcontents[currentsection]
\end{frame}
\subsection{Proceso de decisión}
\begin{frame}[allowframebreaks]
  \frametitle{Proceso de decisión}
  \begin{itemize}
    \item Es el encargado de decidir si la ruta que contiene la información recibida es implantada
    en la tabla de rutas y publicada a encaminadores vecinos.
    \item Es el punto crítico del protocolo y donde se producen mayores problemas.
  \end{itemize}
  Funcionamiento:
  \begin{itemize}
    \item La decisión se toma basándose los atributos que contiene la información recibida y puede
    ser modificada con políticas que el encaminador posee.
    \item Los atributos que definen el peso de esta decisión son: Local Preference, AS PATH, MED,
    Originator y Tie Breaking.
  \end{itemize}

  \begin{figure}
   \centering
   \includegraphics[width=.60\hsize]{Imagenes/grafoCostes1}
   \caption{Ejemplo de topología BGP}
  \end{figure}

  \begin{figure}
   \centering
    \includegraphics[height=.60\vsize]{Imagenes/grafoCostes2}
   \caption{Ejemplo de grafo de costes}
  \end{figure}

\end{frame}

\subsection{Oscilaciones}
\begin{frame}[allowframebreaks]
\frametitle{Oscilaciones}
  \begin{itemize}
    \item Se producen cuando un sistema cambia entre varios estados intermitentemente.
    \item El sistema puede alcanzar un estado final estable o no alcanzarlo nunca.
    \item Es consecuencia de tener un grafo de costes no creciente.
    \item El efecto de las oscilaciones no se limita sólo a los nodos que oscilan, los nodos
    vecinos también se ven afectados.
    \item Cuando el sistema se estabiliza tiene varios estados finales posibles, es decir,
    no converge.
  \end{itemize}

 \begin{columns}[c]
    \begin{column}{.5\textwidth}
    Configuración inicial:
      \begin{itemize}
       \item El atributo Local Preference indica que los nodos B y C prefieren las rutas anunciadas
	entre ellos que la anunciadas anunciadas desde A.
      \end{itemize}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar1}
	\caption{Configuración que oscila}
      \end{figure}
    \end{column}
  \end{columns}
  \begin{columns}
    \begin{column}{.5\textwidth}
      Estado inicial:
      \begin{itemize}
       \item Las comunicación entre los nodos B y C está cortada.
       \item El nodo A publica sus rutas.
	\item Los nodos B y C acceden a la red a través del nodo A.
      \end{itemize}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar2}
	\caption{Estado inicial}
      \end{figure}
    \end{column}
  \end{columns}

 \begin{columns}
    \begin{column}{.5\textwidth}
      Comienza la comunicación:
      \begin{itemize}
	\item Los nodos B y C anuncian su ruta a la red.
      \end{itemize}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar3}
	\caption{Anuncio de rutas}
      \end{figure}
    \end{column}
  \end{columns}
   \begin{columns}
    \begin{column}{.5\textwidth}
    Llegada de los anuncios a sus destinos:
      \begin{itemize}
	\item Los anuncios son procesados por los nodos B y C.
	\item Las nuevas rutas son preferidas y se sustituye en la tabla de rutas la información
	antigua.
      \end{itemize}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar4}
	\caption{Sustitución de las antiguas rutas por la nueva información}
      \end{figure}
    \end{column}
  \end{columns}
   \newpage

  \begin{columns}
    \begin{column}{.5\textwidth}
      Se comunica a los nodos vecinos las rutas que no son utilizadas:
       \begin{itemize}
	\item Se generan anuncios de retirada de ruta, en los nodos B y C a sus vecinos.
      \end{itemize}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar5}
	\caption{Envío de anuncios de retirada}
      \end{figure}
    \end{column}
  \end{columns}

  \begin{columns}
    \begin{column}{.5\textwidth}
    Vuelta al estado inicial:
      \begin{itemize}
	\item Se restaura las rutas a través del nodo A.
	\item BGP-4 vuelve al estado inicial.
      \end{itemize}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar6}
	\caption{Se restaura la ruta por el Nodo A en la tabla de rutas}
      \end{figure}
    \end{column}
  \end{columns}

   \begin{itemize}
      \item Se alcanza un estado final cuando uno de los nodos tiene la información de las dos
      rutas y el otro no.
      \item Uno de los dos nodos decide la ruta a través de su compañero y no realizará su
      anuncio.
   \end{itemize}

  \begin{columns}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar7}
	\caption{Estado final 1}
      \end{figure}
    \end{column}
    \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/ciclar8}
	\caption{Estado final 2}
      \end{figure}
    \end{column}
  \end{columns}
\end{frame}

\subsection{BGP Wedgies}
\begin{frame}[allowframebreaks]
  \frametitle{BGP Wedgies}
  \begin{itemize}
   \item BGP-4 debería ser una herramienta determinista para compartir rutas.
   \item Ciertos escenarios, sin embargo, poseen más de un posible estado final y pueden ser
   alcanzados de manera no determinista. Estos estados son denominados BGP Wedgies.
   \item Fueron detectadas por primera vez por T. Griffin (BGP Wedgies. RFC 4264).
   \item Es consecuencia de tener un grafo de costes no creciente.
  \end{itemize}
  \begin{columns}
   \begin{column}{.5\textwidth}
       \begin{itemize}
	\item Los atributos de los nodos Router1\_3, Router3\_1 y Router3\_4 producen un grafo de
	costes no creciente.
	\item El As-1001 Prefiere las rutas anunciadas por el As-32080.
	\item El As-32080 Tiene un enlace de seguridad para mantener el acceso a las redes.
       \end{itemize}
   \end{column}
   \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/wedgie1}
	\caption{Configuración que sufre BGP wedgies}
      \end{figure}
   \end{column}
  \end{columns}
  \begin{columns}
   \begin{column}{.5\textwidth}
       \begin{itemize}
	\item Se utiliza el enlace principal para acceder a los contenidos
	\item No se produce tráfico de datos por el enlace de seguridad.
       \end{itemize}
   \end{column}
   \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/wedgie2}
	\caption{Estado inicial}
      \end{figure}
   \end{column}
  \end{columns}
  \begin{columns}
   \begin{column}{.5\textwidth}
       \begin{itemize}
	\item Tras una caída del enlace principal el tráfico es redirigido por el enlace de
	seguridad.
       \end{itemize}
   \end{column}
   \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/wedgie3}
	\caption{Caída del enlace principal}
      \end{figure}
   \end{column}
  \end{columns}
  \begin{columns}
   \begin{column}{.5\textwidth}
       \begin{itemize}
	\item Si se recupera la conexión, solo el As-6303 restablece el tráfico por el enlace
	principal.
	\item El As-1001 descarta la ruta porque tienen preferencia las rutas que son anunciadas por
	el As-32080.
       \end{itemize}
   \end{column}
   \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/wedgie4}
	\caption{Recuperación del enlace principal}
      \end{figure}
   \end{column}
  \end{columns}
  \begin{columns}
   \begin{column}{.5\textwidth}
       \begin{itemize}
	\item El As-32080 corta la conexión con el enlace de seguridad eliminando los anuncios de
	que utilizan ese camino.
       \end{itemize}
   \end{column}
   \begin{column}{.5\textwidth}
      \begin{figure}
	\centering
	\includegraphics[width=1\hsize]{Imagenes/wedgie5}
	\caption{Caída del enlace de seguridad}
      \end{figure}
   \end{column}
  \end{columns}

\end{frame}

\section{Conclusión}
\begin{frame}
\tableofcontents[currentsection]
\end{frame}

\subsection{Simulador J-Sim}
\begin{frame}
\begin{itemize}
 \item Se ha integrado el lenguaje de marcas XML al simulador J-Sim que permite usar herramientas
para crear y automatizar simulaciones.
 \item El simulador mantiene la potencia y la integración con el lenguaje de script TCL.
 \item Se ha completado la implementación de BGP-4.
 \item Se ha integrado el protocolo en J-Sim, obteniendo un entorno de simulación completo,
escalable y de fácil uso.
\end{itemize}
\end{frame}

\subsection{Estudio de BGP-4}
\begin{frame}
\begin{itemize}
 \item El uso de políticas y atributos causa que el grafo de costes del proceso de decisión no sea
 creciente.
 \item La consecuencia de esto se traduce en efectos negativos como oscilaciones y wedgies que
 producen un mal funcionamiento en el protocolo.

\end{itemize}
\end{frame}


text:
import html_checker
from os import path as os_path
import re
from sys import path as sys_path
import test_util
import unittest

_HERE = os_path.dirname(os_path.abspath(__file__))
sys_path.append(os_path.join(_HERE, '..', '..', '..', 'build'))

import find_depot_tools  # pylint: disable=W0611
from testing_support.super_mox import SuperMoxTestBase

class HtmlCheckerTest(SuperMoxTestBase):
  def setUp(self):
    SuperMoxTestBase.setUp(self)

    input_api = self.mox.CreateMockAnything()
    input_api.re = re
    output_api = self.mox.CreateMockAnything()
    self.checker = html_checker.HtmlChecker(input_api, output_api)

  def ShouldFailCheck(self, line, checker):
    """Checks that the |checker| flags |line| as a style error."""
    error = checker(1, line)
    self.assertNotEqual('', error, 'Should be flagged as style error: ' + line)
    highlight = test_util.GetHighlight(line, error).strip()

  def ShouldPassCheck(self, line, checker):
    """Checks that the |checker| doesn't flag |line| as a style error."""
    error = checker(1, line)
    self.assertEqual('', error, 'Should not be flagged as style error: ' + line)

  def testClassesUseDashFormCheckFails(self):
    lines = [
      '  ',
      ' ',
      '',
      '
 ',
    ]
    for line in lines:
      self.ShouldFailCheck(line, self.checker.ClassesUseDashFormCheck)

  def testClassesUseDashFormCheckPasses(self):
    lines = [
      ' class="abc" ',
      'class="foo-bar"',
      '<div class="foo-bar" id="classBar"',
    ]
    for line in lines:
      self.ShouldPassCheck(line, self.checker.ClassesUseDashFormCheck)

  def testSingleQuoteCheckFails(self):
    lines = [
      """  """,
      """""",
      """""",
      """""",
      """""",
    ]
    for line in lines:
      self.ShouldFailCheck(line, self.checker.DoNotUseSingleQuotesCheck)

  def testSingleQuoteCheckPasses(self):
    lines = [
      """SO VALID!""",
      """i don't""",
      """[[i18n('blah')]] """,
      """""",
      """""",
    ]
    for line in lines:
      self.ShouldPassCheck(line, self.checker.DoNotUseSingleQuotesCheck)

  def testDoNotCloseSingleTagsCheckFails(self):
    lines = [
      "<input/>",
      ' <input id="a" /> ',
      "
",
      "
",
      "
",
    ]
    for line in lines:
      self.ShouldFailCheck(line, self.checker.DoNotCloseSingleTagsCheck)

  def testDoNotCloseSingleTagsCheckPasses(self):
    lines = [
      "<input>",
      "<link>",
      "

",
      '<input text="/">',
    ]
    for line in lines:
      self.ShouldPassCheck(line, self.checker.DoNotCloseSingleTagsCheck)

  def testDoNotUseBrElementCheckFails(self):
    lines = [
      "
",
      "
  ",
      "
",
      '
',
    ]
    for line in lines:
      self.ShouldFailCheck(
          line, self.checker.DoNotUseBrElementCheck)

  def testDoNotUseBrElementCheckPasses(self):
    lines = [
      "br",
      "br>",
      "give me a break"
    ]
    for line in lines:
      self.ShouldPassCheck(
          line, self.checker.DoNotUseBrElementCheck)

  def testDoNotUseInputTypeButtonCheckFails(self):
    lines = [
      '<input type="button">',
      ' <input id="a" type="button" >',
      '<input type="button" id="a"> ',
    ]
    for line in lines:
      self.ShouldFailCheck(line, self.checker.DoNotUseInputTypeButtonCheck)

  def testDoNotUseInputTypeButtonCheckPasses(self):
    lines = [
      "<input>",
      '<input type="text">',
      '<input type="result">',
      '<input type="submit">',
      "<button>",
      '<button type="button">',
      '<button type="reset">',
      '<button type="submit">',

    ]
    for line in lines:
      self.ShouldPassCheck(line, self.checker.DoNotUseInputTypeButtonCheck)

  def testI18nContentJavaScriptCaseCheckFails(self):
    lines = [
      ' i18n-content="foo-bar" ',
      'i18n-content="foo_bar"',
      'i18n-content="FooBar"',
      'i18n-content="_foo"',
      'i18n-content="foo_"',
      'i18n-content="-foo"',
      'i18n-content="foo-"',
      'i18n-content="Foo"',
    ]
    for line in lines:
      self.ShouldFailCheck(line, self.checker.I18nContentJavaScriptCaseCheck)

  def testI18nContentJavaScriptCaseCheckPasses(self):
    lines = [
      ' i18n-content="abc" ',
      'i18n-content="fooBar"',
      'i18n-content="validName" attr="invalidName_"',
      '<div i18n-content="exampleTitle"',
    ]
    for line in lines:
      self.ShouldPassCheck(line, self.checker.I18nContentJavaScriptCaseCheck)

  def testLabelCheckFails(self):
    lines = [
      ' <label for="abc"',
      " <label for=    ",
      " <label\tfor=    ",
      ' <label\n blah="1" blee="3"\n for="goop"',
    ]
    for line in lines:
      self.ShouldFailCheck(line, self.checker.LabelCheck)

  def testLabelCheckPass(self):
    lines = [
      ' my-for="abc" ',
      ' myfor="abc" ',
      " <for",
      ' <paper-tooltip for="id-name"',
    ]
    for line in lines:
      self.ShouldPassCheck(line, self.checker.LabelCheck)

if __name__ == '__main__':
  unittest.main()

redpajama_set_name: RedPajamaGithub


text:
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE OverlappingInstances #-}

{-  With "hugs -98 +o test.hs" gives me:
    ERROR "test.hs":8 - Cannot justify constraints in instance member binding
    *** Expression    : fromStr
    *** Type          : FromStr [a] => String -> [a]
    *** Given context : FromStr [a]
    *** Constraints   : FromStr [a]

    Adding the constraint "FromStr a" to the declaration of fromStr fixes
    the problem, but that seems like it should be redundant. Removing the
    second instance (lines 10-11) also fixes the problem, interestingly enough.

    /Bjorn Bringert -}

-- August 08: on reflection I think a complaint about overlapping
-- instances for line 8 is absolutely right, so I've changed this to
-- expected-failure

-- Sept 08: on further reflection (!) I'm changing it back
-- See Note [Subtle interaction of recursion and overlap]
-- in TcInstDcls

module ShouldCompile  where

class FromStr a where
     fromStr :: String -> a

typeError :: FromStr a => a -> a
typeError t = error "type error"

instance FromStr [a] where
     fromStr _ = typeError undefined  -- line 8

instance FromStr [(String,a)] where  -- line 10
     fromStr _ = typeError undefined  -- line 11


text:
touch "$DS_LAST_RESTORED_VOLUME"/private/var/db/.RunLanguageChooserToo
rm -f "$DS_LAST_RESTORED_VOLUME"/private/var/log/CDIS.custom

exit 0


text:
const {ok, equal} = require('assert')
const {spawnSync:spawn} = require('child_process')

describe('module/bin', function(){
  Object
    .keys(process.env)
    .filter(prop => /npm_package_bin/.test(prop))
    .forEach(function(prop){
      it(`has executable for ${prop}`, () => {
        equal(spawn(process.env[prop]).error, undefined)
      })
    })
})


text:
package org.apache.phoenix.end2end;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.coprocessor.TaskRegionObserver;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.PIndexState;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.task.Task;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.MetaDataUtil;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.TestUtil;
import org.junit.BeforeClass;
import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Properties;

import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

// disabled -- see PHOENIX-5348
public abstract class IndexRebuildTaskIT extends BaseUniqueNamesOwnClusterIT {
    protected static String TENANT1 = "tenant1";
    private static RegionCoprocessorEnvironment TaskRegionEnvironment;

    @BeforeClass
    public static void doSetup() throws Exception {
        HashMap<String, String> props = new HashMap<>();
        setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
        TaskRegionEnvironment =
                getUtility()
                        .getRSForFirstRegionInTable(
                                PhoenixDatabaseMetaData.SYSTEM_TASK_HBASE_TABLE_NAME)
                        .getRegions(PhoenixDatabaseMetaData.SYSTEM_TASK_HBASE_TABLE_NAME)
                        .get(0).getCoprocessorHost()
                        .findCoprocessorEnvironment(TaskRegionObserver.class.getName());
    }

    private String generateDDL(String format) {
        StringBuilder optionsBuilder = new StringBuilder();

        if (optionsBuilder.length() != 0) optionsBuilder.append(",");
        optionsBuilder.append("MULTI_TENANT=true");

        return String.format(format, "TENANT_ID VARCHAR NOT NULL, ", "TENANT_ID, ", optionsBuilder.toString());
    }

    @Test
    public void testIndexRebuildTask() throws Throwable {
        String baseTable = generateUniqueName();
        Connection conn = null;
        Connection viewConn = null;
        try {
            conn = DriverManager.getConnection(getUrl());
            conn.setAutoCommit(false);
            Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
            props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, TENANT1);

            viewConn =DriverManager.getConnection(getUrl(), props);
            String ddlFormat =
                    "CREATE TABLE IF NOT EXISTS " + baseTable + "  ("
                            + " %s PK2 VARCHAR NOT NULL, V1 VARCHAR, V2 VARCHAR "
                            + " CONSTRAINT NAME_PK PRIMARY KEY (%s PK2)" + " ) %s";
            conn.createStatement().execute(generateDDL(ddlFormat));
            conn.commit();
            // Create a view
            String viewName = generateUniqueName();
            String viewDDL = "CREATE VIEW " + viewName + " AS SELECT * FROM " + baseTable;
            viewConn.createStatement().execute(viewDDL);

            // Create index
            String indexName = generateUniqueName();
            String idxSDDL = String.format("CREATE INDEX %s ON %s (V1)", indexName, viewName);

            viewConn.createStatement().execute(idxSDDL);

            // Insert rows
            int numOfValues = 1000;
            for (int i=0; i < numOfValues; i++){
                viewConn.createStatement().execute(
                        String.format("UPSERT INTO %s VALUES('%s', '%s', '%s')", viewName, String.valueOf(i), "y",
                                "z"));
            }
            viewConn.commit();

            String data = "{IndexName:" + indexName + "}";
            // Run IndexRebuildTask
            TaskRegionObserver.SelfHealingTask task =
                    new TaskRegionObserver.SelfHealingTask(
                            TaskRegionEnvironment, QueryServicesOptions.DEFAULT_TASK_HANDLING_MAX_INTERVAL_MS);

            Timestamp startTs = new Timestamp(EnvironmentEdgeManager.currentTimeMillis());
            // Add a task to System.Task to build indexes
            Task.addTask(conn.unwrap(PhoenixConnection.class), PTable.TaskType.INDEX_REBUILD,
                    TENANT1, null, viewName,
                    PTable.TaskStatus.CREATED.toString(), data, null, startTs, null, true);

            task.run();

            String viewIndexTableName = MetaDataUtil.getViewIndexPhysicalName(baseTable);
            ConnectionQueryServices queryServices = conn.unwrap(PhoenixConnection.class).getQueryServices();
            int count = getUtility().countRows(queryServices.getTable(Bytes.toBytes(viewIndexTableName)));
            assertTrue(count == numOfValues);

            // Remove index contents and try again
            Admin admin = queryServices.getAdmin();
            TableName tableName = TableName.valueOf(viewIndexTableName);
            admin.disableTable(tableName);
            admin.truncateTable(tableName, false);

            data = "{IndexName:" + indexName + ", DisableBefore:true}";

            // Add a new task (update status to created) to System.Task to rebuild indexes
            Task.addTask(conn.unwrap(PhoenixConnection.class), PTable.TaskType.INDEX_REBUILD,
                    TENANT1, null, viewName,
                    PTable.TaskStatus.CREATED.toString(), data, null, startTs, null, true);
            task.run();

            Table systemHTable= queryServices.getTable(Bytes.toBytes("SYSTEM."+PhoenixDatabaseMetaData.SYSTEM_TASK_TABLE));
            count = getUtility().countRows(systemHTable);
            assertEquals(1, count);

            // Check task status and other column values.
            waitForTaskState(conn, PTable.TaskType.INDEX_REBUILD, PTable.TaskStatus.COMPLETED);

            // See that index is rebuilt and confirm index has rows
            Table htable= queryServices.getTable(Bytes.toBytes(viewIndexTableName));
            count = getUtility().countRows(htable);
            assertEquals(numOfValues, count);
        } finally {
            conn.createStatement().execute("DELETE " + " FROM " + PhoenixDatabaseMetaData.SYSTEM_TASK_NAME);
            conn.commit();
            if (conn != null) {
                conn.close();
            }
            if (viewConn != null) {
                viewConn.close();
            }
        }
    }

    public static void waitForTaskState(Connection conn, PTable.TaskType taskType, PTable.TaskStatus expectedTaskStatus) throws InterruptedException,
            SQLException {
        int maxTries = 100, nTries = 0;
        do {
            Thread.sleep(2000);
            ResultSet rs = conn.createStatement().executeQuery("SELECT * " +
                    " FROM " + PhoenixDatabaseMetaData.SYSTEM_TASK_NAME +
                    " WHERE " + PhoenixDatabaseMetaData.TASK_TYPE + " = " +
                    taskType.getSerializedValue());

            String taskStatus = null;

            if (rs.next()) {
                taskStatus = rs.getString(PhoenixDatabaseMetaData.TASK_STATUS);
                boolean matchesExpected = (expectedTaskStatus.toString().equals(taskStatus));
                if (matchesExpected) {
                    return;
                }
            }
        } while (++nTries < maxTries);
        fail("Ran out of time waiting for task state to become " + expectedTaskStatus);
    }
}


text:
lightSync.init({
	_name: "lightsyncjs-example",
	"lightserver": {},
	"dropbox": {
		key: "gjexnb20idqkshp",
		receiverUrl: "http://localhost:8080/example/auth_receiver.html"
	},
	"googledrive": {
		client_id: "175501597543-sis50cnv45ma7bmbtl5cmu795cemsr4q.apps.googleusercontent.com",
		//client_secret: "..." only needed for cordova
	}
});

var onSignin = function(err)
{
	document.getElementById("coerror").style.display = err ? "block" : "none";

	if(err)
		return;

	document.getElementById("user").style.display = "block";
	document.getElementById("signin").style.display = "none";
	document.getElementById("userinfos").innerHTML = lightSync.getUserInfos().name + " (" + lightSync.getServerName() + ")";
	updateSyncTime();
};

var updateSyncTime = function()
{
	var syncTime = lightSync.getLastSyncTime();
	var message;
	if(lightSync.isSyncing())
		message = "(Syncing ...)";
	else
		message = "(Last sync: " + (syncTime === -1 ? "Never" : new Date(syncTime).toString()) + ")";
	document.getElementById("syncstate").innerHTML = message;
};

var notes = lightSync.getCollection("example-notes");
var items = notes.getItems();

window.onload = function()
{

	document.getElementById("sync").addEventListener("click", function(e) {
		lightSync.sync(function(err) {
			if(err)
				console.log(err);
			updateSyncTime();
		});
		e.preventDefault();
		updateSyncTime();
	});

	document.getElementById("signout").addEventListener("click", function(e) {
		lightSync.signout();
		document.getElementById("signin").style.display = "block";
		document.getElementById("user").style.display = "none";
		e.preventDefault();
	});

	(["dropbox", "googledrive", "lightserver"]).forEach(function(server) {
		document.getElementById(server).addEventListener("click", function() {
			lightSync.connect(server, onSignin);
		});
	});

	document.getElementById("addform").addEventListener("submit", function(e) {
		notes.addItem({
			title: document.getElementById("title").value,
			content: document.getElementById("content").value
		});
		document.getElementById("title").value = "";
		document.getElementById("content").value = "";
		e.preventDefault();
	});

	var printNotes = function()
	{
		var code = "";
		for(var i = 0; i < items.length; ++i)
		{
			var note = items[i];
			code += "
" + note.title + "
";
			code += "
" + note.content + "
";
			code += "
" + note.date + "
";
			code += '
Remove
';
			code += "
";
		}

		if(code === "")
			code = "No Note";

		document.getElementById("notes").innerHTML = code;

		var links = document.getElementById("notes").getElementsByTagName("a");
		for(var i = 0; i < links.length; ++i)
		{
			links[i].addEventListener("click", function(e) {
				notes.removeItem(items[parseInt(e.target.id.substr(2))]);
				e.preventDefault();
			});
		}

	};

	notes.on("change", printNotes);
	printNotes();

	var connected = lightSync.isConfigured();

	if(connected)
		onSignin(null);
	else
		document.getElementById("user").style.display = "none";

	document.getElementById("coerror").style.display = "none";

};


text:
package cfg

import (
	"os"

	"github.com/lunixbochs/usercorn/go/cmd"
)

func Main(args []string) {
	var backtrack, json *bool
	c := cmd.NewUsercornCmd()

	c.SetupFlags = func() error {
		backtrack = c.Flags.Bool("backtrack", false, "recursively backtrack cfg emulator")
		json = c.Flags.Bool("json", false, "use json cfg output")
		return nil
	}
	c.RunUsercorn = func() error {
		c.Usercorn.Gate().Lock()
		go func() {
			err := c.Usercorn.Run()
			if err != nil {
				panic(err)
			}
		}()
		return CfgMain(c.Usercorn, *backtrack, *json)
	}
	os.Exit(c.Run(args, os.Environ()))
}

func init() { cmd.Register("cfg", "explore a program's control flow graph", Main) }


text:
<!DOCTYPE html>

  <input id="test" aria-labelledby="t1">

foobarbaz


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" [
<!ENTITY logDir "/opt/lumify/logs">

<!-- Pattern: %d{yyyy-MM-dd HH:mm:ss.SSS/zzz} %-5p [%c{3}] %m%n -->
<!ENTITY pattern "%d{yyyy-MM-dd HH:mm:ss.SSS/zzz} %-5p [%c{3}] %m%n">
]
>

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.vertexium.elasticsearch7.utils.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="&pattern;" />
        </layout>
    </appender>

    <logger name="org.vertexium.query.Query.QUERY" additivity="false">
        <level value="TRACE" />
        <appender-ref ref="console" />
    </logger>
    <logger name="org.vertexium.elasticsearch7.bulk.BulkUpdateService.STACK_TRACE" additivity="false">
        <level value="TRACE" />
        <appender-ref ref="console" />
    </logger>
    <logger name="org.vertexium.elasticsearch7.SCROLL_API_STACK_TRACE" additivity="false">
        <level value="TRACE" />
        <appender-ref ref="console" />
    </logger>
    <logger name="org.vertexium.search.SearchIndex.MUTATION" additivity="false">
        <level value="TRACE" />
        <appender-ref ref="console" />
    </logger>
    <logger name="org.vertexium" additivity="false">
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </logger>
    <root>
        <level value="WARN" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>


text:
namespace SimpleFacade
{
    public interface IExecutable
    {
        object Execute();
    }
}


text:
function OnEnterInGameState() {

    $("#page-play").siblings().css("display", "none");
    $("#page-play").css("display", "block");
	//register key functions
    $('.btnNextQuestion').click(function (e) {
        var answerText = $(this).parent().find("#answer-" + controller.currentQuestionId).val();
        if (controller.isAnswerCorrect(answerText)) {
            changeQuestion(controller.currentQuestionId, controller.nextQuestionId);
            controller.processToNextQuestion();
        }
    });
	controller.startGame();
}

function OnExitInGameState()
{
	document.onkeydown = null;
	document.onkeyup = null;
	controller.stopGame();
}

var InGameState = new State( OnEnterInGameState, OnExitInGameState );


text:
from TreeFragment import parse_from_strings, StringParseContext
from Scanning import StringSourceDescriptor
import Symtab
import Naming
from Cython.Compiler import Visitor
import Code

class NonManglingModuleScope(Symtab.ModuleScope):

    def __init__(self, prefix, *args, **kw):
        self.prefix = prefix
        self.cython_scope = None
        Symtab.ModuleScope.__init__(self, *args, **kw)

    def add_imported_entry(self, name, entry, pos):
        entry.used = True
        return super(NonManglingModuleScope, self).add_imported_entry(
                                                        name, entry, pos)

    def mangle(self, prefix, name=None):
        if name:
            if prefix in (Naming.typeobj_prefix, Naming.func_prefix, Naming.var_prefix, Naming.pyfunc_prefix):
                # Functions, classes etc. gets a manually defined prefix easily
                # manually callable instead (the one passed to CythonUtilityCode)
                prefix = self.prefix
            return "%s%s" % (prefix, name)
        else:
            return Symtab.ModuleScope.mangle(self, prefix)

class CythonUtilityCodeContext(StringParseContext):
    scope = None

    def find_module(self, module_name, relative_to = None, pos = None,
                    need_pxd = 1):

        if module_name != self.module_name:
            if module_name not in self.modules:
                raise AssertionError("Only the cython cimport is supported.")
            else:
                return self.modules[module_name]

        if self.scope is None:
            self.scope = NonManglingModuleScope(self.prefix,
                                                module_name,
                                                parent_module=None,
                                                context=self)

        return self.scope

class CythonUtilityCode(Code.UtilityCodeBase):
    """
    Utility code written in the Cython language itself.

    The @cname decorator can set the cname for a function, method of cdef class.
    Functions decorated with @cname('c_func_name') get the given cname.

    For cdef classes the rules are as follows:
        obj struct      -> <cname>_obj
        obj type ptr    -> <cname>_type
        methods         -> <class_cname>_<method_cname>

    For methods the cname decorator is optional, but without the decorator the
    methods will not be prototyped. See Cython.Compiler.CythonScope and
    tests/run/cythonscope.pyx for examples.
    """

    is_cython_utility = True

    def __init__(self, impl, name="__pyxutil", prefix="", requires=None,
                 file=None, from_scope=None):
        # 1) We need to delay the parsing/processing, so that all modules can be
        #    imported without import loops
        # 2) The same utility code object can be used for multiple source files;
        #    while the generated node trees can be altered in the compilation of a
        #    single file.
        # Hence, delay any processing until later.
        self.impl = impl
        self.name = name
        self.file = file
        self.prefix = prefix
        self.requires = requires or []
        self.from_scope = from_scope

    def get_tree(self, entries_only=False, cython_scope=None):
        from AnalysedTreeTransforms import AutoTestDictTransform
        # The AutoTestDictTransform creates the statement "__test__ = {}",
        # which when copied into the main ModuleNode overwrites
        # any __test__ in user code; not desired
        excludes = [AutoTestDictTransform]

        import Pipeline, ParseTreeTransforms
        context = CythonUtilityCodeContext(self.name)
        context.prefix = self.prefix
        context.cython_scope = cython_scope
        #context = StringParseContext(self.name)
        tree = parse_from_strings(self.name, self.impl, context=context,
                                  allow_struct_enum_decorator=True)
        pipeline = Pipeline.create_pipeline(context, 'pyx', exclude_classes=excludes)

        if entries_only:
            p = []
            for t in pipeline:
                p.append(t)
                if isinstance(p, ParseTreeTransforms.AnalyseDeclarationsTransform):
                    break

            pipeline = p

        transform = ParseTreeTransforms.CnameDirectivesTransform(context)
        # InterpretCompilerDirectives already does a cdef declarator check
        #before = ParseTreeTransforms.DecoratorTransform
        before = ParseTreeTransforms.InterpretCompilerDirectives
        pipeline = Pipeline.insert_into_pipeline(pipeline, transform,
                                                 before=before)

        if self.from_scope:
            def scope_transform(module_node):
                module_node.scope.merge_in(self.from_scope)
                return module_node

            transform = ParseTreeTransforms.AnalyseDeclarationsTransform
            pipeline = Pipeline.insert_into_pipeline(pipeline, scope_transform,
                                                     before=transform)

        (err, tree) = Pipeline.run_pipeline(pipeline, tree, printtree=False)
        assert not err, err
        return tree

    def put_code(self, output):
        pass

    def declare_in_scope(self, dest_scope, used=False, cython_scope=None):
        """
        Declare all entries from the utility code in dest_scope. Code will only
        be included for used entries. If module_name is given, declare the
        type entries with that name.
        """
        tree = self.get_tree(entries_only=True, cython_scope=cython_scope)

        entries = tree.scope.entries
        entries.pop('__name__')
        entries.pop('__file__')
        entries.pop('__builtins__')
        entries.pop('__doc__')

        for name, entry in entries.iteritems():
            entry.utility_code_definition = self
            entry.used = used

        original_scope = tree.scope
        dest_scope.merge_in(original_scope, merge_unused=True)
        tree.scope = dest_scope

        for dep in self.requires:
            if dep.is_cython_utility:
                dep.declare_in_scope(dest_scope)

        return original_scope


text:
require 'kumogata/template/helper'
require 'kumogata/template/sns'

name = _resource_name(args[:name], "topic")
display = _name("display", args)
subscription = _sns_subscription_list(args)
topic = _name("topic", args)

_(name) do
  Type "AWS::SNS::Topic"
  Properties do
    DisplayName display
    Subscription subscription
    TopicName topic
  end
end


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "uploads".
 *
 * @property integer $upload_id
 * @property string $ref
 * @property string $file_name
 * @property string $real_filename
 * @property string $create_date
 * @property integer $type
 */
class Uploads extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'uploads';
    }

    /**
     * @inheritdoc
     */

      public function rules()
        {
            return [
                [['file_name'], 'required'],
                [['upload_id'], 'integer'],
                [['create_date'], 'safe'],
                [['ref'],'string','max'=>100],
                [['file_name', 'real_filename'], 'string', 'max' => 150]
            ];
        }
    /**
     * @inheritdoc
     */
     public function attributeLabels()
    {
        return [
            'upload_id' => 'Upload ID',
            'ref' => 'Ref',
            'file_name' => 'ชื่อไฟล์',
            'real_filename' => 'ชื่อไฟล์จริง',
            'create_date' => 'Create Date',
        ];
    }
}


text:
/*jslint node: true */

// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
    'use strict';

    config.set({
        // base path, that will be used to resolve files and exclude
        basePath: '../',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'src/bower_components/angular/angular.js',
            'src/bower_components/angular-animate/angular-animate.js',
            'src/bower_components/angular-resource/angular-resource.js',
            'src/bower_components/angular-route/angular-route.js',
            'src/bower_components/angular-mocks/angular-mocks.js',
            'src/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
            'src/bower_components/jquery/jquery.js',
            'src/bower_components/lodash/dist/lodash.js',
            'src/bower_components/angular/angular.js',
            'src/bower_components/socket.io-client/dist/socket.io.js',
            'src/bower_components/sinon/index.js',
            'src/scripts/futurism.js',
            'src/scripts/**/*.js',
            'test/mock/**/*.js',
            'test/spec/**/*.js'
        ],

        // list of files / patterns to exclude
        exclude: ['src/scripts/futurismRun.js'],

        // web server port
        port: 8080,

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['Firefox'],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};


text:
<?xml version="1.0"?>
<action-recipes>
    <snippet id="net.bindev.TextActions.INI.AutoPairSquareBrackets" category="hidden">
        <title>Autopair Square Brackets</title>
        <text-trigger key-equivalent="["></text-trigger>
        <text>[$0]</text>
        <syntax-context>ini, ini *</syntax-context>
    </snippet>
</action-recipes>


text:
import java.io.*;
class Test {
  interface InterfA {
    <T extends Cloneable & Iterable> void foo(T x);

    <T extends Iterable & Cloneable> void foo(T x);
  }

  class ANotSame {
    <T extends Cloneable & Iterable> void foo(T x){}

    <T extends Iterable & Cloneable> void foo(T x){}
  }

  class BNotSame extends ANotSame {
      @Override
      <T extends Cloneable & Iterable> void foo(T x){}
  }

  abstract class A<T extends Throwable> {
    abstract <T extends Comparable<?> & Serializable> void foo(T x, A<?> y);

    abstract <T extends Serializable & Comparable<?>> void foo(T x, A<? extends Cloneable> y);
  }

 /* abstract class B<T extends Throwable> {
    abstract <T extends Comparable<?> & Serializable> void foo(T x, B<?> y);

    abstract <T extends Serializable & Comparable<?>> void foo(T x, B<? extends Throwable> y);
  }

  abstract class C<T extends Throwable & Serializable> {
    abstract <T extends Comparable<?> & Serializable> void foo(T x, C<? extends Serializable> y);

    abstract <T extends Serializable & Comparable<?>> void foo(T x, C<? extends Throwable> y);
  }*/

  abstract class D<T extends Throwable & Runnable> {
    <error descr="'foo(T, D<? extends Runnable>)' clashes with 'foo(T, D<? extends Throwable>)'; both methods have same erasure">abstract <T extends Serializable & Comparable<?>> void foo(T x, D<? extends Runnable> y)</error>;

    abstract <T extends Serializable & Comparable<?>> void foo(T x, D<? extends Throwable> y);
  }

  interface IA {}
  interface IB {}
  void testExtendsOrder() {
    class E<T extends IA & IB> {
      <error descr="'foo(E<? extends IA>)' clashes with 'foo(E<? extends IB>)'; both methods have same erasure">void foo(E<? extends IA> x)</error> {}
      void foo(E<? extends IB> x) {}
    }
  }

  abstract class F<T extends Throwable> {
    <error descr="'foo(F<?>)' is already defined in 'Test.F'">abstract void foo(F<?> y)</error>;

    abstract void foo(F<? extends Throwable> y);
  }
}

class Ao {}

class Bo extends Ao {}

class SettingsEditor<T> {
}

abstract class RunConfigurationExtension<T extends Ao> {
    protected abstract <P extends T> SettingsEditor<P> createEditor(final P configuration);
}

class F extends RunConfigurationExtension<Bo> {

    @Override
    protected <P extends Bo> SettingsEditor<P> createEditor(P configuration) {
        return null;
    }
}


text:
import React from 'react';
import { Link } from 'react-router';
import {loginUser,logout, notificationCount} from '../lib/client';

export default class Header extends React.Component{

	constructor(props){
		super(props);
		this.state={};
	}

	componentDidMount(){
		loginUser()
			.then(user => this.setState({user}))
			.catch(err => console.log(err));
		notificationCount(false)
			.then(notificationCount => this.setState({notificationCount}))
			.catch(err => console.log(err));
	}

	handleLogout(){
		logout()
			.then(user => this.setState({user:null}))
			.catch(err => console.log(err));
	}

	render(){
		return (

					      <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
					        Toggle navigation

					      </button>
					      简单论坛系统

					        <Link to="/">首页 (current)</Link>

发帖

					      {this.state.user ? null:(

<Link to="/profile">设置</Link>

					      	)
					      }
					      {this.state.user ? null:(

<Link to="/notification">
					      		消息
					      		{this.state.notificationCount>0 ? ({this.state.notificationCount}未读) : null}
					      		</Link>

					      	)
					      }
					      {this.state.user ?(

注销[{this.state.user.nickname}]

					      	):(

<Link to="/login">登录</Link>
)
					      }
					      {this.state.user ? null:
					      	(

<Link to="/signup">注册</Link>
)
					      }

			);
	}
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float speed = 10f;
    public float airspeed = 0.2f;
    public float jumppower = 50f;
    public float secondjumppower = 60f;
    public float charHeight = 1;

    public bool direction = false; //false = left, true = right

    public bool jumped = false;
    public bool touching = false;

    // Check if is touching the ground
    bool isGrounded()
    {
        return Physics.Raycast(transform.position, -Vector3.up, charHeight/2 + 0.1f);
    }

    // Use this for initialization
    void Start () {
        charHeight = this.transform.localScale.y;
}

    // Update is called once per frame
    void Update()
    {
        float x;
        float y = 0;

        //Check for inputs and move
        x = speed * Input.GetAxis("Horizontal");
        //Adapt for different directions
        if (Input.GetAxis("Horizontal") > 0)
        {
            direction = true;
        } else if (Input.GetAxis("Horizontal") < 0)
        {
            direction = false;
        }
        if (direction)
        {
            this.transform.localEulerAngles = new Vector3(0, 50, 0);
        } else
        {
            this.transform.localEulerAngles = new Vector3(0, 120, 0);
        }
        //Check for jump
        if (isGrounded() || touching) jumped = false;
        if (Input.GetButtonDown("Jump"))
        {
            if (isGrounded() || touching)
            {
                //regular jump
                y = jumppower;
            }
            else if (!jumped)
            {
                //double jump
                y = secondjumppower;
                jumped = true;
            }
        }

        //Apply movement
        this.GetComponent<Rigidbody>().velocity = new Vector3 (x, this.GetComponent<Rigidbody>().velocity.y, 0);
        this.GetComponent<Rigidbody>().AddForce(new Vector3(0, y, 0), ForceMode.Impulse);
    }

    void OnCollisionStay(Collision col)
    {
        touching = true;
    }

    void OnCollisionExit(Collision col)
    {
        touching = false;
    }
}


text:
package com.simsilica.lemur.focus;

import java.util.*;

import com.jme3.app.Application;
import com.jme3.app.state.BaseAppState;
import com.jme3.scene.Spatial;

import com.simsilica.lemur.GuiGlobals;
import com.simsilica.lemur.core.GuiControl;
import com.simsilica.lemur.focus.FocusTraversal.TraversalDirection;
import com.simsilica.lemur.input.FunctionId;
import com.simsilica.lemur.input.InputMapper;
import com.simsilica.lemur.input.InputState;
import com.simsilica.lemur.input.StateFunctionListener;

/**
 *  Manages the input based UI navigation and maybe some minimal
 *  input hookups.
 *
 *  @author    Paul Speed
 */
public class FocusNavigationState extends BaseAppState {

    private FocusManagerState focusState;
    private InputMapper inputMapper;
    private InputHandler inputHandler = new InputHandler();

    public FocusNavigationState( InputMapper inputMapper, FocusManagerState focusState ) {
        this.inputMapper = inputMapper;
        this.focusState = focusState;
    }

    /**
     *  Returns the default focus element for the specified spatial
     *  if it is a focus container, else it returns the spatial directly.
     */
    public Spatial getDefaultFocus( Spatial spatial ) {

        // Resolve down to the deepest default focus
        FocusTraversal ft = getFocusTraversal(spatial);
        return ft != null ? ft.getDefaultFocus() : spatial;
    }

    /**
     *  Attempts to navigate to the next focusable element as specified
     *  by the traversal direction.
     */
    public Spatial requestChangeFocus( Spatial spatial, FocusTraversal.TraversalDirection dir ) {

        if( spatial == null ) {
            throw new IllegalArgumentException("Cannot traverse focus from a null spatial");
        }

        // Find the container of this spatial
        Spatial container = getFocusContainer(spatial);
        if( container == null ) {
            return null;
        }

        FocusTraversal ft = getFocusTraversal(container);
        Spatial next = ft.getRelativeFocus(spatial, dir);

        if( next != null ) {
            focusState.setFocus(next);
            return next;
        } else {
            // Try to go to the default focus of our parent container
            return requestChangeFocus(container, dir);
        }
    }

    @Override
    protected void initialize( Application app ) {

        FocusNavigationFunctions.initializeDefaultMappings(inputMapper);

        inputMapper.addStateListener(inputHandler,
                                     FocusNavigationFunctions.F_NEXT,
                                     FocusNavigationFunctions.F_PREV,
                                     FocusNavigationFunctions.F_X_AXIS,
                                     FocusNavigationFunctions.F_Y_AXIS,
                                     FocusNavigationFunctions.F_ACTIVATE
                                     );
    }

    @Override
    protected void cleanup( Application app ) {
        inputMapper.removeStateListener(inputHandler,
                                        FocusNavigationFunctions.F_NEXT,
                                        FocusNavigationFunctions.F_PREV,
                                        FocusNavigationFunctions.F_X_AXIS,
                                        FocusNavigationFunctions.F_Y_AXIS,
                                        FocusNavigationFunctions.F_ACTIVATE
                                        );
    }

    @Override
    protected void onEnable() {
        inputMapper.activateGroup(FocusNavigationFunctions.UI_NAV);
    }

    @Override
    protected void onDisable() {
        inputMapper.deactivateGroup(FocusNavigationFunctions.UI_NAV);
    }

    protected Spatial getCurrentFocus() {
        return getState(FocusManagerState.class).getFocus();
    }

    /**
     *  Utillity method to get the control for a spatial when we don't
     *  care if the interface implements control.
     */
    protected static <T> T getControl( Spatial s, Class<T> type ) {
        if( s == null ) {
            return null;
        }

        for( int i = 0; i < s.getNumControls(); i++ ) {
            Object c = s.getControl(i);
            if( type.isInstance(c) )
                return type.cast(c);
        }
        return null;
    }

    public static FocusTraversal getFocusTraversal( Spatial s ) {
        if( s == null ) {
            return null;
        }
        FocusTraversal ft = getControl(s, FocusTraversal.class);
        if( ft instanceof GuiControl ) {
            if( ((GuiControl)ft).getLayout() == null ) {
                // It implements the interface but isn't really
                // a container.
                return null;
            }
        }
        return ft;
    }

    protected Spatial getFocusContainer( Spatial spatial ) {
        if( spatial == null ) {
            return null;
        }
        // Find the parent of the spatial that can be a FocusTraversal hub

        // Start at the parent so that we can look for contains of containers
        // easily.
        for( Spatial s = spatial.getParent(); s != null; s = s.getParent() ) {
            FocusTraversal ft = getFocusTraversal(s);
            if( ft != null ) {
                return s;
            }
        }
        return null;
    }

    protected void navigate( TraversalDirection dir ) {
        Spatial current = getCurrentFocus();
        if( current == null ) {
            return;
        }
        requestChangeFocus(current, dir);
    }

    protected void navigateLeft() {
        Spatial current = getCurrentFocus();
        if( current == null ) {
            return;
        }
        requestChangeFocus(current, TraversalDirection.Left);
    }

    protected void navigateRight() {
        Spatial current = getCurrentFocus();
        if( current == null ) {
            return;
        }
        requestChangeFocus(current, TraversalDirection.Right);
    }

    protected void navigateUp() {
        Spatial current = getCurrentFocus();
        if( current == null ) {
            return;
        }
        requestChangeFocus(current, TraversalDirection.Up);
    }

    protected void navigateDown() {
        Spatial current = getCurrentFocus();
        if( current == null ) {
            return;
        }
        requestChangeFocus(current, TraversalDirection.Down);
    }

    private class InputHandler implements StateFunctionListener {
        public void valueChanged( FunctionId func, InputState value, double tpf ) {
            //System.out.println("focus input:" + func + ", " + value);

            // On the down or on the up?  Let's do down in case we
            // do something clever with repeats later
            if( value == InputState.Off ) {
                return;
            }

            if( func == FocusNavigationFunctions.F_NEXT ) {
                navigate(TraversalDirection.Next);
            }

            if( func == FocusNavigationFunctions.F_PREV ) {
                navigate(TraversalDirection.Previous);
            }

            if( func == FocusNavigationFunctions.F_X_AXIS ) {
                if( value == InputState.Positive ) {
                    navigateRight();
                } else {
                    navigateLeft();
                }
            }
            if( func == FocusNavigationFunctions.F_Y_AXIS ) {
                if( value == InputState.Positive ) {
                    navigateUp();
                } else {
                    navigateDown();
                }
            }
        }
    }
}


text:
package com.hazelcast.simulator.protocol.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.hazelcast.simulator.protocol.core.AddressLevel.AGENT;
import static com.hazelcast.simulator.protocol.core.AddressLevel.COORDINATOR;
import static com.hazelcast.simulator.protocol.core.AddressLevel.WORKER;
import static com.hazelcast.simulator.utils.Preconditions.checkPositive;
import static java.lang.Integer.parseInt;
import static java.lang.String.format;

/**
 * Address object which (uniquely) identifies one or more Simulator components.
 *
 * <pre>
 *                                               +---+
 * COORDINATOR           +-----------------------+ C +----------------------+
 *                       |                       +---+                      |
 *                       |                                                  |
 *                       v                                                  v
 *                    +--+---+                                           +---+--+
 * AGENT              |  A1  |                              +------------+  A2  +------------+
 *                    +--+---+                              |            +------+            |
 *                       |                                  |                                |
 *                       v                                  v                                v
 *                  +----+----+                        +----+----+                      +----+----+
 * WORKER           +  A1_W1  +                        +  A2_W1  +                      +  A2_W2  +
 *                  +---------+                        +---------+                      +---------+
 * </pre>
 */
@SuppressWarnings("checkstyle:magicnumber")
public final class SimulatorAddress {

    private static final SimulatorAddress COORDINATOR_ADDRESS = new SimulatorAddress(COORDINATOR, 0, 0);
    private static final String COORDINATOR_STRING = "C";

    private final AddressLevel addressLevel;
    private final int agentIndex;
    private final int workerIndex;

    private SimulatorAddress(AddressLevel addressLevel, int agentIndex, int workerIndex) {
        this.addressLevel = addressLevel;
        this.agentIndex = agentIndex;
        this.workerIndex = workerIndex;
    }

    public static SimulatorAddress coordinatorAddress() {
        return COORDINATOR_ADDRESS;
    }

    public static SimulatorAddress agentAddress(int agentIndex) {
        return new SimulatorAddress(AGENT, checkPositive(agentIndex, "agentIndex"), 0);
    }

    public static SimulatorAddress workerAddress(int agentIndex, int workerIndex) {
        return new SimulatorAddress(WORKER, checkPositive(agentIndex, "agentIndex"), checkPositive(workerIndex, "workerIndex"));
    }

    /**
     * Returns the {@link AddressLevel} of this {@link SimulatorAddress}.
     *
     * @return the {@link AddressLevel}
     */
    public AddressLevel getAddressLevel() {
        return addressLevel;
    }

    /**
     * Returns the Agent index of this {@link SimulatorAddress}.
     *
     * @return the index of the addressed Agent or <tt>0</tt> if all Agents are addressed
     */
    public int getAgentIndex() {
        return agentIndex;
    }

    /**
     * Returns the Worker index of this {@link SimulatorAddress}.
     *
     * @return the index of the addressed Worker or <tt>0</tt> if all Workers are addressed
     */
    public int getWorkerIndex() {
        return workerIndex;
    }

    /**
     * Returns the address index of the defined {@link AddressLevel} of this {@link SimulatorAddress}.
     *
     * @return the index of the {@link AddressLevel}
     */
    public int getAddressIndex() {
        switch (addressLevel) {
            case AGENT:
                return agentIndex;
            case WORKER:
                return workerIndex;
            default:
                throw new IllegalArgumentException("Coordinator has no addressIndex!");
        }
    }

    /**
     * Returns the {@link SimulatorAddress} of the parent Simulator component.
     *
     * @return the {@link SimulatorAddress} of the parent Simulator component
     */
    public SimulatorAddress getParent() {
        switch (addressLevel) {
            case WORKER:
                return agentAddress(agentIndex);
            case AGENT:
                return coordinatorAddress();
            default:
                throw new IllegalArgumentException("Coordinator has no parent!");
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        SimulatorAddress that = (SimulatorAddress) o;
        if (agentIndex != that.agentIndex) {
            return false;
        }
        if (workerIndex != that.workerIndex) {
            return false;
        }
        return (addressLevel == that.addressLevel);
    }

    @Override
    public int hashCode() {
        int result = addressLevel.hashCode();
        result = 31 * result + agentIndex;
        result = 31 * result + workerIndex;
        return result;
    }

    @Override
    public String toString() {
        if (addressLevel == COORDINATOR) {
            return COORDINATOR_STRING;
        } else if (addressLevel == AGENT) {
            return "A" + agentIndex;
        } else {
            return "A" + agentIndex + "_W" + workerIndex;
        }
    }

    public static SimulatorAddress fromString(String sourceString) {
        if (COORDINATOR_STRING.equals(sourceString)) {
            return coordinatorAddress();
        }

        if (!sourceString.startsWith("A")) {
            throw new IllegalArgumentException(format("'%s' is not a valid address", sourceString));
        }

        int indexOfSplit = sourceString.indexOf("_W");
        if (indexOfSplit == -1) {
            int agentIndex = parseInt(sourceString.substring(1, sourceString.length()));
            return agentAddress(agentIndex);
        } else {
            int agentIndex = parseInt(sourceString.substring(1, indexOfSplit));
            int workerIndex = parseInt(sourceString.substring(indexOfSplit + 2, sourceString.length()));
            return workerAddress(agentIndex, workerIndex);
        }
    }

    public static List<SimulatorAddress> fromString(List<String> list) {
        List<SimulatorAddress> result = new ArrayList<SimulatorAddress>(list.size());
        for (String address : list) {
            result.add(fromString(address));
        }
        return result;
    }

    public static String toString(Collection<SimulatorAddress> addresses) {
        StringBuilder sb = new StringBuilder();

        boolean first = true;
        for (SimulatorAddress address : addresses) {
            if (first) {
                first = false;
            } else {
                sb.append(",");
            }
            sb.append(address);
        }

        return sb.toString();
    }
}


text:
namespace AIBots
{
    partial class Main
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnAIBots = new System.Windows.Forms.Button();
            this.btnHarvestBots = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // btnAIBots
            //
            this.btnAIBots.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.btnAIBots.Location = new System.Drawing.Point(12, 12);
            this.btnAIBots.Name = "btnAIBots";
            this.btnAIBots.Size = new System.Drawing.Size(222, 23);
            this.btnAIBots.TabIndex = 0;
            this.btnAIBots.Text = "AI bots";
            this.btnAIBots.UseVisualStyleBackColor = true;
            this.btnAIBots.Click += new System.EventHandler(this.btnAIBots_Click);
            //
            // btnHarvestBots
            //
            this.btnHarvestBots.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.btnHarvestBots.Location = new System.Drawing.Point(12, 41);
            this.btnHarvestBots.Name = "btnHarvestBots";
            this.btnHarvestBots.Size = new System.Drawing.Size(222, 23);
            this.btnHarvestBots.TabIndex = 1;
            this.btnHarvestBots.Text = "Harvest bots";
            this.btnHarvestBots.UseVisualStyleBackColor = true;
            this.btnHarvestBots.Click += new System.EventHandler(this.btnHarvestBots_Click);
            //
            // Main
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(246, 95);
            this.Controls.Add(this.btnHarvestBots);
            this.Controls.Add(this.btnAIBots);
            this.Name = "Main";
            this.Text = "Main";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnAIBots;
        private System.Windows.Forms.Button btnHarvestBots;
    }
}


text:
#include <stdio.h>

#include <iostream>
#include <map>
#include <string>
#include  <sys/time.h>

using namespace std;

#include "vjXdef.h"
//#include "ddlSymbol.h"
#include "aipGraphicsWin.h"
#include "aipCommands.h"
#include "aipDataInfo.h"
#include "aipCFuncs.h"
#include "aipGframeManager.h"
#include "aipDataManager.h"
#include "aipImgInfo.h"
#include "aipMouse.h"
#include "aipVnmrFuncs.h"
#include "aipWinMovie.h"
#include "aipMovie.h"
#include "aipReviewQueue.h"
#include "aipJFuncs.h"

using namespace aip;

extern "C" {
    void aip_movieCmd(char *cmd, const char *message, int x, int y, int w, int h);
}

bool Movie::movieIteratorOod = true;
Movie *Movie::movie = NULL;
std::list<string>::iterator Movie::movieIter;
std::list<string> Movie::imgList;
int Movie::direction = 1;
int Movie::width;
int Movie::height;
int Movie::framePerSecond;
int Movie::savedRows;
int Movie::savedCols;
bool Movie::capture;

/* Class to show images as a movie. */

Movie::Movie()
{
    movieTimerId = 0;
    capture = false;
    width = (int) getReal("aipMovieSettings",4, 400);
    height = (int) getReal("aipMovieSettings",5, 400);
    framePerSecond = (int) getReal("aipMovieRate", 1);

    //Movie::updateList();
}

int
Movie::updateList()
{
    imgList.clear();
    int mode = (int) getReal("aipMovieMode",1);
    ReviewQueue *rq = ReviewQueue::get();
    imgList = rq->getKeylist(mode);

    if(capture) direction = 1;
    else direction = (int) getReal("aipMovieSettings",3, 1);

    // Init the static iterator for use.
    if(imgList.size() > 0) {
	if(direction > 0) Movie::movieIter = imgList.begin();
	else {
	     Movie::movieIter = imgList.end();
	     Movie::movieIter--;
	}
    } else Movie::movieIter = imgList.end();

    return imgList.size();
}

/* Keep only one instance of Movie.  Allow anyone who needs it to
   get it via this static member call.
*/
Movie *Movie::get()
{
    if (!movie) {
	movie = new Movie();
    }
    return movie;
}

void Movie::restoreDisplay()
{
   // char cmd[256];
   Movie::movieIter = imgList.end();
   GframeManager::get()->restoreFrames(savedRows, savedCols);
   int batch = (int)getReal("aipBatch", 1);
   ReviewQueue::get()->displayData(batch);

   if(capture) {
     capture=false;
     // sprintf(cmd,"vnmrjcmd('movie','done')\n");
     // execString(cmd);
     aip_movieCmd("done", NULL,  0, 0, 0, 0);
   }

}

void Movie::setMovieFrame()
{
   int minSize=50; // pixels
   int minRate=1; // frame pe second
   int maxRate=30; // frame pe second

    // check size and rate
   if(width < minSize) {
      width = minSize;
      setReal("aipMovieSettings",4,width,true);
   }
   if(height < minSize) {
      height = minSize;
      setReal("aipMovieSettings",5,height,true);
   }
   if(width > getWinWidth()) {
      width = getWinWidth();
      setReal("aipMovieSettings",4,width,true);
   }
   if(height > getWinHeight()) {
      height = getWinHeight();
      setReal("aipMovieSettings",5,height,true);
   }
   if(framePerSecond > maxRate) {
      framePerSecond = maxRate;
      setReal("aipMovieRate",framePerSecond,true);
   }
   if(framePerSecond < minRate) {
      framePerSecond = minRate;
      setReal("aipMovieRate",framePerSecond,true);
   }

   savedRows = (int)getReal("aipWindowSplit", 1, 1);
   savedCols = (int)getReal("aipWindowSplit", 2, 1);

    GframeManager *gfm = GframeManager::get();
    spGframe_t gf = gfm->getFrameByNumber(0);
    int nf = gfm->getNumberOfFrames();
    if(gf == nullFrame || nf != 1 || gf->pixwd != width || gf->pixht != height) {
        gfm->setMovieFrame(width, height);
    }
}

int Movie::doIt(int argc, char *argv[], int retc, char *retv[])
{
    if(!WinMovie::get()->movieStopped()) {
	Winfoprintf("Error: Movie is not stopped.");
	return 1;
    }
    if(argc < 2) {
	fprintf(stderr, "usage: aipMovie('start'/'continue'/'stop'/'reset'/'step', ...");
	return 1;
    }

    Movie *wm = Movie::get();

    if(strcasecmp(argv[1],"start") == 0) {
      if(argc > 2) framePerSecond=atoi(argv[2]);
      else framePerSecond = (int) getReal("aipMovieRate", 1);
      if(argc > 3) width=atoi(argv[3]);
      else width = (int) getReal("aipMovieSettings",4, 400);
      if(argc > 4) height=atoi(argv[4]);
      else height = (int) getReal("aipMovieSettings",5, 400);
      wm->startMovie(argv[1],NULL);
    } else if(strcasecmp(argv[1],"capture") == 0) {
      string path;
      if(argc > 2) framePerSecond=atoi(argv[2]);
      else framePerSecond = (int) getReal("aipMovieRate", 1);
      if(argc > 3) width=atoi(argv[3]);
      else width = (int) getReal("aipMovieSettings",4, 400);
      if(argc > 4) height=atoi(argv[4]);
      else height = (int) getReal("aipMovieSettings",5, 400);
      if(argc > 5) path = argv[5];
      else path = getString("aipMoviePath","/tmp/myMovie.mov");
      wm->startMovie(argv[1], path.c_str());
    } else if(strcasecmp(argv[1],"continue") == 0) {
      if(argc > 2) framePerSecond=atoi(argv[2]);
      else framePerSecond = (int) getReal("aipMovieRate", 1);
      if(argc > 3) width=atoi(argv[3]);
      else width = (int) getReal("aipMovieSettings",4, 400);
      if(argc > 4) height=atoi(argv[4]);
      else height = (int) getReal("aipMovieSettings",5, 400);
      wm->continueMovie();
    } else if(strcasecmp(argv[1],"pause") == 0) {
      wm->pauseMovie();
    } else if(strcasecmp(argv[1],"next") == 0) {
      wm->next();
    } else if(strcasecmp(argv[1],"stop") == 0) {
      wm->stopMovie();
    } else if(strcasecmp(argv[1],"cancel") == 0) {
      capture=false;
      wm->stopMovie();
    } else if(strcasecmp(argv[1],"step") == 0) {
      int direct = 1;
      if(argc > 2 && argv[2][0] == '-') direct = -1;
      if(argc > 3) width=atoi(argv[3]);
      else width = (int) getReal("aipMovieSettings",4, 400);
      if(argc > 4) height=atoi(argv[4]);
      else height = (int) getReal("aipMovieSettings",5, 400);
      wm->stepMovie(direct);
    } else if(strcasecmp(argv[1],"setsize") == 0) {
      string str = getString("aipMovieSpec","50");
      if(argc > 2) str = argv[2];
      wm->setMovieSize(str.c_str());
    }
    return 0;
}

void  Movie::next()
{
    // char cmd[256];

    if(movieIter == imgList.end()) {
      stopMovie();
      return;
    }

    DataManager *dm = DataManager::get();

    // Display image in first selected frame
    spDataInfo_t dataInfo = DataManager::get()->getDataInfoByKey(*movieIter, true);
    if(dataInfo != (spDataInfo_t)NULL) {
        dm->displayMovieFrame(dataInfo->getKey());
    }

    ++movieIter;

    // sprintf(cmd,"vnmrjcmd('movie','next')\n");
    //  execString(cmd);
    aip_movieCmd("next", NULL, 0, 0, 0, 0);
}

void  Movie::setMovieSize(const char *str)
{
    if(strcasecmp(str,"WxH") == 0) return;

    double w = getWinWidth();
    double wh = getWinHeight();
    if(strcasecmp(str,"full") == 0) {
      setReal("aipMovieSettings",4,(int)w,true);
      setReal("aipMovieSettings",5,(int)wh,true);
      return;
    }

    double aspec= DataManager::get()->getAspectRatio();
    double h = w * aspec;
    if(h > 0 && h > wh) {
      aspec = wh/h;
      w *= aspec;
      h *= aspec;
    }

    double percent=100;
    if(strcasecmp(str,"max") != 0) {
       percent=atoi(str);
    }
    percent /= 100;
    w *= percent;
    h *= percent;
    setReal("aipMovieSettings",4,(int)w,true);
    setReal("aipMovieSettings",5,(int)h,true);
}

void  Movie::continueMovie()
{
    double d;

    Movie *wm = Movie::get();
    if (movieIteratorOod) {
	movieIteratorOod = false;
        wm->updateList();
        wm->setMovieFrame();
    }
    if(wm->imgList.size() < 2) {
	movieIteratorOod = true;
	wm->imgList.clear();
        wm->stopMovie();
	return;
    }

    // Start the timer
    d = framePerSecond;
    if(d > 0) wm->mSec = 1000.0 / d;
    else wm->mSec = 1000.0;

    if(wm->mSec <= 0.5) wm->mSec = 0.5;

    wm->movieTimerInit(wm->mSec);
}

void Movie::startMovie(char *str, const char *path)
{
    double d;
    // char cmd[256];

    if(strcasecmp(str,"capture") == 0) capture=true;

    Movie *wm = Movie::get();
    if(wm->updateList() < 2) {
	wm->imgList.clear();
	return;
    }

    if(Movie::movieIter != imgList.begin() &&
       Movie::movieIter != imgList.end()) wm->stopMovie();

    wm->setMovieFrame();

    if(capture && path != NULL) {
      // sprintf(cmd,"vnmrjcmd('movie','start','%s', %d, %d, %d, %d)\n",
      //    path, width, height, wm->imgList.size(), framePerSecond);
      //  execString(cmd);
       aip_movieCmd("start", path, width, height, wm->imgList.size(), framePerSecond);
    } else {
       d = framePerSecond;
       if( d > 0) wm->mSec = 1000.0 / d;
       else wm->mSec = 1000.0;
       // Start the timer
       wm->movieTimerInit(wm->mSec);

    }
}

void Movie::pauseMovie()
{
    Movie *wm = Movie::get();
    if(wm->movieTimerId != 0)
    {
#if defined (MOTIF) && (ORIG)
	XtRemoveTimeOut(wm->movieTimerId);
#else
	aip_removeTimeOut(wm->movieTimerId);
#endif
	wm->movieTimerId = 0;
    }
    wm->mSec = 0.0;
}

void Movie::stopMovie()
{
    Movie *wm = Movie::get();
    if(wm->movieTimerId != 0)
    {
#if defined (MOTIF) && (ORIG)
	XtRemoveTimeOut(wm->movieTimerId);
#else
	aip_removeTimeOut(wm->movieTimerId);
#endif
	wm->movieTimerId = 0;
    }
    updateList();
    wm->restoreDisplay();
    wm->mSec = 0.0;
    movieIteratorOod = true;
}

void
Movie::stepMovie(int direct)
{
    Movie *wm = Movie::get();
    if (movieIteratorOod) {
	movieIteratorOod = false;
        wm->updateList();
        wm->setMovieFrame();
    }
    if(wm->imgList.size() < 2) {
	wm->imgList.clear();
	movieIteratorOod = true;
        wm->stopMovie();
	return;
    }

    DataManager *dm = DataManager::get();

    if (direct < 0) {
	// Decrement to previous image
	// If at beginning, start at end.  end() puts us one past end
	if(Movie::movieIter == imgList.begin()) {
	    Movie::movieIter = imgList.end();
	}
 	--Movie::movieIter;
    } else {
	// Increment to next image
	++Movie::movieIter;
	if(Movie::movieIter == imgList.end()) {
	    // If at end, start over
	    Movie::movieIter = imgList.begin();
	}
    }
    // Display image in first selected frame
    spDataInfo_t dataInfo = DataManager::get()->getDataInfoByKey(*movieIter, true);
    if(dataInfo != (spDataInfo_t)NULL) {
	dm->displayMovieFrame(dataInfo->getKey());
    }
}

/* Non member function to be passed in as function pointer to timer.
   This fxn is executed at the end of each timer countdown.  It also
   is responsible for restarting the timer. The timer only counts down
   one time each time it is set.
*/
void
Movie::movieTimerProc(void *, unsigned long *)
{
    char cmd[256];
    static bool inuse = false;

    Movie *wm = Movie::get();
    DataManager *dm = DataManager::get();

    // Avoid reentry
    if(inuse) {
	// Even if we are still in this function from the last call, we need
	// to restart the timer.
	wm->movieTimerInit(wm->mSec);
	return;
    }

    inuse = true;

    // Restart the timer to keep the cycle going.
    wm->movieTimerInit(wm->mSec);

    DataMap::iterator pd;
    int forward = (int) getReal("aipMovieSettings",3, 1);
    if(capture) forward = 1;

    // Make sure iterator is still valid
    // DataMap *dataMap = dm->getDataMap();
    if (movieIteratorOod) {
	movieIteratorOod = false;
        if(updateList() < 2) {
	   inuse = false;
	   return;
        }
    }

    if (movieIter == imgList.end()) {
	movieIteratorOod = true;
	inuse = false;
        wm->stopMovie();
	return;
    } else if(forward < 0 && movieIter == imgList.begin()) {
        spDataInfo_t dataInfo = DataManager::get()->getDataInfoByKey(*movieIter, true);
        if(dataInfo != (spDataInfo_t)NULL) {
	    dm->displayMovieFrame(dataInfo->getKey(), true);
        }

	if(getReal("aipMovieSettings",1, 1) > 0) {
	   movieIteratorOod = true;
	} else {
	 if(wm->movieTimerId != 0) {
#if defined (MOTIF) && (ORIG)
           XtRemoveTimeOut(wm->movieTimerId);
#else
           aip_removeTimeOut(wm->movieTimerId);
#endif
           wm->movieTimerId = 0;
           wm->stopMovie();
	 }
         wm->mSec = 0.0;
        }
        inuse = false;
	return;
    }

    // Display image in first selected frame
    if(forward == direction) {
       spDataInfo_t dataInfo = DataManager::get()->getDataInfoByKey(*movieIter, true);
       if(dataInfo != (spDataInfo_t)NULL) {
	    dm->displayMovieFrame(dataInfo->getKey(), true);
       }

    }

    if(capture) {
       sprintf(cmd,"vnmrjcmd('movie','next')\n");
       execString(cmd);
    }

    direction = forward;

    // Increment to next image
    if(forward > 0) {

      Movie::movieIter++;

      if(Movie::movieIter == imgList.end()) {
        if(!capture && getReal("aipMovieSettings",1, 1) > 0) {
	// If at end, start over
	   Movie::movieIter = imgList.begin();
	} else if(wm->movieTimerId != 0) {
#if defined (MOTIF) && (ORIG)
	   XtRemoveTimeOut(wm->movieTimerId);
#else
           aip_removeTimeOut(wm->movieTimerId);
#endif
	   wm->movieTimerId = 0;
           wm->stopMovie();
           wm->mSec = 0.0;
	}
      }
    } else {

      Movie::movieIter--;
    }

    inuse = false;

}

/* Start the movie timer.  It will timeout one time and call movieTimerProc().
   To keep the cycle going, movieTimerProc() must call this function again
   to start another single countdown.
*/
void Movie::movieTimerInit(double ms)
{
    void (* fp)(void *, unsigned long *);

    fp = &movieTimerProc;

    // Movie *wm = Movie::get();
    if(Movie::movieTimerId != 0)
    {
#if defined (MOTIF) && (ORIG)
	XtRemoveTimeOut(Movie::movieTimerId);
#else
	aip_removeTimeOut(Movie::movieTimerId);
#endif
	Movie::movieTimerId = 0;
    }

    mSec = ms;  /* milliseconds */
#if defined (MOTIF) && (ORIG)
    Movie::movieTimerId = XtAddTimeOut(mSec, fp, NULL);
#else
    Movie::movieTimerId = aip_addTimeOut((unsigned long) mSec, (void *)fp, NULL);
#endif

}

// movie running  - movieTimerId != NULL && movieIteratorOod == false
// (timer is running)
// movie paused  - movieTimerId == NULL && movieIteratorOod == false
// (timer is not running, but movie is not stopped, i.e. reset)
// movie stopped - movieTimerId == NULL && movieIteratorOod == true
// (timer is not running, movie is rest)
bool Movie::movieRunning()
{
    if(movieTimerId != 0 && !movieIteratorOod) return true;
    else return false;
}

bool Movie::movieStopped()
{
    if(movieTimerId == 0 && movieIteratorOod) return true;
    else return false;
}

bool Movie::moviePaused()
{
    if(movieTimerId == 0 && !movieIteratorOod) return true;
    else return false;
}


text:
package br.com.ilovebeer.servlet;

import br.com.ilovebeer.controller.ControllerProduto;
import br.com.ilovebeer.model.entity.Produto;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "produtosdelete", urlPatterns = "/produtosdelete")
public class ServletProdutosDelete extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ControllerProduto control = new ControllerProduto();
		Produto produto = new Produto();

		if ((request.getParameter("remover") != null) && request.getParameter("id") != null){
			int id = Integer.parseInt(request.getParameter("id"));
			control.remover(produto,id);
			response.sendRedirect("produtos");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

}


text:
import WholeNumberValidator  from 'ember-cli-data-validation/validators/wholenumber';

export default WholeNumberValidator;


text:
class VirtualMachine::Pricing
  class << self
    def price_for(vm)
    end

    def groups_for_datacenter(datacenter)
      datacenter = location_groups.select { |x| x.name == datacenter }.first
      datacenter.groups.map { |x| x.id }
    end

    def location_groups
      Rails.cache.fetch("softlayer/location_groups", expires_in: 12.hours) do
        Softlayer::Location::Datacenter.mask(location_object_mask).get_datacenters
      end
    end

    def price_options
    end
  end
end


text:
require_relative "../scopes/local_scope"
require_relative "../scopes/custom_scope"

module Catasta::JavaScript
class Loop < Struct.new(:loop_var, :collection, :nodes)
  def render(ctx)
    loop_scope = LocalScope.new
    loop_scope << loop_var.str

    def generate_index_variable(input)
      "_#{input[1..-1]}_index"
    end

    user_index_variable = "@#{loop_var.str}"
    special_loop_scope = CustomScope.new(&method(:generate_index_variable))
    special_loop_scope << user_index_variable

    inner = ctx.add_scope(special_loop_scope) do
      ctx.add_scope(loop_scope) do
        ctx.indent { nodes.map {|n| n.render(ctx)}.join("\n") }
      end
    end

    if special_loop_scope.get_resolve_count(user_index_variable) > 0
      [
        ctx.pad(%Q{(#{collection.render(ctx)} || []).forEach(function(#{loop_var}, #{generate_index_variable(user_index_variable)})\{}),
        inner,
        ctx.pad("});")
      ].join("\n")
    else
      [
        ctx.pad(%Q{(#{collection.render(ctx)} || []).forEach(function(#{loop_var})\{},),
        inner,
        ctx.pad("});")
      ].join("\n")
    end
  end
end
end


text:
A simple script to store Jawbone UP data into your DayOne Journal.

## Usage

Checkout [this blog post](https://stefanzweifel.io/posts/jawbone-up-to-dayone/) on how to setup the script.

## Contribution

Just open an issue or pull request. I will look into that.

## License

See LICENSE File


text:
from monosat.logic import *
from monosat.pbtheory import *
from monosat.graphtheory import *
from monosat.fsmtheory import *
from monosat.bvtheory import *
from monosat.solver import *


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- This is an example InsetDrawable. It should be manually reviewed. -->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_switch_camera_white_48dp_inset"
    android:insetTop="3.333333492dp"
    android:insetLeft="3.333333492dp"
    android:insetBottom="7.333333492dp"
    android:insetRight="3.333333492dp"
    android:visible="true" />


text:
<?php

/* forms/fields/pagemedia/pagemedia.html.twig */
class __TwigTemplate_31003934d19ffd10910eb699229b8030bb7a0b155bca35d6728b7f7a5c42fddc extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $context["value"] = (((null === (isset($context["value"]) ? $context["value"] : null))) ? ($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "default", array())) : ((isset($context["value"]) ? $context["value"] : null)));
        // line 2
        echo "
";
        // line 3
        if ((isset($context["exists"]) ? $context["exists"] : null)) {
            // line 4
            echo "

        ";
            // line 6
            echo twig_escape_filter($this->env, $this->env->getExtension('Grav\Plugin\Admin\AdminTwigExtension')->tuFilter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "label", array())), "html", null, true);
            echo "

        ";
            // line 9
            $context["uploadLimit"] = (($this->getAttribute($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["grav"]) ? $context["grav"] : null), "config", array()), "system", array()), "media", array()), "upload_limit", array()) / 1024) / 1024);
            // line 10
            echo "        ";
            $context["dropzoneSettings"] = array("maxFileSize" => (isset($context["uploadLimit"]) ? $context["uploadLimit"] : null));
            // line 11
            echo "
env, (isset($context["base_url"]) ? $context["base_url"] : null), "html", null, true);
            echo "/media/";
            echo twig_escape_filter($this->env, trim($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "route", array()), "/"), "html", null, true);
            echo ".json\"
             data-media-local=\"";
            // line 14
            echo twig_escape_filter($this->env, $this->env->getExtension('Grav\Common\Twig\TwigExtension')->rtrimFilter((isset($context["base_url_relative_frontend"]) ? $context["base_url_relative_frontend"] : null), "/"), "html", null, true);
            echo "/";
            echo twig_escape_filter($this->env, trim($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "route", array()), "/"), "html", null, true);
            echo "\"
             data-dropzone-options=\"";
            // line 15
            echo twig_escape_filter($this->env, twig_jsonencode_filter((isset($context["dropzoneSettings"]) ? $context["dropzoneSettings"] : null)), "html_attr");
            echo "\">

        ";
            // line 16
            echo twig_escape_filter($this->env, twig_join_filter((isset($context["value"]) ? $context["value"] : null), "
"), "html", null, true);
            echo "

";
        } else {
            // line 20
            echo "

            ";
            // line 23
            echo twig_escape_filter($this->env, $this->env->getExtension('Grav\Plugin\Admin\AdminTwigExtension')->tuFilter("PLUGIN_ADMIN.CANNOT_ADD_MEDIA_FILES_PAGE_NOT_SAVED"), "html", null, true);
            echo "

";
        }
    }

    public function getTemplateName()
    {
        return "forms/fields/pagemedia/pagemedia.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  74 => 23,  69 => 20,  61 => 16,  57 => 15,  51 => 14,  45 => 13,  41 => 11,  38 => 10,  36 => 9,  30 => 6,  26 => 4,  24 => 3,  21 => 2,  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("{% set value = (value is null ? field.default : value) %}

{% if exists %}

        {{ field.label|tu }}

        {% set uploadLimit = grav.config.system.media.upload_limit / 1024 / 1024 %}
        {% set dropzoneSettings = { maxFileSize: uploadLimit } %}

        {{ value|join(\"\\n\") }}

{% else %}

            {{ \"PLUGIN_ADMIN.CANNOT_ADD_MEDIA_FILES_PAGE_NOT_SAVED\"|tu }}

{% endif %}
", "forms/fields/pagemedia/pagemedia.html.twig", "/Users/Thimy/Documents/iris/grav-skeleton-blog-site/user/plugins/admin/themes/grav/templates/forms/fields/pagemedia/pagemedia.html.twig");
    }
}


text:
package org.ovirt.engine.core.bll;

import java.util.List;

import org.ovirt.engine.core.bll.tasks.CommandCoordinatorUtil;
import org.ovirt.engine.core.bll.tasks.interfaces.CommandCallback;
import org.ovirt.engine.core.common.action.VmPoolParametersBase;
import org.ovirt.engine.core.common.businessentities.CommandEntity;
import org.ovirt.engine.core.common.businessentities.VmPool;
import org.ovirt.engine.core.compat.CommandStatus;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;

public class RemoveVmPoolCommandCallback extends CommandCallback {

    @Override
    public void doPolling(Guid cmdId, List<Guid> childCmdIds) {
        RemoveVmPoolCommand<? extends VmPoolParametersBase> command = getCommand(cmdId);

        boolean anyFailed = false;
        for (Guid childCmdId : childCmdIds) {
            CommandEntity entity = CommandCoordinatorUtil.getCommandEntity(childCmdId);
            switch (entity.getCommandStatus()) {
                case ENDED_WITH_FAILURE:
                case FAILED:
                case FAILED_RESTARTED:
                case UNKNOWN:
                    anyFailed = true;
                    break;

                default:
                    break;
            }
        }

        if (anyFailed) {
            command.setCommandStatus(CommandStatus.FAILED);
        } else {
            VmPool pool = DbFacade.getInstance().getVmPoolDao().get(command.getVmPoolId());
            if (pool == null || pool.getRunningVmsCount() == 0) {
                command.setCommandStatus(CommandStatus.SUCCEEDED);
            }
        }
    }

    @Override
    public void onFailed(Guid cmdId, List<Guid> childCmdIds) {
        RemoveVmPoolCommand<? extends VmPoolParametersBase> cmd = getCommand(cmdId);
        CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId);
        cmd.getParameters().setTaskGroupSuccess(false);
        cmd.endAction();
    }

    @Override
    public void onSucceeded(Guid cmdId, List<Guid> childCmdIds) {
        RemoveVmPoolCommand<? extends VmPoolParametersBase> cmd = getCommand(cmdId);
        CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId);
        cmd.getParameters().setTaskGroupSuccess(true);
        cmd.endAction();
    }

    private RemoveVmPoolCommand<? extends VmPoolParametersBase> getCommand(Guid cmdId) {
        return CommandCoordinatorUtil.retrieveCommand(cmdId);
    }

}