text:
from behave import *
import os, sys, subprocess, glob

DNF_FLAGS = ['-y', '--disablerepo=*', '--nogpgcheck']
RPM_INSTALL_FLAGS = ['-Uvh']
RPM_ERASE_FLAGS = ['-e']

def _left_decorator(item):
  " Removed packages "
  return u'-' + item

def _right_decorator(item):
  " Installed packages "
  return u'+' + item

def find_pkg(pkg):
  " Find the package file in the repository "
  candidates = glob.glob('/repo/'+pkg+'*.rpm')
  if len(candidates) == 0:
    print("No candidates for: '{0}'".format(pkg))
  assert len(candidates) == 1
  return candidates[0]

def decorate_rpm_packages(pkgs):
  " Converts package names like TestA, TestB into absolute paths "
  return [find_pkg(p) for p in pkgs]

def get_package_list():
  " Gets all installed packages in the system "
  pkgstr = subprocess.check_output(['rpm', '-qa', '--queryformat', '%{NAME}\n'])
  return pkgstr.splitlines()

def diff_package_lists(a, b):
  " Computes both left/right diff between lists `a` and `b` "
  sa, sb = set(a), set(b)
  return (map(_left_decorator, list(sa - sb)),
      map(_right_decorator, list(sb - sa)))

def execute_dnf_command(cmd, reponame):
  " Execute DNF command with default flags and the specified `reponame` enabled "
  flags = DNF_FLAGS + ['--enablerepo={0}'.format(reponame)]
  return subprocess.call(['dnf'] + flags + cmd, stdout=subprocess.PIPE)

def execute_rpm_command(pkg, action):
  " Execute given action over specified pkg(s) "
  if not isinstance(pkg, list):
    pkg = [pkg]
  if action == "remove":
    action = RPM_ERASE_FLAGS
  elif action == "install":
    action = RPM_INSTALL_FLAGS
    pkg = decorate_rpm_packages(pkg)
  return subprocess.call(['rpm'] + action + pkg, stdout=subprocess.PIPE)

def piecewise_compare(a, b):
  " Check if the two sequences are identical regardless of ordering "
  return sorted(a) == sorted(b)

def split(pkg):
  return [p.strip() for p in pkg.split(',')]

@given('I use the repository "{repo}"')
def given_repo_condition(context, repo):
  " :type context: behave.runner.Context "
  assert repo
  assert os.path.exists('/build/' + repo)
  a = [os.remove(p) for p in os.listdir('/repo')]
  subprocess.check_call(['cp -rs /build/' + repo + '/* /repo/'], shell=True)

@when('I "{action}" a package "{pkg}" with "{manager}"')
def when_action_package(context, action, pkg, manager):
  assert action in ["install", "remove"]
  assert manager in ["rpm", "dnf", "pkcon"]
  assert pkg
  context.pre_packages = get_package_list()
  assert context.pre_packages

  if manager == 'rpm':
    context.rc = execute_rpm_command(split(pkg), action)
  elif manager == 'dnf':
    context.rc = execute_dnf_command([action] + split(pkg), 'test')

def _handle_rc(context, rc, negate):
  if negate:
    return rc != context.rc
  return rc == context.rc

@then('the return code should be "{rc}"')
def then_rc_is(context, rc):
  assert _handle_rc(context, rc, False)

@then('the return code should not be "{rc}"')
def then_rc_is_not(context, rc):
  assert _handle_rc(context, rc, True)

@then('package "{pkg}" should be "{state}"')
def then_package_state(context, pkg, state):
  assert state in ["installed", "removed", "absent"]
  assert pkg
  assert context.rc == 0
  pkgs = get_package_list()
  assert pkgs
  removed, installed = diff_package_lists(context.pre_packages, pkgs)
  assert removed != None and installed != None

  for n in split(pkg):
    c = True
    if state == 'installed':
      c = ('+' + n) in installed
      installed.remove('+' + n)
    if state == 'removed':
      c = ('-' + n) in removed
      removed.remove('-' + n)
    if state == 'absent':
      c = ('+' + n) not in installed
      if c:
        c = ('-' + n) not in removed
    if not c:
      raise Exception("Error '{0}' NOT '{1}'".format(n, state))

  ''' This checks that installations/removals are always fully specified,
  so that we always cover the requirements/expecations entirely '''
  if state != 'absent':
    if installed:
      raise Exception("Error '{0}' NOT IN installed".format(', '.join(installed)))
    if removed:
      raise Exception("Error '{0}' NOT IN removed".format(', '.join(removed)))


text:
package process_manager

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"os"
	"path/filepath"
	"strings"
	"syscall"
)

