text:
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import resize
from skimage import data
from scipy.misc import imresize
import tensorflow as tf
from libs import gif, utils
import IPython.display as ipyd
from datetime import datetime

#np.set_printoptions(threshold=np.inf) # display FULL array (infinite)

plt.ion()

def split_image(img):
    # We'll first collect all the positions in the image in our list, xs
    xs = []

    # And the corresponding colors for each of these positions
    ys = []

    # Now loop over the image
    for row_i in range(img.shape[0]):
        for col_i in range(img.shape[1]):
            # And store the inputs
            xs.append([row_i, col_i])
            # And outputs that the network needs to learn to predict
            ys.append(img[row_i, col_i])

    # we'll convert our lists to arrays
    xs = np.array(xs)
    ys = np.array(ys)
    return xs, ys

def build_model(xs, ys, n_neurons, n_layers, activation_fn,
                final_activation_fn, cost_type):

    xs = np.asarray(xs)
    ys = np.asarray(ys)

    if xs.ndim != 2:
        raise ValueError(
            'xs should be a n_observates x n_features, ' +
            'or a 2-dimensional array.')
    if ys.ndim != 2:
        raise ValueError(
            'ys should be a n_observates x n_features, ' +
            'or a 2-dimensional array.')

    n_xs = xs.shape[1]
    n_ys = ys.shape[1]

    X = tf.placeholder(name='X', shape=[None, n_xs],
                       dtype=tf.float32)
    Y = tf.placeholder(name='Y', shape=[None, n_ys],
                       dtype=tf.float32)

    current_input = X
    for layer_i in range(n_layers):
        current_input = utils.linear(
            current_input, n_neurons,
            activation=activation_fn,
            name='layer{}'.format(layer_i))[0]

    Y_pred = utils.linear(
        current_input, n_ys,
        activation=final_activation_fn,
        name='pred')[0]

    if cost_type == 'l1_norm':
        cost = tf.reduce_mean(tf.reduce_sum(
                tf.abs(Y - Y_pred), 1))
    elif cost_type == 'l2_norm':
        cost = tf.reduce_mean(tf.reduce_sum(
                tf.squared_difference(Y, Y_pred), 1))
    else:
        raise ValueError(
            'Unknown cost_type: {}.  '.format(
            cost_type) + 'Use only "l1_norm" or "l2_norm"')

    return {'X': X, 'Y': Y, 'Y_pred': Y_pred, 'cost': cost}

def train(imgs,
          learning_rate=0.0001,
          batch_size=200,
          n_iterations=10,
          gif_step=2,
          n_neurons=30,
          n_layers=10,
          activation_fn=tf.nn.relu,
          final_activation_fn=tf.nn.tanh,
          cost_type='l2_norm'):

    N, H, W, C = imgs.shape
    all_xs, all_ys = [], []
    for img_i, img in enumerate(imgs):
        xs, ys = split_image(img)
        all_xs.append(np.c_[xs, np.repeat(img_i, [xs.shape[0]])])
        all_ys.append(ys)
    xs = np.array(all_xs).reshape(-1, 3)
    xs = (xs - np.mean(xs, 0)) / np.std(xs, 0)
    ys = np.array(all_ys).reshape(-1, 3)
    ys = ys / 127.5 - 1

    g = tf.Graph()
    with tf.Session(graph=g) as sess:
        model = build_model(xs, ys, n_neurons, n_layers,
                            activation_fn, final_activation_fn,
                            cost_type)
        optimizer = tf.train.AdamOptimizer(
            learning_rate=learning_rate).minimize(model['cost'])
        sess.run(tf.initialize_all_variables())
        gifs = []
        costs = []
        step_i = 0
        for it_i in range(n_iterations):
            # Get a random sampling of the dataset
            idxs = np.random.permutation(range(len(xs)))

            # The number of batches we have to iterate over
            n_batches = len(idxs) // batch_size
            training_cost = 0

            # Now iterate over our stochastic minibatches:
            for batch_i in range(n_batches):

                # Get just minibatch amount of data
                idxs_i = idxs[batch_i * batch_size:
                              (batch_i + 1) * batch_size]

                # And optimize, also returning the cost so we can monitor
                # how our optimization is doing.
                cost = sess.run(
                    [model['cost'], optimizer],
                    feed_dict={model['X']: xs[idxs_i],
                               model['Y']: ys[idxs_i]})[0]
                training_cost += cost

            print('iteration {}/{}: cost {}'.format(
                    it_i + 1, n_iterations, training_cost / n_batches))

            # Also, every 20 iterations, we'll draw the prediction of our
            # input xs, which should try to recreate our image!
            if (it_i + 1) % gif_step == 0:
                costs.append(training_cost / n_batches)
                ys_pred = model['Y_pred'].eval(
                    feed_dict={model['X']: xs}, session=sess)
                img = ys_pred.reshape(imgs.shape)
                gifs.append(img)
        return gifs

import urllib
def get_celeb_files(qfil):
    if not os.path.exists('img_align_celeba'):
        os.mkdir('img_align_celeba')

    for img_i in range(1, qfil+1):

        f = '000%03d.jpg' % img_i

        url = 'https://s3.amazonaws.com/cadl/celeb-align/' + f

        print(url, end='\r')

        urllib.request.urlretrieve(url, os.path.join('img_align_celeba', f))

    files = [os.path.join('img_align_celeba', file_i)
             for file_i in os.listdir('img_align_celeba')
             if '.jpg' in file_i]
    return files[0:qfil]

def get_celeb_imgs(qpic):
    """
    Returns
    -------
    imgs : list of np.ndarray
        List of the first <qpic> images from the celeb dataset
    """
    return [plt.imread(f_i) for f_i in get_celeb_files(qpic)]

#############################################################
#
# MAIN
#

print("Reading images...")
QNT=16
switchcelebs=False
if switchcelebs:
  celeb_imgs = np.array(get_celeb_imgs(QNT))
  plt.figure(figsize=(6, 6))
  print(celeb_imgs)
  print (np.array(celeb_imgs).shape)
  pltdataset=utils.montage(celeb_imgs, saveto="batch2_3_temp_dataset.png").astype(np.uint8)
  plt.imshow(pltdataset)
  plt.imsave(fname='batch2_3_dataset.png', arr=pltdataset)
  trainimgs = np.array(celeb_imgs).copy()
else:
  dirname = "labdogs"
  filenames = [os.path.join(dirname, fname)
            for fname in os.listdir(dirname)]
  filenames = filenames[:QNT]
  assert(len(filenames) == QNT)
  #myimgs = [plt.imread(fname)[..., :3] for fname in filenames]
  myimgs=np.array([plt.imread(fname) for fname in filenames])
  myimgs = [utils.imcrop_tosquare(img_i) for img_i in myimgs]
  myimgs = [resize(img_i, (128,128)) for img_i in myimgs]
  myimgs=np.clip(np.array(myimgs)*255, 0, 255).astype(np.uint8) # fix resize() conversion to 0..1
  pltdataset=utils.montage(myimgs, saveto="batch2_3_temp_dataset.png").astype(np.uint8)
  plt.imshow(pltdataset)
  plt.imsave(fname='batch2_3_dataset.png', arr=pltdataset)
  trainimgs = np.array(myimgs).copy()

plt.show()
plt.pause(1)

print("Training...")
t1 = datetime.now()
trainedgifs = train(imgs=trainimgs, n_iterations=1000, gif_step=50)
t2 = datetime.now()
delta = t2 - t1
print("             Total training time: ", delta.total_seconds())
plt.close()
print("Saving results...")
montage_gifs = [np.clip(utils.montage(
                (m * 127.5) + 127.5, saveto='batch2_3_montage_temp.png'), 0, 255).astype(np.uint8)
                    for m in trainedgifs]
_ = gif.build_gif(montage_gifs, saveto='batch2_3_multiple.gif')

plt.show()
plt.pause(5)
plt.close()

final = trainedgifs[-1]
final_gif = [np.clip(((m * 127.5) + 127.5), 0, 255).astype(np.uint8) for m in final]
gif.build_gif(final_gif, saveto='batch2_3_final.gif')

#plt.imshow(_)
plt.show()
plt.pause(5)
plt.close()

# eop


text:
package edu.usc.pgroup.gml.generator;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import edu.usc.pgroup.gml.generator.Graph.Edge;
import edu.usc.pgroup.gml.generator.Graph.Node;
import static edu.usc.pgroup.gml.generator.GraphConstants.*;

public class GraphTraversal {
	private static final int MIN_SPEED = 25;
	private static final int MAX_SPEED = 65;
	private static Map<Integer, Node> nodesMap;
	private static Map<ReverseEdge, Property> reverseEdgeMap;
	private static Random random = new Random();

