text:
<?php

/**
 * Class View
 * The part that handles all the output
 */
class View
{
  /**
   * simply includes (=shows) the view. this is done from the controller. In the controller, you usually say
   * $this->view->render('help/index'); to show (in this example) the view index.php in the folder help.
   * Usually the Class and the method are the same like the view, but sometimes you need to show different views.
   * @param string $filename Path of the to-be-rendered view, usually folder/file(.php)
   * @param array $data Data to be used in the view
   */
  public function render($filename, $data = null)
  {
    if ($data) {
      foreach ($data as $key => $value) {
        $this->{$key} = $value;
      }
    }

    require Config::get('PATH_VIEW') . 'common/header.php';
    require Config::get('PATH_VIEW') . $filename . '.php';
    require Config::get('PATH_VIEW') . 'common/footer.php';
  }

  /**
   * Same like render(), but does not include header and footer
   * @param string $filename Path of the to-be-rendered view, usually folder/file(.php)
   * @param mixed $data Data to be used in the view
   */
  public function renderBasic($filename, $data = null)
  {
    if ($data) {
      foreach ($data as $key => $value) {
        $this->{$key} = $value;
      }
    }

    require Config::get('PATH_VIEW') . $filename . '.php';
  }

  /**
   * renders the feedback messages into the view
   */
  public function renderFeedbackMessages()
  {
    // echo out the feedback messages (errors and success messages etc.),
    // they are in $_SESSION["feedback_positive"] and $_SESSION["feedback_negative"]
    require Config::get('PATH_VIEW') . 'common/feedback.php';

    // delete these messages (as they are not needed anymore and we want to avoid to show them twice
    Session::set('feedback_positive', null);
    Session::set('feedback_negative', null);
  }

}


text:
package org.newdawn.slick.opengl;

import org.lwjgl.opengl.GL11;

import java.io.IOException;
import java.io.InputStream;

/**
 * A utility class to wrap the Slick internal texture loader and present a rational interface.
 *

 *
 * @author kevin
 */
public class TextureLoader {

    /**
     * Load a texture with a given format from the supplied input stream
     *

     *
     * @param format The format of the texture to be loaded (something like "PNG" or "TGA")
     * @param in     The input stream from which the image data will be read
     *

     *
     * @return The newly created texture
     *

     *
     * @throws IOException Indicates a failure to read the image data
     */
    public static Texture getTexture(String format, InputStream in) throws IOException {
        return getTexture(format, in, false, GL11.GL_LINEAR);
    }

    /**
     * Load a texture with a given format from the supplied input stream
     *

     *
     * @param format  The format of the texture to be loaded (something like "PNG" or "TGA")
     * @param in      The input stream from which the image data will be read
     * @param flipped True if the image should be flipped vertically on loading
     *

     *
     * @return The newly created texture
     *

     *
     * @throws IOException Indicates a failure to read the image data
     */
    public static Texture getTexture(String format, InputStream in, boolean flipped) throws IOException {
        return getTexture(format, in, flipped, GL11.GL_LINEAR);
    }

    /**
     * Load a texture with a given format from the supplied input stream
     *

     *
     * @param format The format of the texture to be loaded (something like "PNG" or "TGA")
     * @param in     The input stream from which the image data will be read
     * @param filter The GL texture filter to use for scaling up and down
     *

     *
     * @return The newly created texture
     *

     *
     * @throws IOException Indicates a failure to read the image data
     */
    public static Texture getTexture(String format, InputStream in, int filter) throws IOException {
        return getTexture(format, in, false, filter);
    }