func (pm *ProcessManager) start(executablePath string, args []string, chroot *string) {

	sysprocattr := &syscall.SysProcAttr{
		Setpgid: true,
	}
	if chroot != nil {
		log.Info("Assets: ", AssetNames())
		err := RestoreAsset(*chroot, "super_chroot")
		if err != nil {
			log.Panic("Unable to decompress: ", err)
		}
		args = append([]string{*chroot, executablePath}, args...)
		executablePath = filepath.Join(*chroot, "super_chroot")
	}
	env := os.Environ()

	procattr := &syscall.ProcAttr{
		Sys:   sysprocattr,
		Env:   env,
		Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()},
	}

	if os.Getenv("HOME") == "" {
		wd, err := os.Getwd()
		if err != nil {
			log.Fatal("Could not get current working directory")
		}
		if chroot != nil {
			procattr.Dir = "/"
		} else {
			procattr.Dir = wd
		}
		homevar := fmt.Sprintf("HOME=%s", wd)
		procattr.Env = append(os.Environ(), homevar)
	}
	pathDetected := false
	for idx, val := range procattr.Env {
		splitArray := strings.Split(val, "=")
		if splitArray[0] == "PATH" {
			splitPath := strings.Split(splitArray[1], ":")
			splitPath = append(splitPath, "/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin:/bin", "/usr/games", "/usr/local/games")
			procattr.Env[idx] = fmt.Sprintf("PATH=%s", strings.Join(splitPath, ":"))
			pathDetected = true
			break
		}
	}
	if !pathDetected {
		procattr.Env = append(procattr.Env, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games")
	}
	var err error
	realArgs := append([]string{executablePath}, args...)

	log.Infof("Getting Ready to start process: %v with args: %v and ProcAttr: %+v and %+v", executablePath, realArgs, procattr, sysprocattr)

	pm.pid, err = syscall.ForkExec(executablePath, realArgs, procattr)
	if err != nil {
		log.Panicf("Error starting process %v", err)
	} else {
		log.Infof("Process Manager started to manage %v at PID: %v", executablePath, pm.pid)
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.grapp.soosec.di.modules;

import com.grapp.soosec.common.mvvm.IUIView;
import com.grapp.soosec.di.scopes.ViewScope;

import dagger.Module;
import dagger.Provides;

@Module
public class ViewModule {
    private final IUIView mView;

    public ViewModule(IUIView view) {
        this.mView = view;
    }

    @ViewScope
    @Provides
    IUIView provideView() {
        return mView;
    }
}


text:
{{ $ctrl.title }}

Select Build Configs

        <add-build-config-widget on-add="$ctrl.onAdd(buildConfig)"></add-build-config-widget>

Selected Build Configs

        <remove-build-configs-widget build-configs="$ctrl.buildConfigs" on-remove="$ctrl.onRemove(buildConfig)"></remove-build-configs-widget>

    <button class="btn btn-primary" type="button" ng-click="$ctrl.save()">Save</button>
    <button class="btn btn-default" type="button" ng-click="$ctrl.cancel()">Cancel</button>


text:
/*jshint node:true */

var app;
var async = require('async');
var bunyan = require('bunyan');
var cloud = require('./lib/modules/cloud');
var db;
var errorHandler = require('./lib/use/errorHandler');
var express = require('express');
var fd;
var flash = require('connect-flash');
var fs = require('fs');
var http = require('http');
var levelup = require('levelup');
var moment = require('moment');
var path = require('path');
var ringbuffer = new bunyan.RingBuffer({ limit: 50 });

var MemDOWN = require('memdown');

/*
	Initialize application.
*/
app = express();

app.set('config', require('./config/client/' + app.get('env') + '.json'));
app.set('package', require('./package.json'));

/*
	Jade locals.
*/
app.locals.logLevels = {
	10: 'TRACE',
	20: 'DEBUG',
	30: 'INFO',
	40: 'WARN',
	50: 'ERROR',
	60: 'FATAL'
};
app.locals.logs = function () {
	var level = app.get('env') === 'production' ? bunyan.resolveLevel('info') : bunyan.resolveLevel('trace');
	var logs = [];

	for (var i = ringbuffer.records.length - 1; i >= 0 && i > ringbuffer.records.length - 11; i--) {
		if (ringbuffer.records[i].level >= level) logs.push({
			level: ringbuffer.records[i].level,
			msg: ringbuffer.records[i].msg,
			object: ringbuffer.records[i],
			time: ringbuffer.records[i].time
		});
	}
	return logs;
};
app.locals.moment = moment;
app.locals.version = app.get('package').version;

/*
	Check writable disk state.
*/
try {
	fs.closeSync(fs.openSync(app.get('config').touchFile, 'w'));
	app.set('environmentWritable', true);
} catch (e) {
	app.set('environmentWritable', false);
}

/*
	Services initialization.
*/
async.series({
	/*
		Bunyan logger.
	*/
	logger: function (next) {
		// Log only to a ringbuffer, except in development mode.
		app.log = bunyan.createLogger({
			name: app.get('package').name,
			serializers: bunyan.stdSerializers,
			streams: [
				{
					level: app.get('env') === 'development' ? 'trace' : 'info',
					type: 'raw',
					stream: ringbuffer
				},
				app.get('env') === 'development' ? {
					level: 'trace',
					stream: process.stdout
				} : undefined
			].filter(function (a) {return !!a;})
		});
		app.log.info({
			environment: {
				name: app.get('env'),
				writable: app.get('environmentWritable')
			}
		}, 'Starting up.');
		app.log.trace('Logger initialized.');
		next();
	},
	/*
		Database.
	*/
	database: function (next) {
		if (app.get('environmentWritable')) {
			// In a writable environment, use leveldb on disk.
			levelup('./leveldb', {
				valueEncoding: 'json'
			}, function (e, db) {
				if (e) return next(e);
				app.db = db;
				app.log.trace({
					store: 'LevelDOWN'
				}, 'Level initialized using disk I/O.');
				next();
			});
		} else {
			// In a read-only environment, use MemDOWN ram store instead.
			levelup('', {
				db: MemDOWN,
				valueEncoding: 'json'
			}, function (e, db) {
				if (e) return next(e);
				app.db = db;
				app.log.trace({
					store: 'MemDOWN'
				}, 'Level initialized using volatile RAM.');
				next();
			});
		}
	},
	/*
		Express.
	*/
	express: function (next) {
		app.set('views', __dirname + '/jade');
		app.set('view engine', 'jade');
		app.use(express.compress());
		app.use(express.static(path.join(__dirname, 'public'), {
			// Set cache age to 1 day in production.
			maxAge: app.get('env') === 'production' ? 86400000 : 0
		}));
		app.use(express.urlencoded());
		app.use(express.json());
		app.use(express.cookieParser());
		app.use(express.cookieSession({
			key: 'csid',
			secret: 'nerple'
		}));
		app.use(flash());
		app.use(app.router);
		require('./routes')(app);
		app.use(errorHandler(app));
		app.log.trace('Express initialized.');
		next();
	},
	/*
		Listen.
	*/
	listen: function (next) {
		var server;

		server = http.createServer(app);
		server.on('error', next);
		server.on('listening', next);
		server.listen(app.get('config').listen);
	}
}, function (e) {
	var settings;

	if (e) {
		app.log.error(e, 'Initialization failed.');
		return process.exit(1);
	}
	app.log.info({
		environment: app.get('env'),
		port: app.get('config').listen,
		version: app.get('package').version
	}, 'Client ready.');
	/*
		Review settings file.
	*/
	try {
		settings = require('./config.json');
		app.set('settings', settings);
	} catch (e) {
		app.log.fatal(e, 'Your config.json file is invalid.');
	}
	/*
		Initialize cloud connection.
	*/
	cloud.initialize(app);
});


text:
$(document).ready(function () {
    $('#form_register').on('keyup','#email_register', function (event) {
        event.preventDefault();

        $('p.error').remove();
        $('.form-group').removeClass('has-error');

        var email_reg = $('#email_register').val();

        $.ajax({
            url: 'processes/ajax_validator.php',
            beforeSend: function(){
                var loading = $('');
                $('#email_register').append(loading);
            },
            complete: function(){
                $('span.spinning').remove();
            },
            timeout: 5000,
            type: 'POST',
            dataType: 'json',
            data: {
                email: email_reg
            },
            success: function (data) {
                if(!data.user_available){
                    var error_mesage = $('
The email address is already used.
');
                    $('#email_register').after(error_mesage).closest('.form-group').addClass('has-error');
                } else {
                   // var no_error_mesage = $('
The email address you entered is uniq.
');
                    $('#email_register').closest('.form-group').addClass('has-success');
                }
            },
            error: function () {
                console.log("Error in ajax!");
                var error_mesage = $('
ERROR: Can not connect to server!
');
                $('#email_register').after(error_mesage).closest('.form-group').addClass('has-error');
            }
        });
    });
});


text:
import React, { Component } from 'react';

export default class SearchBar extends Component {
    constructor(props) {
        super(props);

        this.state = { term: '' }
        this.onInputChange = this.onInputChange.bind(this);
    }

    onInputChange(term) {
        this.setState({term})
        this.props.getResults(term);
    }

    render() {
        return (
            <div className='searchBarContainer'>
                <input type='text'
                       value={this.state.term}
                       onChange={event => this.onInputChange(event.target.value)}
                />
            </div>
        )
    }
}

{/*<button><i id="searchIcon" className="fa fa-search" /></button>*/}


text:
{% extends "layout.html" %}
{% load currency_filters %}
{% load i18n %}
{% load reviews_tags %}
{% load display_tags %}

{% block headertext %}
    {% blocktrans with number=order.number %}Order #{{ number }}{% endblocktrans %}
{% endblock %}

{% block content %}
    {% if order.status %}

{% trans 'Status' %}

{{ order.status }}

    {% endif %}

    {% with address=order.shipping_address %}

{% trans 'Shipping address' %}

                {% trans 'Address' %}

                    {% for field in address.active_address_fields %}
                        {{ field }}

                    {% endfor %}

            {% if address.phone_number %}

                    {% trans 'Contact number' %}
                    {{ address.phone_number }}

            {% endif %}
            {% if address.notes %}

                    {% trans 'Notes' %}
                    {{ address.notes }}

            {% endif %}

    {% endwith %}

{% trans 'Shipping method' %}

{{ order.shipping_method }}

{% trans 'Order contents' %}

    {% csrf_token %}

            {% trans 'Product' %}
            {% trans 'Status' %}
            {% trans 'Estimated dispatch date' %}
            {% trans 'Quantity' %}
            {% trans 'Line price excl. tax' %}
            {% trans 'Line price incl. tax' %}
            {% iffeature "reviews" %}

            {% endiffeature %}

        {% for line in order.lines.all %}

                {{ line.description }}
                {{ line.shipping_status|default:"-" }}
                {{ line.est_dispatch_date|default:"-" }}
                {{ line.quantity }}
                {{ line.line_price_before_discounts_excl_tax|currency:order.currency }}
                {{ line.line_price_before_discounts_incl_tax|currency:order.currency }}
                {% iffeature "reviews" %}

                        {% if line.product|is_review_permitted:user %}
                            {% trans 'Write a review' %}
                        {% endif %}

                {% endiffeature %}

        {% endfor %}
        {% for discount in order.discounts.all %}

                {{ discount.description }}
                -{{ discount.amount|currency:order.currency }}

        {% endfor %}

{% trans 'Totals' %}

            {% trans 'Basket total (inc. tax)' %}
            {{ order.basket_total_incl_tax|currency:order.currency }}

            {% trans 'Shipping charge (inc. tax)' %}
            {{ order.shipping_incl_tax|currency:order.currency }}

            {% trans 'Order total' %}
            {{ order.total_incl_tax|currency:order.currency }}

{% endblock content %}


text:
namespace blink {

WebGraphicsContextImpl::WebGraphicsContextImpl(GraphicsContext& graphicsContext, const DisplayItemClientWrapper& client, DisplayItem::Type type)
    : m_graphicsContext(graphicsContext)
    , m_client(client)
    , m_type(type)
#ifndef NDEBUG
    , m_hasBegunDrawing(false)
#endif
{
}

WebGraphicsContextImpl::~WebGraphicsContextImpl()
{
}

WebCanvas* WebGraphicsContextImpl::beginDrawing(const WebFloatRect& bounds)
{
#ifndef NDEBUG
    ASSERT(!m_hasBegunDrawing);
    m_hasBegunDrawing = true;
#endif
    ASSERT(!DrawingRecorder::useCachedDrawingIfPossible(m_graphicsContext, m_client, m_type));
    m_drawingRecorder = adoptPtr(new DrawingRecorder(m_graphicsContext, m_client, m_type, bounds));
    WebCanvas* canvas = m_graphicsContext.canvas();
    ASSERT(canvas);
    return canvas;
}

void WebGraphicsContextImpl::endDrawing()
{
    ASSERT(m_drawingRecorder);
    m_drawingRecorder.clear();
}

} // namespace blink


text:
<?php
namespace Elgg;
/**
 * Manages core autoloading and caching of class maps
 *
 * @access private
 *
 * @package    Elgg.Core
 * @subpackage Autoloader
 */
class AutoloadManager {

	const FILENAME = 'autoload_data.php';
	const KEY_CLASSES = 'classes';
	const KEY_SCANNED_DIRS = 'scannedDirs';

	/**
	 * @var \Elgg\ClassLoader
	 */
	protected $loader;

	/**
	 * @var array directories that have already been scanned for classes
	 */
	protected $scannedDirs = array();

	/**
	 * @var bool was data in the manager altered?
	 */
	protected $altered = false;

	/**
	 * @var \ElggCache
	 */
	protected $storage = null;

	/**
	 * Constructor
	 *
	 * @param \Elgg\ClassLoader $loader Class loader object
	 */
	public function __construct(\Elgg\ClassLoader $loader) {
		$this->loader = $loader;
	}

	/**
	 * Add classes found in this directory to the class map and allow classes in
	 * subdirectories to be found by PSR-0 rules.
	 *
	 * We keep track of which dirs were scanned on previous requests so we don't need to
	 * rescan unless the cache is emptied.
	 *
	 * @param string $dir Directory of classes
	 * @return \Elgg\AutoloadManager
	 */
	public function addClasses($dir) {
		if (!in_array($dir, $this->scannedDirs)) {
			$map = $this->loader->getClassMap();
			$map->mergeMap($this->scanClassesDir($dir));
			$this->scannedDirs[] = $dir;
			$this->altered = true;
		}
		$this->loader->addFallback($dir);
		return $this;
	}

	/**
	 * Scan (non-recursively) a /classes directory for PHP files to map directly to classes.
	 *
	 * For BC with Elgg 1.8's autoloader we map these files directly, but besides this
	 * the autoloader is PSR-0 compatible.
	 *
	 * @param string $dir Directory of classes
	 * @return array
	 */
	protected function scanClassesDir($dir) {
		$dir = new \DirectoryIterator($dir);
		$map = array();

		foreach ($dir as $file) {
			/* @var \SplFileInfo $file */
			if (!$file->isFile() || !$file->isReadable()) {
				continue;
			}

			$path = $file->getRealPath();

			if (pathinfo($path, PATHINFO_EXTENSION) !== 'php') {
				continue;
			}

			$class = $file->getBasename('.php');
			$map[$class] = $path;
		}
		return $map;
	}

	/**
	 * Register the location of a class on the class map
	 *
	 * @param string $class Class name
	 * @param string $path  Path of class file
	 * @return \Elgg\AutoloadManager
	 */
	public function setClassPath($class, $path) {
		$this->loader->getClassMap()->setPath($class, $path);
		return $this;
	}

	/**
	 * If necessary, save necessary state details
	 *
	 * @return \Elgg\AutoloadManager
	 */
	public function saveCache() {
		if ($this->storage) {
			$map = $this->loader->getClassMap();
			if ($this->altered || $map->getAltered()) {
				$spec[self::KEY_CLASSES] = $map->getMap();
				$spec[self::KEY_SCANNED_DIRS] = $this->scannedDirs;
				$this->storage->save(self::FILENAME, serialize($spec));
			}
		}
		return $this;
	}

	/**
	 * Set the state of the manager from the cache
	 *
	 * @return bool was the cache loaded?
	 */
	public function loadCache() {
		$spec = $this->getSpec();
		if ($spec) {
			// the cached class map will have the full scanned core classes, so
			// don't consider the earlier mappings as "altering" the map
			$this->loader->getClassMap()
				->setMap($spec[self::KEY_CLASSES])
				->setAltered(false);
			$this->scannedDirs = $spec[self::KEY_SCANNED_DIRS];
			return true;
		}
		$this->altered = true;
		return false;
	}

	/**
	 * Some method that does something
	 *
	 * @todo what is a spec?
	 * @return bool|array
	 */
	protected function getSpec() {
		if ($this->storage) {
			$serialization = $this->storage->load(self::FILENAME);
			if ($serialization) {
				$spec = unserialize($serialization);
				if (isset($spec[self::KEY_CLASSES])) {
					return $spec;
				}
			}
		}
		return false;
	}

	/**
	 * Delete the cache file
	 *
	 * @return \Elgg\AutoloadManager
	 */
	public function deleteCache() {
		if ($this->storage) {
			$this->storage->delete(self::FILENAME);
		}
		return $this;
	}

	/**
	 * Get the class loader
	 *
	 * @return \Elgg\ClassLoader
	 */
	public function getLoader() {
		return $this->loader;
	}

	/**
	 * Set the cache storage object
	 *
	 * @param \ElggCache $storage Cache object
	 * @return void
	 */
	public function setStorage(\ElggCache $storage) {
		$this->storage = $storage;
	}
}


text:
package main_test

import (
	"testing"

	"github.com/boltdb/bolt"
	. "github.com/boltdb/bolt/cmd/bolt"
	"github.com/stretchr/testify/assert"
)

// Ensure that a list of keys can be retrieved for a given bucket.
func TestKeys(t *testing.T) {
	SetTestMode(true)
	open(func(db *bolt.DB, path string) {
		db.Update(func(tx *bolt.Tx) error {
			tx.CreateBucket([]byte("widgets"))
			tx.Bucket([]byte("widgets")).Put([]byte("0002"), []byte(""))
			tx.Bucket([]byte("widgets")).Put([]byte("0001"), []byte(""))
			tx.Bucket([]byte("widgets")).Put([]byte("0003"), []byte(""))
			return nil
		})
		db.Close()
		output := run("keys", path, "widgets")
		assert.Equal(t, "0001\n0002\n0003", output)
	})
}

// Ensure that an error is reported if the database is not found.
func TestKeysDBNotFound(t *testing.T) {
	SetTestMode(true)
	output := run("keys", "no/such/db", "widgets")
	assert.Equal(t, "stat no/such/db: no such file or directory", output)
}

// Ensure that an error is reported if the bucket is not found.
func TestKeysBucketNotFound(t *testing.T) {
	SetTestMode(true)
	open(func(db *bolt.DB, path string) {
		db.Close()
		output := run("keys", path, "widgets")
		assert.Equal(t, "bucket not found: widgets", output)
	})
}


text:
namespace ExpressMapper
{
    public class DefaultMappingContext<T, TN> : IMappingContext<T,TN>
    {
        public T Source { get; set; }
        public TN Destination { get; set; }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using umbraco.cms.presentation.Trees;
using umbraco.cms.businesslogic.web;
using System.Linq;
using umbraco.controls;
using Umbraco.Core;

namespace umbraco.settings
{
    public partial class EditContentTypeNew : BasePages.UmbracoEnsuredPage
    {
        public EditContentTypeNew()
        {
            CurrentApp = BusinessLogic.DefaultApps.settings.ToString();
        }

        protected controls.ContentTypeControlNew ContentTypeControlNew1;
        private DocumentType _dt;

        override protected void OnInit(EventArgs e)
        {
            ContentTypeControlNew1.DocumentTypeCallback = new Func<DocumentType, DocumentType>(UpdateAllowedTemplates);
            ContentTypeControlNew1.InfoTabPage.Controls.Add(tmpPane);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _dt = new DocumentType(int.Parse(Request.QueryString["id"]));
            if (!Page.IsPostBack)
            {
                BindTemplates();

                ClientTools
                    .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<loadNodeTypes>().Tree.Alias)
                     .SyncTree("-1,init," + _dt.Path.Replace("-1,", ""), false);
            }
        }

        protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            bool handled = false;
            var eventArgs = args as SaveClickEventArgs;
            if (eventArgs != null)
            {
                var e = eventArgs;
                if (e.Message == "Saved")
                {
                    ClientTools.ShowSpeechBubble(e.IconType, ui.Text("contentTypeSavedHeader"), "");

                    BindTemplates();
                }
                else
                {
                    ClientTools.ShowSpeechBubble(e.IconType, e.Message, "");
                }
                handled = true;
            }
            return handled;
        }

        protected void dgTemplate_itemdatabound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ((CheckBox)e.Item.FindControl("ckbAllowTemplate")).Checked = true;
            }
        }

        private DocumentType UpdateAllowedTemplates(DocumentType documentType)
        {
            var tmp = new ArrayList();

            foreach (ListItem li in templateList.Items)
            {
                if (li.Selected)
                    tmp.Add(new cms.businesslogic.template.Template(int.Parse(li.Value)));
            }

            var tt = new cms.businesslogic.template.Template[tmp.Count];
            for (int i = 0; i < tt.Length; i++)
            {
                tt[i] = (cms.businesslogic.template.Template)tmp[i];
            }

            documentType.allowedTemplates = tt;

            if (documentType.allowedTemplates.Length > 0 && ddlTemplates.SelectedIndex >= 0)
            {
                documentType.DefaultTemplate = int.Parse(ddlTemplates.SelectedValue);
            }
            else
            {
                documentType.RemoveDefaultTemplate();
            }

            _dt = documentType;

            return documentType;
        }

        private void BindTemplates()
        {
            var templates = (from t in cms.businesslogic.template.Template.GetAllAsList()
                             join at in _dt.allowedTemplates on t.Id equals at.Id into at_l
                             from at in at_l.DefaultIfEmpty()
                             select new
                             {
                                 Id = t.Id,
                                 Name = t.Text,
                                 Selected = at != null
                             }).ToList();

            templateList.Items.Clear();
            templateList.Items.AddRange(templates.ConvertAll(item =>
            {
                var li = new ListItem { Text = Server.HtmlEncode(item.Name), Value = item.Id.ToString(CultureInfo.InvariantCulture), Selected = item.Selected };
                return li;
            }).ToArray());

            ddlTemplates.Enabled = templates.Any();
            ddlTemplates.Items.Clear();
            ddlTemplates.Items.Insert(0, new ListItem(ui.Text("choose") + "...", "0"));
            ddlTemplates.Items.AddRange(templates.ConvertAll(item =>
            {
                var li = new ListItem { Text = Server.HtmlEncode(item.Name), Value = item.Id.ToString(CultureInfo.InvariantCulture) };
                return li;
            }).ToArray());

            var ddlTemplatesSelect = ddlTemplates.Items.FindByValue(_dt.DefaultTemplate.ToString(CultureInfo.InvariantCulture));
            if (ddlTemplatesSelect != null)
                ddlTemplatesSelect.Selected = true;
        }

        /// <summary>
        /// tmpPane control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::umbraco.uicontrols.Pane tmpPane;

        /// <summary>
        /// templateList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBoxList templateList;

        /// <summary>
        /// ddlTemplates control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList ddlTemplates;
    }
}


text:
jest.dontMock("../../constants/HealthSorting");
jest.dontMock("../TaskTableUtil");

const MarathonStore = require("../../stores/MarathonStore");
const Service = require("../../structs/Service");
const TaskTableUtil = require("../TaskTableUtil");

describe("TaskTableUtil", function() {
  beforeEach(function() {
    this.getServiceHealth = MarathonStore.getServiceHealth;
    MarathonStore.getServiceHealth = function(prop) {
      return this[prop].get("health");
    }.bind(this);

    this.foo = {
      name: "foo",
      statuses: [{ timestamp: 1 }, { timestamp: 2 }],
      updated: 0,
      resources: {
        cpus: 100,
        mem: [{ value: 2 }, { value: 3 }]
      }
    };
    this.bar = {
      name: "bar",
      statuses: [{ timestamp: 4 }],
      updated: 1,
      resources: {
        cpus: 5,
        mem: [{ value: 0 }, { value: 1 }]
      }
    };

    this.fooStruct = new Service({
      name: "fooStruct",
      statuses: [{ timestamp: 1 }, { timestamp: 2 }],
      updated: 0,
      health: { key: "UNHEALTHY" },
      used_resources: {
        cpus: 100,
        mem: [{ value: 2 }, { value: 3 }]
      }
    });
    this.barStruct = new Service({
      name: "barStruct",
      statuses: [{ timestamp: 4 }],
      updated: 1,
      health: { key: "HEALTHY" },
      used_resources: {
        cpus: 5,
        mem: [{ value: 0 }, { value: 1 }]
      }
    });

    this.sortFunction = TaskTableUtil.getSortFunction("name");
  });

  afterEach(function() {
    MarathonStore.getServiceHealth = this.getServiceHealth;
  });

  describe("#getSortFunction for regular items", function() {
    it("should return a function", function() {
      expect(typeof this.sortFunction).toEqual("function");
    });

    it("should compare the most recent timestamps when prop is updated", function() {
      var sortFunction = this.sortFunction("updated");
      expect(sortFunction(this.foo, this.bar)).toEqual(-1);
    });

    it("should compare tieBreaker values", function() {
      var sortFunction = this.sortFunction("name");

      // 'foo' > 'bar' will equal true and compareValues returns 1
      expect(sortFunction(this.foo, this.bar)).toEqual(1);
    });

    it("should compare resource values", function() {
      var sortFunction = this.sortFunction("cpus");
      expect(sortFunction(this.foo, this.bar)).toEqual(1);
    });

    it("should compare last resource values", function() {
      var sortFunction = this.sortFunction("mem");
      expect(sortFunction(this.foo, this.bar)).toEqual(1);
    });
  });

  describe("#getSortFunction for structs", function() {
    it("should compare the most recent timestamps when prop is updated", function() {
      var sortFunction = this.sortFunction("updated");
      expect(sortFunction(this.fooStruct, this.barStruct)).toEqual(-1);
    });

    it("should compare tieBreaker values", function() {
      var sortFunction = this.sortFunction("name");

      // 'foo' > 'bar' will equal true and compareValues returns 1
      expect(sortFunction(this.fooStruct, this.barStruct)).toEqual(1);
    });

    it("should compare the health correctly", function() {
      var sortFunction = this.sortFunction("health");
      expect(sortFunction(this.fooStruct, this.barStruct)).toEqual(-1);
    });

    it("should use the tieBreaker if health is the same", function() {
      var prevHealth = this.barStruct.get("health").key;
      this.barStruct.get("health").key = this.fooStruct.get("health").key;
      var sortFunction = this.sortFunction("health");

      // Will compare with names now: 'foo' > 'bar' which will return 1
      expect(sortFunction(this.fooStruct, this.barStruct)).toEqual(1);

      // Set it back to original health
      this.barStruct.get("health").key = prevHealth;
    });

    it("should compare resource values", function() {
      var sortFunction = this.sortFunction("cpus");
      expect(sortFunction(this.fooStruct, this.barStruct)).toEqual(1);
    });

    it("should compare last resource values", function() {
      var sortFunction = this.sortFunction("mem");
      expect(sortFunction(this.fooStruct, this.barStruct)).toEqual(1);
    });
  });
});


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

<title>PopupLogHandler (GWT Javadoc)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.gwt.logging.client

Class PopupLogHandler

java.lang.Object

java.util.logging.Handler

com.google.gwt.logging.client.HasWidgetsLogHandler

com.google.gwt.logging.client.PopupLogHandler

public class PopupLogHandler
extends HasWidgetsLogHandler

A handler that logs to LoggingPopup.

Constructor Summary

Constructors

Constructor and Description

PopupLogHandler()

Method Summary

Methods inherited from class com.google.gwt.logging.client.HasWidgetsLogHandler

clear, close, flush, publish

Methods inherited from class java.util.logging.Handler

getEncoding, getErrorManager, getFilter, getFormatter, getLevel, isLoggable, reportError, setEncoding, setErrorManager, setFilter, setFormatter, setLevel

Methods inherited from class java.lang.Object

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

Constructor Detail

PopupLogHandler

public PopupLogHandler()

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
        <ft-spinner [predicate]="!fxUnderlying"></ft-spinner>

                {{fxUnderlying.ccypair}}

{{fxUnderlying.bid}}

{{fxUnderlying.ask}}

            clear


text:
layout: docs
title: Front-matter
prev_section: configuration
next_section: posts
---

The front-matter is where Jekyll starts to get really cool. Any file that
contains a [YAML](http://yaml.org/) front matter block will be processed by
Jekyll as a special file. The front matter must be the first thing in the file
and must take the form of valid YAML set between triple-dashed lines. Here is a
basic example:

{% highlight yaml %}
---
layout: post
title: Blogging Like a Hacker
---
{% endhighlight %}

Between these triple-dashed lines, you can set predefined variables (see below
for a reference) or even create custom ones of your own. These variables will
then be available to you to access using Liquid tags both further down in the
file and also in any layouts or includes that the page or post in question
relies on.

UTF-8 Character Encoding Warning

    If you use UTF-8 encoding, make sure that no BOM header
    characters exist in your files or very, very bad things will happen to
    Jekyll. This is especially relevant if you're running Jekyll on Windows.

## Predefined Global Variables

There are a number of predefined global variables that you can set in the
front-matter of a page or post.

      Variable
      Description

layout

          If set, this specifies the layout file to use. Use the layout file
          name without the file extension. Layout files must be placed in the
          _layouts directory.

permalink

          If you need your processed blog post URLs to be something other than
          the default /year/month/day/title.html then you can set
          this variable and it will be used as the final URL.

published

          Set to false if you don't want a specific post to show up when the
          site is generated.

category

categories

          Instead of placing posts inside of folders, you can specify one or
          more categories that the post belongs to. When the site is generated
          the post will act as though it had been set with these categories
          normally. Categories (plural key) can be specified as a YAML list or a
          space-separated string.

tags

          Similar to categories, one or multiple tags can be added to a post.
          Also like categories, tags can be specified as a YAML list or a space-
          separated string.

## Custom Variables

Any variables in the front matter that are not predefined are mixed into the
data that is sent to the Liquid templating engine during the conversion. For
instance, if you set a title, you can use that in your layout to set the page
title:

{% highlight html %}
<!DOCTYPE HTML>

    <title>{% raw %}{{ page.title }}{% endraw %}</title>

    ...
{% endhighlight %}

## Predefined Variables for Posts

These are available out-of-the-box to be used in the front-matter for a post.

      Variable
      Description

date

          A date here overrides the date from the name of the post. This can be
          used to ensure correct sorting of posts.


text:
namespace media {

namespace {

enum AudioRendererEvent {
  INITIALIZED,
  RENDER_ERROR,
  MAX_EVENTS
};

void HistogramRendererEvent(AudioRendererEvent event) {
  UMA_HISTOGRAM_ENUMERATION("Media.AudioRendererEvents", event, MAX_EVENTS);
}

}  // namespace

AudioRendererImpl::AudioRendererImpl(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    media::AudioRendererSink* sink,
    ScopedVector<AudioDecoder> decoders,
    const SetDecryptorReadyCB& set_decryptor_ready_cb)
    : task_runner_(task_runner),
      weak_factory_(this),
      sink_(sink),
      decoder_selector_(new AudioDecoderSelector(
          task_runner, decoders.Pass(), set_decryptor_ready_cb)),
      now_cb_(base::Bind(&base::TimeTicks::Now)),
      state_(kUninitialized),
      sink_playing_(false),
      pending_read_(false),
      received_end_of_stream_(false),
      rendered_end_of_stream_(false),
      audio_time_buffered_(kNoTimestamp()),
      current_time_(kNoTimestamp()),
      underflow_disabled_(false),
      preroll_aborted_(false) {
}

AudioRendererImpl::~AudioRendererImpl() {
  // Stop() should have been called and |algorithm_| should have been destroyed.
  DCHECK(state_ == kUninitialized || state_ == kStopped);
  DCHECK(!algorithm_.get());
}

void AudioRendererImpl::Play(const base::Closure& callback) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  DCHECK_EQ(state_, kPaused);
  ChangeState_Locked(kPlaying);
  callback.Run();
  earliest_end_time_ = now_cb_.Run();

  if (algorithm_->playback_rate() != 0)
    DoPlay_Locked();
  else
    DCHECK(!sink_playing_);
}

void AudioRendererImpl::DoPlay_Locked() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();
  earliest_end_time_ = now_cb_.Run();

  if ((state_ == kPlaying || state_ == kRebuffering || state_ == kUnderflow) &&
      !sink_playing_) {
    {
      base::AutoUnlock auto_unlock(lock_);
      sink_->Play();
    }

    sink_playing_ = true;
  }
}

void AudioRendererImpl::Pause(const base::Closure& callback) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  DCHECK(state_ == kPlaying || state_ == kUnderflow ||
         state_ == kRebuffering) << "state_ == " << state_;
  ChangeState_Locked(kPaused);

  DoPause_Locked();

  callback.Run();
}

void AudioRendererImpl::DoPause_Locked() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  if (sink_playing_) {
    {
      base::AutoUnlock auto_unlock(lock_);
      sink_->Pause();
    }
    sink_playing_ = false;
  }
}