	public static void bfsTraversal(Graph graph, List<Object> speedLimitList, List<Object> distance){
		Property reverseProperty;
		float dist;
		int speedLimit;
		nodesMap = graph.getNodes();
		reverseEdgeMap = new HashMap<GraphTraversal.ReverseEdge, GraphTraversal.Property>();
		//Get the start node
		Iterator<Node> iterator = nodesMap.values().iterator();
		//Traverse the graph
		Node currentNode = null;
		List<Edge> outEdges;
		while(iterator.hasNext()){
			currentNode = iterator.next();
			outEdges = currentNode.getEdges();
			for(Edge edge : outEdges){
				if(edge.getEdgePropertiesMap().size() <= 0){
					reverseProperty = reverseEdgeMap.get(new ReverseEdge(edge.getSink(), edge.getSource()));
					if(reverseProperty != null){
						edge.addEdgeProperty(DISTANCE, reverseProperty.getDist());
						edge.addEdgeProperty(SPEED_LIMIT, reverseProperty.getSpeed());
					}else{
						dist = Float.parseFloat(distance.get(random.nextInt(4)).toString());
						speedLimit = getSpeedLimit(edge, speedLimitList, outEdges);
						edge.addEdgeProperty(DISTANCE, dist);
						edge.addEdgeProperty(SPEED_LIMIT, speedLimit);
						reverseEdgeMap.put(new ReverseEdge(edge.getSource(), edge.getSink()), new Property(speedLimit, dist));
					}
				}
			}
		}
	}

	private static int getSpeedLimit(Edge currentEdge, List<Object> speedLimit, List<Edge> outEdges){

		int size = outEdges.size();
		Edge inEdge = null;
		if(size > 0){
			boolean firstIteration = false;
			inEdge = outEdges.get(random.nextInt(outEdges.size()));
			//Select a random edge if current and in edge are same
			while(currentEdge.equals(inEdge)){
				if(firstIteration && size <= 1)
					return (int) speedLimit.get(random.nextInt(4));

				inEdge = outEdges.get(random.nextInt(outEdges.size()));
				firstIteration = true;
			}
		}

		Object property = inEdge.getPropertyValue(SPEED_LIMIT);
		Integer value = property == null ? null : (int) property;
		float rFloat;
		int currentIndex;
		int currentSpeed = 0;
		if(value == null){
			currentSpeed = (int) speedLimit.get(random.nextInt(4));
		}else{
			rFloat = random.nextFloat();
			if(rFloat <= 0.6){
				if(value == MIN_SPEED){
					if(random.nextFloat() <= 0.75){
						currentSpeed = value;
					}else{
						currentSpeed = MAX_SPEED;
					}
				}else if(value == MAX_SPEED){
					if(random.nextFloat() <= 0.75){
						currentSpeed = value;
					}else{
						currentSpeed = MIN_SPEED;
					}
				}else{
					currentSpeed = value;
				}
			}else if(rFloat > 0.6 && rFloat <= 0.8 ){
				currentIndex = speedLimit.indexOf(value);
				if(currentIndex < speedLimit.size() - 1)
					currentSpeed = (int) speedLimit.get(currentIndex + 1);
				else
					currentSpeed = value;
			}else{
				currentIndex = speedLimit.indexOf(value);
				if(currentIndex <= 0)
					currentSpeed = value;
				else
					currentSpeed = (int) speedLimit.get(currentIndex - 1);
			}
		}

		return currentSpeed;
	}

	/**
	 * Reverse Edge class to get the same property value on edges
	 */
	static class ReverseEdge {
		private int source;

		private int sink;

		public ReverseEdge(int source, int sink){
			this.source = source;
			this.sink = sink;
		}

		@Override
		public int hashCode() {
			int hash = 7;
			hash = 31 * hash + source + sink;
			hash = 31 * hash + source * sink;
			return hash;
		}

		@Override
		public boolean equals(Object obj) {
			if(obj == null || getClass() != obj.getClass())
				return false;

			ReverseEdge rEdge = (ReverseEdge) obj;
			return (rEdge.sink == this.sink || rEdge.sink == this.source) && (rEdge.source == this.source || rEdge.source == this.sink);
		}
	}

	static class Property{
		private int speed;
		private float dist;

		public Property(int speed, float dist){
			this.speed = speed;
			this.dist = dist;
		}

		public int getSpeed() {
			return speed;
		}