    /**
     * Load a texture with a given format from the supplied input stream
     *

     *
     * @param format  The format of the texture to be loaded (something like "PNG" or "TGA")
     * @param in      The input stream from which the image data will be read
     * @param flipped True if the image should be flipped vertically on loading
     * @param filter  The GL texture filter to use for scaling up and down
     *

     *
     * @return The newly created texture
     *

     *
     * @throws IOException Indicates a failure to read the image data
     */
    public static Texture getTexture(String format, InputStream in, boolean flipped, int filter) throws IOException {
        return InternalTextureLoader.get().getTexture(in, in.toString() + "." + format, flipped, filter);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package sk.mrtn.library.client.model;

/**
 * Created by martinliptak on 18/08/16.
 */

import com.google.gwt.event.shared.HandlerRegistration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author klaun with courtesy of fishi
 */
public class MutableValue<T> implements IMutableValue<T> {

    private static Logger LOG = Logger.getLogger("MutableValue");
    public static <U> MutableValue<U> create(U value) {
        return new MutableValue<>(value);
    }

    private T value;
    private List<IValueChangeHandler<T>> changeHandlers;

    protected MutableValue(final T value) {
        this.value = value;
    }

    @Override
    public T get() {
        return this.value;
    }

    public void set(T value) {
        if (!this.value.equals(value)) {
            this.value = value;
            notifyChangeHandlers();
        }
    }

    protected void notifyChangeHandlers() {
        if (this.changeHandlers != null) {
            for (IValueChangeHandler<T> changeHandler : this.changeHandlers) {
                changeHandler.onValueChanged(this);
            }
        }
    }

    @Override
    public HandlerRegistration addChangeHandler(final IValueChangeHandler<T> changeHandler) {

        if (this.changeHandlers == null) {
            this.changeHandlers = new ArrayList<>();
        }

        this.changeHandlers.add(changeHandler);
        return new HandlerRegistration() {
            @Override
            public void removeHandler() {
                if (changeHandlers != null) {
                    changeHandlers.remove(changeHandler);
                }
            }
        };
    }

    protected void doDestroy() {
        this.value = null;
        safeClear(this.changeHandlers);
        this.changeHandlers = null;
    }

    public static void safeClear(final Collection<?> collection) {
        if (collection != null) {
            try {
                collection.clear();
            } catch (Exception e) {
                LOG.log(Level.SEVERE, "Failed to destroy collection " + collection, e);
            }
        }
    }

    public static void safeClear(final Map<?, ?> map) {
        if (map != null) {
            try {
                map.clear();
            } catch (Exception e) {
                LOG.log(Level.SEVERE, "Failed to destroy map " + map, e);
            }
        }
    }
}


text:
package pm;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

public class SystemConfig {

	static Logger logger = Logger.getLogger(SystemConfig.class.getName());
	static Properties props = System.getProperties();

	// 请参考: http://www.cnblogs.com/qyf404/p/4833261.html
	static {
		try {
			// ClassLoader.getSystemResourceAsStream("/sysconfig.properties");
			InputStream ins = SystemConfig.class
					.getResourceAsStream("/sysconfig.properties");
			props.load(ins);
			logger.info("System configruration loaded.");
		} catch (Exception e) {
			logger.error("System Configuration Error->", e);
		}
	}

	/**
	 * Returns value of properties with the specified key in system
	 * configuration file.
	 *
	 * @param key
	 * @return
	 */
	public static String getProp(String key) {
		return System.getProperty(key);
	}

	/**
	 * Sets value of properties with the specified key in system
	 * configuration file.
	 *
	 * @param key
	 * @param value
	 * @throws IOException
	 */
	public static void setProp(String key, String value) throws Exception {
		System.setProperty(key, value);
		FileOutputStream fos = new FileOutputStream((new SystemConfig())
				.getClass().getResource("/").getPath()
				+ "sysconfig.properties");
		props.store(fos, value);
		fos.close();
	}

	/**
	 * Returns number value of properties with the specified key in
	 * system configuration file.
	 *
	 * @param key
	 * @return
	 */
	public static int getNumberProp(String key) {
		return Integer.valueOf(System.getProperty(key));
	}
}


text:
define(["require", "exports", "../../patchwork/core/EventDispatcher", "./ConnectionsSelectionGrid", "../event/ConnectionsCanvasEvent"], function (require, exports, EventDispatcher_1, ConnectionsSelectionGrid_1, ConnectionsCanvasEvent_1) {
    "use strict";
    class ConnectionsCanvas extends EventDispatcher_1.default {
        constructor(viewOffset) {
            super();
            this.drawDebugSelectionGrid = false; // draws the connection selection grid
            this.connectionMouseOverIndex = -1;
            this.viewOffset = viewOffset;
            this.connectionSelectionGrid = new ConnectionsSelectionGrid_1.default(10, this.drawDebugSelectionGrid);
            // set canvas references
            this.$canvas = $('.draw-area canvas');
            this.canvas = this.$canvas[0];
            // canvas container (to scale the canvas to)
            this.$container = $('.draw-area');
            // get the context
            this.context = this.canvas.getContext('2d');
            // data for creationg a connection
            this.connectionCreationData = null;
            this.setSize();
            this.clear();
            // resize on browser resize
            $(window).resize(function () {
                this.setSize();
                //this.draw(); TODO fix this stuff with having to give a patch
            }.bind(this));
            this.$canvas.on('mousemove', function (event) {
                // get the index of the connection under the mouse
                var connectionMouseOverIndex = this.connectionSelectionGrid.getConnectionIndexAt(event.clientX, event.clientY);
                // redraw if value differs from currently set value
                if (this.connectionMouseOverIndex !== connectionMouseOverIndex) {
                    this.connectionMouseOverIndex = connectionMouseOverIndex;
                }
            }.bind(this));
            this.$canvas.on('click', function (event) {
                if (this.connectionMouseOverIndex >= 0)
                    this.dispatchEvent(ConnectionsCanvasEvent_1.default.CONNECTION_CLICKED, { connectionIndex: this.connectionMouseOverIndex });
            }.bind(this));
        }
        setSize() {
            this.width = this.$container.outerWidth();
            this.height = this.$container.outerHeight();
            this.$canvas.attr({ width: this.width, height: this.height });
            // create new grid
            this.connectionSelectionGrid.create(this.width, this.height);
        }
        clear() {
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.connectionSelectionGrid.create(this.canvas.width, this.canvas.height);
            //var margin = 10;
            //this.context.fillStyle = "rgba(0,0,0,0.3)";
            //this.context.fillRect(margin, margin, this.canvas.width - 2 * margin, this.canvas.height - 2 * margin);
        }
        draw(patch) {
            if (!patch)
                return;
            this.clear();
            // make a list of x,y points
            var lineObjects = [];
            // add all start/end points of all connections
            var connections = patch.connections; // todo skip creation of connections var
            for (var i = 0; i < connections.length; i++) {
                lineObjects = lineObjects.concat(this.createLineSegments(connections[i], i));
            }
            // then draw all lines
            for (var i = 0; i < lineObjects.length; i++)
                this.drawLine(lineObjects[i]);
            if (this.drawDebugSelectionGrid) {
                this.context.strokeStyle = "rgba(255,255,255,0.5)";
                var gridSize = this.connectionSelectionGrid.gridSize;
                var linesX = Math.floor(this.width / gridSize);
                for (var i = 0; i < linesX; i++) {
                    this.context.beginPath();
                    this.context.moveTo(i * gridSize, 0);
                    this.context.lineTo(i * gridSize, this.height);
                    this.context.stroke();
                }
                var linesY = Math.floor(this.height / gridSize);
                for (var i = 0; i < linesX; i++) {
                    this.context.beginPath();
                    this.context.moveTo(0, i * gridSize);
                    this.context.lineTo(this.width, i * gridSize);
                    this.context.stroke();
                }
                for (var i = 0; i < this.connectionSelectionGrid.locations.length; i++) {
                    this.context.fillStyle = "rgba(0,0,0,1)";
                    var x = 1 + this.connectionSelectionGrid.locations[i].x * gridSize;
                    var y = 1 + this.connectionSelectionGrid.locations[i].y * gridSize;
                    this.context.fillRect(x, y, gridSize - 2, gridSize - 2);
                }
            }
        }
        createLineSegments(connection, index) {
            var segments = [];
            var $output = this.findTransputByModuleIdAndIndex(connection.sourceModule.id, connection.sourceOutputIndex, 'output');
            var $input = this.findTransputByModuleIdAndIndex(connection.destinationModule.id, connection.destinationInputIndex, 'input');
            var transputOutDistanceGrowth = 5;
            var transputOutDistance = 8 + connection.sourceOutputIndex * transputOutDistanceGrowth;
            var transputInDistance = 14 + connection.destinationInputIndex * transputOutDistanceGrowth;
            if ($output[0] && $input[0]) {
                var outputOffset = $output.offset();
                var inputOffset = $input.offset();
                var startX = outputOffset.left + $output.outerWidth();
                var startY = outputOffset.top + 0.5 * $output.outerHeight();
                var endX = inputOffset.left;
                var endY = inputOffset.top + 0.5 * $input.outerHeight();
                // decide where the end is with regard to the start
                var positionMode;
                if (endX - transputInDistance > startX + transputOutDistance) {
                    // end to the right
                    positionMode = 'right';
                }
                else {
                    // end to the left
                    positionMode = 'left';
                }
                // first go a little right, out of the output
                segments.push({
                    fromX: startX,
                    fromY: startY,
                    toX: startX + transputOutDistance,
                    toY: startY,
                    connectionIndex: index
                });
                switch (positionMode) {
                    case 'right':
                        {
                            // end is to the right, most simple case. just move to the correct y first, and then go to end
                            segments.push({
                                fromX: startX + transputOutDistance,
                                fromY: startY,
                                toX: startX + transputOutDistance,
                                toY: endY,
                                connectionIndex: index
                            });
                            segments.push({
                                fromX: startX + transputOutDistance,
                                fromY: endY,
                                toX: endX - transputInDistance,
                                toY: endY,
                                connectionIndex: index
                            });
                            break;
                        }
                    case 'left':
                        {
                            // end is to the left, for now jsut go down halfway, then fully to the left, then final half down
                            segments.push({
                                fromX: startX + transputOutDistance,
                                fromY: startY,
                                toX: startX + transputOutDistance,
                                toY: startY + 0.5 * (endY - startY),
                                connectionIndex: index
                            });
                            segments.push({
                                fromX: startX + transputOutDistance,
                                fromY: startY + 0.5 * (endY - startY),
                                toX: endX - transputInDistance,
                                toY: startY + 0.5 * (endY - startY),
                                connectionIndex: index
                            });
                            segments.push({
                                fromX: endX - transputInDistance,
                                fromY: startY + 0.5 * (endY - startY),
                                toX: endX - transputInDistance,
                                toY: endY,
                                connectionIndex: index
                            });
                            break;
                        }
                    default:
                        {
                            // unhandled cases. just draw a straight line
                            segments.push({
                                fromX: startX + transputOutDistance,
                                fromY: startY,
                                toX: endX - transputInDistance,
                                toY: endY,
                                connectionIndex: index
                            });
                        }
                }
                // final part that goes into the input
                segments.push({
                    fromX: endX - transputInDistance,
                    fromY: endY,
                    toX: endX,
                    toY: endY,
                    connectionIndex: index,
                    end: true
                });
            }
            else {
                console.log('No output or input found!');
            }
            return segments;
        }
        drawWithCreation(patch, mouseX, mouseY) {
            // first do a normal draw
            this.draw(patch);
            // then add the mouse-line. connectionsdata is set before the mouse move listener is added
            if (this.connectionCreationData) {
                var lineObject = { connectionIndex: -1, toX: -1, toY: -1, fromX: -1, fromY: -1 }; // todo
                lineObject.toX = mouseX;
                lineObject.toY = mouseY;
                if (this.connectionCreationData.source) {
                    // drawing from an output
                    var $transputElement = this.findTransputByModuleIdAndIndex(this.connectionCreationData.source.moduleId, this.connectionCreationData.source.transputIndex, 'output');
                }
                else {
                    // drawing from an input
                    var $transputElement = this.findTransputByModuleIdAndIndex(this.connectionCreationData.destination.moduleId, this.connectionCreationData.destination.transputIndex, 'input');
                }
                var transputElementOffset = $transputElement.offset();
                lineObject.fromX = transputElementOffset.left + 0.5 * $transputElement.outerWidth();
                lineObject.fromY = transputElementOffset.top + 0.5 * $transputElement.outerHeight();
                this.drawLine(lineObject);
            }
        }
        drawLine(lineObject) {
            //this.context.strokeStyle = (this.connectionMouseOverIndex !== -1 && this.connectionMouseOverIndex === lineObject.connectionIndex) ? 'red' : 'black';
            this.context.strokeStyle = "#999";
            this.context.lineWidth = 2;
            // convert so we have sharp lines
            // lineObject.fromX = this.convertToCanvasSafeNumber(lineObject.fromX);
            // lineObject.fromY = this.convertToCanvasSafeNumber(lineObject.fromY);
            // lineObject.toX = this.convertToCanvasSafeNumber(lineObject.toX);
            // lineObject.toY = this.convertToCanvasSafeNumber(lineObject.toY);
            this.context.beginPath();
            this.context.moveTo(lineObject.fromX, lineObject.fromY);
            this.context.lineTo(lineObject.toX, lineObject.toY);
            this.context.stroke();
            if (lineObject.end === true) {
                // draw arrow
                var arrowWidth = 12;
                var arrowLength = 10;
                var arrowBack = 2;
                this.context.fillStyle = '#999';
                this.context.beginPath();
                this.context.moveTo(lineObject.toX, lineObject.toY);
                this.context.lineTo(lineObject.toX - arrowLength, lineObject.toY - 0.5 * arrowWidth);
                this.context.lineTo(lineObject.toX - arrowLength + arrowBack, lineObject.toY);
                this.context.lineTo(lineObject.toX - arrowLength, lineObject.toY + 0.5 * arrowWidth);
                this.context.lineTo(lineObject.toX, lineObject.toY);
                this.context.fill();
            }
            // give same coordinates to grid
            this.connectionSelectionGrid.drawLine(lineObject.connectionIndex, lineObject.fromX, lineObject.fromY, lineObject.toX, lineObject.toY);
        }
        convertToCanvasSafeNumberfunction(value) {
            return Math.round(value) + 0.5;
        }
        findTransputByModuleIdAndIndex(moduleId, index, type) {
            var typeClass = type === 'input' ? 'input' : 'output';
            var selector = 'div[data-id="' + moduleId + '"].module .' + typeClass + '[data-index="' + index + '"]';
            return $(selector);
        }
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = ConnectionsCanvas;
});


text:
package vn.tale.architecture.counter.effect;

import io.reactivex.Observable;
import vn.tale.architecture.common.redux.Action;
import vn.tale.architecture.common.redux.Function0;
import vn.tale.architecture.common.redux.Result;
import vn.tale.architecture.common.redux.Effect;
import vn.tale.architecture.counter.CounterState;
import vn.tale.architecture.counter.action.ChangeValueAction;
import vn.tale.architecture.counter.result.ChangeValueResult;

/**
 * Created by Giang Nguyen on 3/24/17.
 */

public class ChangeValueEffect implements Effect<CounterState> {

  @Override public Observable<Result> apply(Observable<Action> action$,
      Function0<CounterState> getState) {
    return action$
        .ofType(ChangeValueAction.class)
        .map(action -> {
          final CounterState uiModel = getState.apply();
          if (action == ChangeValueAction.INCREASE) {
            return ChangeValueResult.make(uiModel.value() + 1);
          } else {
            return ChangeValueResult.make(uiModel.value() - 1);
          }
        });
  }
}


text:
{{showController.note.title}}

Created By: {{showController.note.user || showController.note.user.name}}

Description

{{showController.note.description}}

Content

{{showController.note.content}}


text:
{-# LANGUAGE CPP #-}
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module      :  Data.IntMap.Lazy
-- Copyright   :  (c) Daan Leijen 2002
--                (c) Andriy Palamarchuk 2008
-- License     :  BSD-style
-- Maintainer  :  libraries@haskell.org
-- Stability   :  provisional
-- Portability :  portable
--
-- An efficient implementation of maps from integer keys to values
-- (dictionaries).
--
-- API of this module is strict in the keys, but lazy in the values.
-- If you need value-strict maps, use 'Data.IntMap.Strict' instead.
-- The 'IntMap' type itself is shared between the lazy and strict modules,
-- meaning that the same 'IntMap' value can be passed to functions in
-- both modules (although that is rarely needed).
--
-- These modules are intended to be imported qualified, to avoid name
-- clashes with Prelude functions, e.g.
--
-- >  import Data.IntMap.Lazy (IntMap)
-- >  import qualified Data.IntMap.Lazy as IntMap
--
-- The implementation is based on /big-endian patricia trees/.  This data
-- structure performs especially well on binary operations like 'union'
-- and 'intersection'.  However, my benchmarks show that it is also
-- (much) faster on insertions and deletions when compared to a generic
-- size-balanced map implementation (see "Data.Map").
--
--    * Chris Okasaki and Andy Gill,  \"/Fast Mergeable Integer Maps/\",
--      Workshop on ML, September 1998, pages 77-86,
--      <http://citeseer.ist.psu.edu/okasaki98fast.html>
--
--    * D.R. Morrison, \"/PATRICIA -- Practical Algorithm To Retrieve
--      Information Coded In Alphanumeric/\", Journal of the ACM, 15(4),
--      October 1968, pages 514-534.
--
-- Operation comments contain the operation time complexity in
-- the Big-O notation <http://en.wikipedia.org/wiki/Big_O_notation>.
-- Many operations have a worst-case complexity of /O(min(n,W))/.
-- This means that the operation can become linear in the number of
-- elements with a maximum of /W/ -- the number of bits in an 'Int'
-- (32 or 64).
-----------------------------------------------------------------------------

module Data.IntMap.Lazy (
            -- * Strictness properties
            -- $strictness

            -- * Map type
#if !defined(TESTING)
              IntMap, Key          -- instance Eq,Show
#else
              IntMap(..), Key          -- instance Eq,Show
#endif

            -- * Operators
            , (!), (\\)

            -- * Query
            , IM.null
            , size
            , member
            , notMember
            , IM.lookup
            , findWithDefault
            , lookupLT
            , lookupGT
            , lookupLE
            , lookupGE

            -- * Construction
            , empty
            , singleton

            -- ** Insertion
            , insert
            , insertWith
            , insertWithKey
            , insertLookupWithKey

            -- ** Delete\/Update
            , delete
            , adjust
            , adjustWithKey
            , update
            , updateWithKey
            , updateLookupWithKey
            , alter

            -- * Combine

            -- ** Union
            , union
            , unionWith
            , unionWithKey
            , unions
            , unionsWith

            -- ** Difference
            , difference
            , differenceWith
            , differenceWithKey

            -- ** Intersection
            , intersection
            , intersectionWith
            , intersectionWithKey

            -- ** Universal combining function
            , mergeWithKey

            -- * Traversal
            -- ** Map
            , IM.map
            , mapWithKey
            , traverseWithKey
            , mapAccum
            , mapAccumWithKey
            , mapAccumRWithKey
            , mapKeys
            , mapKeysWith
            , mapKeysMonotonic

            -- * Folds
            , IM.foldr
            , IM.foldl
            , foldrWithKey
            , foldlWithKey
            -- ** Strict folds
            , foldr'
            , foldl'
            , foldrWithKey'
            , foldlWithKey'

            -- * Conversion
            , elems
            , keys
            , assocs
            , keysSet
            , fromSet

            -- ** Lists
            , toList
            , fromList
            , fromListWith
            , fromListWithKey

            -- ** Ordered lists
            , toAscList
            , toDescList
            , fromAscList
            , fromAscListWith
            , fromAscListWithKey
            , fromDistinctAscList

            -- * Filter
            , IM.filter
            , filterWithKey
            , partition
            , partitionWithKey

            , mapMaybe
            , mapMaybeWithKey
            , mapEither
            , mapEitherWithKey

            , split
            , splitLookup

            -- * Submap
            , isSubmapOf, isSubmapOfBy
            , isProperSubmapOf, isProperSubmapOfBy

            -- * Min\/Max
            , findMin
            , findMax
            , deleteMin
            , deleteMax
            , deleteFindMin
            , deleteFindMax
            , updateMin
            , updateMax
            , updateMinWithKey
            , updateMaxWithKey
            , minView
            , maxView
            , minViewWithKey
            , maxViewWithKey

            -- * Debugging
            , showTree
            , showTreeWith
            ) where

import Data.IntMap.Base as IM

-- $strictness
--
-- This module satisfies the following strictness property:
--
-- * Key arguments are evaluated to WHNF
--
-- Here are some examples that illustrate the property:
--
-- > insertWith (\ new old -> old) undefined v m  ==  undefined
-- > insertWith (\ new old -> old) k undefined m  ==  OK
-- > delete undefined m  ==  undefined


text:
package action

import (
	"context"
	"errors"
	"fmt"

	"github.com/fatih/color"
	"github.com/muesli/crunchy"
	"github.com/muesli/goprogressbar"
	"github.com/urfave/cli"
)

// auditedSecret with its name, content a warning message and a pipeline error.
type auditedSecret struct {
	name string

	// the secret's content as a string. Needed for checking for duplicates.
	content string

	// message to the user about some flaw in the secret
	message string

	// real error that something in the pipeline went wrong
	err error
}

// Audit validates passwords against common flaws
func (s *Action) Audit(ctx context.Context, c *cli.Context) error {
	t, err := s.Store.Tree()
	if err != nil {
		return s.exitError(ctx, ExitList, err, "failed to get store tree: %s", err)
	}
	list := t.List(0)

	fmt.Printf("Checking %d secrets. This may take some time ...\n", len(list))

	// Secrets that still need auditing.
	secrets := make(chan string)

	// Secrets that have been audited.
	checked := make(chan auditedSecret)

	// Spawn workers that run the auditing of all secrets concurrently.
	validator := crunchy.NewValidator()
	for jobs := 0; jobs < c.Int("jobs"); jobs++ {
		go s.audit(ctx, validator, secrets, checked)
	}

	go func() {
		for _, secret := range list {
			secrets <- secret
		}
		close(secrets)
	}()

	duplicates := make(map[string][]string)
	messages := make(map[string][]string)
	errors := make(map[string][]string)

	bar := &goprogressbar.ProgressBar{
		Total: int64(len(list)),
		Width: 120,
	}

	i := 0
	for secret := range checked {
		if secret.err != nil {
			errors[secret.err.Error()] = append(errors[secret.err.Error()], secret.name)
		} else {
			duplicates[secret.content] = append(duplicates[secret.content], secret.name)
		}
		if secret.message != "" {
			messages[secret.message] = append(messages[secret.message], secret.name)
		}

		i++
		bar.Current = int64(i)
		bar.Text = fmt.Sprintf("%d of %d secrets checked", bar.Current, bar.Total)
		bar.LazyPrint()

		if i == len(list) {
			break
		}
	}
	close(checked)
	fmt.Println() // Print empty line after the progressbar.

	foundDuplicates := false
	for _, secrets := range duplicates {
		if len(secrets) > 1 {
			foundDuplicates = true

			fmt.Println(color.CyanString("Detected a shared secret for:"))
			for _, secret := range secrets {
				fmt.Println(color.CyanString("\t- %s", secret))
			}
		}
	}
	if !foundDuplicates {
		fmt.Println(color.GreenString("No shared secrets found."))
	}

	foundWeakPasswords := printAuditResults(ctx, messages, "%s:\n", color.CyanString)
	if !foundWeakPasswords {
		fmt.Println(color.GreenString("No weak secrets detected."))
	}
	foundErrors := printAuditResults(ctx, errors, "%s:\n", color.RedString)

	if foundWeakPasswords || foundDuplicates || foundErrors {
		return s.exitError(ctx, ExitAudit, nil, "found weak passwords or duplicates")
	}

	return nil
}

func (s *Action) audit(ctx context.Context, validator *crunchy.Validator, secrets <-chan string, checked chan<- auditedSecret) {
	for secret := range secrets {
		// check for context cancelation
		select {
		case <-ctx.Done():
			checked <- auditedSecret{name: secret, content: "", err: errors.New("user aborted")}
			continue
		default:
		}

		sec, err := s.Store.Get(ctx, secret)
		if err != nil {
			pw := ""
			if sec != nil {
				pw = sec.Password()
			}
			checked <- auditedSecret{name: secret, content: pw, err: err}
			continue
		}

		if err := validator.Check(sec.Password()); err != nil {
			checked <- auditedSecret{name: secret, content: sec.Password(), message: err.Error()}
			continue
		}

		checked <- auditedSecret{name: secret, content: sec.Password()}
	}
}

func printAuditResults(ctx context.Context, m map[string][]string, format string, color func(format string, a ...interface{}) string) bool {
	b := false

	for msg, secrets := range m {
		b = true
		fmt.Print(color(format, msg))
		for _, secret := range secrets {
			fmt.Print(color("\t- %s\n", secret))
		}
	}

	return b
}

func printAuditResult(pw string) {
	validator := crunchy.NewValidator()
	if err := validator.Check(pw); err != nil {
		fmt.Println(color.CyanString(fmt.Sprintf("Warning: %s", err)))
	}
}


text:
package org.sherlok;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.sherlok.utils.Create.list;
import static org.sherlok.utils.Create.map;
import static org.slf4j.LoggerFactory.getLogger;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.ruta.engine.Ruta;
import org.apache.uima.ruta.engine.RutaEngine;
import org.apache.uima.ruta.ontologies.OntoActionExtension;
import org.apache.uima.ruta.type.DebugScriptApply;
import org.junit.Test;
import org.sherlok.mappings.JsonAnnotation;
import org.sherlok.mappings.PipelineDef;
import org.sherlok.mappings.PipelineDef.PipelineOutput;
import org.sherlok.mappings.PipelineDef.PipelineTest.Comparison;
import org.sherlok.mappings.SherlokResult;
import org.sherlok.utils.Create;
import org.sherlok.utils.SherlokTests;
import org.slf4j.Logger;

public class UimaPipelineTest {
    private static Logger LOG = getLogger(UimaPipelineTest.class);

    @Test
    public void testOntologyRuta() throws Exception {
        String document = "A rabbit fights a snake to save her babies and wins in one of nature's most epic battles";
        String script = "Document{->ONTO(\"examples/example_ontology.obo\", DebugScriptApply, \"element\")};\n";

        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put(RutaEngine.PARAM_ADDITIONAL_EXTENSIONS,
                new String[] { OntoActionExtension.class.getName() });
        parameters.put(RutaEngine.PARAM_RESOURCE_PATHS,
                new String[] { "config/resources/" });

        JCas jCas = JCasFactory.createJCas();
        jCas.setDocumentText(document);

        Ruta.apply(jCas.getCas(), script, parameters);

        Collection<DebugScriptApply> dsa = JCasUtil.select(jCas,
                DebugScriptApply.class);
        assertEquals(2, dsa.size());
        for (DebugScriptApply d : dsa) {
            System.out.println(d);
        }
    }

    @Test
    public void testNeuronerNtOBOOntology() throws Exception {

        UimaPipeline pipeline = new PipelineLoader(new Controller().load())
                .resolvePipeline("neuroner", null);
        LOG.debug(pipeline.toString());
        String json = pipeline.annotate("glutamatergic neuron");
        LOG.debug(json);
        SherlokTests.assertEquals(
                map("NeurotransmitterProp",
                        list(new JsonAnnotation()
                                .setBegin(0)
                                .setEnd(13)
                                .addProperty("ontologyId",
                                        "HBP_NEUROTRANSMITTER:0000004"))),
                json, Comparison.exact);
    }

    @Test
    public void testDog() throws Exception {

        UimaPipeline pipeline = new PipelineLoader(new Controller().load())
                .resolvePipeline("01.ruta.annotate.dog", null);
        String json = pipeline.annotate("dog");
        LOG.debug(json);
        SherlokTests.assertEquals(
                map("Dog", list(new JsonAnnotation().setBegin(0).setEnd(3))),
                json, Comparison.exact);
    }

    @Test
    public void testLangdetect() throws Exception {

        UimaPipeline pipeline = new PipelineLoader(new Controller().load())
                .resolvePipeline("langdetect", null);

        String json = pipeline.annotate("C'est vraiment chouette comme truc.");

        List<JsonAnnotation> doc = SherlokResult.parse(json).get(
                "DocumentAnnotation");
        assertEquals("fr", doc.get(0).getProperties().get("language"));
    }

    @Test
    public void testCountries() throws Exception {

        UimaPipeline pipeline = new PipelineLoader(new Controller().load())
                .resolvePipeline("02.ruta.annotate.countries", null);
        String json = (pipeline.annotate("Switzerland"));
        LOG.debug(json);
        SherlokTests.assertEquals(
                map("Country", Create.list(new JsonAnnotation().setBegin(0)
                        .setEnd(11))), json, Comparison.exact);
    }

    @Test
    public void testMaltParser() throws Exception {

        UimaPipeline pipeline = new PipelineLoader(new Controller().load())
                .resolvePipeline("maltparser.en", null);
        String json = (pipeline.annotate("The dog walks on the lake."));
        SherlokResult result = SherlokResult.parse(json);
        LOG.debug(result.toString());
        List<JsonAnnotation> deps = result.get("Dependency");

        assertEquals(6, deps.size());
        JsonAnnotation dep = deps.get(0);
        assertEquals("det", dep.getProperty("DependencyType"));
    }

    @Test
    public void testFiltering() throws Exception {

        List<String> scriptLines = list("ENGINE opennlp.segmenter.en:1.7.0;", //
                "ENGINE opennlp.pos.en:1.7.0;");

        PipelineDef pd = (PipelineDef) new PipelineDef()
                .setScriptLines(scriptLines)
                .setOutput(
                        new PipelineOutput().setAnnotationFilters(list( //
                                "de.tudarmstadt.ukp.dkpro.core.api.metadata.type.TagDescription")))
                .setName("testUseUimaEngines").setVersion("0.1");

        UimaPipeline up = new PipelineLoader(new Controller().load()).load(pd);
        String json = up.annotate("A sample sentence.");
        LOG.debug(json);
        SherlokResult result = SherlokResult.parse(json);

        assertEquals("should have 1 sentence", 1, result.get("Sentence").size());
        assertEquals("should have 4 tokens", 4, result.get("Token").size());
        assertEquals("should have 1 article", 1, result.get("ART").size());
        assertEquals("should have 2 nouns", 2, result.get("NN").size());
        assertEquals("should have 1 punctuation", 1, result.get("PUNC").size());
        assertNull("should have no more TagDescription",
                result.get("TagDescription"));
    }
}


text:
original here: https://github.com/smooch/smooch-bot-example

EstherBot here:
http://estherbot.com

# Build Your Bot

Creating this version will give you a web based chat app. With a few integrations inside of Smooch (like Twilio) you can have your bot talking on other platforms too including SMS, Facebook, and Telegram.

![heroku](/img/heroku.gif)

## Get Started:

1. First, sign up for a free account at [smooch.io](https://app.smooch.io/signup)

1. With a new Smooch app created, go to the settings tab and take note of your App Token. Also, generate a new Secret Key, and take note of the key ID and secret.

    ![settings](/img/settings.png)

1. Deploy your app to Heroku using the button below. It's a service for hosting apps so go sign up if you don't already have an account – it's free. You'll need to specify your app token, key ID, and secret in the app's `SMOOCH_APP_TOKEN`, `SMOOCH_KEY_ID`, and `SMOOCH_SECRET` config settings.

    [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/esthercrawford/estherbot)

1. Your app should now be running on Heroku but you're not quite done yet. Take note of the URL where your heroku app is running, for example `https://foo-bar-4242.herokuapp.com`. You'll need to specify this in your heroku app `SERVICE_URL` config variable. You can do this in the Heroku control panel under *Settings* > *Config Variables*. Make sure to go under Deploy and connect to your GitHub repo. Then, enable Automatic Deploys from the master branch (this means anytime you make an edit to your bot's script, it'll automatically update and talk as intended in seconds.)

1. You should be all set. Open your Heroku app and start chatting with your new bot!

##Teach Your Bot To Talk
Now that you have a bot you need to decide what it'll say. That's where the file script.json comes in. It's the document you need to edit to make your bot talk.

By clicking on the pencil icon you can edit the document. The keywords are on the left, and the bot's response is on the right. For example, if a user types "hello" then the bot will say "Sweet, let's do this..."

Keywords are not case sensitive for users.

The only two keywords you don't want to change are CONNECT ME and DISCONNECT. CONNECT ME turns the automated chat off, so the bot will stop responding to keywords. DISCONNECT will turn the bot back on.

Also, the initial script starts with "So you want to learn about Esther? ..." but of course you'll want to change it. You can edit it in the script.js file.

##Add line breaks to your messages
If you want your bot's responses to be broken into different bubbles you'll need to add \n.
Here's an example: Hi there!\nI'm the personal bot of Esther, a Product Marketer from San Francisco.

Now that message will be broken into two bubbles. First, it'll say "Hi there!" then it'll say "I'm the personal bot of Esther, a Product Marketer from San Francisco."

##Add images to your messages
Adding pictures is super easy. Make sure you upload the files to your img folder. Then click on the image and select Raw to get the link for your image.

Here's an example of the syntax for adding an image:

    Hi there!\nI'm the personal bot of Esther, a Product Marketer from San Francisco.\n![esther](https://raw.githubusercontent.com/esthercrawford/EstherBot/master/img/esther.jpg)

##Add buttons to your messages
On Facebook Messenger these buttons are called "structured messages". It makes it easier for your user to follow the script. They don't even have to type the keywords - they just have to select a button. That means fewer user errors and less frustration.

In the script.json file you'll notice this:

    %[Tweet Esther](http://bit.ly/estherbot-tweet)

This is a smiple link button. When the user taps it, they will open the link in a new browser window.

If you want to have a button trigger your bot to do something, you can use a postback buttons that looks like this:

    %[Tell her](postback:twitter)

The syntax is similar to a link button, but note the `postback:` prefix. The "Tell her" piece is what the button says, and the "twitter" part after the `postback:` prefix is an extra note you can include in the notificaiton your bot receieves when the user taps the button.

⚠ **Note:** Postback buttons work using Smooch webhooks. This means that your bot needs to be deployed to heroku before the buttons will do anything. If you want to test your bot on your local machine you'll have to use a tunnel service such as [ngrok.io](https://ngrok.io) to make your internet visible, and set your local `SERVICE_URL` environment variable appropraitely. For more information bout postbacks, you can check out the Smooch docs here:

- Postbacks: http://docs.smooch.io/#postbacks
- Webhooks: http://docs.smooch.io/rest/#webhooks

The good news is Estherbot is clever, and simplifies much of this! Estherbot [will automatically](https://github.com/esthercrawford/EstherBot/blob/master/heroku/index.js#L113) accept postback events and treat them as if they were a keyword sent by the user. For example, when a user taps a postback button such as `%[Tell her](postback:twitter)` Estherbot will react as if they had typed out the message `Tell her`.

##Bring it altogether
Read the JSON below and you'll see there are line breaks, an image, and 3 buttons in this bot's response.

    {
        "BOT": "Hi there!\nI'm the personal bot of Esther, a Product Marketer from San Francisco.\n![esther](https://raw.githubusercontent.com/esthercrawford/smooch-bot-example/master/img/esther.jpg)\nWant to know more about bots or learn about Esther? %[I'm here for the bot](postback:here_for_the_bot) %[Learn about Esther](postback:learn_about_esther) %[One random fact!](postback:random_fact)"
    }

⚠ **Note:** If you're not familiar with the JSON syntax you can always paste your script into http://jsonlint.com/ to make sure your syntax in order.

##Bonus
Open the Smooch [control panel](https://app.smooch.io) and add more integrations. You can add new user channels like Twilio SMS, or you can add Slack or HipChat which will let you join in on the conversation along side your bot. Pretty neat!

![slack](/img/slack.png)

# Troubleshooting your bot

Is your bot misbehaving? Not working? Here are some steps you can follow to figure out what's going wrong.

**Warning:** command line instructions incoming. You may not be accustomed to using the command line but don't worry, it's much easier than you think.

## Check your bot's logs on heroku

If there's a bug in your code, checking the heroku logs is the best way to figure out what's going wrong. Here's how:

1. Install the heroku toolbelt: https://toolbelt.heroku.com/ These are power tools that let you do a lot more than what Heroku dashboard alone allows.

2. Next, open your preferred terminal app. On OSX the default Terminal app will work fine here.

3. Log in to the heroku toolbelt with the following command:

        heroku login

    If the command heroku isn't found, try restarting your terminal app. Once logged in you should be able to list all of your heroku apps like so:

        heroku apps

    which should give you something like this:

        $ heroku apps
        === My Apps
        your-app

4. Now you can check the logs of your heroku app like so:

        heroku logs -a your-app

    This will give you a dump of your most recent app logs. They will look something like the following. Can you spot the error below?

        2016-05-09T14:08:34.966358+00:00 heroku[slug-compiler]: Slug compilation started
        2016-05-09T14:08:34.966363+00:00 heroku[slug-compiler]: Slug compilation finished
        2016-05-09T14:08:34.946344+00:00 heroku[web.1]: State changed from up to starting
        2016-05-09T14:08:34.945605+00:00 heroku[web.1]: Restarting
        2016-05-09T14:08:37.860802+00:00 heroku[web.1]: Stopping all processes with SIGTERM
        2016-05-09T14:08:39.493078+00:00 heroku[web.1]: Process exited with status 143
        2016-05-09T14:08:41.182450+00:00 heroku[web.1]: Starting process with command `npm start`
        2016-05-09T14:08:45.818995+00:00 app[web.1]:
        2016-05-09T14:08:45.819017+00:00 app[web.1]: > smooch-bot-example@1.0.0 start /app
        2016-05-09T14:08:45.819018+00:00 app[web.1]: > node heroku
        2016-05-09T14:08:45.819019+00:00 app[web.1]:
        2016-05-09T14:08:46.601444+00:00 app[web.1]: module.js:433
        2016-05-09T14:08:46.601454+00:00 app[web.1]:     throw err;
        2016-05-09T14:08:46.601455+00:00 app[web.1]:     ^
        2016-05-09T14:08:46.601456+00:00 app[web.1]:
        2016-05-09T14:08:46.601457+00:00 app[web.1]: SyntaxError: /app/script.json: Unexpected token }
        2016-05-09T14:08:46.601458+00:00 app[web.1]:     at Object.parse (native)
        2016-05-09T14:08:46.601458+00:00 app[web.1]:     at Object.Module._extensions..json (module.js:430:27)
        2016-05-09T14:08:46.601459+00:00 app[web.1]:     at Module.load (module.js:357:32)
        2016-05-09T14:08:46.601460+00:00 app[web.1]:     at Function.Module._load (module.js:314:12)
        2016-05-09T14:08:46.601460+00:00 app[web.1]:     at Module.require (module.js:367:17)
        2016-05-09T14:08:46.601461+00:00 app[web.1]:     at require (internal/module.js:20:19)
        2016-05-09T14:08:46.601462+00:00 app[web.1]:     at Object.<anonymous> (/app/script.js:6:21)
        2016-05-09T14:08:46.601473+00:00 app[web.1]:     at Module._compile (module.js:413:34)
        2016-05-09T14:08:46.601474+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:422:10)
        2016-05-09T14:08:46.601474+00:00 app[web.1]:     at Module.load (module.js:357:32)

    Did you notice the `SyntaxError` part? It looks like there's a problem in my script.json. If I inspect that file in github I'll see that indeed, I have a stray comma at the end if the second to last line.

    ![image](/img/script-error.png)

    After I remove that comma and redeploy, everything will return to normal.

## How do I deploy my fixes to Heroku?

Great question! Now that you've found your bug and fixed it, you want to redeploy your app. With Heroku you can trigger a deployment using git. Without going into detail, git is a code versioning system it's where github gets its name. Git is the software, github.com is a separate company that hosts git code repositories. If you're using a Mac you should already have git installed. Although git is a very complex tool, it's worth [learning if you're eager](https://www.atlassian.com/git/tutorials/what-is-git), but for this guide's purposes we'll be using only the most basic concepts of git, `pull`ing changes from a remote github repository, `commit`ing changes, and then `push`ing those changes out to a remote repository.

1. To deploy using git you first have to download a copy of your heroku app's code, like so:

        git clone https://github.com/your-github-username/your-app

    Note that git will prompt you to enter your github credentials.

2. This will create a new git copy of your code in a new folder. You can go into that folder like so:

        cd your-app

3. Now you can use the heroku toolbelt to link this git copy up to your heroku app with the following command:

        heroku git:remote -a your-app

4. Once that's done, you can now deploy to heroku directly from this directory. If you've made any fixes on github directly, be sure to sync them here like so:

        git pull origin master
        git push heroku master

5. You can also make changes to your local copy of the code. To do this, edit whatever file you wish in your preferred text editor, and then commit and push them up to github. You'll add a commit message, which is a short sentence decribing what you changed.

        git commit -a -m 'Your commit message'
        git push origin master

    Then, you can deploy those changes to heroku in the same way:

        git push heroku master


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-parent</artifactId>
    <version>2.11-SNAPSHOT</version>
    <relativePath>../../parent</relativePath>
  </parent>

  <groupId>org.apache.camel</groupId>
  <artifactId>camel-apns</artifactId>
  <packaging>bundle</packaging>

  <name>Camel :: APNS</name>
  <description>A Camel Apple Push Notification Server Component</description>

  <properties>
    <camel.osgi.export.pkg>org.apache.camel.component.apns.*</camel.osgi.export.pkg>
  </properties>

  <dependencies>

    <!-- Camel -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-core</artifactId>
    </dependency>

    <!-- Apns -->
    <dependency>
      <groupId>com.notnoop.apns</groupId>
      <artifactId>apns</artifactId>
      <version>${java-apns-version}</version>
      <exclusions>
        <exclusion>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-core-asl</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- lets use the same version as in camel-jackson -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>${jackson-version}</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>${jackson-version}</version>
    </dependency>

    <!-- Camel for test -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <!-- Use of Spring for tests -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Logging -->
    <!-- Use logging for test -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- for testing apns -->
    <dependency>
      <groupId>com.notnoop.apns</groupId>
      <artifactId>apns</artifactId>
      <version>${java-apns-version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>

	<plugins>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <forkMode>once</forkMode>
          <forkedProcessTimeoutInSeconds>300</forkedProcessTimeoutInSeconds>
          <excludes>
            <!-- tests may fail on CI servers -->
            <exclude>**/*Test.*</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>

  </build>

</project>


text:
import urllib2
import os
import sys
import time

if len(sys.argv) != 3:
    print "USAGE: fetch_genome.py <genome_id_list> <out_dir>"
    sys.exit(1)

url_template = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=protein&id=%s&rettype=fasta&retmode=text"
# can change rettype to fasta to get just the fasta files &rettype=fasta&retmode=text

if not os.path.exists(sys.argv[2]):
    os.makedirs(sys.argv[2])

for id in open(sys.argv[1]):
    id = id.strip()
    if id == "":
        continue

    sys.stdout.write("Fetching %s..." % id)
    sys.stdout.flush()
    gbk_out_file = os.path.join(sys.argv[2], id + ".fasta")
    if os.path.exists(gbk_out_file):
        print "already fetched"

    open(gbk_out_file, "w").write(urllib2.urlopen(url_template % id).read())
    print "Done"
    time.sleep(1.0/3)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Enum. pl. (Kjbenhavn) 2: 233 (1803)

#### Original name
Uredo angelicae Schumach., 1803

### Remarks
null


text:
Rails engine for static pages.

... but be careful. [Danger!](http://www.youtube.com/watch?v=HD5tnb2RBYg)

## Static pages?

Yeah, like "About us", "Directions", marketing pages, etc.

## Installation

    $ gem install high_voltage

Include in your Gemfile:

```ruby
gem 'high_voltage', '~> 2.3.0`
```

For Rails versions prior to 3.0, use the 0.9.2 tag of high_voltage:

    https://github.com/thoughtbot/high_voltage/tree/v0.9.2

## Usage

Write your static pages and put them in the RAILS_ROOT/app/views/pages directory.

    $ mkdir app/views/pages
    $ touch app/views/pages/about.html.erb

After putting something interesting there, you can link to it from anywhere in your app with:

```ruby
link_to 'About', page_path('about')
```

You can nest pages in a directory structure, if that makes sense from a URL perspective for you:

```ruby
link_to 'Q4 Reports', page_path('about/corporate/policies/HR/en_US/biz/sales/Quarter-Four')
```

Bam.

## Configuration

#### Routing overview

By default, the static page routes will be like /pages/:id (where :id is the view filename).

If you want to route to a static page in another location (for example, a homepage), do this:

```ruby
get 'pages/home' => 'high_voltage/pages#show', id: 'home'
```

In that case, you'd need an `app/views/pages/home.html.erb` file.

Generally speaking, you need to route to the 'show' action with an `:id` param of the view filename.

High Voltage will generate a named route method of `page_path`. If you want to generate
your own named route (with the :as routing option), make sure not to use `:page`
as it will conflict with the High Voltage named route.

#### Specifying a root path

You can configure the root route to a High Voltage page like this:

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.home_page = 'home'
end
```

Which will render the page from `app/views/pages/home.html.erb` when the '/'
route of the site is accessed.

Note: High Voltage also creates a search engine friendly 301 redirect. Any attempt to
access the path '/home' will be redirected to '/'.

#### Top-level routes

You can remove the directory `pages` from the URL path and serve up routes from
the root of the domain path:

    http://www.example.com/about
    http://www.example.com/company

Would look for corresponding files:

    app/views/pages/about.html.erb
    app/views/pages/company.html.erb

This is accomplished by setting the `route_drawer` to `HighVoltage::RouteDrawers::Root`

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.route_drawer = HighVoltage::RouteDrawers::Root
end
```

#### Disabling routes

The default routes can be completely removed by setting the `routes` to `false`:

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.routes = false
end
```

#### Specifying Rails engine for routes

If you are using multiple Rails engines within your application, you can
specify which engine to define the default HighVoltage routes on.

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.parent_engine = MyEngine
end
```

#### Page titles and meta-data

We suggest using `content_for` and `yield` for setting custom page titles and
meta-data on High Voltage pages.

```ruby
# app/views/pages/about.html.erb
<%= content_for :page_title, 'About Us - Custom page title' %>
```

Then print the contents of `:title` into the layout:

```ruby
# app/views/layouts/application.html.erb
<title><%= yield(:page_title) %></title>
```
#### Content path

High Voltage uses a default path and folder of 'pages', i.e. 'url.com/pages/contact',
'app/views/pages'.

You can change this in an initializer:

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.content_path = 'site/'
end
```

#### Caching

Caching has been deprecated and will be removed in the next release.

Page caching and action caching can be done via Rails. Visit the [Caching with
Rails: An overview](http://guides.rubyonrails.org/caching_with_rails.html) guide
for more details. You can utilize the methods described there by overriding the
HighVoltage controller as described [below](#override).

## Override

Most common reasons to override?

  * You need authentication around the pages to make sure a user is signed in.
  * You need to render different layouts for different pages.
  * You need to render a partial from the `app/views/pages` directory.

Create a `PagesController` of your own:

    $ rails generate controller pages

Disable the default routes:

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.routes = false
end
```

Define a route for the new `PagesController`:

```ruby
# config/routes.rb
get "/pages/*id" => 'pages#show', as: :page, format: false

# if routing the root path, update for your controller
root to: 'pages#show', id: 'home'
```

Then modify new `PagesController` to include the High Voltage static page concern:

```ruby
# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  include HighVoltage::StaticPage

  before_filter :authenticate
  layout :layout_for_page

  private

  def layout_for_page
    case params[:id]
    when 'home'
      'home'
    else
      'application'
    end
  end
end
```

To set up a different layout for all High Voltage static pages, use an initializer:

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.layout = 'your_layout'
end
```

## Custom finding

You can further control the algorithm used to find pages by overriding
the `page_finder_factory` method:

```ruby
# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  include HighVoltage::StaticPage

  private

  def page_finder_factory
    Rot13PageFinder
  end
end
```

The easiest thing is to subclass `HighVoltage::PageFinder`, which
provides you with `page_id`:

```ruby
class Rot13PageFinder < HighVoltage::PageFinder
  def find
    paths = super.split('/')
    directory = paths[0..-2]
    filename = paths[-1].tr('a-z','n-za-m')

    File.join(*directory, filename)
  end
end
```

Use this to create a custom file mapping, clean filenames for your file
system, A/B test, and so on.

## Localization

[Rails I18n guides](http://guides.rubyonrails.org/i18n.html).

Add a before filter to the Application controller

```ruby
# app/controllers/application_controller.rb
before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end
```

Disable the default High Voltage routes

```ruby
# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.routes = false
end
```

```ruby
# config/routes.rb
scope "/:locale", locale: /en|bn|hi/ do
  get "/pages/:id" => "high_voltage/pages#show", :as => :page, :format => false
end
```

Add a static page to the project

```
# app/views/pages/about.html.erb
<%= t "hello" %>
```

Make sure that there are corresponding locale files

```
/config/locale/bn.yml
/config/locale/en.yml
/config/locale/hi.yml
```

One last note is there is a [know
issue](https://github.com/thoughtbot/high_voltage/issues/59) with High Voltage.

You'll need to specify routes like this `<%= link_to "About Us", page_path(id:
"about") %>`

## Testing

You can test your static pages using [RSpec](https://github.com/rspec/rspec-rails)
and [shoulda-matchers](https://github.com/thoughtbot/shoulda-matchers):

```ruby
# spec/controllers/pages_controller_spec.rb
describe PagesController, '#show' do
  %w(earn_money screencast about contact).each do |page|
    context 'on GET to /pages/#{page}' do
      before do
        get :show, id: page
      end

      it { should respond_with(:success) }
      it { should render_template(page) }
    end
  end
end
```

If you're not using a custom PagesController be sure to test
`HighVoltage::PagesController` instead.

Enjoy!

## Contributing

Please see [CONTRIBUTING.md].
Thank you, [contributors]!

[CONTRIBUTING.md]: /CONTRIBUTING.md
[contributors]: https://github.com/thoughtbot/high_voltage/graphs/contributors

## License

High Voltage is copyright © 2009-2015 thoughtbot. It is free software, and may
be redistributed under the terms specified in the [`LICENSE`] file.

[`LICENSE`]: /MIT-LICENSE

## About thoughtbot

![thoughtbot](https://thoughtbot.com/logo.png)

High Voltage is maintained and funded by thoughtbot, inc.
The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We love open source software!
See [our other projects][community].
We are [available for hire][hire].

[community]: https://thoughtbot.com/community?utm_source=github
[hire]: https://thoughtbot.com/hire-us?utm_source=github


text:
import requests
# using lxml tree to keep the example short
from lxml import html
from asynchronizer import asynchronize, Wait, setWorkers,a

# to time this script
from datetime import datetime
startTime = datetime.now()

# to set custom number of threads
setWorkers(64)
session = requests.Session()
requests_made = 0
total_requests = 0

# try commenting this decorator out, and notice the effect on the speed
@asynchronize
def extract_title(url):
    global requests_made,total_requests

    r = session.get('https://en.wikipedia.org'+url)
    tree = html.fromstring(r.text)
    try:
        title = tree.xpath('//*[@id="firstHeading"]/text()')[0]
        requests_made += 1
        print 'Requests made: ',requests_made,'/',total_requests,\
        '  Title extracted :',title,'from url',url
    except Exception as e:
        print 'Error parsing url :',url
        total_requests -= 1

# To populate the initial list of urls
r = session.get('https://en.wikipedia.org/wiki/Python_(programming_language)')
tree = html.fromstring(r.text)

# Extract href from all 'a' tags in the div with id 'mw-content-text'
l=[x.xpath('.//@href')[0] for x in tree.xpath('//*[@id="mw-content-text"]//a')]

for url in l:
    # Just a little cleaning to remove invalid urls
    if (':' not in url) and (url[0:6] == '/wiki/' and url[-4:-3] != '.'):
        extract_title(url)
        total_requests += 1

Wait()
# Output the total excecution time
print 'Total Excecution time: ',(datetime.now() - startTime)


text:
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
//  Author(s):
//
//      Atif Aziz, http://www.raboof.com
//
// 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.
//
#endregion

[assembly: Elmah.Scc("$Id$")]

namespace Elmah
{
    #region Imports

    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Web;
    using System.Collections.Generic;

    using IDictionary = System.Collections.IDictionary;

    #endregion

    /// <summary>
    /// HTTP module implementation that posts tweets (short messages
    /// usually limited to 140 characters) about unhandled exceptions in
    /// an ASP.NET Web application to a Twitter account.
    /// </summary>
    /// <remarks>
    /// This module requires that the hosting application has permissions
    /// send HTTP POST requests to another Internet domain.
    /// </remarks>

    public class ErrorTweetModule : HttpModuleBase, IExceptionFiltering
    {
        public event ExceptionFilterEventHandler Filtering;

        private ICredentials _credentials;
        private string _statusFormat;
        private Uri _url;
        private int _maxStatusLength;
        private string _ellipsis;
        private string _formFormat;
        private List<WebRequest> _requests;

        /// <summary>
        /// Initializes the module and prepares it to handle requests.
        /// </summary>

        protected override void OnInit(HttpApplication application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            //
            // Get the configuration section of this module.
            // If it's not there then there is nothing to initialize or do.
            // In this case, the module is as good as mute.
            //

            IDictionary config = (IDictionary) GetConfig();

            if (config == null)
                return;

            string userName = GetSetting(config, "userName", string.Empty);
            string password = GetSetting(config, "password", string.Empty);
            string statusFormat = GetSetting(config, "statusFormat", "{Message}");
            int maxStatusLength = int.Parse(GetSetting(config, "maxStatusLength", "140"), NumberStyles.None, CultureInfo.InvariantCulture);
            string ellipsis = GetSetting(config, "ellipsis", /* ... */ "\x2026");
            string formFormat = GetSetting(config, "formFormat", "status={0}");
            Uri url = new Uri(GetSetting(config, "url", "http://twitter.com/statuses/update.xml"), UriKind.Absolute);

            _credentials = new NetworkCredential(userName, password);
            _statusFormat = statusFormat;
            _url = url;
            _maxStatusLength = maxStatusLength;
            _ellipsis = ellipsis;
            _formFormat = formFormat;
            _requests = new List<WebRequest>();

            application.Error += new EventHandler(OnError);
            ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled);
        }

        /// <summary>
        /// Gets the <see cref="ErrorLog"/> instance to which the module
        /// will log exceptions.
        /// </summary>

        protected virtual ErrorLog GetErrorLog(HttpContext context)
        {
            return ErrorLog.GetDefault(context);
        }

        /// <summary>
        /// The handler called when an unhandled exception bubbles up to
        /// the module.
        /// </summary>

        protected virtual void OnError(object sender, EventArgs args)
        {
            HttpApplication application = (HttpApplication) sender;
            LogException(application.Server.GetLastError(), application.Context);
        }

        /// <summary>
        /// The handler called when an exception is explicitly signaled.
        /// </summary>

        protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args)
        {
            LogException(args.Exception, args.Context);
        }

        /// <summary>
        /// Logs an exception and its context to the error log.
        /// </summary>

        protected virtual void LogException(Exception e, HttpContext context)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            //
            // Fire an event to check if listeners want to filter out
            // logging of the uncaught exception.
            //

            ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context);
            OnFiltering(args);

            if (args.Dismissed)
                return;

            //
            // Tweet away...
            //

            HttpWebRequest request = null;

            try
            {
                string status = StringFormatter.Format(_statusFormat, new Error(e, context));

                //
                // Apply ellipsis if status is too long. If the trimmed
                // status plus ellipsis yields nothing then just use
                // the trimmed status without ellipsis. This can happen if
                // someone gives an ellipsis that is ridiculously long.
                //

                int maxLength = _maxStatusLength;
                if (status.Length > maxLength)
                {
                    string ellipsis = _ellipsis;
                    int trimmedStatusLength = maxLength - ellipsis.Length;
                    status = trimmedStatusLength >= 0
                           ? status.Substring(0, trimmedStatusLength) + ellipsis
                           : status.Substring(0, maxLength);
                }

                //
                // Submit the status by posting form data as typically down
                // by browsers for forms found in HTML.
                //

                request = (HttpWebRequest) WebRequest.Create(_url);
                request.Method = "POST"; // WebRequestMethods.Http.Post;
                request.ContentType = "application/x-www-form-urlencoded";

                if (_credentials != null)   // Need Basic authentication?
                {
                    request.Credentials = _credentials;
                    request.PreAuthenticate = true;
                }

                // See http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx
                request.ServicePoint.Expect100Continue = false;

                //
                // URL-encode status into the form and get the bytes to
                // determine and set the content length.
                //

                string encodedForm = string.Format(_formFormat, HttpUtility.UrlEncode(status));
                byte[] data = Encoding.ASCII.GetBytes(encodedForm);
                Debug.Assert(data.Length > 0);
                request.ContentLength = data.Length;

                //
                // Get the request stream into which the form data is to
                // be written. This is done asynchronously to free up this
                // thread.
                //
                // NOTE: We maintain a (possibly paranoid) list of
                // outstanding requests and add the request to it so that
                // it does not get treated as garbage by GC. In effect,
                // we are creating an explicit root. It is also possible
                // for this module to get disposed before a request
                // completes. During the callback, no other member should
                // be touched except the requests list!
                //

                _requests.Add(request);

                IAsyncResult ar = request.BeginGetRequestStream(
                    new AsyncCallback(OnGetRequestStreamCompleted),
                    AsyncArgs(request, data));
            }
            catch (Exception localException)
            {
                //
                // IMPORTANT! We swallow any exception raised during the
                // logging and send them out to the trace . The idea
                // here is that logging of exceptions by itself should not
                // be  critical to the overall operation of the application.
                // The bad thing is that we catch ANY kind of exception,
                // even system ones and potentially let them slip by.
                //

                OnWebPostError(request, localException);
            }
        }

        private void OnWebPostError(WebRequest request, Exception e)
        {
            Debug.Assert(e != null);
            Trace.WriteLine(e);
            if (request != null) _requests.Remove(request);
        }

        private static object[] AsyncArgs(params object[] args)
        {
            return args;
        }

        private void OnGetRequestStreamCompleted(IAsyncResult ar)
        {
            if (ar == null) throw new ArgumentNullException("ar");
            object[] args = (object[]) ar.AsyncState;
            OnGetRequestStreamCompleted(ar, (WebRequest) args[0], (byte[]) args[1]);
        }

        private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data)
        {
            Debug.Assert(ar != null);
            Debug.Assert(request != null);
            Debug.Assert(data != null);
            Debug.Assert(data.Length > 0);

            try
            {
                using (Stream output = request.EndGetRequestStream(ar))
                    output.Write(data, 0, data.Length);
                request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request);
            }
            catch (Exception e)
            {
                OnWebPostError(request, e);
            }
        }

        private void OnGetResponseCompleted(IAsyncResult ar)
        {
            if (ar == null) throw new ArgumentNullException("ar");
            OnGetResponseCompleted(ar, (WebRequest) ar.AsyncState);
        }

        private void OnGetResponseCompleted(IAsyncResult ar, WebRequest request)
        {
            Debug.Assert(ar != null);
            Debug.Assert(request != null);

            try
            {
                Debug.Assert(request != null);
                request.EndGetResponse(ar).Close(); // Not interested; assume OK
                _requests.Remove(request);
            }
            catch (Exception e)
            {
                OnWebPostError(request, e);
            }
        }

        /// <summary>
        /// Raises the <see cref="Filtering"/> event.
        /// </summary>

        protected virtual void OnFiltering(ExceptionFilterEventArgs args)
        {
            ExceptionFilterEventHandler handler = Filtering;

            if (handler != null)
                handler(this, args);
        }

        /// <summary>
        /// Determines whether the module will be registered for discovery
        /// in partial trust environments or not.
        /// </summary>

        protected override bool SupportDiscoverability
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the configuration object used by <see cref="OnInit"/> to read
        /// the settings for module.
        /// </summary>

        protected virtual object GetConfig()
        {
            return Configuration.GetSubsection("errorTweet");
        }

        private static string GetSetting(IDictionary config, string name, string defaultValue)
        {
            Debug.Assert(config != null);
            Debug.AssertStringNotEmpty(name);

            string value = ((string)config[name]) ?? string.Empty;

            if (value.Length == 0)
            {
                if (defaultValue == null)
                {
                    throw new ApplicationException(string.Format(
                        "The required configuration setting '{0}' is missing for the error tweeting module.", name));
                }

                value = defaultValue;
            }

            return value;
        }
    }
}


