text:
{-# LANGUAGE RankNTypes #-}
module Parser where

import Debug.Trace

import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Prim
import Text.Parsec.String(Parser)
import Control.Monad
import Control.Monad.Identity(Identity)
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (javaStyle)

import AST

smallCStyle = javaStyle
            { P.nestedComments = False
            , P.reservedNames = ["if", "else", "while", "return", "int", "void"]
            , P.reservedOpNames = ["*", "/", "+", "-", ">", "<", "<=", ">=", "==", "!=", "&&", "||", "="]
            }

lexer :: P.TokenParser()
lexer = P.makeTokenParser smallCStyle

whiteSpace :: Parser ()
whiteSpace = P.whiteSpace lexer

lexeme :: forall a. Parser a -> Parser a
lexeme = P.lexeme lexer

identifier :: Parser String
identifier = P.identifier lexer

symbol :: String -> Parser String
symbol = P.symbol lexer

natural :: Parser Integer
natural = P.natural lexer

semi :: Parser String
semi = P.semi lexer

comma :: Parser String
comma = P.comma lexer

reservedOp :: String -> Parser ()
reservedOp = P.reservedOp lexer

parens :: forall a. Parser a -> Parser a
parens = P.parens lexer

braces :: forall a. Parser a -> Parser a
braces = P.braces lexer

brackets :: forall a. Parser a -> Parser a
brackets = P.brackets lexer

{- =========
 -  Parser
   ========-}

parseProgram :: String -> Either String Program
parseProgram input = case parse program "Parse" input of
                     Left  err -> Left $ show err
                     Right val -> Right val

program :: Parser Program
program = do
  x <- many1 externalDeclaration
  return x
  <?> "program"

externalDeclaration :: Parser ExternalDeclaration
externalDeclaration = try (do x <- declaration
                              return x)
                  <|> try ( do pos                <- getPosition
                               t                  <- typeSpecifier
                               (p, fname, params) <- funcDeclarator <* semi
                               return $ FuncProt pos (checkPointer p t) fname params)
                  <|> (do pos <- getPosition
                          t    <- typeSpecifier
                          (p, fname, params) <- funcDeclarator
                          s    <- stmt
                          return $ FuncDef pos (checkPointer p t) fname params s)
                  <?> "parseExternalDeclaration"

declaration :: Parser ExternalDeclaration
declaration = do
  pos <- getPosition
  d   <- declaratorList <* semi
  return $ Decl pos d
  <?> "declaration"

checkPointer :: String -> Type -> Type
checkPointer p t =
  if p == "*" then CPointer t else t

{- =====================================
 - int a, * b, c
 - (CInt a), (CPointer CInt b), (CInt c)
 - ===================================== -}

genDecl :: Type -> [(String, DirectDeclarator)] -> DeclaratorList
genDecl t str_decl = foldr f [] str_decl
  where f (p, direct) acc = (checkPointer p t, direct):acc

declaratorList :: Parser DeclaratorList
declaratorList = do
  t <- typeSpecifier
  x <- sepBy declarator $ symbol ","
  return (genDecl t x)
  <?> "declarator list"

pointer :: Parser String
pointer = option "" $ symbol "*"

declarator :: Parser (String, DirectDeclarator)
declarator = do
  p    <- pointer
  decl <- directDecl
  return (p, decl)
  <?> "declarator"

directDecl :: Parser DirectDeclarator
directDecl = try ( do pos  <- getPosition
                      name <- identifier
                      size <- brackets natural
                      return $ Sequence pos name size )
             <|> ( do pos  <- getPosition
                      name <- identifier
                      return $ Variable pos name)
             <?> "directDeclarator"

typeSpecifier :: Parser Type
typeSpecifier =  (symbol "int"  >> return CInt)
             <|> (symbol "void" >> return CVoid)
             <?> "typeSpecifier"

funcDeclarator :: Parser (String, Identifier, [(Type, Identifier)])
funcDeclarator = do
  p      <- pointer
  fname  <- identifier
  params <- parens $ paramDeclaration `sepBy` (symbol ",")
  return $ (p, fname, params)
  <?> "functionDeclarator"

paramDeclaration :: Parser (Type, Identifier)
paramDeclaration = do
  t    <- typeSpecifier
  p    <- pointer
  name <- identifier
  return $ (checkPointer p t, name)
  <?> "paramDeclaration"

{-  ===================
 -       Statement
 -  =================== -}

compoundStmt :: Parser Stmt
compoundStmt = do
  pos      <- getPosition
  _        <- symbol "{"
  declList <- many $ try (declaratorList <* semi)
  stmtList <- many $ try stmt
  _        <- symbol "}"
  return $ CompoundStmt pos (concat declList) stmtList
  <?> "compound statement"

stmt :: Parser Stmt
stmt =  try (do pos <- getPosition
                _   <- semi
                return $ EmptyStmt pos)
    <|> try (do e   <- expr <* semi
                pos <- getPosition
                return $ ExprStmt pos e)
    <|> try compoundStmt
    <|> try (do e   <- symbol "if"   >> parens expr
                pos <- getPosition
                s1  <- stmt
                s2  <- symbol "else" >> stmt
                return $ IfStmt pos e s1 s2)
    <|> try (do symbol "if"
                pos <- getPosition
                e   <- parens expr
                s   <- stmt
                return $ IfStmt pos e s (EmptyStmt pos))
    <|> try (do e   <- symbol "while" >> parens expr
                pos <- getPosition
                s   <- stmt
                return $ WhileStmt pos e s)
    <|> try (do symbol "for"
                symbol "("
                pos    <- getPosition
                dec    <- expr <* semi
                cond   <- expr <* semi
                update <- expr <* symbol ")"
                s      <- stmt
--              return $ ForStmt pos dec cond update s)
                return $ CompoundStmt pos
                                      []
                                      [ExprStmt pos dec,
                                       WhileStmt pos cond (CompoundStmt pos
                                                                        []
                                                                        [s, ExprStmt pos update])])
    <|> try (do symbol "return"
                pos <- getPosition
                e   <- expr <* semi
                return $ ReturnStmt pos e)
    <?> "statement"

expr :: Parser Expr
expr = liftM2 ExprList getPosition (assignExpr `sepBy` comma)
    <?> "expression"

assignExpr :: Parser Expr
assignExpr = try ( do
    pos    <- getPosition
    dest   <- logicalOrExpr
    symbol "="
    assign <- assignExpr
    return $ AssignExpr pos dest assign)
  <|>  logicalOrExpr
  <?> "assignExpr"

logicalOrExpr :: Parser Expr
logicalOrExpr =  buildExpressionParser table unaryExpr
             <?> "logicalOrExpr"

{- =========================
 -  build expression parser
 - ========================= -}

table :: [[Operator String () Identity Expr]]
table = [[op "*"  Multiple AssocLeft, op "/"  Divide   AssocLeft]
        ,[op "+"  Plus     AssocLeft, op "-"  Minus    AssocLeft]
        ,[op "<"  Lt       AssocLeft, op ">"  Gt       AssocLeft,
          op "<=" Lte      AssocLeft, op ">=" Gte      AssocLeft]
        ,[op "==" Equal    AssocLeft, op "!=" NotEqual AssocLeft]
        ,[op "&&" And      AssocLeft]
        ,[op "||" Or       AssocLeft]]
  where op s f = Infix(do {
                        pos <- getPosition;
                        _   <- reservedOp s;
                        return $ f pos;}
                        <?> "table")

unaryExpr :: Parser Expr
unaryExpr =  try postFixExpr
         <|> try ( do symbol "-"
                      pos <- getPosition
                      p   <- unaryExpr
--                    return $ UnaryMinus pos p)
                      return $ Minus pos (Constant pos 0) p)
         <|> try ( do symbol "&"
                      pos <- getPosition
                      p   <- unaryExpr
                      return $ UnaryAddress pos p)
         <|> try ( do symbol "*"
                      pos <- getPosition
                      p   <- unaryExpr
                      return $ UnaryPointer pos p)
         <?> "unaryExpr"

postFixExpr :: Parser Expr
postFixExpr = try (do pos   <- getPosition
                      fname <- identifier
                      args  <- parens argExprList
                      return $ CallFunc pos fname args)
          <|> try (do arrayName    <- primaryExpr
                      arrayAccess  <- arrayAccessExpr arrayName
                      return arrayAccess)
          <|> primaryExpr
          <?> "postFixExpr"

arrayAccessExpr :: Expr -> Parser Expr
arrayAccessExpr left = do
  accessor <- many1 $ liftTM getPosition (brackets expr)
  return $ foldl (\acc (pos, i) -> UnaryPointer pos (Plus pos acc i)) left accessor
  <?> "arrayAccessExpr"

argExprList :: Parser [Expr]
argExprList = try (assignExpr `sepBy` comma)
          <?> "expression"

primaryExpr :: Parser Expr
primaryExpr =  try (parens expr)
           <|> try (liftM2 Constant getPosition natural)
           <|> liftM2 IdentExpr getPosition identifier
           <?> "primaryExpr"

liftTM :: Monad m => m a -> m b -> m (a, b)
liftTM ma mb = do
  a <- ma
  b <- mb
  return (a, b)