		public float getDist() {
			return dist;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Bolt;

/**
 * A class for choosing whichever template should be used.
 */
class TemplateChooser
{
    /** @var Config */
    private $config;

    /**
     * Constructor.
     *
     * @param Config $config
     */
    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * Choose a template for the homepage.
     *
     * @param \Bolt\Legacy\Content|\Bolt\Legacy\Content[] $content
     *
     * @return string[]
     */
    public function homepage($content)
    {
        $templates = [];

        // First candidate: Theme-specific config.yml file.
        if ($template = $this->config->get('theme/homepage_template')) {
            $templates[] = $template;
        }

        // Second candidate: Global config.yml file.
        if ($template = $this->config->get('general/homepage_template')) {
            $templates[] = $template;
        }

        if (empty($content)) {
            // Fallback if no content: index.twig
            $templates[] = 'index.twig';
        } elseif (is_array($content)) {
            // Fallback with multiple content: use listing() to choose template
            $first = reset($content);
            $templates = array_merge($templates, $this->listing($first->contenttype));
        } else {
            // Fallback with single content: use record() to choose template
            $templates = array_merge($templates, $this->record($content));
        }

        return $templates;
    }

    /**
     * Choose a template for a single record page, e.g.:
     * - '/page/about'
     * - '/entry/lorum-ipsum'
     *
     * Refactor note: Using a FQCN for the hint here as a `use` statement causes
     * a fatal in the unit tests… 'cause PHP and class_alias() versus namespaces.
     *
     * @param \Bolt\Legacy\Content $record
     * @param array                $data
     *
     * @return string[]
     */
    public function record($record, $data = null)
    {
        $templates = [];

        // First candidate: A legacy Content record has a templateselect field, and it's set.
        if (isset($record->contenttype['fields'])) {
            foreach ($record->contenttype['fields'] as $name => $field) {
                if ($field['type'] == 'templateselect' && !empty($record->values[$name])) {
                    $templates[] = $record->values[$name];
                }
            }
        }

        // Second candidate: An entity has a templateselect field, and it's set.
        if (isset($record->contenttype['fields'])) {
            foreach ($record->contenttype['fields'] as $name => $field) {
                if ($field['type'] == 'templateselect' && !empty($record[$name])) {
                    $templates[] = $record[$name];
                }

                if ($field['type'] == 'templateselect' && $data !== null && !empty($data[$name])) {
                    $templates[] = $data[$name];
                }
            }
        }

        // Third candidate: defined specifically in the contenttype.
        if (isset($record->contenttype['record_template'])) {
            $templates[] = $record->contenttype['record_template'];
        }

        // Fourth candidate: a template with the same filename as the name of
        // the contenttype.
        if (isset($record->contenttype['singular_slug'])) {
            $templates[] = $record->contenttype['singular_slug'] . '.twig';
        }

        // Fifth candidate: Theme-specific config.yml file.
        if ($template = $this->config->get('theme/record_template')) {
            $templates[] = $template;
        }

        // Sixth candidate: global config.yml
        $templates[] = $this->config->get('general/record_template');

        // Seventh candidate: fallback to 'record.twig'
        $templates[] = 'record.twig';

        return $templates;
    }

    /**
     * Select a template for listing pages.
     *
     * @param array $contenttype
     *
     * @return string[]
     */
    public function listing($contenttype)
    {
        $templates = [];

        // First candidate: defined specifically in the contenttype.
        if (!empty($contenttype['listing_template'])) {
            $templates[] = $contenttype['listing_template'];
        }

        // Second candidate: a template with the same filename as the name of
        // the contenttype.
        $templates[] = $contenttype['slug'] . '.twig';

        // Third candidate: Theme-specific config.yml file.
        if ($template = $this->config->get('theme/listing_template')) {
            $templates[] = $template;
        }

        // Fourth candidate: Global config.yml
        $templates[] = $this->config->get('general/listing_template');

        // Fifth candidate: fallback to 'listing.twig'
        $templates[] = 'listing.twig';

        return $templates;
    }

    /**
     * Select a template for taxonomy.
     *
     * @param string $taxonomyslug
     *
     * @return string[]
     */
    public function taxonomy($taxonomyslug)
    {
        $templates = [];

        // First candidate: defined specifically in the taxonomy
        if ($template = $this->config->get('taxonomy/' . $taxonomyslug . '/listing_template')) {
            $templates[] = $template;
        }

        // Second candidate: Theme-specific config.yml file.
        if ($template = $this->config->get('theme/listing_template')) {
            $templates[] = $template;
        }

        // Third candidate: Global config.yml
        $templates[] = $this->config->get('general/listing_template');

        return $templates;
    }

    /**
     * Select a search template.
     *
     * @return string[]
     */
    public function search()
    {
        $templates = [];

        // First candidate: specific search setting in global config.
        if ($template = $this->config->get('theme/search_results_template')) {
            $templates[] = $template;
        }

        // Second candidate: specific search setting in global config.
        if ($template = $this->config->get('general/search_results_template')) {
            $templates[] = $template;
        }

        // Third candidate: listing config setting.
        $templates[] = $this->config->get('general/listing_template');

        return $templates;
    }

    /**
     * Select a template to use for the "maintenance" page.
     *
     * @return string[]
     */
    public function maintenance()
    {
        $templates = [];

        // First candidate: Theme-specific config.
        if ($template = $this->config->get('theme/maintenance_template')) {
            $templates[] = $template;
        }

        // Second candidate: global config.
        $templates[] = $this->config->get('general/maintenance_template');

        return $templates;
    }
}


text:
<resources>
    <string name="app_name">ESS Glass Support Library</string>
    <string name="cam_name">ESS Camera Support Service</string>
</resources>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
	<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
	<meta http-equiv="Content-Language" content="en" />

	<meta http-equiv="X-UA-Compatible" content="IE=edge" />

	<meta name="description" content="AppStorm.JS is a framework for build fast and structured application" />
	<meta name="keywords" content="appstorm, appstorm.js, appstormjs, framework, framework-javascript, javascript, framework-js, js, appstorm-javascript" />
	<meta name="robots" content="index, follow, all" />
    <title>AppStorm.JS / API: a.state.helper.chainer</title>

	<link rel="icon" type="image/png" href="http://appstormjs.com/site/favicon.png" />

    <link rel="stylesheet" href="http://yui.yahooapis.com/3.8.0pr2/build/cssgrids/cssgrids-min.css">
	<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">

API

Classes

a

a.ajax

a.callback.chainer

a.callback.synchronizer

a.console

a.environment

a.eventEmitter

a.form

a.keyboard

a.language

a.loader

a.message

a.page.event

a.page.event.hash

a.page.template

a.parser.json

a.parser.xml

a.state

a.state.helper.chainer

a.state.helper.parameter

a.state.helper.tree

a.state.type

a.storage

a.storage.cookie

a.storage.external

a.storage.memory

a.storage.persistent

a.storage.temporary

a.storage.type.cookie

a.storage.type.flash

a.storage.type.globalStorage

a.storage.type.javafx

a.storage.type.localStorage

a.storage.type.memory

a.storage.type.sessionStorage

a.storage.type.silverlight

a.storage.type.userData

a.timer

Methods On Page

__error

__generateDefaultDataLoader

__generateDefaultLoader

__generateLoader

__generateStartLevelCallback

__parseOptions

__startLevel

__startState

Files

..\framework\appstorm\a.js/

..\framework\appstorm\core\ajax.js/

..\framework\appstorm\core\console.js/

..\framework\appstorm\core\environment.js/

..\framework\appstorm\core\loader.js/

..\framework\appstorm\core\message.js/

..\framework\appstorm\core\parser.js/

..\framework\appstorm\core\timer.js/

..\framework\appstorm\plugin\callback.js/

..\framework\appstorm\plugin\form.js/

..\framework\appstorm\plugin\keyboard.js/

..\framework\appstorm\plugin\language.js/

..\framework\appstorm\plugin\page.js/

..\framework\appstorm\plugin\state.js/

..\framework\appstorm\plugin\storage.js/

Class a.state.helper.chainer

Class defined in: ..\framework\appstorm\plugin\state.js:1180

INTERNAL USE
Release a chain (full state unload, or full state load)

Examples: here

     a.state.helper.chainer( type, path, allowed, id, callback  )

        ..\framework\appstorm\plugin\state.js:1180

    Parameters:

            type <String>

Can be "unload", or "load"

            path <Array>

The path to add or delete

            allowed <Array>

Array of id allowed into system

            id <Integer>

The unique id to be able to control system flow (too long request should be stopped)

            callback <Function>

On full chain finish, the callback called

Methods

     __error( resource, status  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1204

Handle a chain error

    Parameters:

            resource <String>

The uri which fail to load

            status <String>

The error status (like 404)

    Function __generateDefaultDataLoader( name, data, options, internal  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1292

Specific data loading for data parameter

    Parameters:

            name <String | null>

The name to give to data

            data <String>

The data url to load

            options <Object>

The data parameter for calling ajax request

            internal <String>

The hash (internal one with param definition)

Returns: <Function>
The function to use for loading data

     __generateDefaultLoader( fct, uri, extra  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1252

Create a callback function for loader system

    Parameters:

            fct <Function>

The loader function used

            uri <String>

The uri to load

            extra <Function | null>

The extra parsing function (may be needed)

     __generateLoader( state, callback  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1363

From a list of url, load every resource

    Parameters:

            state <Object>

The state object with all needed data inside to perform scan

            callback <Function>

The function to call when load is finished

     __generateStartLevelCallback( level  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1239

start level callback function.
This is used to not have outside scope problem.

    Parameters:

            level <Array>

The current level to perform

     __parseOptions( name, internal, options  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1273

Replace every needed content with data stored

    Parameters:

            name <String | null>

The name to give to data

            internal <String>

The hash (internal one with param definition)

            options <Object>

The data parameter for calling ajax request

     __startLevel( stateList, clb  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1573

Unload a full state level

    Parameters:

            stateList <Array>

A list of state to delete

            clb <Function>

The callback to apply on success (or fail)

     __startState( state, clb  ) /* private method */

        ..\framework\appstorm\plugin\state.js:1496

Start a state chain (unload, or load chain)

    Parameters:

            state <Object>

A state to start

            clb <Function>

The callback to apply on success (or fail)


text:
module RemoteExecutable (remoteExecutable) where

import Control.Distributed.Task.Types.TaskTypes

remoteExecutable :: Task
remoteExecutable = error "example signature for remote executable, not a real implementation"


text:
<?php

namespace Documents\Functional\Ticket\GH683;

use Cloudtek\DynamoDM\Mapping\Annotation as ODM;

/**
 * @ODM\EmbeddedDocument
 * @ODM\Discriminator(
 *     attribute="type",
 *     map={"e1"=EmbeddedSubDocument1::class, "e2"=EmbeddedSubDocument2::class}
 * )
 */
class AbstractEmbedded
{
    /** @ODM\Attribute(type="string") */
    public $name;
}


text:
package com.davidbracewell.hermes.tokenization;

import com.davidbracewell.apollo.ml.sequence.*;
import com.davidbracewell.conversion.Convert;
import com.davidbracewell.function.SerializableFunction;
import com.davidbracewell.guava.common.base.Throwables;
import com.davidbracewell.io.Resources;
import com.davidbracewell.io.resource.Resource;
import lombok.NonNull;

import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author David B. Bracewell
 */
public class CharacterBasedWordSegmenter implements Serializable, Tokenizer {
   private static final long serialVersionUID = 1L;
   private final SequenceLabeler labeler;
   private final SerializableFunction<String, TokenType> tokenClassifier;
   private final SequenceFeaturizer<Character> featurizer;

   public CharacterBasedWordSegmenter(SequenceLabeler labeler, SerializableFunction<String, TokenType> tokenClassifier, SequenceFeaturizer<Character> featurizer) {
      this.labeler = labeler;
      this.tokenClassifier = tokenClassifier;
      this.featurizer = featurizer;
   }

   private Tokenizer.Token createToken(String content, int start, int end, int index) {
      String token = content.substring(start, end);
      return new Tokenizer.Token(token,
                                 tokenClassifier.apply(token),
                                 start,
                                 end,
                                 index
      );
   }

   @Override
   public Iterable<Token> tokenize(String content) {
      Sequence input = featurizer.extractSequence(
         new SequenceInput<>(Convert.convert(content.toCharArray(), List.class, Character.class)).iterator());
      List<Tokenizer.Token> tokens = new ArrayList<>();
      Labeling labeling = labeler.label(input);
      int lastStart = 0;
      int lastEnd = 1;
      for (int i = 0; i < labeling.size(); i++) {
         if (labeling.getLabel(i).equals("true")) {
            lastEnd = i + 1;
            tokens.add(createToken(content, lastStart, lastEnd, tokens.size()));
            lastStart = i + 1;
            lastEnd = -1;
         } else {
            lastEnd = i + 1;
         }
      }

      if (lastEnd != -1) {
         tokens.add(createToken(content, lastStart, lastEnd, tokens.size()));
      }

      return tokens;
   }

   @Override
   public Iterable<Token> tokenize(Reader reader) {
      try {
         String content = Resources.fromReader(reader).readToString();
         return tokenize(content);
      } catch (Exception e) {
         throw Throwables.propagate(e);
      }
   }

   /**
    * Reads the model from the given resource
    *
    * @param modelResource the resource containing the serialized model
    * @return the deserialized model
    * @throws Exception Something went wrong reading the model
    */
   public static CharacterBasedWordSegmenter read(@NonNull Resource modelResource) throws Exception {
      return modelResource.readObject();
   }

   /**
    * Serializes the model to the given resource.
    *
    * @param modelResource the resource to serialize the model to
    * @throws Exception Something went wrong serializing the model
    */
   public void write(@NonNull Resource modelResource) throws Exception {
      modelResource.setIsCompressed(true).writeObject(this);
   }

}// END OF CharacterBasedWordSegmenter


text:
namespace llvm {
class MCContext;
class MCObjectStreamer;
class MCStreamer;
class CodeViewContext;

/// Instances of this class represent the information from a
/// .cv_loc directive.
class MCCVLoc {
  uint32_t FunctionId;
  uint32_t FileNum;
  uint32_t Line;
  uint16_t Column;
  uint16_t PrologueEnd : 1;
  uint16_t IsStmt : 1;

private: // CodeViewContext manages these
  friend class CodeViewContext;
  MCCVLoc(unsigned functionid, unsigned fileNum, unsigned line, unsigned column,
          bool prologueend, bool isstmt)
      : FunctionId(functionid), FileNum(fileNum), Line(line), Column(column),
        PrologueEnd(prologueend), IsStmt(isstmt) {}

  // Allow the default copy constructor and assignment operator to be used
  // for an MCCVLoc object.

public:
  unsigned getFunctionId() const { return FunctionId; }

  /// Get the FileNum of this MCCVLoc.
  unsigned getFileNum() const { return FileNum; }

  /// Get the Line of this MCCVLoc.
  unsigned getLine() const { return Line; }

  /// Get the Column of this MCCVLoc.
  unsigned getColumn() const { return Column; }

  bool isPrologueEnd() const { return PrologueEnd; }
  bool isStmt() const { return IsStmt; }

  void setFunctionId(unsigned FID) { FunctionId = FID; }

  /// Set the FileNum of this MCCVLoc.
  void setFileNum(unsigned fileNum) { FileNum = fileNum; }

  /// Set the Line of this MCCVLoc.
  void setLine(unsigned line) { Line = line; }

  /// Set the Column of this MCCVLoc.
  void setColumn(unsigned column) {
    assert(column <= UINT16_MAX);
    Column = column;
  }

  void setPrologueEnd(bool PE) { PrologueEnd = PE; }
  void setIsStmt(bool IS) { IsStmt = IS; }
};

/// Instances of this class represent the line information for
/// the CodeView line table entries.  Which is created after a machine
/// instruction is assembled and uses an address from a temporary label
/// created at the current address in the current section and the info from
/// the last .cv_loc directive seen as stored in the context.
class MCCVLineEntry : public MCCVLoc {
  const MCSymbol *Label;

private:
  // Allow the default copy constructor and assignment operator to be used
  // for an MCCVLineEntry object.

public:
  // Constructor to create an MCCVLineEntry given a symbol and the dwarf loc.
  MCCVLineEntry(const MCSymbol *Label, const MCCVLoc loc)
      : MCCVLoc(loc), Label(Label) {}

  const MCSymbol *getLabel() const { return Label; }

  // This is called when an instruction is assembled into the specified
  // section and if there is information from the last .cv_loc directive that
  // has yet to have a line entry made for it is made.
  static void Make(MCObjectStreamer *MCOS);
};

/// Information describing a function or inlined call site introduced by
/// .cv_func_id or .cv_inline_site_id. Accumulates information from .cv_loc
/// directives used with this function's id or the id of an inlined call site
/// within this function or inlined call site.
struct MCCVFunctionInfo {
  /// If this represents an inlined call site, then ParentFuncIdPlusOne will be
  /// the parent function id plus one. If this represents a normal function,
  /// then there is no parent, and ParentFuncIdPlusOne will be FunctionSentinel.
  /// If this struct is an unallocated slot in the function info vector, then
  /// ParentFuncIdPlusOne will be zero.
  unsigned ParentFuncIdPlusOne = 0;

  enum : unsigned { FunctionSentinel = ~0U };

  struct LineInfo {
    unsigned File;
    unsigned Line;
    unsigned Col;
  };

  LineInfo InlinedAt;

  /// The section of the first .cv_loc directive used for this function, or null
  /// if none has been seen yet.
  MCSection *Section = nullptr;

  /// Map from inlined call site id to the inlined at location to use for that
  /// call site. Call chains are collapsed, so for the call chain 'f -> g -> h',
  /// the InlinedAtMap of 'f' will contain entries for 'g' and 'h' that both
  /// list the line info for the 'g' call site.
  DenseMap<unsigned, LineInfo> InlinedAtMap;

  /// Returns true if this is function info has not yet been used in a
  /// .cv_func_id or .cv_inline_site_id directive.
  bool isUnallocatedFunctionInfo() const { return ParentFuncIdPlusOne == 0; }

  /// Returns true if this represents an inlined call site, meaning
  /// ParentFuncIdPlusOne is neither zero nor ~0U.
  bool isInlinedCallSite() const {
    return !isUnallocatedFunctionInfo() &&
           ParentFuncIdPlusOne != FunctionSentinel;
  }

  unsigned getParentFuncId() const {
    assert(isInlinedCallSite());
    return ParentFuncIdPlusOne - 1;
  }
};

/// Holds state from .cv_file and .cv_loc directives for later emission.
class CodeViewContext {
public:
  CodeViewContext();
  ~CodeViewContext();

  bool isValidFileNumber(unsigned FileNumber) const;
  bool addFile(MCStreamer &OS, unsigned FileNumber, StringRef Filename,
               ArrayRef<uint8_t> ChecksumBytes, uint8_t ChecksumKind);

  /// Records the function id of a normal function. Returns false if the
  /// function id has already been used, and true otherwise.
  bool recordFunctionId(unsigned FuncId);

  /// Records the function id of an inlined call site. Records the "inlined at"
  /// location info of the call site, including what function or inlined call
  /// site it was inlined into. Returns false if the function id has already
  /// been used, and true otherwise.
  bool recordInlinedCallSiteId(unsigned FuncId, unsigned IAFunc,
                               unsigned IAFile, unsigned IALine,
                               unsigned IACol);

  /// Retreive the function info if this is a valid function id, or nullptr.
  MCCVFunctionInfo *getCVFunctionInfo(unsigned FuncId);

  /// Saves the information from the currently parsed .cv_loc directive
  /// and sets CVLocSeen.  When the next instruction is assembled an entry
  /// in the line number table with this information and the address of the
  /// instruction will be created.
  void setCurrentCVLoc(unsigned FunctionId, unsigned FileNo, unsigned Line,
                       unsigned Column, bool PrologueEnd, bool IsStmt) {
    CurrentCVLoc.setFunctionId(FunctionId);
    CurrentCVLoc.setFileNum(FileNo);
    CurrentCVLoc.setLine(Line);
    CurrentCVLoc.setColumn(Column);
    CurrentCVLoc.setPrologueEnd(PrologueEnd);
    CurrentCVLoc.setIsStmt(IsStmt);
    CVLocSeen = true;
  }

  bool getCVLocSeen() { return CVLocSeen; }
  void clearCVLocSeen() { CVLocSeen = false; }

  const MCCVLoc &getCurrentCVLoc() { return CurrentCVLoc; }

  bool isValidCVFileNumber(unsigned FileNumber);

  /// Add a line entry.
  void addLineEntry(const MCCVLineEntry &LineEntry);

  std::vector<MCCVLineEntry> getFunctionLineEntries(unsigned FuncId);

  std::pair<size_t, size_t> getLineExtent(unsigned FuncId);

  ArrayRef<MCCVLineEntry> getLinesForExtent(size_t L, size_t R);

  /// Emits a line table substream.
  void emitLineTableForFunction(MCObjectStreamer &OS, unsigned FuncId,
                                const MCSymbol *FuncBegin,
                                const MCSymbol *FuncEnd);

  void emitInlineLineTableForFunction(MCObjectStreamer &OS,
                                      unsigned PrimaryFunctionId,
                                      unsigned SourceFileId,
                                      unsigned SourceLineNum,
                                      const MCSymbol *FnStartSym,
                                      const MCSymbol *FnEndSym);

  /// Encodes the binary annotations once we have a layout.
  void encodeInlineLineTable(MCAsmLayout &Layout,
                             MCCVInlineLineTableFragment &F);

  void
  emitDefRange(MCObjectStreamer &OS,
               ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
               StringRef FixedSizePortion);

  void encodeDefRange(MCAsmLayout &Layout, MCCVDefRangeFragment &F);

  /// Emits the string table substream.
  void emitStringTable(MCObjectStreamer &OS);

  /// Emits the file checksum substream.
  void emitFileChecksums(MCObjectStreamer &OS);

  /// Emits the offset into the checksum table of the given file number.
  void emitFileChecksumOffset(MCObjectStreamer &OS, unsigned FileNo);

  /// Add something to the string table.  Returns the final string as well as
  /// offset into the string table.
  std::pair<StringRef, unsigned> addToStringTable(StringRef S);

private:
  /// The current CodeView line information from the last .cv_loc directive.
  MCCVLoc CurrentCVLoc = MCCVLoc(0, 0, 0, 0, false, true);
  bool CVLocSeen = false;

  /// Map from string to string table offset.
  StringMap<unsigned> StringTable;

  /// The fragment that ultimately holds our strings.
  MCDataFragment *StrTabFragment = nullptr;
  bool InsertedStrTabFragment = false;

  MCDataFragment *getStringTableFragment();

  /// Get a string table offset.
  unsigned getStringTableOffset(StringRef S);

  struct FileInfo {
    unsigned StringTableOffset;

    // Indicates if this FileInfo corresponds to an actual file, or hasn't been
    // set yet.
    bool Assigned = false;

    uint8_t ChecksumKind;

    ArrayRef<uint8_t> Checksum;

    // Checksum offset stored as a symbol because it might be requested
    // before it has been calculated, so a fixup may be needed.
    MCSymbol *ChecksumTableOffset;
  };

  /// Array storing added file information.
  SmallVector<FileInfo, 4> Files;

  /// The offset of the first and last .cv_loc directive for a given function
  /// id.
  std::map<unsigned, std::pair<size_t, size_t>> MCCVLineStartStop;

  /// A collection of MCCVLineEntry for each section.
  std::vector<MCCVLineEntry> MCCVLines;

  /// All known functions and inlined call sites, indexed by function id.
  std::vector<MCCVFunctionInfo> Functions;

  /// Indicate whether we have already laid out the checksum table addresses or
  /// not.
  bool ChecksumOffsetsAssigned = false;
};

} // end namespace llvm
#endif


text:
<?php
//
// Copyright (c) 2013, Zynga Inc.
// https://github.com/zynga/saigon
// Author: Matt West (https://github.com/mhwest13)
// License: BSD 2-Clause
//

require HTML_HEADER;
$deployment = $viewData->deployment;
$action = $viewData->action;

$cgName = isset($viewData->contactInfo['contactgroup_name'])?$viewData->contactInfo['contactgroup_name']:'null or incl from template';
$cgAlias = isset($viewData->contactInfo['alias'])?$viewData->contactInfo['alias']:'null or incl from template';

if ((isset($viewData->contactInfo['members'])) && (!empty($viewData->contactInfo['members']))) {
    $cgMembers = implode(',', $viewData->contactInfo['members']);
}
else {
    $cgMembers = null;
}

if ((isset($viewData->contactInfo['contactgroup_members'])) && (!empty($viewData->contactInfo['contactgroup_members']))) {
    $cgGroupMembers = implode(',', $viewData->contactInfo['contactgroup_members']);
}
else {
    $cgGroupMembers = null;
}

?>
<link type="text/css" rel="stylesheet" href="static/css/tables.css" />

<?php
if ($viewData->delFlag === true) {
?>
        Delete Contact Group Information for <?php echo $cgName?> from <?php echo $deployment?>
<?php
} else {
?>
        Contact Group Information for <?php echo $cgName?> in <?php echo $deployment?>
<?php
}
?>

        Name:
        <?php echo $cgName?>

        Alias:
        <?php echo $cgAlias?>

<?php
if ($cgMembers != null) {
?>

        Member(s):
        <?php echo $cgMembers?>

<?php
}
if ($cgGroupMembers != null) {
?>

        Member Group(s):
        <?php echo $cgGroupMembers?>

<?php
}
?>

<?php
if ($viewData->delFlag === true) {
?>
<a href="action.php?controller=contactgrp&action=<?php echo $action?>&deployment=<?php echo $deployment?>&cgName=<?php echo $cgName?>" class="deployBtn">Delete
<a href="action.php?controller=contactgrp&action=stage&deployment=<?php echo $deployment?>" class="deployBtn">Cancel
<?php
} else {
?>
<a href="action.php?controller=contactgrp&action=stage&deployment=<?php echo $deployment?>" class="deployBtn">Contact Groups
<?php
}
?>

<?php

require HTML_FOOTER;


text:
package careerCup;

import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;

/*
 * Link: http://codereview.stackexchange.com/questions/75819/efficiently-squaring-each-element-in-a-sorted-array-keeping-it-sorted
 */
public class _02googleCareerCup {

	public static void main(String[] args) {
		Scanner scanner=new Scanner(new InputStreamReader(System.in));
		String inputStringArray[]="-6,-5,-4,-3,-2,-1,3,5,7".split(",");//scanner.nextLine().split(",");
		scanner.close();
		int inputSortedArray[]=new int[inputStringArray.length];
		for (int i = 0; i < inputSortedArray.length; i++) {
			inputSortedArray[i]=Integer.parseInt(inputStringArray[i]);
		}
		System.out.println(Arrays.toString(inputSortedArray));
		int outputSortedArray[]=squareSorted(inputSortedArray);
		System.out.println(Arrays.toString(outputSortedArray));
	}

	private static int[] squareSorted(int[] inputSortedArray) {
		int sum=inputSortedArray[0],index=0;
		if(sum>=0)
			index=0;
		else{
			index=doSearch(inputSortedArray);
			System.out.println(index);
		}
		return  doMerge(index,inputSortedArray);
	}

	private static int[] doMerge(int index, int[] inputSortedArray) {
		int startIndex=0,endIndex=inputSortedArray.length-1;
		int leftIndex=index-1;
		int rightIndex=index;
		int outputArray[]=new int[inputSortedArray.length];
		int outputIndex=0;
		while(outputIndex<inputSortedArray.length){
			if(leftIndex>=startIndex && rightIndex<=endIndex)
			{
				if(-1*inputSortedArray[leftIndex]<inputSortedArray[rightIndex]){
					outputArray[outputIndex]=(int) Math.pow(inputSortedArray[leftIndex],2);
					outputIndex++;
					leftIndex--;
				}
				else{
					outputArray[outputIndex]=(int) Math.pow(inputSortedArray[rightIndex],2);
					outputIndex++;
					rightIndex++;
				}
			}
			else{
				if(leftIndex>=startIndex)
				{
					outputArray[outputIndex]=(int) Math.pow(inputSortedArray[leftIndex],2);
					outputIndex++;
					leftIndex--;
				}
				else{
					outputArray[outputIndex]=(int) Math.pow(inputSortedArray[rightIndex],2);
					outputIndex++;
					rightIndex++;
				}
			}

		}
		return outputArray;
	}

	private static int doSearch(int[] inputSortedArray) {//change to binary search
		for (int i = 1; i < inputSortedArray.length; i++) {
			if(inputSortedArray[i-1]<0 && inputSortedArray[i]>=0)
				return i;
		}
		return 0;
	}
}


text:
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#import <Foundation/Foundation.h>

/* -----------------------------------------------------------------------------
   Step 1
   Set the UTI types the importer supports

   Modify the CFBundleDocumentTypes entry in Info.plist to contain
   an array of Uniform Type Identifiers (UTI) for the LSItemContentTypes
   that your importer can handle

   ----------------------------------------------------------------------------- */

/* -----------------------------------------------------------------------------
   Step 2
   Implement the GetMetadataForFile function

   Implement the GetMetadataForFile function below to scrape the relevant
   metadata from your document and return it as a CFDictionary using standard keys
   (defined in MDItem.h) whenever possible.
   ----------------------------------------------------------------------------- */

/* -----------------------------------------------------------------------------
   Step 3 (optional)
   If you have defined new attributes, update the schema.xml file

   Edit the schema.xml file to include the metadata keys that your importer returns.
   Add them to the <allattrs> and <displayattrs> elements.

   Add any custom types that your importer requires to the <attributes> element

   <attribute name="com_mycompany_metadatakey" type="CFString" multivalued="true"/>

   ----------------------------------------------------------------------------- */

/* -----------------------------------------------------------------------------
	Get metadata attributes from file

   This function's job is to extract useful information your file format supports
   and return it as a dictionary
   ----------------------------------------------------------------------------- */

Boolean GetMetadataForFile(void* thisInterface,
			   CFMutableDictionaryRef attributes,
			   CFStringRef contentTypeUTI,
			   CFStringRef pathToFile)
{
	/* Pull any available metadata from the file at the specified path */
	/* Return the attribute keys and attribute values in the dict */
	/* Return TRUE if successful, FALSE if there was no data provided */

	Boolean success = NO;
	NSAutoreleasePool *pool;

	pool = [[NSAutoreleasePool alloc] init];

	NSDictionary * book = [NSUnarchiver unarchiveObjectWithFile:(NSString *) pathToFile];

	NSEnumerator * enumerator = [[book allKeys] objectEnumerator];

	NSString * key = nil;
	while (key = [enumerator nextObject])
	{
		NSObject * value = [book valueForKey:key];

		if ([key isEqual:@"authors"])
		{
			value = [(NSString *) value componentsSeparatedByString:@";"];
			key = @"kMDItemAuthors";
		}
		else if ([key isEqual:@"publishPlace"])
			key = @"kMDItemCity";
		else if ([key isEqual:@"summary"])
			key = @"kMDItemComment";
		else if ([key isEqual:@"publishDate"])
			key = @"kMDItemContentCreationDate";
		else if ([key isEqual:@"id"])
			key = @"kMDItemIdentifier";
		else if ([key isEqual:@"title"])
			key = @"kMDItemTitle";
		else if ([key isEqual:@"keywords"])
		{
			value = [(NSString *) value componentsSeparatedByString:@";"];
			key = @"kMDItemKeywords";
		}
		else if ([key isEqual:@"publisher"])
		{
			value = [(NSString *) value componentsSeparatedByString:@";"];
			key = @"kMDItemPublishers";
		}

		[((NSMutableDictionary *) attributes) setValue:value forKey:key];
		success = YES;
	}

	[pool release];

	return success;
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;

namespace WebsitePanel.Portal.VPS
{
    public partial class VdcHome : WebsitePanelModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                searchBox.AddCriteria("ItemName", GetLocalizedString("SearchField.ItemName"));
                searchBox.AddCriteria("Username", GetLocalizedString("SearchField.Username"));
                searchBox.AddCriteria("ExternalIP", GetLocalizedString("SearchField.ExternalIP"));
                searchBox.AddCriteria("IPAddress", GetLocalizedString("SearchField.IPAddress"));
            }
            searchBox.AjaxData = this.GetSearchBoxAjaxData();

            // toggle columns
            bool isUserSelected = PanelSecurity.SelectedUser.Role == WebsitePanel.EnterpriseServer.UserRole.User;
            gvServers.Columns[3].Visible = !isUserSelected;
            gvServers.Columns[4].Visible = !isUserSelected;

            // check package quotas
            bool manageAllowed = VirtualMachinesHelper.IsVirtualMachineManagementAllowed(PanelSecurity.PackageId);

            btnCreate.Visible = manageAllowed;
            btnImport.Visible = (PanelSecurity.EffectiveUser.Role == UserRole.Administrator);
            gvServers.Columns[5].Visible = manageAllowed; // delete column

            // admin operations column
            gvServers.Columns[6].Visible = (PanelSecurity.EffectiveUser.Role == UserRole.Administrator);
        }

        public string GetServerEditUrl(string itemID)
        {
            return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "vps_general",
                    "ItemID=" + itemID);
        }

        public string GetSpaceHomeUrl(string spaceId)
        {
            return EditUrl("SpaceID", spaceId, "");
        }

        public string GetUserHomeUrl(int userId)
        {
            return PortalUtils.GetUserHomePageUrl(userId);
        }

        protected void odsServersPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (e.Exception != null)
            {
                messageBox.ShowErrorMessage("EXCHANGE_GET_MAILBOXES", e.Exception);
                e.ExceptionHandled = true;
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "vdc_create_server"));
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "vdc_import_server"));
        }

        protected void gvServers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteItem")
            {
                // get server ID
                int itemId = Utils.ParseInt(e.CommandArgument.ToString(), 0);

                // go to delete page
                Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "vps_tools_delete",
                    "ItemID=" + itemId));
            }
            else if (e.CommandName == "Detach")
            {
                // remove item from meta base
                int itemId = Utils.ParseInt(e.CommandArgument.ToString(), 0);

                int result = ES.Services.Packages.DetachPackageItem(itemId);
                if (result < 0)
                {
                    ShowResultMessage(result);
                    return;
                }

                // refresh the list
                gvServers.DataBind();
            }
            else if (e.CommandName == "Move")
            {
                // get server ID
                int itemId = Utils.ParseInt(e.CommandArgument.ToString(), 0);

                // go to delete page
                Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "vps_tools_move",
                    "ItemID=" + itemId));
            }
        }

        public string GetSearchBoxAjaxData()
        {
            StringBuilder res = new StringBuilder();
            res.Append("PagedStored: 'VirtualMachines'");
            res.Append(", RedirectUrl: '" + GetServerEditUrl("{0}").Substring(2) + "'");
            res.Append(", PackageID: " + (String.IsNullOrEmpty(Request["SpaceID"]) ? "0" : Request["SpaceID"]));
            res.Append(", Recursive: true");
            res.Append(", VPSTypeID: 'VPS'");
            return res.ToString();
        }
    }
}