text:
package openperipheral.adapter.types;

import openperipheral.api.adapter.IScriptType;

public class BoundedType implements IScriptType {

	public final IScriptType type;

	public final IRange range;

	public BoundedType(IScriptType type, IRange range) {
		this.type = type;
		this.range = range;
	}

	@Override
	public String describe() {
		return type.describe() + range.describe();
	}

}


text:
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.taskrouter.v1.workspace.TaskChannel;

public class ListTaskChannels {
	// Find your Account Sid and Token at twilio.com/user/account
	private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	private static final String AUTH_TOKEN = "your_auth_token";
	private static final String WORKSPACE_SID = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

	public static void main(String[] args) {
		Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

		ResourceSet<TaskChannel> channels = TaskChannel.reader(WORKSPACE_SID).read();

		for (TaskChannel channel : channels) {
			System.out.println(channel.getUniqueName());
		}
	}

}


text:
package com.razorpay;

import org.json.JSONObject;

public class Payment extends Entity {

  public Payment(JSONObject jsonObject) {
    super(jsonObject);
  }
}


text:
<!--
Description: rang
Expect:      feed['title'] == 'testing \u27E9 entity'
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>testing ⟩ entity</title>
</feed>


text:
namespace {

// Returns true if the app was a default app in Chrome 22
bool IsOldDefaultApp(const std::string& extension_id) {
  return extension_id == extension_misc::kGmailAppId ||
         extension_id == extension_misc::kYoutubeAppId;
}

bool IsLocaleSupported() {
  // Don't bother installing default apps in locales where it is known that
  // they don't work.
  // TODO(rogerta): Do this check dynamically once the webstore can expose
  // an API. See http://crbug.com/101357
  const std::string& locale = g_browser_process->GetApplicationLocale();
  static const char* const unsupported_locales[] = {"CN", "TR", "IR"};
  for (size_t i = 0; i < arraysize(unsupported_locales); ++i) {
    if (base::EndsWith(locale, unsupported_locales[i],
                       base::CompareCase::INSENSITIVE_ASCII)) {
      return false;
    }
  }
  return true;
}

}  // namespace