void AudioRendererImpl::Flush(const base::Closure& callback) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  DCHECK_EQ(state_, kPaused);
  DCHECK(flush_cb_.is_null());

  flush_cb_ = callback;

  if (pending_read_) {
    ChangeState_Locked(kFlushing);
    return;
  }

  DoFlush_Locked();
}

void AudioRendererImpl::DoFlush_Locked() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  DCHECK(!pending_read_);
  DCHECK_EQ(state_, kPaused);

  if (decrypting_demuxer_stream_) {
    decrypting_demuxer_stream_->Reset(
        base::Bind(&AudioRendererImpl::ResetDecoder, weak_this_));
    return;
  }

  ResetDecoder();
}

void AudioRendererImpl::ResetDecoder() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  decoder_->Reset(base::Bind(&AudioRendererImpl::ResetDecoderDone, weak_this_));
}

void AudioRendererImpl::ResetDecoderDone() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  {
    base::AutoLock auto_lock(lock_);
    if (state_ == kStopped)
      return;

    DCHECK_EQ(state_, kPaused);
    DCHECK(!flush_cb_.is_null());

    audio_time_buffered_ = kNoTimestamp();
    current_time_ = kNoTimestamp();
    received_end_of_stream_ = false;
    rendered_end_of_stream_ = false;
    preroll_aborted_ = false;

    earliest_end_time_ = now_cb_.Run();
    splicer_->Reset();
    algorithm_->FlushBuffers();
  }
  base::ResetAndReturn(&flush_cb_).Run();
}