text:
<?php

namespace Viteloge\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class VitelogeUserBundle extends Bundle
{

	public function getParent() {
         return 'FOSUserBundle';
        }
}


text:
using DigitalHammer.Testing;
using Xunit;

namespace Nmea.Core0183;

public class NmeaSerialPortSpec
{

    [Fact]
    public void EmptyLinesInBuffer() {
        int counter = 0;
        EmulatedSerialPort port = new EmulatedSerialPort();
        NmeaSerialPort nmea = new NmeaSerialPort(port);
        nmea.SentenceReceived += sentence => { counter++; };
        nmea.Open();
        port.QueueData("$sent1\r\n\r\n$sent2\r\n".ToCharArray());
        counter.ShouldBe(2);
        port.BytesToRead.ShouldBe(0);
        nmea.BufferCount.ShouldBe(0);
        nmea.Close();
    }

    [Fact]
    public void MultipleSentencesInBuffer() {
        int counter = 0;
        EmulatedSerialPort port = new EmulatedSerialPort();
        NmeaSerialPort nmea = new NmeaSerialPort(port);
        nmea.SentenceReceived += sentence => { counter++; };
        nmea.Open();
        port.QueueData("$sent1\r\n$sent2\r\n".ToCharArray());
        counter.ShouldBe(2);
        port.BytesToRead.ShouldBe(0);
        nmea.BufferCount.ShouldBe(0);
        nmea.Close();
    }