namespace default_apps {

void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterIntegerPref(prefs::kDefaultAppsInstallState, kUnknown);
}

bool Provider::ShouldInstallInProfile() {
  // We decide to install or not install default apps based on the following
  // criteria, from highest priority to lowest priority:
  //
  // - The command line option.  Tests use this option to disable installation
  //   of default apps in some cases.
  // - If the locale is not compatible with the defaults, don't install them.
  // - The kDefaultApps preferences value in the profile.  This value is
  //   usually set in the master_preferences file.
  bool install_apps =
      profile_->GetPrefs()->GetString(prefs::kDefaultApps) == "install";

  InstallState state =
      static_cast<InstallState>(profile_->GetPrefs()->GetInteger(
          prefs::kDefaultAppsInstallState));

  is_migration_ = (state == kProvideLegacyDefaultApps);

  switch (state) {
    case kUnknown: {
      // Only new installations and profiles get default apps. In theory the
      // new profile checks should catch new installations, but that is not
      // always the case (http:/crbug.com/145351).
      bool is_new_profile = profile_->WasCreatedByVersionOrLater(
          version_info::GetVersionNumber());
      bool is_first_run = first_run::IsChromeFirstRun();
      if (!is_first_run && !is_new_profile)
        install_apps = false;
      break;
    }

    // The old default apps were provided as external extensions and were
    // installed everytime Chrome was run. Thus, changing the list of default
    // apps affected all users. Migrate old default apps to new mechanism where
    // they are installed only once as INTERNAL.
    // TODO(grv) : remove after Q1-2013.
    case kProvideLegacyDefaultApps:
      profile_->GetPrefs()->SetInteger(
          prefs::kDefaultAppsInstallState,
          kAlreadyInstalledDefaultApps);
      break;

    case kAlreadyInstalledDefaultApps:
    case kNeverInstallDefaultApps:
      install_apps = false;
      break;
    default:
      NOTREACHED();
  }

  if (install_apps && !IsLocaleSupported())
    install_apps = false;

  // Default apps are only installed on profile creation or a new chrome
  // download.
  if (state == kUnknown) {
    if (install_apps) {
      profile_->GetPrefs()->SetInteger(prefs::kDefaultAppsInstallState,
                                       kAlreadyInstalledDefaultApps);
    } else {
      profile_->GetPrefs()->SetInteger(prefs::kDefaultAppsInstallState,
                                       kNeverInstallDefaultApps);
    }
  }

  return install_apps;
}