void AudioRendererImpl::Stop(const base::Closure& callback) {
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(!callback.is_null());
  DCHECK(stop_cb_.is_null());

  stop_cb_ = callback;

  // TODO(scherkus): Consider invalidating |weak_factory_| and replacing
  // task-running guards that check |state_| with DCHECK().

  {
    base::AutoLock auto_lock(lock_);
    if (state_ == kInitializing) {
      decoder_selector_->Abort();
      return;
    }

    if (state_ == kStopped) {
      task_runner_->PostTask(FROM_HERE, base::ResetAndReturn(&stop_cb_));
      return;
    }

    ChangeState_Locked(kStopped);
    algorithm_.reset();
    underflow_cb_.Reset();
    time_cb_.Reset();
    flush_cb_.Reset();
  }

  if (sink_) {
    sink_->Stop();
    sink_ = NULL;
  }

  if (decrypting_demuxer_stream_) {
    decrypting_demuxer_stream_->Stop(
        base::Bind(&AudioRendererImpl::StopDecoder, weak_this_));
    return;
  }

  StopDecoder();
}

void AudioRendererImpl::StopDecoder() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(!stop_cb_.is_null());

  if (decoder_) {
    decoder_->Stop(base::ResetAndReturn(&stop_cb_));
    return;
  }

  task_runner_->PostTask(FROM_HERE, base::ResetAndReturn(&stop_cb_));
}

void AudioRendererImpl::Preroll(base::TimeDelta time,
                                const PipelineStatusCB& cb) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  DCHECK(!sink_playing_);
  DCHECK_EQ(state_, kPaused);
  DCHECK(!pending_read_) << "Pending read must complete before seeking";
  DCHECK(preroll_cb_.is_null());

  ChangeState_Locked(kPrerolling);
  preroll_cb_ = cb;
  preroll_timestamp_ = time;

  AttemptRead_Locked();
}

void AudioRendererImpl::Initialize(DemuxerStream* stream,
                                   const PipelineStatusCB& init_cb,
                                   const StatisticsCB& statistics_cb,
                                   const base::Closure& underflow_cb,
                                   const TimeCB& time_cb,
                                   const base::Closure& ended_cb,
                                   const base::Closure& disabled_cb,
                                   const PipelineStatusCB& error_cb) {
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(stream);
  DCHECK_EQ(stream->type(), DemuxerStream::AUDIO);
  DCHECK(!init_cb.is_null());
  DCHECK(!statistics_cb.is_null());
  DCHECK(!underflow_cb.is_null());
  DCHECK(!time_cb.is_null());
  DCHECK(!ended_cb.is_null());
  DCHECK(!disabled_cb.is_null());
  DCHECK(!error_cb.is_null());
  DCHECK_EQ(kUninitialized, state_);
  DCHECK(sink_);

  state_ = kInitializing;

  weak_this_ = weak_factory_.GetWeakPtr();
  init_cb_ = init_cb;
  statistics_cb_ = statistics_cb;
  underflow_cb_ = underflow_cb;
  time_cb_ = time_cb;
  ended_cb_ = ended_cb;
  disabled_cb_ = disabled_cb;
  error_cb_ = error_cb;

  decoder_selector_->SelectDecoder(
      stream,
      statistics_cb,
      base::Bind(&AudioRendererImpl::OnDecoderSelected, weak_this_));
}

void AudioRendererImpl::OnDecoderSelected(
    scoped_ptr<AudioDecoder> decoder,
    scoped_ptr<DecryptingDemuxerStream> decrypting_demuxer_stream) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  scoped_ptr<AudioDecoderSelector> deleter(decoder_selector_.Pass());
  decoder_ = decoder.Pass();

  if (!decoder_ || !stop_cb_.is_null()) {
    {
      base::AutoLock auto_lock(lock_);
      ChangeState_Locked(kUninitialized);
    }
    // Stop() called during initialization.
    if (!stop_cb_.is_null()) {
      base::ResetAndReturn(&init_cb_).Run(PIPELINE_ERROR_ABORT);
      Stop(base::ResetAndReturn(&stop_cb_));
    } else {
      base::ResetAndReturn(&init_cb_).Run(DECODER_ERROR_NOT_SUPPORTED);
    }
    return;
  }

  base::AutoLock auto_lock(lock_);
  decrypting_demuxer_stream_ = decrypting_demuxer_stream.Pass();

  int sample_rate = decoder_->samples_per_second();

  // The actual buffer size is controlled via the size of the AudioBus
  // provided to Render(), so just choose something reasonable here for looks.
  int buffer_size = decoder_->samples_per_second() / 100;
  audio_parameters_ = AudioParameters(
      AudioParameters::AUDIO_PCM_LOW_LATENCY, decoder_->channel_layout(),
      sample_rate, decoder_->bits_per_channel(), buffer_size);
  if (!audio_parameters_.IsValid()) {
    ChangeState_Locked(kUninitialized);
    base::ResetAndReturn(&init_cb_).Run(PIPELINE_ERROR_INITIALIZATION_FAILED);
    return;
  }

  splicer_.reset(new AudioSplicer(sample_rate));

  // We're all good! Continue initializing the rest of the audio renderer
  // based on the decoder format.
  algorithm_.reset(new AudioRendererAlgorithm());
  algorithm_->Initialize(0, audio_parameters_);

  ChangeState_Locked(kPaused);

  HistogramRendererEvent(INITIALIZED);

  {
    base::AutoUnlock auto_unlock(lock_);
    sink_->Initialize(audio_parameters_, weak_this_.get());
    sink_->Start();

    // Some sinks play on start...
    sink_->Pause();
  }

  DCHECK(!sink_playing_);

  base::ResetAndReturn(&init_cb_).Run(PIPELINE_OK);
}

void AudioRendererImpl::ResumeAfterUnderflow() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  base::AutoLock auto_lock(lock_);
  if (state_ == kUnderflow) {
    // The "!preroll_aborted_" is a hack. If preroll is aborted, then we
    // shouldn't even reach the kUnderflow state to begin with. But for now
    // we're just making sure that the audio buffer capacity (i.e. the
    // number of bytes that need to be buffered for preroll to complete)
    // does not increase due to an aborted preroll.
    // TODO(vrk): Fix this bug correctly! (crbug.com/151352)
    if (!preroll_aborted_)
      algorithm_->IncreaseQueueCapacity();

    ChangeState_Locked(kRebuffering);
  }
}

void AudioRendererImpl::SetVolume(float volume) {
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(sink_);
  sink_->SetVolume(volume);
}

void AudioRendererImpl::DecodedAudioReady(
    AudioDecoder::Status status,
    const scoped_refptr<AudioBuffer>& buffer) {
  DVLOG(1) << __FUNCTION__ << "(" << status << ")";
  DCHECK(task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  DCHECK(state_ != kUninitialized);

  CHECK(pending_read_);
  pending_read_ = false;

  if (status == AudioDecoder::kAborted) {
    HandleAbortedReadOrDecodeError(false);
    return;
  }

  if (status == AudioDecoder::kDecodeError) {
    HandleAbortedReadOrDecodeError(true);
    return;
  }

  DCHECK_EQ(status, AudioDecoder::kOk);
  DCHECK(buffer.get());

  if (state_ == kFlushing) {
    ChangeState_Locked(kPaused);
    DoFlush_Locked();
    return;
  }

  if (!splicer_->AddInput(buffer)) {
    HandleAbortedReadOrDecodeError(true);
    return;
  }

  if (!splicer_->HasNextBuffer()) {
    AttemptRead_Locked();
    return;
  }

  bool need_another_buffer = false;
  while (splicer_->HasNextBuffer())
    need_another_buffer = HandleSplicerBuffer(splicer_->GetNextBuffer());

  if (!need_another_buffer && !CanRead_Locked())
    return;

  AttemptRead_Locked();
}

bool AudioRendererImpl::HandleSplicerBuffer(
    const scoped_refptr<AudioBuffer>& buffer) {
  if (buffer->end_of_stream()) {
    received_end_of_stream_ = true;

    // Transition to kPlaying if we are currently handling an underflow since
    // no more data will be arriving.
    if (state_ == kUnderflow || state_ == kRebuffering)
      ChangeState_Locked(kPlaying);
  } else {
    if (state_ == kPrerolling) {
      if (IsBeforePrerollTime(buffer))
        return true;

      // Trim off any additional time before the preroll timestamp.
      const base::TimeDelta trim_time =
          preroll_timestamp_ - buffer->timestamp();
      if (trim_time > base::TimeDelta()) {
        buffer->TrimStart(buffer->frame_count() *
                          (static_cast<double>(trim_time.InMicroseconds()) /
                           buffer->duration().InMicroseconds()));
      }
      // If the entire buffer was trimmed, request a new one.
      if (!buffer->frame_count())
        return true;
    }

    if (state_ != kUninitialized && state_ != kStopped)
      algorithm_->EnqueueBuffer(buffer);
  }

  switch (state_) {
    case kUninitialized:
    case kInitializing:
    case kFlushing:
      NOTREACHED();
      return false;

    case kPaused:
      DCHECK(!pending_read_);
      return false;

    case kPrerolling:
      if (!buffer->end_of_stream() && !algorithm_->IsQueueFull())
        return true;
      ChangeState_Locked(kPaused);
      base::ResetAndReturn(&preroll_cb_).Run(PIPELINE_OK);
      return false;

    case kPlaying:
    case kUnderflow:
      return false;

    case kRebuffering:
      if (!algorithm_->IsQueueFull())
        return true;
      ChangeState_Locked(kPlaying);
      return false;

    case kStopped:
      return false;
  }
  return false;
}

void AudioRendererImpl::AttemptRead() {
  base::AutoLock auto_lock(lock_);
  AttemptRead_Locked();
}

void AudioRendererImpl::AttemptRead_Locked() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  if (!CanRead_Locked())
    return;

  pending_read_ = true;
  decoder_->Read(base::Bind(&AudioRendererImpl::DecodedAudioReady, weak_this_));
}