    [Fact]
    public void PartialSentenceInBuffer() {
        int counter = 0;
        EmulatedSerialPort port = new EmulatedSerialPort();
        NmeaSerialPort nmea = new NmeaSerialPort(port);
        nmea.SentenceReceived += sentence => { counter++; };
        nmea.Open();
        port.QueueData("$sent1\r\n$sent2\r\n$sent3".ToCharArray());
        counter.ShouldBe(2);
        port.BytesToRead.ShouldBe(0);
        nmea.BufferCount.ShouldBe(6);
        nmea.Close();
    }

    [Fact]
    public void SplitNewlineAcrossTwoReceiveEvents() {
        int counter = 0;
        EmulatedSerialPort port = new EmulatedSerialPort();
        NmeaSerialPort nmea = new NmeaSerialPort(port);
        nmea.SentenceReceived += sentence => { counter++; };
        nmea.Open();
        port.QueueData("$sent1\r".ToCharArray());
        counter.ShouldBe(0);
        port.BytesToRead.ShouldBe(0);
        nmea.BufferCount.ShouldBe(7);
        port.QueueData("\n$sent2\r\n".ToCharArray());
        counter.ShouldBe(2);
        port.BytesToRead.ShouldBe(0);
        nmea.BufferCount.ShouldBe(0);
        nmea.Close();
    }