Provider::Provider(Profile* profile,
                   VisitorInterface* service,
                   extensions::ExternalLoader* loader,
                   extensions::Manifest::Location crx_location,
                   extensions::Manifest::Location download_location,
                   int creation_flags)
    : extensions::ExternalProviderImpl(service, loader, profile, crx_location,
                                       download_location, creation_flags),
      profile_(profile),
      is_migration_(false) {
  DCHECK(profile);
  set_auto_acknowledge(true);
}

void Provider::VisitRegisteredExtension() {
  if (!profile_ || !ShouldInstallInProfile()) {
    base::DictionaryValue* prefs = new base::DictionaryValue;
    SetPrefs(prefs);
    return;
  }

  extensions::ExternalProviderImpl::VisitRegisteredExtension();
}

void Provider::SetPrefs(base::DictionaryValue* prefs) {
  if (is_migration_) {
    std::set<std::string> new_default_apps;
    for (base::DictionaryValue::Iterator i(*prefs); !i.IsAtEnd(); i.Advance()) {
      if (!IsOldDefaultApp(i.key()))
        new_default_apps.insert(i.key());
    }
    // Filter out the new default apps for migrating users.
    for (std::set<std::string>::iterator it = new_default_apps.begin();
         it != new_default_apps.end(); ++it) {
      prefs->Remove(*it, NULL);
    }
  }

  ExternalProviderImpl::SetPrefs(prefs);
}

}  // namespace default_apps


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _utils = require('../utils/utils.js');