bool AudioRendererImpl::CanRead_Locked() {
  lock_.AssertAcquired();

  switch (state_) {
    case kUninitialized:
    case kInitializing:
    case kPaused:
    case kFlushing:
    case kStopped:
      return false;

    case kPrerolling:
    case kPlaying:
    case kUnderflow:
    case kRebuffering:
      break;
  }

  return !pending_read_ && !received_end_of_stream_ &&
      !algorithm_->IsQueueFull();
}

void AudioRendererImpl::SetPlaybackRate(float playback_rate) {
  DVLOG(1) << __FUNCTION__ << "(" << playback_rate << ")";
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK_GE(playback_rate, 0);
  DCHECK(sink_);

  base::AutoLock auto_lock(lock_);

  // We have two cases here:
  // Play: current_playback_rate == 0 && playback_rate != 0
  // Pause: current_playback_rate != 0 && playback_rate == 0
  float current_playback_rate = algorithm_->playback_rate();
  if (current_playback_rate == 0 && playback_rate != 0)
    DoPlay_Locked();
  else if (current_playback_rate != 0 && playback_rate == 0)
    DoPause_Locked();

  algorithm_->SetPlaybackRate(playback_rate);
}

bool AudioRendererImpl::IsBeforePrerollTime(
    const scoped_refptr<AudioBuffer>& buffer) {
  DCHECK_EQ(state_, kPrerolling);
  return buffer && !buffer->end_of_stream() &&
         (buffer->timestamp() + buffer->duration()) < preroll_timestamp_;
}

int AudioRendererImpl::Render(AudioBus* audio_bus,
                              int audio_delay_milliseconds) {
  const int requested_frames = audio_bus->frames();
  base::TimeDelta current_time = kNoTimestamp();
  base::TimeDelta max_time = kNoTimestamp();
  base::TimeDelta playback_delay = base::TimeDelta::FromMilliseconds(
      audio_delay_milliseconds);

  int frames_written = 0;
  base::Closure underflow_cb;
  {
    base::AutoLock auto_lock(lock_);

    // Ensure Stop() hasn't destroyed our |algorithm_| on the pipeline thread.
    if (!algorithm_)
      return 0;

    float playback_rate = algorithm_->playback_rate();
    if (playback_rate == 0)
      return 0;

    // Mute audio by returning 0 when not playing.
    if (state_ != kPlaying)
      return 0;

    // We use the following conditions to determine end of playback:
    //   1) Algorithm can not fill the audio callback buffer
    //   2) We received an end of stream buffer
    //   3) We haven't already signalled that we've ended
    //   4) Our estimated earliest end time has expired
    //
    // TODO(enal): we should replace (4) with a check that the browser has no
    // more audio data or at least use a delayed callback.
    //
    // We use the following conditions to determine underflow:
    //   1) Algorithm can not fill the audio callback buffer
    //   2) We have NOT received an end of stream buffer
    //   3) We are in the kPlaying state
    //
    // Otherwise the buffer has data we can send to the device.
    frames_written = algorithm_->FillBuffer(audio_bus, requested_frames);
    if (frames_written == 0) {
      const base::TimeTicks now = now_cb_.Run();

      if (received_end_of_stream_ && !rendered_end_of_stream_ &&
          now >= earliest_end_time_) {
        rendered_end_of_stream_ = true;
        ended_cb_.Run();
      } else if (!received_end_of_stream_ && state_ == kPlaying &&
                 !underflow_disabled_) {
        ChangeState_Locked(kUnderflow);
        underflow_cb = underflow_cb_;
      } else {
        // We can't write any data this cycle. For example, we may have
        // sent all available data to the audio device while not reaching
        // |earliest_end_time_|.
      }
    }

    if (CanRead_Locked()) {
      task_runner_->PostTask(FROM_HERE, base::Bind(
          &AudioRendererImpl::AttemptRead, weak_this_));
    }

    // The |audio_time_buffered_| is the ending timestamp of the last frame
    // buffered at the audio device. |playback_delay| is the amount of time
    // buffered at the audio device. The current time can be computed by their
    // difference.
    if (audio_time_buffered_ != kNoTimestamp()) {
      // Adjust the delay according to playback rate.
      base::TimeDelta adjusted_playback_delay =
          base::TimeDelta::FromMicroseconds(ceil(
              playback_delay.InMicroseconds() * playback_rate));

      base::TimeDelta previous_time = current_time_;
      current_time_ = audio_time_buffered_ - adjusted_playback_delay;

      // Time can change in one of two ways:
      //   1) The time of the audio data at the audio device changed, or
      //   2) The playback delay value has changed
      //
      // We only want to set |current_time| (and thus execute |time_cb_|) if
      // time has progressed and we haven't signaled end of stream yet.
      //
      // Why? The current latency of the system results in getting the last call
      // to FillBuffer() later than we'd like, which delays firing the 'ended'
      // event, which delays the looping/trigging performance of short sound
      // effects.
      //
      // TODO(scherkus): revisit this and switch back to relying on playback
      // delay after we've revamped our audio IPC subsystem.
      if (current_time_ > previous_time && !rendered_end_of_stream_) {
        current_time = current_time_;
      }
    }

    // The call to FillBuffer() on |algorithm_| has increased the amount of
    // buffered audio data. Update the new amount of time buffered.
    max_time = algorithm_->GetTime();
    audio_time_buffered_ = max_time;

    if (frames_written > 0) {
      UpdateEarliestEndTime_Locked(
          frames_written, playback_delay, now_cb_.Run());
    }
  }

  if (current_time != kNoTimestamp() && max_time != kNoTimestamp())
    time_cb_.Run(current_time, max_time);

  if (!underflow_cb.is_null())
    underflow_cb.Run();

  DCHECK_LE(frames_written, requested_frames);
  return frames_written;
}

void AudioRendererImpl::UpdateEarliestEndTime_Locked(
    int frames_filled, const base::TimeDelta& playback_delay,
    const base::TimeTicks& time_now) {
  DCHECK_GT(frames_filled, 0);

  base::TimeDelta predicted_play_time = base::TimeDelta::FromMicroseconds(
      static_cast<float>(frames_filled) * base::Time::kMicrosecondsPerSecond /
      audio_parameters_.sample_rate());

  lock_.AssertAcquired();
  earliest_end_time_ = std::max(
      earliest_end_time_, time_now + playback_delay + predicted_play_time);
}

void AudioRendererImpl::OnRenderError() {
  HistogramRendererEvent(RENDER_ERROR);
  disabled_cb_.Run();
}

void AudioRendererImpl::DisableUnderflowForTesting() {
  underflow_disabled_ = true;
}

void AudioRendererImpl::HandleAbortedReadOrDecodeError(bool is_decode_error) {
  lock_.AssertAcquired();

  PipelineStatus status = is_decode_error ? PIPELINE_ERROR_DECODE : PIPELINE_OK;
  switch (state_) {
    case kUninitialized:
    case kInitializing:
      NOTREACHED();
      return;
    case kPaused:
      if (status != PIPELINE_OK)
        error_cb_.Run(status);
      return;
    case kFlushing:
      ChangeState_Locked(kPaused);

      if (status == PIPELINE_OK) {
        DoFlush_Locked();
        return;
      }

      error_cb_.Run(status);
      base::ResetAndReturn(&flush_cb_).Run();
      return;
    case kPrerolling:
      // This is a signal for abort if it's not an error.
      preroll_aborted_ = !is_decode_error;
      ChangeState_Locked(kPaused);
      base::ResetAndReturn(&preroll_cb_).Run(status);
      return;
    case kPlaying:
    case kUnderflow:
    case kRebuffering:
    case kStopped:
      if (status != PIPELINE_OK)
        error_cb_.Run(status);
      return;
  }
}

void AudioRendererImpl::ChangeState_Locked(State new_state) {
  DVLOG(1) << __FUNCTION__ << " : " << state_ << " -> " << new_state;
  lock_.AssertAcquired();
  state_ = new_state;
}

}  // namespace media


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    _ = require('lodash'),
    fs = require('fs'),
    nconf = require('nconf');

// Get setting by by userid

exports.show = function(req, res) {
    nconf.use('file', { file: './user-setting.json' });
    if (nconf.get('message:' + req.user._id.toString()) == undefined) {
        nconf.set('message:' + req.user._id.toString(),true);
        nconf.set('chat:' + req.user._id.toString(),true);
        nconf.set('email:' + req.user._id.toString(),true);
        nconf.save(function (err) {
            fs.readFile('./user-setting.json' , function (err, data) {
              console.dir(JSON.parse(data.toString()))
            });
          });
    }
    res.jsonp({ 'message' : nconf.get('message:' + req.user._id.toString()),'chat' : nconf.get('chat:' + req.user._id.toString()),'email' : nconf.get('email:' + req.user._id.toString()) });
};

exports.update = function(req, res) {
    var setting;
    nconf.use('file', { file: './user-setting.json' });
    nconf.set('message:' + req.user._id.toString(),req.body.message);
    nconf.set('chat:' + req.user._id.toString(),req.body.chat);
    nconf.set('email:' + req.user._id.toString(),req.body.email);

    nconf.save(function (err) {
        fs.readFile('./user-setting.json' , function (err, data) {
          console.dir(JSON.parse(data.toString()))
        });
      });
    res.jsonp({ 'message' : nconf.get('message:' + req.user._id.toString()),'chat' : nconf.get('chat:' + req.user._id.toString()),'email' : nconf.get('email:' + req.user._id.toString()) });

};

exports.logo = function(req,res){
    // chagne logo
    var fs = require('fs-extra');
    var path = require('path');

    fs.copy('./public/uploads/tmp/' + req.body.logo, './public/lib/images/logo1.png', function(err) {
            if (err) {
                console.error(err);
            } else {
                console.log("move file success!")
                // remove tmp file
                fs.remove('./public/uploads/tmp/' + req.body.logo,function(e){
                    if(e)
                        return console.error(e);
                });

                var easyimg = require('easyimage');

                // crop file
                // small size
                easyimg.thumbnail(
                  {
                     src: './public/lib/images/logo1.png', dst: './public/lib/images/logo1.png',
                     width:168, height:32
                },
                  function(err, image) {
                     if (err) console.error(err)
                        else
                        console.log('Resized : ' + image.width + ' x ' + image.height);
                  }
                );
            }
    });
    res.jsonp({status : 'success'});

}


text:
package com.arkcraft.module.items;

import java.util.HashMap;
import java.util.Map;

import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fml.common.registry.GameRegistry;