text:
layout: single
header:
    image: "https://didevo.files.wordpress.com/2016/10/cropped-charlesdarwin.jpg"
title: "La teoría de la evolución en informática"
date: 2017-11-11 18:17:33
categories:
- inteligencia artificial
tags:
- aprendizaje automático
- computación
- algoritmos genéticos
- informática
---

Hoy voy a plantearte la siguiente pregunta: _¿puede un algoritmo mejorarse a sí mismo?_

Bueno, es una pregunta realmente difícil de responder. Ya vimos el concepto de **redes neuronales** en el post de [_Cómo aprenden las máquinas_]({{ site.baseurl }}{% post_url 2017-10-05-como-aprenden-las-maquinas %}), las cuales son excelentes para reconocer patrones y son capaces de entrenarse a sí mismas para dar mejores resultados.

En este caso vamos a conocer otro tipo de sistemas que se utilizan para solucionar problemas que tienen muchas posibles soluciones pero no todas son igual de buenas. Hablamos de los **algoritmos genéticos** los cuales son muy utilizados para resolver problemas de _optimización_.

Estos algoritmos no son especialmente nuevos, pues llevan desde los años 70 siendo objeto de discusión, pero son particularmente interesantes, pues se basan en el concepto de la [_evolución biológica_](https://es.wikipedia.org/wiki/Evolución_biológica) comunmente conocida como _selección natural_.

Seguro que [Charles Darwin](https://es.wikipedia.org/wiki/Charles_Darwin) estaría orgulloso de estos algoritmos.

### --- Bien, entonces... ¿estos algoritmos pueden mejorarse a sí mismos?
{: .notice}

Más o menos. No es el algoritmo en sí el que se cambia, pero sí que permite mejorar la solución proporcionada conforme avanza el tiempo.

En la naturaleza y según el mecanismo de la selección natural los seres vivos se adaptan al entorno gracias a las características heredadas de sus progenitores, y dentro de los individuos de una especie en una generación determinada las probabilidades de supervivencia son proporcionales al rendimiento de esas características.

El funcionamiento de estos algoritmos pretende simular ese comportamiento. Enfrentaremos a nuestro algoritmo genético a un escenario para el que no ha sido preparado. Buscaremos entonces el mejor **individuo** (como analogía de la mejor solución) que sepa desenvolverse eficazmente en este escenario. Para esto partiremos de una _selección aleatoria_ de individuos, los pondremos a prueba en este escenario y una vez obtengamos los resultados seleccionaremos un conjunto de ellos, donde los que han mostrado mejores resultados tienen más probabilidades de ser elegidos. Combinaremos los individuos seleccionados mediante las técnicas de [**cruce**](https://es.wikipedia.org/wiki/Recombinación_(computación_evolutiva)) y [**mutación**](https://es.wikipedia.org/wiki/Mutación_(computación_evolutiva)), dando lugar a una nueva generación de individuos, los cuales pueden ser potencialmente mejores a la anterior generación. Repetiremos este proceso tantas veces como necesitemos.

Para poder realizar esto necesitaremos lo siguiente:

- Un **_cromosoma_**: La representación de cada individuo en forma de cadena, donde cada símbolo de esta cadena se llama _gen_. Si la cadena es de dígitos binarios lo llamaremos _genotipo_.
- Una **_función de fitness_**: Cómo evaluar el rendimiento de una solución.
- Los **_operadores genéticos_**: Cómo realizar la selección, el cruce y la mutación de los individuos.

![](https://www.renovablesverdes.com/wp-content/uploads/2017/03/mariposas.png)

Nótese que, dada la naturaleza probabilística de estos algoritmos, habrá individuos que se repitan y otros que no aparezcan. Así pues, no tendremos asegurada la solución más óptima para un problema, pero sí que obtendremos una solución _bastante buena_ en un momento determinado. Las mejoras que nos proporciona cada generación siguen un _incremento logarítmico_, de forma que llegaremos a un punto en el que necesitaremos muchas iteraciones para lograr una pequeña mejora de la solución. El coste de este proceso dependerá en su mayoría del tiempo que se tarde en probar y evaluar cada solución.

Posiblemente estés un poco confuso con todo esto, así que lo mejor para asimilarlo es mediante un ejemplo. El ejemplo que he seleccionado es un simulador donde buscaremos encontrar la criatura que se mueva más rápido y por tanto logre una mayor distancia en un tiempo determinado. Te dejo las 4 partes aquí (están en inglés):

### Parte 1

### Parte 2

### Parte 3

### Parte 4

Puedes probarlo tú mismo aquí:

[ACTUALLY Improved Evolution Simulator](https://www.openprocessing.org/sketch/377698){: .btn .btn--info .center }

Tienes el código escrito en [Processing](https://www.processing.org) disponible en la misma página.

Además, por si te parece poco, estos algoritmos pueden combinarse con las redes neuronales, permitiendo enfrentar el mismo algoritmo genético a escenarios diferentes y obtener mejores resultados a la hora de mejorar los pesos de una red neuronal. Podemos ver esto en un ejemplo, utilizando un algoritmo genético y una red neuronal para hacer que un ordenador aprenda a jugar al mítico dinosaurio de Chrome cuando no hay conexión a Internet. En este caso el escenario es diferente porque en cada ejecución de este juego la distribución del nivel es diferente. También nos ofrece una sencilla explicación sobre redes neuronales y algoritmos genéticos, no tiene desperdicio:

Está en portugués, pero para lo que no se entienda tiene subtítulos en inglés.

Por supuesto, también tienes el código disponible [aquí ](https://github.com/ivanseidel/IAMDinosaur).

Fascinante, ¿verdad?

redpajama_set_name: RedPajamaGithub


text:
naughty_substrs = ["ab","cd","pq","xy"]

a=File.open('data/dec5/input.txt').select do |st|
  # Always naughty, so check this first
  if nil != naughty_substrs.index { |ns| st.include?(ns) }
    false
  elsif st.count("aeiou") < 3
    false
  elsif st.match(/(.)\1/)
    true
  else
    false
  end
end

puts a.length


text:
title: "Third party drivers and plugins"
weight: 2
---

{{% notice info %}}
<i class="fas fa-language"></i> 页面需要从英语翻译为简体中文。
您熟悉英语与简体中文吗?帮助我们翻译它,通过 pull requests 给我们!
{{% /notice %}}

Selenium can be extended through the use of plugins. Here are a number of
plugins created and maintained by third parties. For more information on how
to create your own plugin or have it listed, consult the docs.

Please note that these plugins are not supported, maintained, hosted, or
endorsed by the Selenium project. In addition, be advised that the plugins
listed below are not necessarily licensed under the Apache License v.2.0.
Some of the plugins are available under another free and open source software
license; others are only available under a proprietary license. Any questions
about plugins and their license of distribution need to be raised with their
respective developer(s).

| Browser | Latest version | Changelog | Issues | Wiki |
| -------- | ---------- | ---------- | ---------- | ---------- |
| [Google ChromeDriver](//sites.google.com/a/chromium.org/chromedriver/) | [2.29](//chromedriver.storage.googleapis.com/index.html) |  [changelog](//chromedriver.storage.googleapis.com/2.29/notes.txt) | [issues](//bugs.chromium.org/p/chromedriver/issues/list) | [wiki](//github.com/SeleniumHQ/selenium/wiki/ChromeDriver)


text:
<?php
/**
 * @package PayPal
 */

/**
 * Make sure our parent class is defined.
 */
require_once 'PayPal/Type/AbstractRequestType.php';

/**
 * CreateRecurringPaymentsProfileRequestType
 *
 * @package PayPal
 */
class CreateRecurringPaymentsProfileRequestType extends AbstractRequestType
{
    var $CreateRecurringPaymentsProfileRequestDetails;

    function CreateRecurringPaymentsProfileRequestType()
    {
        parent::AbstractRequestType();
        $this->_namespace = 'urn:ebay:api:PayPalAPI';
        $this->_elements = array_merge($this->_elements,
            array (
              'CreateRecurringPaymentsProfileRequestDetails' =>
              array (
                'required' => true,
                'type' => 'CreateRecurringPaymentsProfileRequestDetailsType',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
            ));
    }

    function getCreateRecurringPaymentsProfileRequestDetails()
    {
        return $this->CreateRecurringPaymentsProfileRequestDetails;
    }
    function setCreateRecurringPaymentsProfileRequestDetails($CreateRecurringPaymentsProfileRequestDetails, $charset = 'iso-8859-1')
    {
        $this->CreateRecurringPaymentsProfileRequestDetails = $CreateRecurringPaymentsProfileRequestDetails;
        $this->_elements['CreateRecurringPaymentsProfileRequestDetails']['charset'] = $charset;
    }
}


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZEMARK_FLENS_INIT_GEMATRIX_H_
#define _BLAZEMARK_FLENS_INIT_GEMATRIX_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <flens/matrixtypes/general/impl/gematrix.h>
#include <blaze/util/Random.h>
#include <blazemark/system/Types.h>

namespace blazemark {

namespace flens {

//=================================================================================================
//
//  INITIALIZATION FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\name FLENS initialization functions */
//@{
template< typename Type >
void init( ::flens::GeMatrix< ::flens::FullStorage<Type,::flens::RowMajor> >& m );

template< typename Type >
void init( ::flens::GeMatrix< ::flens::FullStorage<Type,::flens::ColMajor> >& m );
//@}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Random initialization of the given row-major dense matrix.
//
// \param m The row-major dense matrix to be initialized.
// \return void
//
// This function initializes the given row-major dense matrix with random values.
*/
template< typename Type >  // Data type of the matrix
void init( ::flens::GeMatrix< ::flens::FullStorage<Type,::flens::RowMajor> >& m )
{
   typedef typename ::flens::GeMatrix< ::flens::FullStorage<Type,::flens::RowMajor> >::IndexType  IndexType;

   for( IndexType i=m.firstRow(); i<=m.lastRow(); ++i ) {
      for( IndexType j=m.firstCol(); j<=m.lastCol(); ++j ) {
         m(i,j) = ::blaze::rand<Type>( 0, 10 );
      }
   }
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Random initialization of the given column-major dense matrix.
//
// \param m The column-major dense matrix to be initialized.
// \return void
//
// This function initializes the given column-major dense matrix with random values.
*/
template< typename Type >  // Data type of the matrix
void init( ::flens::GeMatrix< ::flens::FullStorage<Type,::flens::ColMajor> >& m )
{
   typedef typename ::flens::GeMatrix< ::flens::FullStorage<Type,::flens::ColMajor> >::IndexType  IndexType;

   for( IndexType j=m.firstCol(); j<=m.lastCol(); ++j ) {
      for( IndexType i=m.firstRow(); i<=m.lastRow(); ++i ) {
         m(i,j) = ::blaze::rand<Type>( 0, 10 );
      }
   }
}
//*************************************************************************************************

} // namespace flens

} // namespace blazemark

#endif


text:
#ifndef H_BLE_LL_RESOLV_
#define H_BLE_LL_RESOLV_

/*
 * An entry in the resolving list.
 *      The identity address is stored in little endian format.
 *      The local rpa is stored in little endian format.
 *      The IRKs are stored in big endian format.
 */
struct ble_ll_resolv_entry
{
    uint8_t rl_addr_type;
    uint8_t rl_local_rpa_set;
    uint16_t rl_reserved;
    uint8_t rl_local_irk[BLE_ENC_BLOCK_SIZE];
    uint8_t rl_peer_irk[BLE_ENC_BLOCK_SIZE];
    uint8_t rl_identity_addr[BLE_DEV_ADDR_LEN];
    uint8_t rl_local_rpa[BLE_DEV_ADDR_LEN];
};

extern struct ble_ll_resolv_entry g_ble_ll_resolv_list[];

/* Clear the resolving list */
int ble_ll_resolv_list_clr(void);

/* Read the size of the resolving list */
int ble_ll_resolv_list_read_size(uint8_t *rspbuf, uint8_t *rsplen);

/* Add a device to the resolving list */
int ble_ll_resolv_list_add(uint8_t *cmdbuf);

/* Remove a device from the resolving list */
int ble_ll_resolv_list_rmv(uint8_t *cmdbuf);

/* Address resolution enable command */
int ble_ll_resolv_enable_cmd(uint8_t *cmdbuf);

/* XXX: implement */
int ble_ll_resolv_peer_addr_rd(uint8_t *cmdbuf);
void ble_ll_resolv_local_addr_rd(uint8_t *cmdbuf);

/* Finds 'addr' in resolving list. Doesnt check if address resolution enabled */
struct ble_ll_resolv_entry *
ble_ll_resolv_list_find(uint8_t *addr, uint8_t addr_type);

/* Called to determine if the IRK is all zero. */
int ble_ll_resolv_irk_nonzero(uint8_t *irk);

/* Returns true if address resolution is enabled */
uint8_t ble_ll_resolv_enabled(void);

/* Reset private address resolution */
void ble_ll_resolv_list_reset(void);

void ble_ll_resolv_gen_priv_addr(struct ble_ll_resolv_entry *rl, int local,
                                 uint8_t *addr);

/* Generate a resolvable private address. */
int ble_ll_resolv_gen_rpa(uint8_t *addr, uint8_t addr_type, uint8_t *rpa,
                          int local);

/* Set the resolvable private address timeout */
int ble_ll_resolv_set_rpa_tmo(uint8_t *cmdbuf);

/* Get the RPA timeout, in seconds */
uint32_t ble_ll_resolv_get_rpa_tmo(void);

/* Resolve a resolvable private address */
int ble_ll_resolv_rpa(uint8_t *rpa, uint8_t *irk);

/* Initialize resolv*/
void ble_ll_resolv_init(void);

#endif


text:
<?xml version="1.0" ?>
<doc>
	<str name="Patent Number">
		US7938958
	</str>
	<str name="Application Number">
		US12371948
	</str>
	<str name="Kind Code">
		B2
	</str>
	<str name="Title">
		De-aeration system
	</str>
	<str name="Abstract">
		A de-aeration system for a fuel system, the fuel system having a housing for containing a fuel filter element, a fuel inlet and a fuel outlet is disclosed. The de-aeration system includes a de-aeration valve having a valve inlet in a lower face of the valve for connection to the housing for purging the air trapped in the housing. The de-aeration valve also includes a valve outlet in an upper face of the valve and a ball. The ball is configured to lift between the lower face and the upper face in response to an air pressure differential acting on the ball. This opens the valve to purge air trapped in the housing. The ball is further configured to close the valve by sealing against the valve outlet in the upper face in response to a pressure differential across the ball created by unfiltered fuel entering the valve.
	</str>
	<str name="Document Types">
		US | USB
	</str>
	<str name="Application Date">
		2009-02-17
	</str>
	<str name="Application Year">
		2009
	</str>
	<str name="Application(Year/Month)">
		2009-02
	</str>
	<str name="Publication Date">
		2011-05-10
	</str>
	<str name="Publication Year">
		2011
	</str>
	<str name="Publication(Year/Month)">
		2011-05
	</str>
	<str name="All IPC">
		B01D35/01 | B01D19/00 | B01D35/147 | B01D27/10
	</str>
	<str name="IPC Primary">
		B01D35/01
	</str>
	<str name="IPC Section">
		B
	</str>
	<str name="IPC Class">
		B01
	</str>
	<str name="IPC Subclass">
		B01D
	</str>
	<str name="IPC Group">
		B01D35
	</str>
	<str name="All UPC">
		123/510 | 210/188 | 210/137 | 96/219 | 96/162 | 210/133 | 96/165 | 96/163 | 210/130 | 96/156 | 210/129 | 210/472 | 210/436 | 210/128
	</str>
	<str name="UPC Primary">
		123/510
	</str>
	<str name="UPC Class">
		123
	</str>
	<str name="Family Member Count">
		0
	</str>
	<str name="Family Members Cited By Count">
		0
	</str>
	<str name="Other References">
		Siebels, Karl H; Machine Translation of EP-0207739-A2 (German version submitted by applicant as prior art). cited by examiner . | DE 10345225 A1--English Machine Translation. cited by examiner . | Notification of Transmittal of the International Search Report and The Written Opinion of the International Searching Authority, or the Declaration dated Mar. 6, 2008 in corresponding International Application No. PCT/GB2007/003130. cited by other . | Examination Report under Section 18(3) of the UK Intellectual Property Office dated Oct. 7, 2010 in corresponding Great Britain Application No. GB0616515.3. cited by other . | Schachtrup, Ludger et al.; Machine Translation of FR-2830284-A1 (French version referenced above). cited by examiner . | International Preliminary Report on Patentability dated Oct. 30, 2008 of the European Patent Office in corresponding International Application No. PCT/GB2007/003130. cited by other.
	</str>
	<str name="Other References Count">
		6
	</str>
	<str name="Cited By Count">
		0
	</str>
	<str name="Cites">
		US20050011497 | US20040103883 | US6520162 | DE20118185 | FR2830284 | DE10345225 | EP0307739 | DE4015551
	</str>
	<str name="Cites Count">
		8
	</str>
	<str name="Assignee(s)">
		PARKER HANNIFIN (UK) LIMITED
	</str>
	<str name="1st Assignee">
		PARKER HANNIFIN (UK) LIMITED
	</str>
	<str name="Number of Assignees">
		1
	</str>
	<str name="1st Assignee Address">
		Dewsbury, GB
	</str>
	<str name="Assignee(s) Address">
		Dewsbury, GB
	</str>
	<str name="Inventor(s)">
		CORE, PHIL | ASHTON, JAMES | WILSON, STEVEN
	</str>
	<str name="1st Inventor">
		CORE, PHIL
	</str>
	<str name="Number of Inventors">
		3
	</str>
	<str name="1st Inventor Address">
		West, Yorkshire, GB
	</str>
	<str name="Inventor(s) Address">
		West, Yorkshire, GB | South, Yorkshire, GB | York, GB
	</str>
	<str name="Agent/Attorney">
		HUNTER, CHRISTOPHER H.
	</str>
	<str name="Primary Examiner">
		SMITH, DUANE
	</str>
	<str name="Assistant Examiner">
		DURAND, PAUL J
	</str>
	<str name="cited by within 3 years">
		0
	</str>
	<str name="cited by within 5 years">
		0
	</str>
</doc>


text:
namespace {

// Print the command line help.
void PrintHelp() {
  LOG(ERROR) << "schema_org_name_generator <schema-file> ... <schema-file>"
             << " <output-file>";
}

}  // namespace

int main(int argc, char* argv[]) {
  base::CommandLine::Init(argc, argv);
  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();

  logging::LoggingSettings settings;
  settings.logging_dest =
      logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
  logging::InitLogging(settings);

#if defined(OS_WIN)
  std::vector<std::string> args;
  base::CommandLine::StringVector wide_args = command_line.GetArgs();
  for (const auto& arg : wide_args) {
    args.push_back(base::UTF16ToUTF8(arg));
  }
#else
  base::CommandLine::StringVector args = command_line.GetArgs();
#endif
  if (args.size() < 2U) {
    PrintHelp();
    return 1;
  }

  // Read all the args and convert to file paths.
  std::vector<base::FilePath> paths;
  for (auto& arg : args) {
    paths.push_back(base::FilePath::FromUTF8Unsafe(arg));
  }

  // Check we have at least two paths.
  if (paths.size() < 2U) {
    PrintHelp();
    return 1;
  }

  // Get the last path which is the output file.
  base::FilePath output_path = paths.back();
  paths.pop_back();

  base::DictionaryValue output_map;
  std::set<std::string> names_to_generate;

  for (auto& path : paths) {
    path = base::MakeAbsoluteFilePath(path);
    if (!base::PathExists(path)) {
      LOG(ERROR) << "Input JSON file doesn't exist.";
      return 1;
    }

    std::string json_input;
    if (!base::ReadFileToString(path, &json_input)) {
      LOG(ERROR) << "Could not read input JSON file.";
      return 1;
    }

    auto value = base::JSONReader::Read(json_input);
    base::DictionaryValue* dict_value = nullptr;
    if (!value.has_value() || !value->GetAsDictionary(&dict_value)) {
      LOG(ERROR) << "Could not parse the input JSON file";
      return 1;
    }

    const base::ListValue* graph = nullptr;
    if (!dict_value->GetList("@graph", &graph)) {
      LOG(ERROR) << "Could not parse the @graph in the input JSON";
      return 1;
    }

    for (size_t i = 0; i < graph->GetSize(); ++i) {
      const base::DictionaryValue* parsed = nullptr;
      if (!graph->GetDictionary(i, &parsed)) {
        LOG(ERROR) << "Could not parse entry " << i << " in the input JSON";
        return 1;
      }

      std::string id;
      if (!parsed->GetString("@id", &id)) {
        LOG(ERROR) << "Could not extract the id from the entry";
        return 1;
      }

      if (id.empty()) {
        LOG(ERROR) << "ID was empty";
        return 1;
      }

      names_to_generate.insert(id);
      names_to_generate.insert(GURL(id).path().substr(1));
    }
  }

  std::set<unsigned> generated_hashes;
  for (auto& name : names_to_generate) {
    auto hash = base::PersistentHash(name);

    if (base::Contains(generated_hashes, hash)) {
      LOG(ERROR) << "Hash collision: " << name;
      return 1;
    }

    output_map.SetStringKey(name, base::StringPrintf("0x%x", hash));
    generated_hashes.insert(hash);
  }

  std::string output;
  if (!base::JSONWriter::Write(output_map, &output)) {
    LOG(ERROR) << "Failed to convert output to JSON.";
    return 1;
  }

  if (base::WriteFile(output_path, output.c_str(),
                      static_cast<uint32_t>(output.size())) <= 0) {
    LOG(ERROR) << "Failed to write output.";
    return 1;
  }

  return 0;
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/dataflow/v1beta3/metrics.proto

namespace Google\Cloud\Dataflow\V1beta3;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * JobMetrics contains a collection of metrics describing the detailed progress
 * of a Dataflow job. Metrics correspond to user-defined and system-defined
 * metrics in the job.
 * This resource captures only the most recent values of each metric;
 * time-series data can be queried for them (under the same metric names)
 * from Cloud Monitoring.
 *
 * Generated from protobuf message google.dataflow.v1beta3.JobMetrics
 */
class JobMetrics extends \Google\Protobuf\Internal\Message
{
    /**
     * Timestamp as of which metric values are current.
     *
     * Generated from protobuf field .google.protobuf.Timestamp metric_time = 1;
     */
    private $metric_time = null;
    /**
     * All metrics for this job.
     *
     * Generated from protobuf field repeated .google.dataflow.v1beta3.MetricUpdate metrics = 2;
     */
    private $metrics;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Protobuf\Timestamp $metric_time
     *           Timestamp as of which metric values are current.
     *     @type \Google\Cloud\Dataflow\V1beta3\MetricUpdate[]|\Google\Protobuf\Internal\RepeatedField $metrics
     *           All metrics for this job.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Dataflow\V1Beta3\Metrics::initOnce();
        parent::__construct($data);
    }

    /**
     * Timestamp as of which metric values are current.
     *
     * Generated from protobuf field .google.protobuf.Timestamp metric_time = 1;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getMetricTime()
    {
        return $this->metric_time;
    }

    public function hasMetricTime()
    {
        return isset($this->metric_time);
    }

    public function clearMetricTime()
    {
        unset($this->metric_time);
    }

    /**
     * Timestamp as of which metric values are current.
     *
     * Generated from protobuf field .google.protobuf.Timestamp metric_time = 1;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setMetricTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->metric_time = $var;

        return $this;
    }

    /**
     * All metrics for this job.
     *
     * Generated from protobuf field repeated .google.dataflow.v1beta3.MetricUpdate metrics = 2;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getMetrics()
    {
        return $this->metrics;
    }

    /**
     * All metrics for this job.
     *
     * Generated from protobuf field repeated .google.dataflow.v1beta3.MetricUpdate metrics = 2;
     * @param \Google\Cloud\Dataflow\V1beta3\MetricUpdate[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setMetrics($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dataflow\V1beta3\MetricUpdate::class);
        $this->metrics = $arr;

        return $this;
    }

}


text:
FROM wangjianyong/jupyter-cuda:7.5
MAINTAINER Jianyong Wang <wangjianyongscu@gmail.com>
ENV REFRESHED_AT 2016-05-05

#############
RUN apt-get update && apt-get install -y \
  git \
  libopenblas-dev \
  libopencv-dev \
  python-dev \
  python-numpy \
  python-setuptools

# install the core library
# Clone MXNet repo and move into it
RUN cd /root && git clone --recursive https://github.com/dmlc/mxnet && cd mxnet && \
# Copy config.mk
  cp make/config.mk config.mk && \
# Set OpenBLAS
  sed -i 's/USE_BLAS = atlas/USE_BLAS = openblas/g' config.mk && \
# Set CUDA flag
  sed -i 's/USE_CUDA = 0/USE_CUDA = 1/g' config.mk && \
  sed -i 's/USE_CUDA_PATH = NONE/USE_CUDA_PATH = \/usr\/local\/cuda/g' config.mk && \
# Set cuDNN flag
# TODO: Change when cuDNN v4 supported
  sed -i 's/USE_CUDNN = 0/USE_CUDNN = 1/g' config.mk && \
# Make
  make -j"$(nproc)"

# Install Python package
RUN cd /root/mxnet/python && python setup.py install
#############

# python pakcage
# graphviz ensures the visualization of mx.viz.plot_network in ipython notebook
RUN apt-get install -y python-numpy wget unzip graphviz
ENV MXNET_EXEC_INPLACE_GRAD_SUM_CAP 888000000
RUN pip install graphviz


text:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * CS 180 - Dynamic Generation Project
 *
 * This class provides methods to train the Dynamic Text Generator program. This
 * class only provides static methods and should never be instantiated.
 *
 * @author (Jay Patel, Arjun Bagla) <(patel445@purdue.edu, bagla@purdue.edu)>
 *
 * @lab (Your Lab Section)
 *
 * @version (03-25-2015)
 *
 */
public class PrefixGenerator {

	/**
	 * Using a given map of String[]'s to Prefix objects and the name of the
	 * training file, this method trains the program by associating Prefix
	 * objects with the suffix string (i.e. the word that appears directly after
	 * the current prefix). The resulting trained Prefix objects are stored in
	 * the given map.
	 * <P>
	 * It is valid that the map object can contain the results of prior training
	 * when this method is called. In fact, supporting this case is required to
	 * allow your program to be trained on multiple files.
	 *
	 * @param map
	 *            The map of String[] to Prefix objects to which the resulting
	 *            mappings are appended
	 * @param filename
	 *            The name of the file on which to train the model
	 */
	public static void trainPrefixMap(StringArrayMap map, String filename) {
		// Open scanner on the file
		Scanner text;
		try {
			text = new Scanner(new File(filename));
		} catch (IOException io) {
			System.out.printf("File '%s' failed to open\n", filename);
			return;
		}

		// Assumes that the file has at least 1 word in it
		if (!text.hasNext()) {
			System.out.println("File is empty");
			text.close();
			return;
		}
		Prefix.initializeSentenceStartArray();
		String[] prefix = Prefix.getStartOfSentencePrefixes();
		while (text.hasNext()) {
			String x = text.next().toLowerCase();
			Prefix a = map.getPrefix(prefix);
			if (a == null) {
				a = new Prefix(prefix);
				map.putPrefix(prefix, a);
			}
			a.addSuffix(x);
			for (int i = 0; i < prefix.length - 1; i++) {
				prefix[i] = prefix[i + 1];
			}
			prefix[prefix.length - 1] = x;
			if (TextGenerationEngine.shouldTerminate(x)) {
				prefix = Prefix.getStartOfSentencePrefixes();
			}
		}
		// TODO: Implement training algorithm
		map.printMap();
		text.close();
	}
}


text:
using System;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Progress;
using OpenLiveWriter.Controls;
using OpenLiveWriter.Controls.Wizard;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Detection ;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Localization;
using OpenLiveWriter.PostEditor ;
using System.Globalization;

namespace OpenLiveWriter.PostEditor.Configuration.Wizard
{

	internal interface IWizardAutoDetectionOperation
	{
        OpenLiveWriter.CoreServices.AsyncOperation CreateOperation(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, TemporaryBlogSettings temporarySettings);

		bool FatalErrorOccurred { get; }

		bool AuthenticationErrorOccurred { get; }

		void ShowFatalError(IWin32Window owner) ;

		bool WasCancelled { get; }

		void OperationCompleted() ;

		WizardStep ExcludedStepIfCompleted { get; }

		void ShowNonFatalErrors(IWin32Window owner);
	}

	internal class WizardWeblogAndSettingsAutoDetectionOperation : IWizardAutoDetectionOperation
	{
		public WizardWeblogAndSettingsAutoDetectionOperation(WizardStep editWithStyleStep)
		{
			_editWithStyleStep = editWithStyleStep ;
		}

        public virtual OpenLiveWriter.CoreServices.AsyncOperation CreateOperation(IBlogClientUIContext uiContext, Control parentConrol, TemporaryBlogSettings temporarySettings)
		{
			_temporarySettings = temporarySettings ;

			// create and start the account detector
			_blogServiceDetector = new BlogServiceDetector(
				uiContext,
				parentConrol,
				_temporarySettings.Id, _temporarySettings.HomepageUrl,
				new BlogCredentialsAccessor(_temporarySettings.Id, _temporarySettings.Credentials) ) ;

			return _blogServiceDetector;
		}

		public bool FatalErrorOccurred
		{
			get
			{
				return _blogServiceDetector.ErrorOccurred;
			}
		}

        public void Cancel()
        {
            if (_blogServiceDetector == null)
                return;

            Debug.Assert(_blogServiceDetector!=null && !_blogServiceDetector.IsDone);
            if (!_blogServiceDetector.IsDone)
                _blogServiceDetector.Cancel();
        }

	    public bool IsDone
	    {
	        get
	        {
                if (_blogServiceDetector == null)
                    return true;
	            return _blogServiceDetector.IsDone;
	        }
	    }

		public bool AuthenticationErrorOccurred
		{
			get { return _blogServiceDetector.AuthenticationErrorOccurred; }
		}

		public void ShowFatalError(IWin32Window owner)
		{
			_blogServiceDetector.ShowLastError(owner);
		}

		public bool WasCancelled
		{
			get
			{
				return _blogServiceDetector.WasCancelled;
			}
		}

		public void OperationCompleted()
		{
            _temporarySettings.ClearProvider();

			// copy the detected settings
			_temporarySettings.SetProvider( _blogServiceDetector.ProviderId, _blogServiceDetector.ServiceName, _blogServiceDetector.PostApiUrl, _blogServiceDetector.ClientType);
			if ( _temporarySettings.BlogName == String.Empty )
				_temporarySettings.BlogName = _blogServiceDetector.BlogName ;
			_temporarySettings.HostBlogId = _blogServiceDetector.HostBlogId;
			_temporarySettings.HostBlogs = _blogServiceDetector.UsersBlogs ;
			_temporarySettings.ManifestDownloadInfo = _blogServiceDetector.ManifestDownloadInfo ;
            _temporarySettings.ClientType = _blogServiceDetector.ClientType;

			// values that the service detector attempts to retreive -- if the attempt fails
			// for any reason then don't update the value (i.e. a failed attempt to get the
			// list of categories should not be construed as "there are no categories")
			if ( _blogServiceDetector.Categories != null )
				_temporarySettings.Categories = _blogServiceDetector.Categories;
            if (_blogServiceDetector.Keywords != null)
                _temporarySettings.Keywords = _blogServiceDetector.Keywords;
			if ( _blogServiceDetector.FavIcon != null )
				_temporarySettings.FavIcon = _blogServiceDetector.FavIcon ;
			if ( _blogServiceDetector.Image != null )
				_temporarySettings.Image = _blogServiceDetector.Image ;
			if ( _blogServiceDetector.WatermarkImage != null )
				_temporarySettings.WatermarkImage = _blogServiceDetector.WatermarkImage ;

            if (_blogServiceDetector.OptionOverrides != null)
                _temporarySettings.OptionOverrides = _blogServiceDetector.OptionOverrides;
			if ( _blogServiceDetector.HomePageOverrides!= null )
                _temporarySettings.HomePageOverrides = _blogServiceDetector.HomePageOverrides;

			if ( _blogServiceDetector.ButtonDescriptions != null )
				_temporarySettings.ButtonDescriptions = _blogServiceDetector.ButtonDescriptions ;

			if ( _blogServiceDetector.AvailableImageEndpoints != null )
				_temporarySettings.AvailableImageEndpoints = _blogServiceDetector.AvailableImageEndpoints;

            if ( _blogServiceDetector.BlogTemplateFiles != null)
                _temporarySettings.TemplateFiles = _blogServiceDetector.BlogTemplateFiles;

            if (_blogServiceDetector.PostBodyBackgroundColor != null)
                _temporarySettings.UpdatePostBodyBackgroundColor(_blogServiceDetector.PostBodyBackgroundColor.Value);
		}

		public WizardStep ExcludedStepIfCompleted
		{
			get
			{
				return _editWithStyleStep ;
			}
		}

		public void ShowNonFatalErrors(IWin32Window owner)
		{
			// if a template error occurred then show it now
			if ( _blogServiceDetector.TemplateDownloadFailed )
				DisplayMessage.Show(MessageId.TemplateDownloadFailed, owner);

		}

		protected BlogServiceDetectorBase _blogServiceDetector ;
		protected TemporaryBlogSettings _temporarySettings ;
		private WizardStep _editWithStyleStep ;
	}

	/// <summary>
	/// Provides auto-detection support for SharePoint blogs.
	/// </summary>
	internal class WizardSharePointAutoDetectionOperation : WizardWeblogAndSettingsAutoDetectionOperation
	{
		public WizardSharePointAutoDetectionOperation(WizardStep editWithStyleStep) : base(editWithStyleStep)
		{
		}

        public override OpenLiveWriter.CoreServices.AsyncOperation CreateOperation(IBlogClientUIContext uiContext, Control parentConrol, TemporaryBlogSettings temporarySettings)
		{
			_temporarySettings = temporarySettings ;

			// create and start the account detector
			_blogServiceDetector = new SharePointBlogDetector(
				uiContext,
				parentConrol,
				_temporarySettings.Id, _temporarySettings.HomepageUrl,
				new BlogCredentialsAccessor(_temporarySettings.Id, _temporarySettings.Credentials),
				_temporarySettings.Credentials) ;

			return _blogServiceDetector;
		}
	}

	internal class WizardSettingsAutoDetectionOperation : IWizardAutoDetectionOperation
	{
		private IBlogClientUIContext _uiContext ;

		public WizardSettingsAutoDetectionOperation(WizardStep editWithStyleStep)
		{
			_editWithStyleStep = editWithStyleStep ;
		}

        public OpenLiveWriter.CoreServices.AsyncOperation CreateOperation(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, TemporaryBlogSettings temporarySettings)
		{
			// save references
			_uiContext = uiContext ;
			_temporarySettings = temporarySettings ;

			// create operation
			_hostOperation = new MultipartAsyncOperation(uiContext);
			_hostOperation.AddProgressOperation( new ProgressOperation(DetectWeblogSettings), 50 );
			_blogEditingTemplateDetector = new BlogEditingTemplateDetector( _uiContext, hiddenBrowserParentControl, temporarySettings, false ) ;
			_hostOperation.AddProgressOperation( new ProgressOperation(_blogEditingTemplateDetector.DetectTemplate), 50 );
			return _hostOperation ;
		}

		// settings detection is never a fatal error
		public bool FatalErrorOccurred { get { return false; } }
		public bool AuthenticationErrorOccurred { get { return false; } }

		public void ShowFatalError(IWin32Window owner) {}

		public bool WasCancelled
		{
			get
			{
				return (_hostOperation as IProgressHost).CancelRequested;
			}
		}

		public void OperationCompleted()
		{
			_temporarySettings.TemplateFiles = _blogEditingTemplateDetector.BlogTemplateFiles ;
            if (_blogEditingTemplateDetector.PostBodyBackgroundColor != null)
                _temporarySettings.UpdatePostBodyBackgroundColor(_blogEditingTemplateDetector.PostBodyBackgroundColor.Value);
		}

		public WizardStep ExcludedStepIfCompleted
		{
			get { return _editWithStyleStep; }
		}

		public void ShowNonFatalErrors(IWin32Window owner)
		{
			// if a template error occurred then show it now
			if ( _blogEditingTemplateDetector.ExceptionOccurred )
				DisplayMessage.Show(MessageId.TemplateDownloadFailed, owner);
		}

		private object DetectWeblogSettings(IProgressHost progressHost)
		{
			using ( BlogClientUIContextScope uiContextScope = new BlogClientUIContextScope(_uiContext) )
			{
				try
				{
					BlogSettingsDetector blogSettingsDetector = new BlogSettingsDetector(_temporarySettings);
					blogSettingsDetector.DetectSettings(progressHost);
				}
				catch(OperationCancelledException)
				{
					// WasCancelled == true
				}
				catch(BlogClientOperationCancelledException)
				{
					_hostOperation.Cancel();
					// WasCancelled == true
				}
				catch(Exception ex)
				{
					Trace.Fail("Error occurred while downloading weblog posts and  categories: " + ex.ToString());
				}

				return this ;
			}
		}

		private TemporaryBlogSettings _temporarySettings ;
		private BlogEditingTemplateDetector _blogEditingTemplateDetector ;
		private MultipartAsyncOperation _hostOperation ;
		WizardStep _editWithStyleStep ;

	}

}


text:
package exps.codepattern.code.cfg;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import exps.codepattern.adt.graph.Node;
import exps.codepattern.code.ir.statement.IRStatement;

public interface CFGBlock extends Node {
	@Override
    ImmutableSet<? extends CFGBlock> getNexts();

	@Override
    ImmutableSet<? extends CFGBlock> getPrevs();

	ImmutableList<IRStatement> getStatements();
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.sheets.v4.model;

/**
 * Inserts data into the spreadsheet starting at the specified coordinate.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Google Sheets API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class PasteDataRequest extends com.google.api.client.json.GenericJson {

  /**
   * The coordinate at which the data should start being inserted.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GridCoordinate coordinate;

  /**
   * The data to insert.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String data;

  /**
   * The delimiter in the data.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String delimiter;

  /**
   * True if the data is HTML.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean html;

  /**
   * How the data should be pasted.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String type;

  /**
   * The coordinate at which the data should start being inserted.
   * @return value or {@code null} for none
   */
  public GridCoordinate getCoordinate() {
    return coordinate;
  }

  /**
   * The coordinate at which the data should start being inserted.
   * @param coordinate coordinate or {@code null} for none
   */
  public PasteDataRequest setCoordinate(GridCoordinate coordinate) {
    this.coordinate = coordinate;
    return this;
  }

  /**
   * The data to insert.
   * @return value or {@code null} for none
   */
  public java.lang.String getData() {
    return data;
  }

  /**
   * The data to insert.
   * @param data data or {@code null} for none
   */
  public PasteDataRequest setData(java.lang.String data) {
    this.data = data;
    return this;
  }

  /**
   * The delimiter in the data.
   * @return value or {@code null} for none
   */
  public java.lang.String getDelimiter() {
    return delimiter;
  }

  /**
   * The delimiter in the data.
   * @param delimiter delimiter or {@code null} for none
   */
  public PasteDataRequest setDelimiter(java.lang.String delimiter) {
    this.delimiter = delimiter;
    return this;
  }

  /**
   * True if the data is HTML.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getHtml() {
    return html;
  }

  /**
   * True if the data is HTML.
   * @param html html or {@code null} for none
   */
  public PasteDataRequest setHtml(java.lang.Boolean html) {
    this.html = html;
    return this;
  }

  /**
   * How the data should be pasted.
   * @return value or {@code null} for none
   */
  public java.lang.String getType() {
    return type;
  }

  /**
   * How the data should be pasted.
   * @param type type or {@code null} for none
   */
  public PasteDataRequest setType(java.lang.String type) {
    this.type = type;
    return this;
  }

  @Override
  public PasteDataRequest set(String fieldName, Object value) {
    return (PasteDataRequest) super.set(fieldName, value);
  }

  @Override
  public PasteDataRequest clone() {
    return (PasteDataRequest) super.clone();
  }

}


text:
.. _max30101:

MAX30101 Heart Rate Sensor
##########################

Overview
********

A sensor application that demonstrates how to poll data from the max30101 heart
rate sensor.

Building and Running
********************

This project configures the max30101 sensor on the :ref:`hexiwear_k64` board to
enable the green LED and measure the reflected light with a photodiode. The raw
ADC data prints to the console. Further processing (not included in this
sample) is required to extract a heart rate signal from the light measurement.

.. zephyr-app-commands::
   :zephyr-app: samples/sensors/max30101
   :board: hexiwear_k64
   :goals: build
   :compact:

Sample Output
=============

.. code-block:: console

   GREEN=5731
   GREEN=5750
   GREEN=5748
   GREEN=5741
   GREEN=5735
   GREEN=5737
   GREEN=5736
   GREEN=5748

<repeats endlessly>


text:
mode="dev"
if [[ -n "$1" ]]
then
   mode=$1
fi

if [ $mode = "prod" ]
then
   app/console assets:install --symlink
   app/console cache:clear --env=prod
   app/console assetic:dump --env=prod
elif [ $mode = "staging" ]
then
   app/console assets:install --symlink
   app/console cache:clear --env=prod
   app/console assetic:dump --env=prod
elif [ $mode = "dev" ]
then
  app/console assets:install --symlink
  app/console cache:clear --env=dev
  app/console assetic:dump --env=dev
fi


text:
<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class CategoriesTableSeeder extends Seeder {

	public function run()
	{
		DB::table('categories')->delete();
		Category::create(array(
			'name' => 'Pets',
			));
		Category::create(array(
			'name' => 'Cosmetics',
			));
		Category::create(array(
			'name' => 'Clothes and shoes',
			));
		Category::create(array(
			'name' => 'Large & small appliance',
			));
		Category::create(array(
			'name' => 'IT and communications',
			));
		Category::create(array(
			'name' => 'TV and Audio',
			));
	}

}


text:
"""
Exceptions for oxml sub-package
"""

class ValidationError(Exception):
    """
    Raised when invalid XML is encountered, such as on attempt to access a
    missing required child element
    """


text:
<?php

require_once 'phing/Task.php';
require_once 'phing/system/io/PhingFile.php';

/**
 * Task ověří existenci adresáře. Pokud neexistuje, vytvoří jej.
 *
 * <code>
 * <require dir="dirname"/>
 * </code>
 */
class FsRequireTask extends Task
{

	/**
	 * directory to create
	 */
	private $dir;

	/**
	 * Mode to create directory with
	 * @var integer
	 */
	private $mode = 0755;

	/**
	 * create the directory and all parents
	 *
	 * @throws BuildException if dir is somehow invalid, or creation failed.
	 */
	function main()
	{
		if ($this->dir === null) {
			throw new BuildException("dir attribute is required", $this->location);
		}

		if ($this->dir->isFile()) {
			throw new BuildException("Unable to create directory as a file already exists with that name: " . $this->dir->getAbsolutePath());
		}

		if (!$this->dir->exists()) {
			$result = $this->dir->mkdirs($this->mode);
			if (!$result) {
				$msg = "Directory " . $this->dir->getAbsolutePath() . " creation was not successful for an unknown reason";
				throw new BuildException($msg, $this->location);
			}
			$this->log("Created dir: " . $this->dir->getAbsolutePath());
		}
	}

	/**
	 * the directory to create; required.
	 */
	function setDir(PhingFile $dir)
	{
		$this->dir = $dir;
	}

	/**
	 * Sets mode to create directory with
	 * @param mixed $mode
	 */
	function setMode($mode)
	{
		$this->mode = base_convert((int) $mode, 8, 10);
	}

}


text:
import unittest

from kraken.core.builder import Builder
from kraken.core.objects.rig import Rig

class TestBuilder(unittest.TestCase):

    def testBuilderClass(self):
        builder = Builder()

        self.assertIsNotNone(builder)

    def testBuild(self):
        builder = Builder()
        bobRig = Rig("testRig")

        builder.build(bobRig)

def suite():
    return unittest.TestLoader().loadTestsFromTestCase(TestBuilder)

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


text:
'use strict';

angular.module('users').directive('signIn', [
	function() {
		return {
			templateUrl: 'modules/users/icons/signin.html',
			restrict: 'E',
			link: function postLink(scope, element, attrs) {

			}
		};
	}
]);


text:
@implementation FLFriendModel

@end


text:
using System;
using Heleonix.Validation.Tests.Common;
using Moq;
using NUnit.Framework;

namespace Heleonix.Validation.Tests
{
    /// <summary>
    /// Tests the <see cref="ValidationController"/>.
    /// </summary>
    public class ValidationControllerTests
    {
        #region Tests

        /// <summary>
        /// Tests the <see cref="ValidationController"/>.
        /// </summary>
        [Test]
        public void Constructor([Values(true, false)] bool passValidatorProvider)
        {
            if (passValidatorProvider)
            {
                var provider = new DefaultValidatorProvider(false);
                var mock = new Mock<ValidationController>(provider) {CallBase = true};

                Assert.That(() => mock.InvokeGetter("ValidatorProvider"), Is.EqualTo(provider));
            }
            else
            {
                Assert.That(Assert.Catch<ArgumentNullException>(() => new ValidationController(null)).ParamName,
                    Is.EqualTo("validatorProvider"));
            }
        }

        #endregion
    }
}


text:
#ifndef PRIMITIV_CORE_MODEL_H_
#define PRIMITIV_CORE_MODEL_H_

#include <initializer_list>
#include <map>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>

#include <primitiv/core/error.h>
#include <primitiv/core/mixins/nonmovable.h>

namespace primitiv {

class Device;
class Parameter;

/**
 * Set of parameters and specific algorithms.
 */
class Model : mixins::Nonmovable<Model> {
public:
  Model() = default;
  virtual ~Model() = default;

  /**
   * Loads all parameters from a file.
   * @param path Path of the file.
   * @param with_stats Whether or not to load all additional statistics.
   * @param device Device object to manage parameters.
   */
  void load(const std::string &path, bool with_stats, Device *device);

  /**
   * Loads all parameters from a file.
   * @param path Path of the file.
   * @param with_stats Whether or not to load all additional statistics.
   * @param device Device object to manage parameters.
   */
  void load(const std::string &path, bool with_stats, Device &device) {
    load(path, with_stats, &device);
  }

  /**
   * Loads all parameters from a file.
   * @param path Path of the file.
   * @param with_stats Whether or not to load all additional statistics.
   */
  void load(const std::string &path, bool with_stats) {
    load(path, with_stats, nullptr);
  }

  /**
   * Loads all parameters from a file.
   * @param path Path of the file.
   */
  void load(const std::string &path) {
    load(path, true, nullptr);
  }

  /**
   * Saves all parameters to a file.
   * @param path Path of the file.
   * @param with_stats Whether or not to save all additional statistics.
   */
  void save(const std::string &path, bool with_stats) const;

  /**
   * Saves all parameters to a file.
   * @param path Path of the file.
   */
  void save(const std::string &path) const {
    save(path, true);
  }

  /**
   * Registers a new parameter.
   * @param name Name of the parameter.
   * @param param Reference to the parameter.
   * @remarks `name` should not be overlapped with all registered parameters and
   *          submodels.
   */
  void add(const std::string &name, Parameter &param);

  /**
   * Registers a new submodel.
   * @param name Name of the submodel.
   * @param model Reference to the submodel.
   * @remarks `name` should not be overlapped with all registered parameters and
   *          submodels.
   */
  void add(const std::string &name, Model &model);

  /**
   * Retrieves a parameter with specified name.
   * @param name Name of the parameter.
   * @return Const-reference of the corresponding `Parameter` object.
   * @throw primitiv::Error Parameter with `name` not found.
   */
  const Parameter &get_parameter(const std::string &name) const {
    const auto it = param_kv_.find(name);
    if (it == param_kv_.end()) {
      PRIMITIV_THROW_ERROR("Parameter with name '" << name << "' not found.");
    }
    return *it->second;
  }

  /**
   * Retrieves a parameter with specified name.
   * @param name Name of the parameter.
   * @return Reference of the corresponding `Parameter` object.
   * @throw primitiv::Error Parameter with `name` not found.
   */
  Parameter &get_parameter(const std::string &name) {
    return const_cast<Parameter &>(
        static_cast<const Model *>(this)->get_parameter(name));
  }

  /**
   * Recursively searches a parameter with specified name hierarchy.
   * @param names Name hierarchy of the parameter.
   * @return Const-reference of the corresponding `Parameter` object.
   * @throw primitiv::Error Parameter with `names` not found.
   */
  const Parameter &get_parameter(const std::vector<std::string> &names) const;

  /**
   * Recursively searches a parameter with specified name hierarchy.
   * @param names Name hierarchy of the parameter.
   * @return Const-reference of the corresponding `Parameter` object.
   * @throw primitiv::Error Parameter with `names` not found.
   */
  Parameter &get_parameter(const std::vector<std::string> &names) {
    return const_cast<Parameter &>(
        static_cast<const Model *>(this)->get_parameter(names));
  }

  /**
   * Recursively searches a parameter with specified name hierarchy.
   * @param names Name hierarchy of the parameter.
   * @return Const-reference of the corresponding `Parameter` object.
   * @throw primitiv::Error Parameter with `names` not found.
   */
  const Parameter &get_parameter(
      const std::initializer_list<std::string> names) const {
    return get_parameter(std::vector<std::string>(names));
  }

  /**
   * Recursively searches a parameter with specified name hierarchy.
   * @param names Name hierarchy of the parameter.
   * @return Const-reference of the corresponding `Parameter` object.
   * @throw primitiv::Error Parameter with `names` not found.
   */
  Parameter &get_parameter(const std::initializer_list<std::string> names) {
    return get_parameter(std::vector<std::string>(names));
  }

  /**
   * Retrieves a submodel with specified name.
   * @param name Name of the submodel.
   * @return Const-reference of the corresponding `Model` object.
   * @throw primitiv::Error Submodel with `name` not found.
   */
  const Model &get_submodel(const std::string &name) const {
    const auto it = submodel_kv_.find(name);
    if (it == submodel_kv_.end()) {
      PRIMITIV_THROW_ERROR("Submodel with name '" << name << "' not found.");
    }
    return *it->second;
  }

  /**
   * Retrieves a submodel with specified name.
   * @param name Name of the submodel.
   * @return Reference of the corresponding `Model` object.
   * @throw primitiv::Error Submodel with `name` not found.
   */
  Model &get_submodel(const std::string &name) {
    return const_cast<Model &>(
        static_cast<const Model *>(this)->get_submodel(name));
  }

  /**
   * Recursively searches a submodel with specified name hierarchy.
   * @param names Name hierarchy of the submodel.
   * @return Const-reference of the corresponding `Model` object.
   * @throw primitiv::Error Submodel with `names` not found.
   */
  const Model &get_submodel(const std::vector<std::string> &names) const;

  /**
   * Recursively searches a submodel with specified name hierarchy.
   * @param names Name hierarchy of the submodel.
   * @return Const-reference of the corresponding `Model` object.
   * @throw primitiv::Error Submodel with `names` not found.
   */
  Model &get_submodel(const std::vector<std::string> &names) {
    return const_cast<Model &>(
        static_cast<const Model *>(this)->get_submodel(names));
  }

  /**
   * Recursively searches a submodel with specified name hierarchy.
   * @param names Name hierarchy of the submodel.
   * @return Const-reference of the corresponding `Model` object.
   * @throw primitiv::Error Submodel with `names` not found.
   */
  const Model &get_submodel(
      const std::initializer_list<std::string> names) const {
    return get_submodel(std::vector<std::string>(names));
  }

  /**
   * Recursively searches a submodel with specified name hierarchy.
   * @param names Name hierarchy of the submodel.
   * @return Const-reference of the corresponding `Model` object.
   * @throw primitiv::Error Submodel with `names` not found.
   */
  Model &get_submodel(const std::initializer_list<std::string> names) {
    return get_submodel(std::vector<std::string>(names));
  }

  /**
   * Retrieves all parameters in the model.
   * @return Dictionary of parameters.
   */
  std::map<std::vector<std::string>, Parameter *> get_all_parameters() const;

  /**
   * Retrieves trainable parameters in the model.
   * @return Dictionary of parameters.
   */
  std::map<std::vector<std::string>, Parameter *> get_trainable_parameters(
      ) const {
    // NOTE(odashi):
    // Currently this function returns all parameters.
    return get_all_parameters();
  }

private:
  /**
   * Check whether specified model is contained or not in the submodel
   * hierarchy.
   * All descendant submodels will be searched by this function.
   * @param model Start point of the traversing path.
   * @return true if at least one descendant submodel is equal to `model`,
   *         false otherwise.
   */
  bool has_submodel(const Model &model) const;

  std::unordered_map<std::string, Parameter *> param_kv_;
  std::unordered_map<std::string, Model *> submodel_kv_;
  std::unordered_set<std::string> name_set_;
  std::unordered_set<Parameter *> param_set_;
  std::unordered_set<Model *> submodel_set_;

  /**
   * Searches semi-terminal submodel with specified name hierarchy.
   * @param names Name hierarchy of the submodel or parameter.
   * @return Const-reference of the corresponding semi-terminal `Model` object.
   * @throw primitiv::Error Submodel with specified hierarchy not found.
   */
  const Model &get_semiterminal(const std::vector<std::string> &names) const;
};

}  // namespace primitiv

#endif  // PRIMITIV_CORE_MODEL_H_


text:
package net.mntone.httpclient.headers;

import javax.xml.ws.Holder;

abstract class HttpHeaderParser
{
	private static final String DEFAULT_SEPARATOR = ", ";

	private final boolean _supportsMultipleValues;
	private final String _separator;

	protected HttpHeaderParser(final boolean supportsMultipleValues)
	{
		this._supportsMultipleValues = supportsMultipleValues;
		this._separator = DEFAULT_SEPARATOR;
	}

	protected HttpHeaderParser(final boolean supportsMultipleValues, final String separator)
	{
		this._supportsMultipleValues = supportsMultipleValues;
		this._separator = separator;
	}

	public abstract boolean tryParseValue(final String input, final Object storeValue, final Holder<Integer> index, final Holder<Object> parsedValue);

	public final boolean tryParseValue(final String input, final Holder<Object> parsedValue)
	{
		final Holder<Integer> index = new Holder<Integer>(0);
		return this.tryParseValue(input, null, index, parsedValue);
	}

	public final Object parseValue(final String input)
	{
		final Holder<Integer> index = new Holder<Integer>(0);
		return this.parseValue(input, null, index);
	}

	public final Object parseValue(final String input, final Object storeValue, final Holder<Integer> index)
	{
		final Holder<Object> result = new Holder<Object>();
		if (!this.tryParseValue(input, storeValue, index, result))
		{
			throw new IllegalArgumentException();
		}
		return result;
	}

	public String toString(final Object value)
	{
		return value.toString();
	}

	public final boolean isSupportsMultipleValues()
	{
		return this._supportsMultipleValues;
	}

	public final String getSeparator()
	{
		return this._separator;
	}

	public EqualityComparer getComparer()
	{
		return null;
	}

	public interface EqualityComparer
	{
		boolean equals(final Object x, final Object y);
	}
}


text:
title: "Teaching My Brother to Code"
layout: post
date: 2016-05-15 22:48
image: /assets/images/markdown.jpg
headerImage: false
tag:
- Mentoring
category: blog
author: andrewpierce
description: Teaching my little brother how to write the codez
# jemoji: '<img class="emoji" title=":ramen:" alt=":ramen:" src="https://assets.github.com/images/icons/emoji/unicode/1f35c.png" height="20" width="20" align="absmiddle">'
---

I have a 19 year old little brother named Kyle who's recently shown some interest in learning to code. Luckily, [I really enjoy teaching others](http://andrewmpierce.io/2016/02/28/Volunteering-at-Railsbridge.html) and get a lot of satisfaction from being able to share what I know.

Kyle had zero previous experience learning to code, so it was fun to start from total scratch with someone. I chose to start teaching him Python for a few reasons.

1) I know Python.

2) My first exposure to Python was [Learn Python the Hard Way](http://learnpythonthehardway.org/) and is available as a free resource online that I knew Kyle could easily refer to. [Invent Your Own Computer Games with Python](https://inventwithpython.com/chapters/) is another free online book that I utilized and knew Kyle could.

3) I think that Python is still among the most readable and straightforward languages and is pretty great for raw beginners.

Anywho, I got him set up with a basic Python install on his Windows machine and showed him how to write simple programs in Notepad and run them via Powershell. I chose to show him Notepad over a fancier editor like Atom or Sublime or an IDE because I think the simpler you can make things at stage zero, the better. There's not much to figure out with Notepad, so it wasn't going to present any new obstacles.

Over the course of a couple hours I showed him variables, if statements, and a basic for loop. Then we started to build the ever popular number guessing game. I gave him surprisingly little help, and he actually did really well! In the course of 4-5 hours we went from zero knowledge, to a basic implementation of a number guessing game that asked the user how many games they wanted to play, played the games, and even kept score of how the player did. To be completely honest, I was very proud.

It made me remember the ground zero that I started from around a year ago, and how far someone can come in that amount of time. I don't claim to be a phenomenal programmer by any means, but I contribute well at work and I like to think that sometimes I can do cool things and be helpful. It's pretty cool to think that my little brother or even people that I've mentored at RailsBridge events could be at a solid junior developer level in a year, which is where I consider myself to be.

Between volunteering at RailsBridge events and Hour of Code events and working with Kyle, I've realized how much I enjoy mentoring people new to programming.  With another RailsBridge event coming up in late June, I'm pretty pumped to continue to mentor people new to programming.


text:
BUILDDIR = ../../../..
PACKAGE = com.sun.security.auth
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk

#
# Files
#
include FILES_java.gmk

#
# Resources
#
LOCALE_SET_DEFINITION = jre
RESOURCE_BUNDLES_JAVA = sun/security/util/AuthResources.java

#
# Rules
#
include $(BUILDDIR)/common/Classes.gmk


text:
/*
 * walkers.h
 *
 *  Created on: Feb 8, 2011
 *      Author: siva
 */

#ifndef WALKERS_H_
#define WALKERS_H_

#include "nodes/nodes.h"
#include "nodes/parsenodes.h"
#include "nodes/nodeFuncs.h"
#include "nodes/relation.h"

/* The plan associated with a SubPlan is found in a list.  During planning this is in
 * the global structure found through the root PlannerInfo.  After planning this is in
 * the PlannedStmt.
 *
 * Structure plan_tree_base_prefix carries the appropriate pointer for GPDB's general plan
 * tree walker/mutator framework.  All users of the framework must prefix their context
 * structure with a plan_tree_base_prefix and initialize it appropriately.
 */
typedef struct plan_tree_base_prefix
{
	Node *node; /* PlannerInfo* or PlannedStmt* */
} plan_tree_base_prefix;

/*
 * Structure to hold the SUBPLAN plan_id used in the plan
 */
typedef struct SubPlanWalkerContext
{
	plan_tree_base_prefix base; /* Required prefix for plan_tree_walker/mutator */
	Bitmapset	   *bms_subplans; /* Bitmapset for used subplans */
} SubPlanWalkerContext;

extern void planner_init_plan_tree_base(plan_tree_base_prefix *base, PlannerInfo *root);
extern void exec_init_plan_tree_base(plan_tree_base_prefix *base, PlannedStmt *stmt);
extern Plan *plan_tree_base_subplan_get_plan(plan_tree_base_prefix *base, SubPlan *subplan);
extern void plan_tree_base_subplan_put_plan(plan_tree_base_prefix *base, SubPlan *subplan, Plan *plan);

extern bool walk_plan_node_fields(Plan *plan, bool (*walker) (), void *context);

extern bool plan_tree_walker(Node *node, bool (*walker) (), void *context);

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Useful functions that aggregate information from expressions or plans.
 */
extern List *extract_nodes(PlannerGlobal *glob, Node *node, int nodeTag);
extern List *extract_nodes_plan(Plan *pl, int nodeTag, bool descendIntoSubqueries);
extern List *extract_nodes_expression(Node *node, int nodeTag, bool descendIntoSubqueries);
extern int find_nodes(Node *node, List *nodeTags);

#ifdef __cplusplus
}
#endif

#endif /* WALKERS_H_ */


text:
/** @babel */

import path from 'path'
import { client } from '../connection'
import { CompositeDisposable } from 'atom'

const format = client.import('format')

export function formatCode () {
  const editor = atom.workspace.getActiveTextEditor()
  if (!editor) return

  const selections = editor.getSelections()
  if (selections.length === 1 && !selections[0].getText()) {
    formatEditor(editor)
  } else {
    selections.forEach((selection) => {
      formatEditorWithSelection(editor, selection)
    })
  }
}

function formatEditor (editor) {
  const range = editor.getBuffer().getRange()
  return formatEditorTextInRange(editor, range, editor.getText())
}

function formatEditorWithSelection (editor, selection) {
  const range = selection.getBufferRange()
  return formatEditorTextInRange(editor, range, selection.getText())
}

function formatEditorTextInRange (editor, range, text) {
  const dir = path.dirname(client.editorPath(editor))
  const marker = markRange(editor, range)
  // NOTE: Branch on `getSoftTabs` if supported by formatter.
  const indent = editor.getTabLength()
  const margin = editor.getPreferredLineLength()
  format({
    text,
    dir,
    indent,
    margin,
  }).then(({ error, formattedtext }) => {
    if (error) {
      atom.notifications.addError('Julia-Client: Format-Code', {
        description: error,
        dismissable: true
      })
    } else {
      if (marker.isValid()) {
        const pos = editor.getCursorBufferPosition()
        editor.setTextInBufferRange(marker.getBufferRange(), formattedtext)
        editor.scrollToBufferPosition(pos)
        editor.setCursorBufferPosition(pos)
      } else {
        atom.notifications.addError('Julia-Client: Format-Code', {
          description: 'Cancelled the formatting task because the selected code has been manually modified.',
          dismissable: true
        })
      }
    }
  }).catch(err => {
    console.log(err)
  }).finally(() => {
    marker.destroy()
  })
}

function markRange(editor, range) {
  const marker = editor.markBufferRange(range, {
    invalidate: 'inside'
  })
  editor.decorateMarker(marker, {
    type: 'highlight',
    class: 'ink-block'
  })
  return marker
}

let subs

export function activate() {
  subs = new CompositeDisposable()
  const edWatch = new WeakSet()

  subs.add(atom.workspace.observeTextEditors(ed => {
    edWatch.add(ed)
    // use onDidSave instead of onWillSave to guarantee our formatter is the last to run:
    const edsub = ed.getBuffer().onDidSave(() => {
      if (ed && ed.getGrammar && ed.getGrammar().id === 'source.julia') {
        if (client.isActive() && edWatch.has(ed)) {
          formatEditor(ed).then(() => {
            edWatch.delete(ed)
            ed.save().then(() => {
              edWatch.add(ed)
            }).catch(err => {
              console.log(err)
            })
          }).catch(err => {
            console.log(err)
          })
        }
      }
    })
    subs.add(edsub)

    subs.add(ed.onDidDestroy(() => {
      edsub.dispose()
    }))
  }))
}

export function deactivate() {
  subs && subs.dispose && subs.dispose()
}