var _ClockHand = require('./ClockHand.js');

var _ClockHand2 = _interopRequireDefault(_ClockHand);

var _ClockFace = require('./ClockFace.js');

var _ClockFace2 = _interopRequireDefault(_ClockFace);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var minutes = (0, _utils.range)(0, 60, 5);
var step = 360 / 60;

var Minutes = function (_Component) {
  _inherits(Minutes, _Component);

  function Minutes() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Minutes);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Minutes.__proto__ || Object.getPrototypeOf(Minutes)).call.apply(_ref, [this].concat(args))), _this), _this.handleHandMove = function (degrees) {
      _this.props.onChange(degrees / step);
    }, _this.handleMouseDown = function (event) {
      _this.refs.hand.mouseStart(event);
    }, _this.handleTouchStart = function (event) {
      _this.refs.hand.touchStart(event);
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Minutes, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(_ClockFace2.default, {
          onTouchStart: this.handleTouchStart,
          onMouseDown: this.handleMouseDown,
          numbers: minutes,
          spacing: this.props.spacing,
          radius: this.props.radius,
          active: this.props.selected,
          theme: this.props.theme,
          twoDigits: true
        }),
        _react2.default.createElement(_ClockHand2.default, { ref: 'hand',
          className: minutes.indexOf(this.props.selected) === -1 ? this.props.theme.small : '',
          angle: this.props.selected * step,
          length: this.props.radius - this.props.spacing,
          onMove: this.handleHandMove,
          origin: this.props.center,
          theme: this.props.theme,
          step: step
        })
      );
    }
  }]);

  return Minutes;
}(_react.Component);