import com.arkcraft.module.core.GlobalAdditions;
import com.arkcraft.module.core.client.gui.book.Dossier;
import com.arkcraft.module.crafting.common.config.ModuleItemBalance;
import com.arkcraft.module.creature.common.entity.SaddleType;
import com.arkcraft.module.items.common.general.ItemARKArmor;
import com.arkcraft.module.items.common.general.ItemARKBase;
import com.arkcraft.module.items.common.general.ItemARKFood;
import com.arkcraft.module.items.common.general.ItemARKSeed;
import com.arkcraft.module.items.common.general.ItemCrystal;
import com.arkcraft.module.items.common.general.ItemDinosaurEgg;
import com.arkcraft.module.items.common.general.ItemDinosaurSaddle;
import com.arkcraft.module.items.common.general.ItemFeces;
import com.arkcraft.module.items.common.general.ItemSpyGlass;
import com.arkcraft.module.items.common.general.ItemThatch;

/**
 * @author wildbill22
 */
public class ARKCraftItems
{
	public static ItemARKFood tintoBerry, amarBerry, azulBerry, mejoBerry,
			narcoBerry, stimBerry, meat_raw, meat_cooked, primemeat_raw,
			primemeat_cooked, spoiled_meat;
	public static ItemARKSeed tintoBerrySeed, amarBerrySeed, azulBerrySeed, mejoBerrySeed, narcoBerrySeed, stimBerrySeed;
	public static ItemARKBase rock, cementing_pastes, fiber, chitin, narcotics,dodo_bag, dodo_feather, gun_powder, spark_powder, hide;
	public static ItemThatch thatch;
	public static ItemARKBase wood, metal, metal_ingot, flint;
	public static ItemFeces small_feces, medium_feces, large_feces, fertilizer, player_feces;
	public static ItemDinosaurEgg dodo_egg;
	public static ItemDinosaurSaddle saddle_small, saddle_medium, saddle_large;
	public static ItemARKArmor chitinHelm, chitinChest, chitinLegs,chitinBoots;
	public static ItemARKArmor clothHelm, clothChest, clothLegs, clothBoots;
	public static ItemARKArmor hideHelm, hideChest, hideLegs, hideBoots;
	public static ItemARKArmor furHelm, furChest, furLegs, furBoots;
	public static Dossier dino_book;
	public static ItemCrystal item_crystal;
	public static ItemSpyGlass spy_glass;

	//Armor
	public static ArmorMaterial CLOTH = EnumHelper.addArmorMaterial(
			"CLOTH_MAT", "CLOTH_MAT", 4, new int[] { 1, 2, 1, 1 }, 15);
	public static ArmorMaterial CHITIN = EnumHelper.addArmorMaterial(
			"CHITIN_MAT", "CHITIN_MAT", 16, new int[] { 3, 7, 6, 3 }, 10);
	public static ArmorMaterial HIDE = EnumHelper.addArmorMaterial
			("HIDE_MAT", "HIDE_MAT", 40, new int[] { 3, 8, 6, 3 }, 30);
	public static ArmorMaterial FUR = EnumHelper.addArmorMaterial(
			"FUR_MAT", "HIDE_MAT", 40, new int[] { 3, 8, 6, 3 }, 30);

	public static ARKCraftItems getInstance()
	{
		return new ARKCraftItems();
	}

	public static Map<String, Item> allItems = new HashMap<String, Item>();

	public static Map<String, Item> getAllItems()
	{
		return allItems;
	}

	public static void init()
	{
		// Food
		tintoBerry = addFood("tinto", 4, 0.3F, false, true);
		amarBerry = addFood("amar", 4, 0.3F, false, true);
		azulBerry = addFood("azul", 4, 0.3F, false, true);
		mejoBerry = addFood("mejo", 4, 0.3F, false, true);
		narcoBerry = addFood("narco", 4, 0.3F, true, true);
		stimBerry = addFood("stim", 4, 0.3F, true, true);
		meat_raw = addFood("meat_raw", 3, 0.3F, false, false);
		meat_cooked = addFood("meat_cooked", 6, 0.9F, false, false);
		primemeat_raw = addFood("primemeat_raw", 3, 0.3F, false, false);
		primemeat_cooked = addFood("primemeat_cooked", 8, 1.2F, false, false);
		spoiled_meat = addFood("spoiled_meat", 2, 0.1F, false, false);

		// Seeds
		tintoBerrySeed = addSeedItem("tintoBerrySeed");
		amarBerrySeed = addSeedItem("amarBerrySeed");
		azulBerrySeed = addSeedItem("azulBerrySeed");
		mejoBerrySeed = addSeedItem("mejoBerrySeed");
		narcoBerrySeed = addSeedItem("narcoBerrySeed");
		stimBerrySeed = addSeedItem("stimBerrySeed");

		// world generated

		// Regular Items
		rock = addItem("rock");
		cementing_pastes = addItem("cementing_paste");
		fiber = addItem("fiber");
		thatch = addThatchItem("thatch");
		wood = addItem("wood");
		metal = addItem("metal");
		metal_ingot = addItem("metal_ingot");
		flint = addItem("flint");
		chitin = addItem("chitin");
		dodo_feather = addItem("dodo_feather");
		dodo_bag = addItem("dodo_bag");
		gun_powder = addItem("gun_powder");
		spark_powder = addItem("spark_powder");
		hide = addItem("hide");
		spy_glass = addSpyGlass("spy_glass");

		// feces (2nd parameter is the seconds to decompose)
		//TODO
		small_feces = addFecesItem(
				"small_feces",
				ModuleItemBalance.CROP_PLOT.SECONDS_FOR_SMALL_FECES_TO_DECOMPOSE);
		medium_feces = addFecesItem(
				"medium_feces",
				ModuleItemBalance.CROP_PLOT.SECONDS_FOR_SMALL_FECES_TO_DECOMPOSE);
		large_feces = addFecesItem(
				"large_feces",
				ModuleItemBalance.CROP_PLOT.SECONDS_FOR_SMALL_FECES_TO_DECOMPOSE);
		player_feces = addFecesItem(
				"player_feces",
				ModuleItemBalance.CROP_PLOT.SECONDS_FOR_PLAYER_FECES_TO_DECOMPOSE);

		// Technically not feces, but used in all situations the same
		// (currently)
		fertilizer = addFecesItem("fertilizer",
				ModuleItemBalance.CROP_PLOT.SECONDS_FOR_FERTILIZER_TO_DECOMPOSE);

		// Other Types of Items
		dodo_egg = addEggItem("dodo_egg");
		dino_book = addDossier("dossier");
		narcotics = addItem("narcotics");
		saddle_small = addSaddle("saddle_small");
		saddle_small.setSaddleType(SaddleType.SMALL);
		saddle_medium = addSaddle("saddle_medium");
		saddle_medium.setSaddleType(SaddleType.MEDIUM);
		saddle_large = addSaddle("saddle_large");
		saddle_large.setSaddleType(SaddleType.LARGE);

		// Armor
		chitinHelm = addArmorItem("chitin_helm", CHITIN, "chitinArmor", 0,false);
		chitinChest = addArmorItem("chitin_chest", CHITIN, "chitinArmor", 1,false);
		chitinLegs = addArmorItem("chitin_legs", CHITIN, "chitinArmor", 2,false);
		chitinBoots = addArmorItem("chitin_boots", CHITIN, "chitinArmor", 3,false);

		clothHelm = addArmorItem("cloth_helm", CLOTH, "clothArmor", 0, false);
		clothChest = addArmorItem("cloth_chest", CLOTH, "clothArmor", 1, false);
		clothLegs = addArmorItem("cloth_legs", CLOTH, "clothArmor", 2, false);
		clothBoots = addArmorItem("cloth_boots", CLOTH, "clothArmor", 3, false);

		hideHelm = addArmorItem("hide_helm", HIDE, "hideArmor", 0, false);
		hideChest = addArmorItem("hide_chest", HIDE, "hideArmor", 1, false);
		hideLegs = addArmorItem("hide_legs", HIDE, "hideArmor", 2, false);
		hideBoots = addArmorItem("hide_boots", HIDE, "hideArmor", 3, false);

		furHelm = addArmorItem("fur_helm", FUR, "furArmor", 0, false);
		furChest = addArmorItem("fur_chest", FUR, "furArmor", 1, false);
		furLegs = addArmorItem("fur_legs", FUR, "furArmor", 2, false);
		furBoots = addArmorItem("fur_boots", FUR, "furArmor", 3, false);
	}

	protected static ItemARKBase addItem(String name)
	{
		ItemARKBase i = new ItemARKBase();
		registerItem(name, i);
		return i;
	}

	protected static ItemThatch addThatchItem(String name)
	{
		ItemThatch t = new ItemThatch();
		registerItem(name, t);
		return t;
	}

	protected static ItemARKSeed addSeedItem(String name)
	{
		ItemARKSeed i = new ItemARKSeed();
		registerItem(name, i);
		return i;
	}

	protected static ItemDinosaurEgg addEggItem(String name)
	{
		ItemDinosaurEgg i = new ItemDinosaurEgg();
		registerItem(name, i);
		return i;
	}

	protected static ItemCrystal addCrystalItem(String name)
	{
		ItemCrystal i = new ItemCrystal();
		registerItem(name, i);
		return i;
	}

	protected static ItemSpyGlass addSpyGlass(String name)
	{
		ItemSpyGlass i = new ItemSpyGlass();
		registerItem(name, i);
		return i;
	}

	protected static ItemFeces addFecesItem(String name, int maxDamageIn)
	{
		ItemFeces i = new ItemFeces();
		i.setMaxDamage(maxDamageIn);
		registerItem(name, i);
		return i;
	}

	protected static ItemARKFood addFood(String name, int heal, float sat, boolean fav, boolean alwaysEdible)
	{
		ItemARKFood f = new ItemARKFood(heal, sat, fav, alwaysEdible);
		registerItem(name, f);
		return f;
	}

	protected static Dossier addDossier(String name)
	{
		Dossier dossier = new Dossier(name);
		registerItem(name, dossier);
		return dossier;
	}

	public static ItemARKFood addFood(String name, int heal, float sat, boolean fav, boolean alwaysEdible, PotionEffect... effect)
	{
		ItemARKFood f = new ItemARKFood(heal, sat, fav, alwaysEdible, effect);
		registerItem(name, f);
		return f;
	}

	public static ItemARKArmor addArmorItem(String name, ArmorMaterial mat, String armorTexName, int type, boolean golden)
	{
		ItemARKArmor item = new ItemARKArmor(mat, armorTexName, type, golden);
		registerItem(name, item);
		return item;
	}

	public static ItemDinosaurSaddle addSaddle(String name)
	{
		ItemDinosaurSaddle item = new ItemDinosaurSaddle();
		registerItem(name, item);
		return item;
	}

	public static void registerItem(String name, Item item)
	{
		allItems.put(name, item);
		item.setUnlocalizedName(name);
		item.setCreativeTab(GlobalAdditions.tabARKMisc);
		GameRegistry.registerItem(item, name);
	}
}


text:
namespace blink {

class FederatedCredentialInit;
class FederatedIdentityProvider;

class MODULES_EXPORT FederatedCredential final : public Credential {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static FederatedCredential* Create(const FederatedCredentialInit*,
                                     ExceptionState&);
  static FederatedCredential* Create(
      const String& id,
      scoped_refptr<const SecurityOrigin> provider,
      const String& name,
      const KURL& icon_url);

  FederatedCredential(const String& id,
                      scoped_refptr<const SecurityOrigin> provider,
                      const String& name,
                      const KURL& icon_url);

  scoped_refptr<const SecurityOrigin> GetProviderAsOrigin() const {
    return provider_;
  }

  // Credential:
  bool IsFederatedCredential() const override;

  // FederatedCredential.idl
  String provider() const {
    CHECK(provider_);
    return provider_->ToString();
  }
  const String& name() const { return name_; }
  const KURL& iconURL() const { return icon_url_; }
  const String& protocol() const {
    // TODO(mkwst): This is a stub, as we don't yet have any support on the
    // Chromium-side.
    return g_empty_string;
  }

  const String& idToken() const {
    // TODO(goto): This is a stub, so that we can port the WebID API
    // gradually.
    return g_empty_string;
  }

  const String& approvedBy() const {
    // TODO(goto): This is a stub, so that we can port the WebID API
    // gradually.
    return g_empty_string;
  }

  static ScriptPromise logout(ScriptState*,
                              const HeapVector<Member<WebIdLogoutRequest>>&);
  static ScriptPromise revoke(ScriptState*,
                              const String&,
                              FederatedIdentityProvider*,
                              ExceptionState&);