    [Fact]
    public void StartMidSentence() {
        int counter = 0;
        EmulatedSerialPort port = new EmulatedSerialPort();
        NmeaSerialPort nmea = new NmeaSerialPort(port);
        nmea.SentenceReceived += sentence => { counter++; };
        nmea.Open();
        port.QueueData("nt1\r\n$sent2\r\n".ToCharArray());
        counter.ShouldBe(1);
        port.BytesToRead.ShouldBe(0);
        nmea.BufferCount.ShouldBe(0);
        nmea.Close();
    }

}


text:
A tool to help manage [codebar.io](http://codebar.io) members and events.

[![Build Status](https://travis-ci.org/codebar/planner.png?branch=master)](https://travis-ci.org/codebar/planner)
[![Coverage Status](https://coveralls.io/repos/codebar/planner/badge.png)](https://coveralls.io/r/codebar/planner)
[![Code Climate](https://codeclimate.com/github/codebar/planner.png)](https://codeclimate.com/github/codebar/planner)
[![Dependency Status](https://gemnasium.com/codebar/planner.png)](https://gemnasium.com/codebar/planner)

If you are considering making a PR, please take a look at the Waffle board to see if someone else has already started work on an existing issue.

#### [Waffle board](https://waffle.io/codebar/planner)

#### [We're on Slack!](https://codebar-slack.herokuapp.com)

## Getting started

First thing you will need, is to install Ruby 2.2.2

### Using [rvm](https://rvm.io/rvm/install)

```bash
rvm install 2.2.2
```

### Using [rbenv](https://github.com/sstephenson/rbenv) and [ruby-build](https://github.com/sstephenson/ruby-build)

```bash
rbenv install 2.2.2
rbenv global 2.2.2
```

### Install the gems!

```bash
gem install bundler
bundle install --without production
```

### Setup the database

Adjust `config/database.yml` as needed.

```bash
bundle exec rake db:create
bundle exec rake db:migrate db:test:prepare
```

### Enable GitHub authentication

Create an application at `https://github.com/settings/applications/new` with
`http://localhost:3000` as the `Homepage URL` and `http://localhost:3000/auth/github`
as the `Authorization callback URL`.

Once your development application is setup, create a file named `.env` in the root of the
application folder with the GitHub key and secret like so:

    GITHUB_KEY=YOUR_KEY
    GITHUB_SECRET=YOUR_SECRET

Note: Windows doesn't like creating a file named .env so do the following from a cmd prompt in your application folder:

    echo GITHUB_KEY=YOUR_KEY >> .env
    echo GITHUB_SECRET=YOUR_SECRET >> .env

### Generate some data!

```bash
bundle exec rake db:seed
```

### Run the tests
```bash
bundle exec rake
```

Note: JavaScript acceptance tests are relying on the [Poltergeist](https://github.com/teampoltergeist/poltergeist) driver, which requires
[PhantomJS](http://phantomjs.org). For more information about installing PhantomJS, please take a look
[here](https://github.com/teampoltergeist/poltergeist#installing-phantomjs).

### Find something to work on
You can pick one of the open [issues](https://github.com/codebar/planner/issues), fix a bug, improve the interface, refactor the code or improve test coverage!

If there is something else that you would like to work on, open an issue first so we can discuss it. We are always open to new ideas and ways of improving planner!

[Guidelines on contributing to planner](https://github.com/codebar/planner/blob/master/CONTRIBUTING.md)


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

<TITLE>
PnMessage
</TITLE>

<META NAME="date" CONTENT="2015-06-22">

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

      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.pubnub.api

Class PnMessage

java.lang.Object
  org.json.JSONObject
      com.pubnub.api.PnMessage

public class PnMessage
extends org.json.JSONObject

Pubnub Message Object

Author:

Pubnub

Field Summary

Fields inherited from class org.json.JSONObject

NULL

Constructor Summary

PnMessage()

          Constructor for Pubnub Message Class

PnMessage(PnApnsMessage apnsMsg)

          Constructor for Pubnub Message Class

PnMessage(PnApnsMessage apnsMsg,
          PnGcmMessage gcmMsg)

          Constructor for Pubnub Message Class

PnMessage(PnGcmMessage gcmMsg)

          Constructor for Pubnub Message Class

PnMessage(Pubnub pubnub,
          java.lang.String channel,
          Callback callback)

          Constructor for Pubnub Message Class

PnMessage(Pubnub pubnub,
          java.lang.String channel,
          Callback callback,
          PnApnsMessage apnsMsg)

          Constructor for Pubnub Message Class

PnMessage(Pubnub pubnub,
          java.lang.String channel,
          Callback callback,
          PnApnsMessage apnsMsg,
          PnGcmMessage gcmMsg)

          Constructor for Pubnub Message Class

PnMessage(Pubnub pubnub,
          java.lang.String channel,
          Callback callback,
          PnGcmMessage gcmMsg)

          Constructor for Pubnub Message Class

Method Summary

 Callback
getCallback()

          Getter for callback set on PnMessage object

 java.lang.String
getChannel()

          Getter for channel set on PnMessage Object

 Pubnub
getPubnub()

          Getter for pubnub set on PnMessage object

 void
publish()

          Publish Message

 void
publish(boolean storeInHistory)

          Publish Message

 void
publish(Pubnub pubnub,
        java.lang.String channel,
        boolean storeInHistory,
        Callback callback)

          Publish Message

 void
publish(Pubnub pubnub,
        java.lang.String channel,
        Callback callback)

          Publish Message

 void
setCallback(Callback callback)

          Setter for callback on PnMessage object

 void
setChannel(java.lang.String channel)

          Setter for channel on PnMessage Object

 void
setPubnub(Pubnub pubnub)

          Setter for pubnub on PnMessage object

Methods inherited from class org.json.JSONObject

accumulate, append, doubleToString, get, getBoolean, getDouble, getInt, getJSONArray, getJSONObject, getLong, getNames, getNames, getString, has, increment, isNull, keys, length, names, numberToString, opt, optBoolean, optBoolean, optDouble, optDouble, optInt, optInt, optJSONArray, optJSONObject, optLong, optLong, optString, optString, put, put, put, put, put, put, put, putOnce, putOpt, quote, remove, sortedKeys, stringToValue, toJSONArray, toString, toString, write

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

PnMessage

public PnMessage(Pubnub pubnub,
                 java.lang.String channel,
                 Callback callback)

Constructor for Pubnub Message Class

Parameters:
pubnub - Pubnub object
channel - Channel name
callback - Callback object

PnMessage

public PnMessage()

Constructor for Pubnub Message Class

PnMessage

public PnMessage(PnApnsMessage apnsMsg,
                 PnGcmMessage gcmMsg)

Constructor for Pubnub Message Class

Parameters:
apnsMsg - Pubnub APNS message object
gcmMsg - Pubnub GCM message object

PnMessage

public PnMessage(Pubnub pubnub,
                 java.lang.String channel,
                 Callback callback,
                 PnApnsMessage apnsMsg,
                 PnGcmMessage gcmMsg)

Constructor for Pubnub Message Class

Parameters:
pubnub - Pubnub object
callback - Callback object
apnsMsg - Pubnub APNS message object
gcmMsg - Pubnub GCM message object

PnMessage

public PnMessage(PnGcmMessage gcmMsg)

Constructor for Pubnub Message Class

Parameters:
gcmMsg - Pubnub GCM message object

PnMessage

public PnMessage(Pubnub pubnub,
                 java.lang.String channel,
                 Callback callback,
                 PnGcmMessage gcmMsg)

Constructor for Pubnub Message Class

Parameters:
pubnub - Pubnub
channel - Channel
callback - Callback object
gcmMsg - Pubnub GCM message object

PnMessage

public PnMessage(PnApnsMessage apnsMsg)

Constructor for Pubnub Message Class

Parameters:
apnsMsg - Pubnub APNS message object

PnMessage

public PnMessage(Pubnub pubnub,
                 java.lang.String channel,
                 Callback callback,
                 PnApnsMessage apnsMsg)

Constructor for Pubnub Message Class

Parameters:
pubnub - Pubnub
channel - Channel
callback - Callback object
apnsMsg - Pubnub APNS message object

Method Detail

getChannel

public java.lang.String getChannel()

Getter for channel set on PnMessage Object

Returns:
channel

setChannel

public void setChannel(java.lang.String channel)

Setter for channel on PnMessage Object

Parameters:
channel - Channel name

getCallback

public Callback getCallback()

Getter for callback set on PnMessage object

Returns:
callback

setCallback

public void setCallback(Callback callback)

Setter for callback on PnMessage object

Parameters:
callback - Callback

getPubnub

public Pubnub getPubnub()

Getter for pubnub set on PnMessage object

Returns:
pubnub

setPubnub

public void setPubnub(Pubnub pubnub)

Setter for pubnub on PnMessage object

Parameters:
pubnub - Pubnub object

publish

public void publish(Pubnub pubnub,
                    java.lang.String channel,
                    Callback callback)
             throws PubnubException

Publish Message

Parameters:
pubnub - Pubnub object
channel - Channel
callback - Callback object

Throws:

PubnubException - Exception if either channel or pubnub object is not set

publish

public void publish(Pubnub pubnub,
                    java.lang.String channel,
                    boolean storeInHistory,
                    Callback callback)
             throws PubnubException

Publish Message

Parameters:
pubnub - Pubnub object
channel - Channel
storeInHistory - Store in History
callback - Callback object

Throws:

PubnubException - Exception if either channel or pubnub object is not set

publish

public void publish()
             throws PubnubException

Publish Message

Throws:

PubnubException - Exception if either channel or pubnub object is not set

publish

public void publish(boolean storeInHistory)
             throws PubnubException

Publish Message

Parameters:
storeInHistory - Store in History

Throws:

PubnubException - Exception if either channel or pubnub object is not set

      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<document>
    <properties>
        <title>Apache Synapse - Sample 381</title>
    </properties>

<definitions xmlns="http://ws.apache.org/ns/synapse">

    <proxy name="JMSBinaryProxy" transports="jms">
        <target inSequence="BINARY_CBR_SEQ"/>
    </proxy>

    <sequence name="BINARY_CBR_SEQ">
        <in>
            <log level="full"/>
            <property action="set" name="OUT_ONLY" value="true"/>
            <class name="samples.mediators.BinaryExtractMediator">
                <property name="offset" value="11"/>
                <property name="length" value="4"/>
                <property name="variableName" value="symbol"/>
                <property name="binaryEncoding" value="utf-8"/>
            </class>
            <log level="custom">
                <property name="symbol" expression="get-property('symbol')"/>
            </log>
            <switch source="get-property('symbol')">
                <case regex="GOOG">
                    <send>
                        <endpoint>
                            <address
                                    uri="jms:/dynamicTopics/mdd.GOOG?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
                        </endpoint>
                    </send>
                </case>
                <case regex="MSFT">
                    <send>
                        <endpoint>
                            <address
                                    uri="jms:/dynamicTopics/mdd.MSFT?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
                        </endpoint>
                    </send>
                </case>
                <default/>
            </switch>
        </in>
    </sequence>

</definitions>

            <subsection name="Objective">

                    Demonstrate an advanced content based routing (CBR) scenario using a custom mediator

            </subsection>
            <subsection name="Pre-requisites">

                            Setup and start a JMS broker (Apache ActiveMQ can be used as the
                            JMS broker for this scenario.Refer JMS setup guide for information on
                            how to run ActiveMQ.)

                            Enable the JMS transport receiver and sender of Synapse (Refer JMS setup
                            guide for more details)

                            Start Synapse using the configuration numbered 381 (repository/conf/sample/synapse_sample_381.xml)

                                Unix/Linux: sh synapse.sh -sample 381

                                Windows: synapse.bat -sample 381

            </subsection>
            <subsection name="Executing the Client">

                    In this configuration, a proxy service has been defined to accept incoming JMS
                    messages. JMS messages contain binary payloads. User configures the offset, length,
                    and binary encoding of the text literal that Synapse should use for CBR. Configuration
                    simply routes the messages based on this text to different endpoints.

                    A JMS producer and two instances of a consumer used to demonstrate the CBR functionality.

                    Now run the first consumer using the following command.

ant mddconsumer -Djms_topic=mdd.MSFT

                    Now run the second consumer using the following command.

ant mddconsumer -Djms_topic=mdd.GOOG

                    Now run the market data producer to genenrate market data for symbol 'MSFT' using
                    the following command.

ant mddproducer -Dsymbol=MSFT

                    Now run the market data producer to genenrate market data for symbol 'GOOG' using
                    the following command.

ant mddproducer -Dsymbol=GOOG

                    You will see the below output in the client console(s) based on the symbol.

mddconsumer:
     [java]  Market data recived for symbol : topic://mdd.MSFT
     [java]  Market data recived for symbol : topic://mdd.MSFT

            </subsection>

Back to Catalog

</document>


text:
<?php

namespace Rx\Observable;

use Exception;
use Rx\Disposable\RefCountDisposable;
use Rx\Observer\CallbackObserver;
use Rx\TestCase;

class GroupedObservableTest extends TestCase
{
    /**
     * @test
     */
    public function it_returns_the_disposable_of_the_underlying_disposable()
    {
        $this->markTestSkipped("Disposable is now wrapped by AnonymousObservable. Find other way to test?");
        $disposable = $this->getMock('Rx\DisposableInterface');
        $observable = new AnonymousObservable(function() use (&$disposable) {
            return $disposable;
        });

        $groupedObservable = new GroupedObservable('key', $observable);

        $this->assertEquals($disposable, $groupedObservable->subscribe(new CallbackObserver()));
    }

    /**
     * @test
     */
    public function it_returns_a_composite_disposable_with_the_given_merged_disposable()
    {
        $this->markTestSkipped("Disposable is now wrapped by AnonymousObservable. Find other way to test?");
        $d1 = $this->getMock('Rx\DisposableInterface');
        $d2 = new RefCountDisposable($d1);

        $observable = new AnonymousObservable(function() use (&$d1) {
            return $d1;
        });

        $groupedObservable = new GroupedObservable('key', $observable, $d2);

        $disposable = $groupedObservable->subscribe(new CallbackObserver());
        $this->assertInstanceOf('Rx\Disposable\CompositeDisposable', $disposable);
    }

    /**
     * @test
     */
    public function it_exposes_its_key()
    {
        $observable = new AnonymousObservable(function(){});

        $groupedObservable = new GroupedObservable('key', $observable);
        $this->assertEquals('key', $groupedObservable->getKey());
    }
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/app_restore/app_restore_arc_task_handler.h"

#include "ash/constants/ash_features.h"
#include "chrome/browser/ash/app_restore/app_restore_arc_task_handler_factory.h"
#include "chrome/browser/ash/app_restore/arc_app_launch_handler.h"
#include "chrome/browser/ash/app_restore/arc_window_handler.h"
#include "chrome/browser/ash/app_restore/arc_window_utils.h"
#include "chrome/browser/ash/arc/session/arc_session_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "components/app_restore/app_restore_arc_info.h"

namespace ash {
namespace app_restore {
namespace {

::app_restore::AppRestoreArcInfo* GetAppRestoreArcInfo() {
  return ::app_restore::AppRestoreArcInfo::GetInstance();
}

}  // namespace

// static
AppRestoreArcTaskHandler* AppRestoreArcTaskHandler::GetForProfile(
    Profile* profile) {
  return AppRestoreArcTaskHandlerFactory::GetForProfile(profile);
}

AppRestoreArcTaskHandler::AppRestoreArcTaskHandler(Profile* profile) {
  ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile);
  if (!prefs)
    return;

  arc_prefs_observer_.Observe(prefs);

#if BUILDFLAG(ENABLE_WAYLAND_SERVER)
  if (full_restore::IsArcGhostWindowEnabled())
    window_handler_ = std::make_unique<full_restore::ArcWindowHandler>();
#endif

  if (ash::features::AreDesksTemplatesEnabled()) {
    desks_templates_arc_app_launch_handler_ =
        std::make_unique<ArcAppLaunchHandler>();
  }
  full_restore_arc_app_launch_handler_ =
      std::make_unique<ArcAppLaunchHandler>();

  arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get();
  // arc::ArcSessionManager might not be set in tests.
  if (arc_session_manager)
    arc_session_manager->AddObserver(this);
}

AppRestoreArcTaskHandler::~AppRestoreArcTaskHandler() {
  arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get();
  // arc::ArcSessionManager may be released first.
  if (arc_session_manager)
    arc_session_manager->RemoveObserver(this);
}

void AppRestoreArcTaskHandler::OnTaskCreated(int32_t task_id,
                                             const std::string& package_name,
                                             const std::string& activity,
                                             const std::string& intent,
                                             int32_t session_id) {
  const std::string app_id = ArcAppListPrefs::GetAppId(package_name, activity);
  GetAppRestoreArcInfo()->NotifyTaskCreated(app_id, task_id, session_id);
}

void AppRestoreArcTaskHandler::OnTaskDestroyed(int32_t task_id) {
  GetAppRestoreArcInfo()->NotifyTaskDestroyed(task_id);
}

void AppRestoreArcTaskHandler::OnTaskDescriptionChanged(
    int32_t task_id,
    const std::string& label,
    const arc::mojom::RawIconPngData& icon,
    uint32_t primary_color,
    uint32_t status_bar_color) {
  GetAppRestoreArcInfo()->NotifyTaskThemeColorUpdated(task_id, primary_color,
                                                      status_bar_color);
}

void AppRestoreArcTaskHandler::OnAppConnectionReady() {
#if BUILDFLAG(ENABLE_WAYLAND_SERVER)
  if (window_handler_)
    window_handler_->OnAppInstanceConnected();
#endif

  for (auto* handler : {desks_templates_arc_app_launch_handler(),
                        full_restore_arc_app_launch_handler()}) {
    if (handler)
      handler->OnAppConnectionReady();
  }

  GetAppRestoreArcInfo()->NotifyArcConnectionChanged(
      /*is_connection_ready=*/true);
}

void AppRestoreArcTaskHandler::OnAppConnectionClosed() {
  GetAppRestoreArcInfo()->NotifyArcConnectionChanged(
      /*is_connection_ready=*/false);
}

void AppRestoreArcTaskHandler::OnArcAppListPrefsDestroyed() {
  arc_prefs_observer_.Reset();
}

void AppRestoreArcTaskHandler::OnArcPlayStoreEnabledChanged(bool enabled) {
  for (auto* handler : {desks_templates_arc_app_launch_handler(),
                        full_restore_arc_app_launch_handler()}) {
    if (handler)
      handler->OnArcPlayStoreEnabledChanged(enabled);
  }

  GetAppRestoreArcInfo()->NotifyPlayStoreEnabledChanged(enabled);
}

void AppRestoreArcTaskHandler::OnShelfReady() {
  for (auto* handler : {desks_templates_arc_app_launch_handler(),
                        full_restore_arc_app_launch_handler()}) {
    if (handler)
      handler->OnShelfReady();
  }
}

void AppRestoreArcTaskHandler::Shutdown() {
  desks_templates_arc_app_launch_handler_.reset();
  full_restore_arc_app_launch_handler_.reset();
  window_handler_.reset();
}

}  // namespace app_restore
}  // namespace ash


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RequiredAnnotation.cs" company="Quartz Software SRL">
//   Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
//   Implements the required annotation class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Model.Elements.Annotations
{
    using System.Threading;
    using System.Threading.Tasks;

    using Kephas.Behavior;
    using Kephas.Model.Behaviors;
    using Kephas.Model.Construction;

    /// <summary>
    /// A required annotation.
    /// </summary>
    public class RequiredAnnotation : Annotation, IRequiredBehaviorRule
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RequiredAnnotation"/> class.
        /// </summary>
        /// <param name="constructionContext">Context for the construction.</param>
        /// <param name="name">The name.</param>
        public RequiredAnnotation(IModelConstructionContext constructionContext, string name)
            : base(constructionContext, name)
        {
        }

        /// <summary>
        /// Gets the processing priority.
        /// </summary>
        /// <value>
        /// The processing priority.
        /// </value>
        public int ProcessingPriority { get; } = int.MinValue;

        /// <summary>
        /// Gets a value indicating whether this rule ends the processing flow.
        /// </summary>
        /// <value>
        /// <c>true</c> if this rule ends the processing flow, <c>false</c> if not.
        /// </value>
        public bool IsEndRule { get; } = true;

        /// <summary>
        /// Gets a value asynchronously indicating whether the rule may be applied or not.
        /// </summary>
        /// <param name="context">          The context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A promise of a value indicating whether the rule may be applied or not.
        /// </returns>
        public Task<bool> CanApplyAsync(IInstanceContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            return Task.FromResult(true);
        }

        /// <summary>
        /// Gets the behavior value asynchronously.
        /// </summary>
        /// <param name="context">          The context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A promise of the behavior value.
        /// </returns>
        public Task<IBehaviorValue<bool>> GetValueAsync(IInstanceContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult((IBehaviorValue<bool>)BehaviorValue.True);
        }

        /// <summary>
        /// Gets the behavior value asynchronously.
        /// </summary>
        /// <param name="context">          The context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A promise of the behavior value.
        /// </returns>
        Task<IBehaviorValue> IAsyncBehaviorRule<IInstanceContext>.GetValueAsync(IInstanceContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult((IBehaviorValue)BehaviorValue.True);
        }
    }
}