Minutes.propTypes = {
  center: _react.PropTypes.object,
  onChange: _react.PropTypes.func,
  radius: _react.PropTypes.number,
  selected: _react.PropTypes.number,
  spacing: _react.PropTypes.number,
  theme: _react.PropTypes.shape({
    small: _react.PropTypes.string
  })
};
Minutes.defaultProps = {
  selected: 0,
  onChange: null
};
exports.default = Minutes;


text:
using UnityEngine;
using System.Collections;

public class PauseScreen : BaseMenu {

	private GUIStyle titleStyle;
	private GUIStyle buttonStyle;

	private GUIContent titleContent;
	private Vector2 titleDimensions;
	private Rect titleRect;

	private GUIContent resumeGameContent;
	private Vector2 resumeGameDimensions;
	private Rect resumeGameRect;

	private GUIContent quitToMainContent;
	private Vector2 quitToMainDimensions;
	private Rect quitToMainRect;

	// Use this for initialization
	protected override void Start ()
	{
		base.Start ();

		titleContent = new GUIContent ("Game Paused");
		titleDimensions = titleStyle.CalcSize (titleContent);
		titleRect = new Rect((Screen.width - titleDimensions.x)/2,
		                    (Screen.height - titleDimensions.y)/16,
		                    titleDimensions.x,
		                    titleDimensions.y);

		resumeGameContent = new GUIContent ("Resume Game");
		resumeGameDimensions = buttonStyle.CalcSize (resumeGameContent);
		resumeGameRect = new Rect((Screen.width - resumeGameDimensions.x) / 2,
		                         (Screen.height - resumeGameDimensions.y)/2,
		                         resumeGameDimensions.x,
		                         resumeGameDimensions.y);

		quitToMainContent = new GUIContent ("Quit To Main Menu");
		quitToMainDimensions = buttonStyle.CalcSize (quitToMainContent);
		quitToMainRect = new Rect ((Screen.width - quitToMainDimensions.x) / 2 + quitToMainDimensions.x/8,
		                          (Screen.height - quitToMainDimensions.y)/2 + quitToMainDimensions.y,
		                          resumeGameDimensions.x,
		                          resumeGameDimensions.y);
	}

	// Update is called once per frame
	protected override void Update ()
	{
		base.Update();
	}

	public override void OnGUI ()
	{
		GUI.Box (new Rect (0, 0, Screen.width, Screen.height), ""); // Darkens the sprites/images beneath
		GUI.Label (titleRect, titleContent, titleStyle); // Pause title

		// The Resume Game Button
		if (GUI.Button (resumeGameRect, resumeGameContent, buttonStyle))
		{
			Debug.Log("Resuming Game");
			// Resume the game
		}
		// The Quit to Main Menu Button
		if (GUI.Button (quitToMainRect, quitToMainContent, buttonStyle))
		{
			Debug.Log("Quitting to Main Menu");
			// Load MainMenu
		}
	}

	protected override void InitStyles ()
	{
		titleStyle = new GUIStyle (baseLabelStyle);
		titleStyle.fontSize = Mathf.RoundToInt(Screen.height/9f);

		buttonStyle = new GUIStyle (baseButtonStyle);
		buttonStyle.fontSize = Mathf.RoundToInt(Screen.height/15f);
	}

	public override void HandleInputs()
	{
		//
	}
}