 private:
  const scoped_refptr<const SecurityOrigin> provider_;
  const String name_;
  const KURL icon_url_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_CREDENTIALMANAGER_FEDERATED_CREDENTIAL_H_


text:
using System;
using Xunit;

namespace System.Tests
{
    public static class StackOverflowExceptionTests
    {
        private const int COR_E_STACKOVERFLOW = -2147023895;

        [Fact]
        public static void Ctor_Empty()
        {
            var exception = new StackOverflowException();
            Assert.NotNull(exception);
            Assert.NotEmpty(exception.Message);
            Assert.Equal(COR_E_STACKOVERFLOW, exception.HResult);
        }

        [Fact]
        public static void Ctor_String()
        {
            string message = "Created StackOverflowException";
            var exception = new StackOverflowException(message);
            Assert.Equal(message, exception.Message);
            Assert.Equal(COR_E_STACKOVERFLOW, exception.HResult);
        }

        [Fact]
        public static void Ctor_String_Exception()
        {
            string message = "Created StackOverflowException";
            var innerException = new Exception("Created inner exception");
            var exception = new StackOverflowException(message, innerException);
            Assert.Equal(message, exception.Message);
            Assert.Equal(COR_E_STACKOVERFLOW, exception.HResult);
            Assert.Equal(innerException, exception.InnerException);
            Assert.Equal(innerException.HResult, exception.InnerException.HResult);
        }
    }
}


text:
require 'rails_helper'

RSpec.describe Admin::CancelOrderService do
  let(:cancel_order) { described_class.new(order: order, user: user) }

  let(:customer) do
    Customer.create!(title: 'Mr', first_name: 'Joe',
                     last_name: 'Smith', address: '123 Sesame Street',
                     city_town: 'Wellington', post_code: '1234',
                     ta: 'wellington')
  end
  let(:ordered_item) { Item.first }
  let(:order) { Order.create!(customer: customer, item_ids: [ordered_item.id]) }
  let(:user) { double(:admin, id: 55) }

  describe "#perform" do
    it "creates a cancelled order event" do
      cancel_order.perform
      expect(CancelledOrderEvent.last).
        to have_attributes(cancelled_by_id: user.id,
                           customer_id: customer.id,
                           order_details: hash_including(item_ids: [ordered_item.id]))
    end

    it "deletes the order" do
      cancel_order.perform
      expect(order).to be_destroyed
    end
  end
end


text:
'''
Module for handling openstack glance calls.

:optdepends:    - glanceclient Python adapter
:configuration: This module is not usable until the following are specified
    either in a pillar or in the minion's config file::

        keystone.user: admin
        keystone.password: verybadpass
        keystone.tenant: admin
        keystone.tenant_id: f80919baedab48ec8931f200c65a50df
        keystone.insecure: False   #(optional)
        keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'

    If configuration for multiple openstack accounts is required, they can be
    set up as different configuration profiles:
    For example::

        openstack1:
          keystone.user: admin
          keystone.password: verybadpass
          keystone.tenant: admin
          keystone.tenant_id: f80919baedab48ec8931f200c65a50df
          keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'

        openstack2:
          keystone.user: admin
          keystone.password: verybadpass
          keystone.tenant: admin
          keystone.tenant_id: f80919baedab48ec8931f200c65a50df
          keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'

    With this configuration in place, any of the keystone functions can make use
    of a configuration profile by declaring it explicitly.
    For example::

        salt '*' glance.image_list profile=openstack1
'''

# Import third party libs
HAS_GLANCE = False
try:
    from glanceclient import client
    import glanceclient.v1.images
    HAS_GLANCE = True
except ImportError:
    pass

def __virtual__():
    '''
    Only load this module if glance
    is installed on this minion.
    '''
    if HAS_GLANCE:
        return 'glance'
    return False

__opts__ = {}

def _auth(profile=None):
    '''
    Set up keystone credentials
    '''
    kstone = __salt__['keystone.auth'](profile)
    token = kstone.auth_token
    endpoint = kstone.service_catalog.url_for(
        service_type='image',
        endpoint_type='publicURL',
        )

    return client.Client('1', endpoint, token=token)

def image_create(profile=None, **kwargs):
    '''
    Create an image (glance image-create)

    CLI Example:

    .. code-block:: bash

        salt '*' glance.image_create name=f16-jeos is_public=true \\
                 disk_format=qcow2 container_format=ovf \\
                 copy_from=http://berrange.fedorapeople.org/images/2012-02-29/f16-x86_64-openstack-sda.qcow2

    For all possible values, run ``glance help image-create`` on the minion.
    '''
    nt_ks = _auth(profile)
    fields = dict(
        filter(
            lambda x: x[0] in glanceclient.v1.images.CREATE_PARAMS,
            kwargs.items()
        )
    )

    image = nt_ks.images.create(**fields)
    newimage = image_list(str(image.id))
    return {newimage['name']: newimage}

def image_delete(id=None, name=None, profile=None):  # pylint: disable=C0103
    '''
    Delete an image (glance image-delete)

    CLI Examples:

    .. code-block:: bash

        salt '*' glance.image_delete c2eb2eb0-53e1-4a80-b990-8ec887eae7df
        salt '*' glance.image_delete id=c2eb2eb0-53e1-4a80-b990-8ec887eae7df
        salt '*' glance.image_delete name=f16-jeos
    '''
    nt_ks = _auth(profile)
    if name:
        for image in nt_ks.images.list():
            if image.name == name:
                id = image.id  # pylint: disable=C0103
                continue
    if not id:
        return {'Error': 'Unable to resolve image id'}
    nt_ks.images.delete(id)
    ret = 'Deleted image with ID {0}'.format(id)
    if name:
        ret += ' ({0})'.format(name)
    return ret

def image_show(id=None, name=None, profile=None):  # pylint: disable=C0103
    '''
    Return details about a specific image (glance image-show)

    CLI Example:

    .. code-block:: bash

        salt '*' glance.image_get
    '''
    nt_ks = _auth(profile)
    ret = {}
    if name:
        for image in nt_ks.images.list():
            if image.name == name:
                id = image.id  # pylint: disable=C0103
                continue
    if not id:
        return {'Error': 'Unable to resolve image id'}
    image = nt_ks.images.get(id)
    ret[image.name] = {
            'id': image.id,
            'name': image.name,
            'checksum': image.checksum,
            'container_format': image.container_format,
            'created_at': image.created_at,
            'deleted': image.deleted,
            'disk_format': image.disk_format,
            'is_public': image.is_public,
            'min_disk': image.min_disk,
            'min_ram': image.min_ram,
            'owner': image.owner,
            'protected': image.protected,
            'size': image.size,
            'status': image.status,
            'updated_at': image.updated_at,
            }
    return ret

def image_list(id=None, profile=None):  # pylint: disable=C0103
    '''
    Return a list of available images (glance image-list)

    CLI Example:

    .. code-block:: bash

        salt '*' glance.image_list
    '''
    nt_ks = _auth(profile)
    ret = {}
    for image in nt_ks.images.list():
        ret[image.name] = {
                'id': image.id,
                'name': image.name,
                'checksum': image.checksum,
                'container_format': image.container_format,
                'created_at': image.created_at,
                'deleted': image.deleted,
                'disk_format': image.disk_format,
                'is_public': image.is_public,
                'min_disk': image.min_disk,
                'min_ram': image.min_ram,
                'owner': image.owner,
                'protected': image.protected,
                'size': image.size,
                'status': image.status,
                'updated_at': image.updated_at,
            }
        if id == image.id:
            return ret[image.name]
    return ret

def _item_list(profile=None):
    '''
    Template for writing list functions
    Return a list of available items (glance items-list)

    CLI Example:

    .. code-block:: bash

        salt '*' glance.item_list
    '''
    nt_ks = _auth(profile)
    ret = []
    for item in nt_ks.items.list():
        ret.append(item.__dict__)
        #ret[item.name] = {
        #        'name': item.name,
        #    }
    return ret

#The following is a list of functions that need to be incorporated in the
#glance module. This list should be updated as functions are added.

#image-download      Download a specific image.
#image-update        Update a specific image.
#member-create       Share a specific image with a tenant.
#member-delete       Remove a shared image from a tenant.
#member-list         Describe sharing permissions by image or tenant.


text:
layout: post
status: publish
published: true
title: Choosing an Scheduler Service for Workflows in ASP.NET
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 914
wordpress_url: http://winterdom.com/2006/04/choosinganschedulerserviceforworkflowsinaspnet
date: '2006-04-28 14:25:23 +0000'
date_gmt: '2006-04-28 14:25:23 +0000'
categories:
- Architecture
- WinFX
- Workflow
tags: []
comments: []
---

The Advanced Workflow

blog has an interesting

post on choosing the correct scheduling service for the Windows Workflow

Runtime when you are going to be running workflows from within ASP.NET

applications. The recommendation is to use the ManualWorkflowSchedulerService

instead of the DefaultWorkflowSchedulerService that is normally used in other

scenarios, because it forces an explicit model instead of stealing threads from

the ASP.NET Thread Pool.

The benefit of this is that it solved some potential problems under stress

and guarantees a more optimal use of the threads available. The downside is that

it becomes the responsability of the developer and the ASP.NET application that

hosts the runtime choosing when to allow workflows to be executed. In other

words, the flow of the execution context from regular ASP.NET code to Workflow

Code becomes explicit: you have to choose when to yield your execution thread

over to the workflow runtime. This is significant because you are responsible

for doing this every time, including when indirect behavior in the workflow

is triggered, such as a long-running workflow getting reloaded for execution, or

when a delay fires. Basically, I think this means that your developer

responsability as a workflow scheduler is somewhat more complex than just

calling workflows when necessary (there are quite a lot of discussions about

this topic over on the WF

forums).

Personally my opinion is: while

hosting WF in ASP.NET can be seen as useful (and possibly simpler for some

scenarios), this is only an acceptable for short-lived workflows such as page

flows (modeling page interactions). ASP.NET most certainly is not, to me, an

acceptable hosting environment for long-running workflows.

Now, I'll be

honest and tell you that I don't know what an alternative hosting model might

be. Most likely, we won't have some kind of really robust hosting

environment until (and if) BizTalk 200X (with X>6) ships with WF facilities

built-in (and I don't know how much change we'll need to see in WF itself for

this to be a reality).

I would consider hosting my long-running workflows inside a

Windows Service instead, and take advantage of the SCM facilities for automatic

restarting of failed services, and possibly look into clustering the service in

an active/passive fashion. This does bring a few problems with it, of course,

and will take quite a bit more work, since it requires you to implement

communicating the workflows in your custom host with the external applications

that access it, but that can be helped by exposing workflows as WCF services (a

pattern advocated in the post,

as well).

Update: Paul Andrew posts about upcoming

changes to the ManualWorkflowSchedulerService post-Beta2.2 which should

alleviate some of the issues with ASP.NET Hosting.


text:
#include <typeinfo>  // for 'typeid' to work

#include "unicode/utypes.h"
#include "unicode/ustring.h"
#include "unicode/ucnv_err.h"
#include "unicode/uchar.h"
#include "unicode/umsg.h"
#include "unicode/rbnf.h"
#include "cmemory.h"
#include "util.h"
#include "uassert.h"
#include "ustrfmt.h"
#include "uvector.h"

#include "unicode/selfmt.h"
#include "selfmtimpl.h"

#if !UCONFIG_NO_FORMATTING

U_NAMESPACE_BEGIN

UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SelectFormat)

#define MAX_KEYWORD_SIZE 30
static const UChar SELECT_KEYWORD_OTHER[] = {LOW_O, LOW_T, LOW_H, LOW_E, LOW_R, 0};

SelectFormat::SelectFormat(const UnicodeString& pat, UErrorCode& status) : parsedValuesHash(NULL) {
   if (U_FAILURE(status)) {
      return;
   }
   initHashTable(status);
   applyPattern(pat, status);
}

SelectFormat::SelectFormat(const SelectFormat& other) : Format(other), parsedValuesHash(NULL) {
   UErrorCode status = U_ZERO_ERROR;
   pattern = other.pattern;
   copyHashtable(other.parsedValuesHash, status);
}

SelectFormat::~SelectFormat() {
  cleanHashTable();
}

void SelectFormat::initHashTable(UErrorCode &status) {
  if (U_FAILURE(status)) {
    return;
  }
  // has inited
  if (parsedValuesHash != NULL) {
    return;
  }

  parsedValuesHash = new Hashtable(TRUE, status);
  if (U_FAILURE(status)) {
    cleanHashTable();
    return;
  } else {
    if (parsedValuesHash == NULL) {
      status = U_MEMORY_ALLOCATION_ERROR;
      return;
    }
  }
  // to use hashtable->equals(), must set Value Compartor.
  parsedValuesHash->setValueComparator(uhash_compareCaselessUnicodeString);
}

void SelectFormat::cleanHashTable() {
  if (parsedValuesHash != NULL) {
    delete parsedValuesHash;
    parsedValuesHash = NULL;
  }
}

void
SelectFormat::applyPattern(const UnicodeString& newPattern, UErrorCode& status) {
    if (U_FAILURE(status)) {
      return;
    }

    pattern = newPattern;
    enum State{ startState, keywordState, pastKeywordState, phraseState};

    //Initialization
    UnicodeString keyword ;
    UnicodeString phrase ;
    UnicodeString* ptrPhrase ;
    int32_t braceCount = 0;

    if (parsedValuesHash == NULL) {
      initHashTable(status);
      if (U_FAILURE(status)) {
        return;
      }
    }
    parsedValuesHash->removeAll();
    parsedValuesHash->setValueDeleter(uhash_deleteUnicodeString);

    //Process the state machine
    State state = startState;
    for (int32_t i = 0; i < pattern.length(); ++i) {
        //Get the character and check its type
        UChar ch = pattern.charAt(i);
        CharacterClass type = classifyCharacter(ch);

        //Allow any character in phrase but nowhere else
        if ( type == tOther ) {
            if ( state == phraseState ){
                phrase += ch;
                continue;
            }else {
                status = U_PATTERN_SYNTAX_ERROR;
                cleanHashTable();
                return;
            }
        }

        //Process the state machine
        switch (state) {
            //At the start of pattern
            case startState:
                switch (type) {
                    case tSpace:
                        break;
                    case tStartKeyword:
                        state = keywordState;
                        keyword += ch;
                        break;
                    //If anything else is encountered, it's a syntax error
                    default:
                        status = U_PATTERN_SYNTAX_ERROR;
                        cleanHashTable();
                        return;
                }//end of switch(type)
                break;

            //Handle the keyword state
            case keywordState:
                switch (type) {
                    case tSpace:
                        state = pastKeywordState;
                        break;
                    case tStartKeyword:
                    case tContinueKeyword:
                        keyword += ch;
                        break;
                    case tLeftBrace:
                        state = phraseState;
                        break;
                    //If anything else is encountered, it's a syntax error
                    default:
                        status = U_PATTERN_SYNTAX_ERROR;
                        cleanHashTable();
                        return;
                }//end of switch(type)
                break;

            //Handle the pastkeyword state
            case pastKeywordState:
                switch (type) {
                    case tSpace:
                        break;
                    case tLeftBrace:
                        state = phraseState;
                        break;
                    //If anything else is encountered, it's a syntax error
                    default:
                        status = U_PATTERN_SYNTAX_ERROR;
                        cleanHashTable();
                        return;
                }//end of switch(type)
                break;

            //Handle the phrase state
            case phraseState:
                switch (type) {
                    case tLeftBrace:
                        braceCount++;
                        phrase += ch;
                        break;
                    case tRightBrace:
                        //Matching keyword, phrase pair found
                        if (braceCount == 0){
                            //Check validity of keyword
                            if (parsedValuesHash->get(keyword) != NULL) {
                                status = U_DUPLICATE_KEYWORD;
                                cleanHashTable();
                                return;
                            }
                            if (keyword.length() == 0) {
                                status = U_PATTERN_SYNTAX_ERROR;
                                cleanHashTable();
                                return;
                            }

                            //Store the keyword, phrase pair in hashTable
                            ptrPhrase = new UnicodeString(phrase);
                            parsedValuesHash->put( keyword, ptrPhrase, status);

                            //Reinitialize
                            keyword.remove();
                            phrase.remove();
                            ptrPhrase = NULL;
                            state = startState;
                        }

                        if (braceCount > 0){
                            braceCount-- ;
                            phrase += ch;
                        }
                        break;
                    default:
                        phrase += ch;
                }//end of switch(type)
                break;

            //Handle the  default case of switch(state)
            default:
                status = U_PATTERN_SYNTAX_ERROR;
                cleanHashTable();
                return;

        }//end of switch(state)
    }

    //Check if the state machine is back to startState
    if ( state != startState){
        status = U_PATTERN_SYNTAX_ERROR;
        cleanHashTable();
        return;
    }

    //Check if "other" keyword is present
    if ( !checkSufficientDefinition() ) {
        status = U_DEFAULT_KEYWORD_MISSING;
        cleanHashTable();
    }
    return;
}

UnicodeString&
SelectFormat::format(const Formattable& obj,
                   UnicodeString& appendTo,
                   FieldPosition& pos,
                   UErrorCode& status) const
{
    switch (obj.getType())
    {
    case Formattable::kString:
        return format(obj.getString(), appendTo, pos, status);
    default:
        if( U_SUCCESS(status) ){
            status = U_ILLEGAL_ARGUMENT_ERROR;
        }
        return appendTo;
    }
}

UnicodeString&
SelectFormat::format(const UnicodeString& keyword,
                     UnicodeString& appendTo,
                     FieldPosition& /*pos */,
                     UErrorCode& status) const {

    if (U_FAILURE(status)) return appendTo;

    if (parsedValuesHash == NULL) {
        status = U_INVALID_FORMAT_ERROR;
        return appendTo;
    }

    //Check for the validity of the keyword
    if ( !checkValidKeyword(keyword) ){
        status = U_ILLEGAL_ARGUMENT_ERROR;
        return appendTo;
    }

    UnicodeString *selectedPattern = (UnicodeString *)parsedValuesHash->get(keyword);
    if (selectedPattern == NULL) {
        selectedPattern = (UnicodeString *)parsedValuesHash->get(SELECT_KEYWORD_OTHER);
    }

    return appendTo += *selectedPattern;
}

UnicodeString&
SelectFormat::toPattern(UnicodeString& appendTo) {
    return appendTo += pattern;
}

SelectFormat::CharacterClass
SelectFormat::classifyCharacter(UChar ch) const{
    if ((ch >= CAP_A) && (ch <= CAP_Z)) {
        return tStartKeyword;
    }
    if ((ch >= LOW_A) && (ch <= LOW_Z)) {
        return tStartKeyword;
    }
    if ((ch >= U_ZERO) && (ch <= U_NINE)) {
        return tContinueKeyword;
    }
    if ( uprv_isRuleWhiteSpace(ch) ){
        return tSpace;
    }
    switch (ch) {
        case LEFTBRACE:
            return tLeftBrace;
        case RIGHTBRACE:
            return tRightBrace;
        case HYPHEN:
        case LOWLINE:
            return tContinueKeyword;
        default :
            return tOther;
    }
}

UBool
SelectFormat::checkSufficientDefinition() {
    // Check that at least the default rule is defined.
    return (parsedValuesHash != NULL &&
           parsedValuesHash->get(SELECT_KEYWORD_OTHER) != NULL) ;
}

UBool
SelectFormat::checkValidKeyword(const UnicodeString& argKeyword ) const{
    int32_t len = argKeyword.length();
    if (len < 1){
        return FALSE;
    }
    CharacterClass type = classifyCharacter(argKeyword.charAt(0));
    if( type != tStartKeyword ){
        return FALSE;
    }

    for (int32_t i = 0; i < argKeyword.length(); ++i) {
        type = classifyCharacter(argKeyword.charAt(i));
        if( type != tStartKeyword && type != tContinueKeyword ){
            return FALSE;
        }
    }
    return TRUE;
}

Format* SelectFormat::clone() const
{
    return new SelectFormat(*this);
}

SelectFormat&
SelectFormat::operator=(const SelectFormat& other) {
    if (this != &other) {
        UErrorCode status = U_ZERO_ERROR;
        pattern = other.pattern;
        copyHashtable(other.parsedValuesHash, status);
    }
    return *this;
}

UBool
SelectFormat::operator==(const Format& other) const {
    if( this == &other){
        return TRUE;
    }
    if (typeid(*this) != typeid(other)) {
        return  FALSE;
    }
    SelectFormat* fmt = (SelectFormat*)&other;
    Hashtable* hashOther = fmt->parsedValuesHash;
    if ( parsedValuesHash == NULL && hashOther == NULL)
        return TRUE;
    if ( parsedValuesHash == NULL || hashOther == NULL)
        return FALSE;
    return parsedValuesHash->equals(*hashOther);
}

UBool
SelectFormat::operator!=(const Format& other) const {
    return  !operator==(other);
}

void
SelectFormat::parseObject(const UnicodeString& /*source*/,
                        Formattable& /*result*/,
                        ParsePosition& pos) const
{
    // TODO: not yet supported in icu4j and icu4c
    pos.setErrorIndex(pos.getIndex());
}

void
SelectFormat::copyHashtable(Hashtable *other, UErrorCode& status) {
    if (U_FAILURE(status)) {
      return;
    }
    if (other == NULL) {
      cleanHashTable();
      return;
    }
    if (parsedValuesHash == NULL) {
      initHashTable(status);
      if (U_FAILURE(status)) {
        return;
      }
    }

    parsedValuesHash->removeAll();
    parsedValuesHash->setValueDeleter(uhash_deleteUnicodeString);

    int32_t pos = -1;
    const UHashElement* elem = NULL;

    // walk through the hash table and create a deep clone
    while ((elem = other->nextElement(pos)) != NULL){
        const UHashTok otherKeyTok = elem->key;
        UnicodeString* otherKey = (UnicodeString*)otherKeyTok.pointer;
        const UHashTok otherKeyToVal = elem->value;
        UnicodeString* otherValue = (UnicodeString*)otherKeyToVal.pointer;
        parsedValuesHash->put(*otherKey, new UnicodeString(*otherValue), status);
        if (U_FAILURE(status)){
            cleanHashTable();
            return;
        }
    }
}

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_FORMATTING */

//eof


text:
Getting Started
===============

Installation
------------

Method 1
^^^^^^^^
Download the setup script `InitialSetup.jl <https://github.com/GDPlumb/SnFFT.jl/blob/master/InitialSetUp.jl>`_.
Then open a Julia session and run:

.. code-block:: julia

    julia> require("InitialSetUp.jl")

This script will install and load the SnFFT library and then run the examples.

Method 2
^^^^^^^^
SnFFT can also be installed using Julia's pakage manager as follows:

.. code-block:: julia

    julia> Pkg.add("SnFFT")

Set Up
------
After the installation, the user can load the library with:

.. code-block:: julia

    julia> using SnFFT

By default, lower level functions in the source code are not made available during installation.
These functions are often wrapper or helper functions that may not be relevant to most users.
However, these internal functions can be made available by modifying the file `SnFFT.jl <https://github.com/GDPlumb/SnFFT.jl/blob/master/src/SnFFT.jl>`_.

Parallelism
-----------
*SnFFT* allows the user to compute fast Fourier transforms and inverse fast Fourier transforms in parralel with no change to their code.
On startup, simply run:

.. code-block:: julia

	julia> addprocs(p)
	julia> using SnFFT

This will and *p* worker processes and load the SnFFT library onto them.
Afterwards, parts of *SnFFT* will automatically run in parallel, if their heuristics think say that it will be beneficial.


text:
export const RECEIVE_PAGE_META = "RECEIVE_PAGE_META";

export default (state = {}, {type, payload}) => {
  switch(type) {
    case RECEIVE_PAGE_META: {
      const {title, meta} = payload;
      return {title, meta}
    }

    default:
      return state;
  }
}

export const selectPageMeta = (state) => state;
export const selectPageTitle = (state) => state.title;
export const selectMetaTags = (state) => state.meta;