text:
package parser

import (
	"fmt"
	"sort"

	"github.com/robertkrimen/otto/file"
	"github.com/robertkrimen/otto/token"
)

const (
	err_UnexpectedToken      = "Unexpected token %v"
	err_UnexpectedEndOfInput = "Unexpected end of input"
	err_UnexpectedEscape     = "Unexpected escape"
)

//    UnexpectedNumber:  'Unexpected number',
//    UnexpectedString:  'Unexpected string',
//    UnexpectedIdentifier:  'Unexpected identifier',
//    UnexpectedReserved:  'Unexpected reserved word',
//    NewlineAfterThrow:  'Illegal newline after throw',
//    InvalidRegExp: 'Invalid regular expression',
//    UnterminatedRegExp:  'Invalid regular expression: missing /',
//    InvalidLHSInAssignment:  'Invalid left-hand side in assignment',
//    InvalidLHSInForIn:  'Invalid left-hand side in for-in',
//    MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
//    NoCatchOrFinally:  'Missing catch or finally after try',
//    UnknownLabel: 'Undefined label \'%0\'',
//    Redeclaration: '%0 \'%1\' has already been declared',
//    IllegalContinue: 'Illegal continue statement',
//    IllegalBreak: 'Illegal break statement',
//    IllegalReturn: 'Illegal return statement',
//    StrictModeWith:  'Strict mode code may not include a with statement',
//    StrictCatchVariable:  'Catch variable may not be eval or arguments in strict mode',
//    StrictVarName:  'Variable name may not be eval or arguments in strict mode',
//    StrictParamName:  'Parameter name eval or arguments is not allowed in strict mode',
//    StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
//    StrictFunctionName:  'Function name may not be eval or arguments in strict mode',
//    StrictOctalLiteral:  'Octal literals are not allowed in strict mode.',
//    StrictDelete:  'Delete of an unqualified identifier in strict mode.',
//    StrictDuplicateProperty:  'Duplicate data property in object literal not allowed in strict mode',
//    AccessorDataProperty:  'Object literal may not have data and accessor property with the same name',
//    AccessorGetSet:  'Object literal may not have multiple get/set accessors with the same name',
//    StrictLHSAssignment:  'Assignment to eval or arguments is not allowed in strict mode',
//    StrictLHSPostfix:  'Postfix increment/decrement may not have eval or arguments operand in strict mode',
//    StrictLHSPrefix:  'Prefix increment/decrement may not have eval or arguments operand in strict mode',
//    StrictReservedWord:  'Use of future reserved word in strict mode'

// A SyntaxError is a description of an ECMAScript syntax error.

// An Error represents a parsing error. It includes the position where the error occurred and a message/description.
type Error struct {
	Position file.Position
	Message  string
}

// FIXME Should this be "SyntaxError"?

func (self Error) Error() string {
	filename := self.Position.Filename
	if filename == "" {
		filename = "(anonymous)"
	}
	return fmt.Sprintf("%s: Line %d:%d %s",
		filename,
		self.Position.Line,
		self.Position.Column,
		self.Message,
	)
}

func (self *_parser) error(place interface{}, msg string, msgValues ...interface{}) *Error {
	idx := file.Idx(0)
	switch place := place.(type) {
	case int:
		idx = self.idxOf(place)
	case file.Idx:
		if place == 0 {
			idx = self.idxOf(self.chrOffset)
		} else {
			idx = place
		}
	default:
		panic(fmt.Errorf("error(%T, ...)", place))
	}

	position := self.position(idx)
	msg = fmt.Sprintf(msg, msgValues...)
	self.errors.Add(position, msg)
	return self.errors[len(self.errors)-1]
}

func (self *_parser) errorUnexpected(idx file.Idx, chr rune) error {
	if chr == -1 {
		return self.error(idx, err_UnexpectedEndOfInput)
	}
	return self.error(idx, err_UnexpectedToken, token.ILLEGAL)
}

func (self *_parser) errorUnexpectedToken(tkn token.Token) error {
	switch tkn {
	case token.EOF:
		return self.error(file.Idx(0), err_UnexpectedEndOfInput)
	}
	value := tkn.String()
	switch tkn {
	case token.BOOLEAN, token.NULL:
		value = self.literal
	case token.IDENTIFIER:
		return self.error(self.idx, "Unexpected identifier")
	case token.KEYWORD:
		// TODO Might be a future reserved word
		return self.error(self.idx, "Unexpected reserved word")
	case token.NUMBER:
		return self.error(self.idx, "Unexpected number")
	case token.STRING:
		return self.error(self.idx, "Unexpected string")
	}
	return self.error(self.idx, err_UnexpectedToken, value)
}

// ErrorList is a list of *Errors.
//
type ErrorList []*Error

// Add adds an Error with given position and message to an ErrorList.
func (self *ErrorList) Add(position file.Position, msg string) {
	*self = append(*self, &Error{position, msg})
}

// Reset resets an ErrorList to no errors.
func (self *ErrorList) Reset() { *self = (*self)[0:0] }

func (self ErrorList) Len() int      { return len(self) }
func (self ErrorList) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self ErrorList) Less(i, j int) bool {
	x := &self[i].Position
	y := &self[j].Position
	if x.Filename < y.Filename {
		return true
	}
	if x.Filename == y.Filename {
		if x.Line < y.Line {
			return true
		}
		if x.Line == y.Line {
			return x.Column < y.Column
		}
	}
	return false
}

func (self ErrorList) Sort() {
	sort.Sort(self)
}

// Error implements the Error interface.
func (self ErrorList) Error() string {
	switch len(self) {
	case 0:
		return "no errors"
	case 1:
		return self[0].Error()
	}
	return fmt.Sprintf("%s (and %d more errors)", self[0].Error(), len(self)-1)
}

// Err returns an error equivalent to this ErrorList.
// If the list is empty, Err returns nil.
func (self ErrorList) Err() error {
	if len(self) == 0 {
		return nil
	}
	return self
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="../css/ol.css" type="text/css">
    <link rel="stylesheet" href="../resources/bootstrap/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="../resources/layout.css" type="text/css">
    <link rel="stylesheet" href="../resources/bootstrap/css/bootstrap-responsive.min.css" type="text/css">
    <title>Symbols with WebGL example</title>

           OpenLayers 3 Examples

Symbols with WebGL example

Using symbols in an atlas with WebGL.

When using symbol styles with WebGL, OpenLayers would render the symbol
            on a temporary image and would create a WebGL texture for each image. For a
            better performance, it is recommended to use atlas images (similar to
            image sprites with CSS), so that the number of textures is reduced. OpenLayers
            provides an AtlasManager, which when passed to the constructor
            of a symbol style, will create atlases for the symbols.

See the symbol-atlas-webgl.js source to see how this is done.

webgl, symbol, atlas, vector, point

redpajama_set_name: RedPajamaGithub


text:
import { module } from 'angular';

import IntroController from './controllers/intro.controller';
import GameController from './controllers/game.controller';
import HighscoreController from './controllers/highscore.controller';

import GameService from './service/game.service';
import HttpClientService from './service/http-client.service';
import PointsCalculatorService from './service/points-calculator.service';
import WordGeneratorService from './service/word-generator.service';
import TimeService from './service/time.service';
import WordHandlerService from './service/word-handler.service';
import HighscoreService from './service/highscore.service';

export let app: ng.IModule = module('words', [require('angular-route')]);

app.controller('IntroController', IntroController);
app.controller('GameController', GameController);
app.controller('HighscoreController', HighscoreController);

app.service('GameService', GameService);
app.service('HttpClientService', HttpClientService);
app.service('PointsCalculatorService', PointsCalculatorService);
app.service('WordGeneratorService', WordGeneratorService);
app.service('TimeService', TimeService);
app.service('WordHandlerService', WordHandlerService);
app.service('HighscoreService', HighscoreService);

app.config(function ($routeProvider: angular.route.IRouteProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'src/view/intro.html',
            controller: 'IntroController',
            controllerAs: 'intro'
        })
        .when('/game', {
            templateUrl: 'src/view/game.html',
            controller: 'GameController',
            controllerAs: 'game'
        })
        .when('/highscore', {
            templateUrl: 'src/view/highscore.html',
            controller: 'HighscoreController',
            controllerAs: 'highscore'
        });
});


text:
package executor

import (
	"context"
	gjson "encoding/json"
	"fmt"

	"github.com/pingcap/errors"
	"github.com/pingcap/tidb/domain/infosync"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/parser/ast"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/parser/mysql"
	"github.com/pingcap/tidb/privilege"
	"github.com/pingcap/tidb/store/helper"
	"github.com/pingcap/tidb/table"
	"github.com/pingcap/tidb/tablecodec"
	"github.com/pingcap/tidb/types/json"
	"github.com/pingcap/tidb/util/codec"
	"github.com/pingcap/tidb/util/sqlexec"
	"golang.org/x/exp/slices"
)

type showPlacementLabelsResultBuilder struct {
	labelKey2values map[string]interface{}
}

func (b *showPlacementLabelsResultBuilder) AppendStoreLabels(bj json.BinaryJSON) error {
	if b.labelKey2values == nil {
		b.labelKey2values = make(map[string]interface{})
	}

	data, err := bj.MarshalJSON()
	if err != nil {
		return errors.Trace(err)
	}

	if string(data) == "null" {
		return nil
	}

	if bj.TypeCode != json.TypeCodeArray {
		return errors.New("only array or null type is allowed")
	}

	labels := make([]*helper.StoreLabel, 0, bj.GetElemCount())
	err = gjson.Unmarshal(data, &labels)
	if err != nil {
		return errors.Trace(err)
	}

	for _, label := range labels {
		if values, ok := b.labelKey2values[label.Key]; ok {
			values.(map[string]interface{})[label.Value] = true
		} else {
			b.labelKey2values[label.Key] = map[string]interface{}{label.Value: true}
		}
	}

	return nil
}

func (b *showPlacementLabelsResultBuilder) BuildRows() ([][]interface{}, error) {
	rows := make([][]interface{}, 0, len(b.labelKey2values))
	for _, key := range b.sortMapKeys(b.labelKey2values) {
		values := b.sortMapKeys(b.labelKey2values[key].(map[string]interface{}))
		d, err := gjson.Marshal(values)
		if err != nil {
			return nil, errors.Trace(err)
		}

		valuesJSON := json.BinaryJSON{}
		err = valuesJSON.UnmarshalJSON(d)
		if err != nil {
			return nil, errors.Trace(err)
		}

		rows = append(rows, []interface{}{key, valuesJSON})
	}

	return rows, nil
}

func (b *showPlacementLabelsResultBuilder) sortMapKeys(m map[string]interface{}) []string {
	sorted := make([]string, 0, len(m))
	for key := range m {
		sorted = append(sorted, key)
	}

	slices.Sort(sorted)
	return sorted
}

func (e *ShowExec) fetchShowPlacementLabels(ctx context.Context) error {
	exec := e.ctx.(sqlexec.RestrictedSQLExecutor)
	rows, _, err := exec.ExecRestrictedSQL(ctx, nil, "SELECT DISTINCT LABEL FROM %n.%n", "INFORMATION_SCHEMA", infoschema.TableTiKVStoreStatus)
	if err != nil {
		return errors.Trace(err)
	}

	b := &showPlacementLabelsResultBuilder{}
	for _, row := range rows {
		bj := row.GetJSON(0)
		if err := b.AppendStoreLabels(bj); err != nil {
			return err
		}
	}

	result, err := b.BuildRows()
	if err != nil {
		return err
	}

	for _, row := range result {
		e.appendRow(row)
	}

	return nil
}

func (e *ShowExec) fetchShowPlacementForDB(ctx context.Context) (err error) {
	checker := privilege.GetPrivilegeManager(e.ctx)
	if checker != nil && e.ctx.GetSessionVars().User != nil {
		if !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, e.DBName.String()) {
			return e.dbAccessDenied()
		}
	}

	dbInfo, ok := e.is.SchemaByName(e.DBName)
	if !ok {
		return infoschema.ErrDatabaseNotExists.GenWithStackByArgs(e.DBName.O)
	}

	placement, err := e.getDBPlacement(dbInfo)
	if err != nil {
		return err
	}

	if placement != nil {
		state, err := fetchDBScheduleState(ctx, nil, dbInfo)
		if err != nil {
			return err
		}
		e.appendRow([]interface{}{"DATABASE " + dbInfo.Name.String(), placement.String(), state.String()})
	}

	return nil
}

func (e *ShowExec) fetchShowPlacementForTable(ctx context.Context) (err error) {
	tbl, err := e.getTable()
	if err != nil {
		return err
	}

	tblInfo := tbl.Meta()
	placement, err := e.getTablePlacement(tblInfo)
	if err != nil {
		return err
	}

	if placement != nil {
		state, err := fetchTableScheduleState(ctx, nil, tblInfo)
		if err != nil {
			return err
		}
		ident := ast.Ident{Schema: e.Table.DBInfo.Name, Name: tblInfo.Name}
		e.appendRow([]interface{}{"TABLE " + ident.String(), placement.String(), state.String()})
	}

	return nil
}

func (e *ShowExec) fetchShowPlacementForPartition(ctx context.Context) (err error) {
	tbl, err := e.getTable()
	if err != nil {
		return err
	}

	tblInfo := tbl.Meta()
	if tblInfo.Partition == nil {
		return errors.Trace(table.ErrUnknownPartition.GenWithStackByArgs(e.Partition.O, tblInfo.Name.O))
	}

	var partition *model.PartitionDefinition
	for i := range tblInfo.Partition.Definitions {
		par := tblInfo.Partition.Definitions[i]
		if par.Name.L == e.Partition.L {
			partition = &par
			break
		}
	}

	if partition == nil {
		return errors.Trace(table.ErrUnknownPartition.GenWithStackByArgs(e.Partition.O, tblInfo.Name.O))
	}

	placement, err := e.getTablePlacement(tblInfo)
	if err != nil {
		return err
	}

	placement, err = e.getPartitionPlacement(placement, partition)
	if err != nil {
		return err
	}

	if placement != nil {
		state, err := fetchPartitionScheduleState(ctx, nil, partition)
		if err != nil {
			return err
		}
		tableIndent := ast.Ident{Schema: e.Table.DBInfo.Name, Name: tblInfo.Name}
		e.appendRow([]interface{}{
			fmt.Sprintf("TABLE %s PARTITION %s", tableIndent.String(), partition.Name.String()),
			placement.String(),
			state.String(),
		})
	}

	return nil
}

func (e *ShowExec) fetchShowPlacement(ctx context.Context) error {
	if err := e.fetchAllPlacementPolicies(); err != nil {
		return err
	}

	scheduled := make(map[int64]infosync.PlacementScheduleState)

	if err := e.fetchAllDBPlacements(ctx, scheduled); err != nil {
		return err
	}

	return e.fetchAllTablePlacements(ctx, scheduled)
}

func (e *ShowExec) fetchAllPlacementPolicies() error {
	policies := e.is.AllPlacementPolicies()
	slices.SortFunc(policies, func(i, j *model.PolicyInfo) bool { return i.Name.O < j.Name.O })
	for _, policy := range policies {
		name := policy.Name
		settings := policy.PlacementSettings
		e.appendRow([]interface{}{"POLICY " + name.String(), settings.String(), "NULL"})
	}

	return nil
}

func (e *ShowExec) fetchAllDBPlacements(ctx context.Context, scheduleState map[int64]infosync.PlacementScheduleState) error {
	checker := privilege.GetPrivilegeManager(e.ctx)
	activeRoles := e.ctx.GetSessionVars().ActiveRoles

	dbs := e.is.AllSchemas()
	slices.SortFunc(dbs, func(i, j *model.DBInfo) bool { return i.Name.O < j.Name.O })

	for _, dbInfo := range dbs {
		if e.ctx.GetSessionVars().User != nil && checker != nil && !checker.DBIsVisible(activeRoles, dbInfo.Name.O) {
			continue
		}

		placement, err := e.getDBPlacement(dbInfo)
		if err != nil {
			return err
		}

		if placement != nil {
			state, err := fetchDBScheduleState(ctx, scheduleState, dbInfo)
			if err != nil {
				return err
			}
			e.appendRow([]interface{}{"DATABASE " + dbInfo.Name.String(), placement.String(), state.String()})
		}
	}

	return nil
}

type tableRowSet struct {
	name string
	rows [][]interface{}
}

func (e *ShowExec) fetchAllTablePlacements(ctx context.Context, scheduleState map[int64]infosync.PlacementScheduleState) error {
	checker := privilege.GetPrivilegeManager(e.ctx)
	activeRoles := e.ctx.GetSessionVars().ActiveRoles

	dbs := e.is.AllSchemas()
	slices.SortFunc(dbs, func(i, j *model.DBInfo) bool { return i.Name.O < j.Name.O })

	for _, dbInfo := range dbs {
		tableRowSets := make([]tableRowSet, 0)

		for _, tbl := range e.is.SchemaTables(dbInfo.Name) {
			tblInfo := tbl.Meta()
			if checker != nil && !checker.RequestVerification(activeRoles, dbInfo.Name.O, tblInfo.Name.O, "", mysql.AllPrivMask) {
				continue
			}

			var rows [][]interface{}
			ident := ast.Ident{Schema: dbInfo.Name, Name: tblInfo.Name}
			tblPlacement, err := e.getTablePlacement(tblInfo)
			if err != nil {
				return err
			}

			if tblPlacement != nil {
				state, err := fetchTableScheduleState(ctx, scheduleState, tblInfo)
				if err != nil {
					return err
				}
				rows = append(rows, []interface{}{"TABLE " + ident.String(), tblPlacement.String(), state.String()})
			}

			if tblInfo.Partition != nil {
				for i := range tblInfo.Partition.Definitions {
					partition := tblInfo.Partition.Definitions[i]
					partitionPlacement, err := e.getPartitionPlacement(tblPlacement, &partition)
					if err != nil {
						return err
					}

					if partitionPlacement != nil {
						state, err := fetchPartitionScheduleState(ctx, scheduleState, &partition)
						if err != nil {
							return err
						}
						rows = append(rows, []interface{}{
							fmt.Sprintf("TABLE %s PARTITION %s", ident.String(), partition.Name.String()),
							partitionPlacement.String(),
							state.String(),
						})
					}
				}
			}

			if len(rows) > 0 {
				tableRowSets = append(tableRowSets, struct {
					name string
					rows [][]interface{}
				}{
					name: tblInfo.Name.String(),
					rows: rows,
				})
			}
		}

		slices.SortFunc(tableRowSets, func(i, j tableRowSet) bool { return i.name < j.name })
		for _, rowSet := range tableRowSets {
			for _, row := range rowSet.rows {
				e.appendRow(row)
			}
		}
	}

	return nil
}

func (e *ShowExec) getDBPlacement(dbInfo *model.DBInfo) (*model.PlacementSettings, error) {
	return e.getPolicyPlacement(dbInfo.PlacementPolicyRef)
}

func (e *ShowExec) getTablePlacement(tblInfo *model.TableInfo) (*model.PlacementSettings, error) {
	return e.getPolicyPlacement(tblInfo.PlacementPolicyRef)
}

func (e *ShowExec) getPartitionPlacement(tblPlacement *model.PlacementSettings, partition *model.PartitionDefinition) (*model.PlacementSettings, error) {
	placement, err := e.getPolicyPlacement(partition.PlacementPolicyRef)
	if err != nil {
		return nil, err
	}

	if placement != nil {
		return placement, nil
	}

	return tblPlacement, nil
}

func (e *ShowExec) getPolicyPlacement(policyRef *model.PolicyRefInfo) (settings *model.PlacementSettings, err error) {
	if policyRef == nil {
		return nil, nil
	}

	policy, ok := e.is.PolicyByName(policyRef.Name)
	if !ok {
		return nil, errors.Errorf("Policy with name '%s' not found", policyRef.Name)
	}
	return policy.PlacementSettings, nil
}

func fetchScheduleState(ctx context.Context, scheduleState map[int64]infosync.PlacementScheduleState, id int64) (infosync.PlacementScheduleState, error) {
	if s, ok := scheduleState[id]; ok {
		return s, nil
	}
	startKey := codec.EncodeBytes(nil, tablecodec.GenTablePrefix(id))
	endKey := codec.EncodeBytes(nil, tablecodec.GenTablePrefix(id+1))
	schedule, err := infosync.GetReplicationState(ctx, startKey, endKey)
	if err == nil && scheduleState != nil {
		scheduleState[id] = schedule
	}
	return schedule, err
}

func fetchPartitionScheduleState(ctx context.Context, scheduleState map[int64]infosync.PlacementScheduleState, part *model.PartitionDefinition) (infosync.PlacementScheduleState, error) {
	return fetchScheduleState(ctx, scheduleState, part.ID)
}

func fetchTableScheduleState(ctx context.Context, scheduleState map[int64]infosync.PlacementScheduleState, table *model.TableInfo) (infosync.PlacementScheduleState, error) {
	state := infosync.PlacementScheduleStateScheduled

	schedule, err := fetchScheduleState(ctx, scheduleState, table.ID)
	if err != nil {
		return state, err
	}
	state = accumulateState(state, schedule)
	if state != infosync.PlacementScheduleStateScheduled {
		return state, nil
	}

	if table.GetPartitionInfo() != nil {
		for _, part := range table.GetPartitionInfo().Definitions {
			schedule, err = fetchScheduleState(ctx, scheduleState, part.ID)
			if err != nil {
				return infosync.PlacementScheduleStatePending, err
			}
			state = accumulateState(state, schedule)
			if state != infosync.PlacementScheduleStateScheduled {
				break
			}
		}
	}

	return schedule, nil
}

func fetchDBScheduleState(ctx context.Context, scheduleState map[int64]infosync.PlacementScheduleState, db *model.DBInfo) (infosync.PlacementScheduleState, error) {
	state := infosync.PlacementScheduleStateScheduled
	for _, table := range db.Tables {
		schedule, err := fetchTableScheduleState(ctx, scheduleState, table)
		if err != nil {
			return state, err
		}
		state = accumulateState(state, schedule)
		if state != infosync.PlacementScheduleStateScheduled {
			break
		}
	}
	return state, nil
}

func accumulateState(curr, news infosync.PlacementScheduleState) infosync.PlacementScheduleState {
	a, b := int(curr), int(news)
	if a > b {
		return news
	}
	return curr
}


text:
#include "Application.h"
#include <thread>
#include "Task.h"
#include "task_group.h"
#if !QT_STATIC
#include <dw/AutoTimer.h>
#endif

Application::Application()
{
	m_threads = std::thread::hardware_concurrency();
	m_tasks = m_threads * 4;
}

Application::~Application()
{

}

void Application::reset(U32 burstLength)
{
	// before we sum our result, we set everything to zero
	m_dmgPerBurstTotal = 0.0f;
	m_dmgPerBurstBody = 0.0f;
	m_dmgPerBurstHead = 0.0f;

	m_headrate.clear();
	m_bodyrate.clear();
	m_sumRates.clear();

	m_headrate.resize(burstLength);
	m_bodyrate.resize(burstLength);
	m_sumRates.resize(burstLength);
}

void Application::sumResult(U32 burstLength)
{
	// sum results
	for (int j = 0; j < burstLength; j++)
	{
		m_sumRates.at(j) = m_headrate.at(j) + m_bodyrate.at(j);
		m_dmgPerBurstTotal += m_sumRates.at(j);
		m_dmgPerBurstBody += m_bodyrate.at(j);
		m_dmgPerBurstHead += m_headrate.at(j);
	}
}

void Application::updateResult(const OutputData &result, U32 burstLength, U32 runs)
{
	for (int j = 0; j < burstLength; j++)
	{
		m_headrate.at(j) += static_cast<F32>(result.headshotCount.at(j)) / runs;
		m_bodyrate.at(j) += static_cast<F32>(result.bodyshotCount.at(j)) / runs;
	}
}

void Application::run(const InputSettingsUI &inputSettings, bool bMT)
{
	reset(inputSettings.m_burstlength);

	if (bMT)
		runMT(inputSettings);
	else
		runSingle(inputSettings);
}

void Application::runSingle(const InputSettingsUI &inputSettings)
{
	std::mt19937_64 m_rng;

	U32 burstLength = inputSettings.m_burstlength;
	U32 runs = inputSettings.m_runs;

	InputSettings settings(inputSettings);

	Task task(std::mt19937_64::default_seed, burstLength);
	auto result = task(0, runs, settings);

	// sum results
	updateResult(result, burstLength, runs);
	sumResult(burstLength);
}

void Application::runMT(const InputSettingsUI &inputSettings)
{
	const U32 minWorkForTask = 500000u;

	const U32 burstLength = inputSettings.m_burstlength;
	const U32 runs = inputSettings.m_runs;
	U32 totalWork = burstLength * runs;
	const U32 taskCount = totalWork / minWorkForTask;
	// have to add one, don't forget main thread (also divide by zero)
	const U32 workPerTask = totalWork / (taskCount + 1);
	printf("taskCount %u\n", taskCount);
	printf("workPerTask %u\n", workPerTask);

	std::vector<U32> seeds(taskCount);
	std::seed_seq seedSeq;

	seedSeq.generate(seeds.begin(), seeds.end());

#if !QT_STATIC
	AutoTimer timer;
#endif
	dw::task_group<OutputData> group;

	//Task task(seeds.at(0), burstLength);
	//auto ftr = std::async(std::move(task), 0, 1, settings);

	InputSettings settings(inputSettings);
	U32 i = 0;
	while (totalWork > minWorkForTask)
	{
		totalWork -= minWorkForTask;
		//group.create(Task(seeds.at(i), burstLength), from, to, settings);
		++i;
	}
	printf("totalWork %u\n", totalWork);
	//Task task(seeds.at(i), burstLength);
	//auto output = task(0, 0, settings);
	//updateResult(output, burstLength, runs);

	/*for (U32 i = 0; i < m_tasks; ++i)
	{
		const U32 from = (i * runs) / m_tasks;
		const U32 to = ((i + 1) * runs) / m_tasks;

		//Task task(seeds.at(i), burstLength);
		group.create(Task(seeds.at(i), burstLength), from, to, settings);
	}*/

	// sum results
	/*for (auto &it : group.getFutures())
	{
		auto result = it.get();
		updateResult(result, burstLength, runs);
	}

	sumResult(burstLength);*/
}

const std::vector<F32>& Application::getHeadrate() const
{
	return m_headrate;
}

const std::vector<F32>& Application::getBodyrate() const
{
	return m_bodyrate;
}

F32 Application::getDmgPerBurstTotal() const
{
	return m_dmgPerBurstTotal;
}

F32 Application::getDmgPerBurstBody() const
{
	return m_dmgPerBurstBody;
}

F32 Application::getDmgPerBurstHead() const
{
	return m_dmgPerBurstHead;
}

const std::vector<F32>& Application::getSumRates() const
{
	return m_sumRates;
}


text: A midi bridge to run on a Raspberry Pi for Rockband on xbox


text:
(function () {
    'use strict';

    angular
        .module('app')
        .factory('DocumentService', Service);

    function Service($http, $q) {
        var service = {};

        service.GetCurrent = GetCurrent;
        service.GetAll = GetAll;
        service.GetById = GetById;
        service.Create = Create;
        service.Update = Update;
        service.Delete = Delete;

        return service;

        function GetCurrent() {
            return $http.get('/api/document/current').then(handleSuccess, handleError);
        }

        function GetAll() {
            var then = $http.get('/api/document').then(handleSuccess, handleError);
            return then;
        }

        function GetById(_id) {
            var then = $http.get('/api/document/' + _id).then(handleSuccess, handleError);
            return then;
        }

        function Create(document) {
            return $http.post('/api/document', document).then(handleSuccess, handleError);
        }

        function Update(document) {
            return $http.put('/api/document/' + document._id, document).then(handleSuccess, handleError);
        }

        function Delete(_id) {
            return $http.delete('/api/document/' + _id).then(handleSuccess, handleError);
        }

        // private functions

        function handleSuccess(res) {
            return res.data;
        }

        function handleError(res) {
            return $q.reject(res.data);
        }
    }

})();


text:
import jQuery from "../core.js";
import nodeName from "../core/nodeName.js";

function getAll( context, tag ) {

	// Support: IE <=9 - 11+
	// Use typeof to avoid zero-argument method invocation on host objects (trac-15151)
	var ret;

	if ( typeof context.getElementsByTagName !== "undefined" ) {
		ret = context.getElementsByTagName( tag || "*" );

	} else if ( typeof context.querySelectorAll !== "undefined" ) {
		ret = context.querySelectorAll( tag || "*" );

	} else {
		ret = [];
	}

	if ( tag === undefined || tag && nodeName( context, tag ) ) {
		return jQuery.merge( [ context ], ret );
	}

	return ret;
}

export default getAll;


text:
class TranslatorGLSL : public TCompiler
{
  public:
    TranslatorGLSL(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output);

  protected:
    void initBuiltInFunctionEmulator(BuiltInFunctionEmulator *emu, int compileOptions) override;

    virtual void translate(TIntermNode *root, int compileOptions);

  private:
    void writeVersion(TIntermNode *root);
    void writeExtensionBehavior();
};

#endif  // COMPILER_TRANSLATOR_TRANSLATORGLSL_H_


text: default_app_config = 'readthedocs.organizations.apps.OrganizationsConfig'  # noqa


text:
'use strict';

const run = require('../run');

function gitPush(directory, origin, refs) {
  return run('git', ['push', origin].concat(refs), {
    cwd: directory,
  }).then(s => s.trim());
}

module.exports = gitPush;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="ar.com.uade.dao.model.TipoProducto" table="TIPOPRODUCTO">
		<id name="id">
			<column name="ID" />
		</id>
		<property column="DESCRIPCION" name="descripcion" />
	</class>
</hibernate-mapping>


text:
require 'test_helper'

class TargetTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
using System;
using System.Web;

namespace Provider.Models
{
    internal static class Util
    {
        internal static Uri GetAppPathRootedUri(string value) {
            string appPath = HttpContext.Current.Request.ApplicationPath.ToLowerInvariant();
            if (!appPath.EndsWith("/")) {
                appPath += "/";
            }

            return new Uri(HttpContext.Current.Request.Url, appPath + value);
        }
    }
}


text:
import {StyleSheet} from "aphrodite";

export const styles = StyleSheet.create({
  formGroup: {
    marginBottom: '8px',
  },
});


text:
#include <jni.h>

#include <string>
#include <assert.h>

#include <mesos/mesos.hpp>

#include "convert.hpp"

using namespace mesos;

using std::string;

// Facilities for loading Mesos-related classes with the correct
// ClassLoader. Unfortunately, JNI's FindClass uses the system
// ClassLoader when it is called from a C++ thread, but in Scala (and
// probably other Java environments too), this ClassLoader is not
// enough to locate mesos.jar. Instead, we try to capture
// Thread.currentThread()'s context ClassLoader when the Mesos library
// is initialized, in case it has more paths that we can search. We
// store this in mesosClassLoader and access it through
// FindMesosClass(). We initialize the mesosClassLoader variable in
// JNI_OnLoad and uninitialize it in JNI_OnUnLoad (see below).
//
// This code is based on Apache 2 licensed Android code obtained from
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/jni/AndroidRuntime.cpp;h=f61e2476c71191aa6eabc93bcb26b3c15ccf6136;hb=HEAD
namespace {

jweak mesosClassLoader = NULL; // Initialized in JNI_OnLoad later in this file.

jclass FindMesosClass(JNIEnv* env, const char* className)
{
  if (env->ExceptionCheck()) {
      fprintf(stderr, "ERROR: exception pending on entry to "
                      "FindMesosClass()\n");
      return NULL;
  }

  if (mesosClassLoader == NULL) {
    return env->FindClass(className);
  }

  // JNI FindClass uses class names with slashes, but
  // ClassLoader.loadClass uses the dotted "binary name"
  // format. Convert formats.
  string convName = className;
  for (int i = 0; i < convName.size(); i++) {
    if (convName[i] == '/')
      convName[i] = '.';
  }

  jclass javaLangClassLoader = env->FindClass("java/lang/ClassLoader");
  assert(javaLangClassLoader != NULL);
  jmethodID loadClass =
    env->GetMethodID(javaLangClassLoader,
                     "loadClass",
                     "(Ljava/lang/String;)Ljava/lang/Class;");
  assert(loadClass != NULL);

  // Create an object for the class name string; alloc could fail.
  jstring strClassName = env->NewStringUTF(convName.c_str());
  if (env->ExceptionCheck()) {
    fprintf(stderr, "ERROR: unable to convert '%s' to string\n",
            convName.c_str());
    return NULL;
  }

  // Try to find the named class.
  jclass cls = (jclass) env->CallObjectMethod(mesosClassLoader,
                                              loadClass,
                                              strClassName);

  if (env->ExceptionCheck()) {
    fprintf(stderr, "ERROR: unable to load class '%s' from %p\n",
            className, mesosClassLoader);
    return NULL;
  }

  return cls;
}

} // namespace {

// Called by JVM when it loads our library.
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* jvm, void* reserved)
{
  // Grab the context ClassLoader of the current thread, if any.
  JNIEnv* env;
  if (jvm->GetEnv((void**) &env, JNI_VERSION_1_2)) {
    return JNI_ERR; // JNI version not supported.
  }

  // Find thread's context class loader.
  jclass javaLangThread = env->FindClass("java/lang/Thread");
  assert(javaLangThread != NULL);

  jclass javaLangClassLoader = env->FindClass("java/lang/ClassLoader");
  assert(javaLangClassLoader != NULL);

  jmethodID currentThread = env->GetStaticMethodID(
      javaLangThread, "currentThread", "()Ljava/lang/Thread;");
  assert(currentThread != NULL);

  jmethodID getContextClassLoader = env->GetMethodID(
      javaLangThread, "getContextClassLoader", "()Ljava/lang/ClassLoader;");
  assert(getContextClassLoader != NULL);

  jobject thread = env->CallStaticObjectMethod(javaLangThread, currentThread);
  assert(thread != NULL);

  jobject classLoader = env->CallObjectMethod(thread, getContextClassLoader);

  if (classLoader != NULL) {
    mesosClassLoader = env->NewWeakGlobalRef(classLoader);
  }

  return JNI_VERSION_1_2;
}

// Called by JVM when it unloads our library.
JNIEXPORT void JNICALL JNI_OnUnLoad(JavaVM* jvm, void* reserved)
{
  JNIEnv* env;
  if (jvm->GetEnv((void**) &env, JNI_VERSION_1_2)) {
    return;
  }

  if (mesosClassLoader != NULL) {
    env->DeleteWeakGlobalRef(mesosClassLoader);
    mesosClassLoader = NULL;
  }
}

template <>
jobject convert(JNIEnv* env, const string& s)
{
  return env->NewStringUTF(s.c_str());
}

template <>
jobject convert(JNIEnv* env, const FrameworkID& frameworkId)
{
  string data;
  frameworkId.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // FrameworkID frameworkId = FrameworkID.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$FrameworkID");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$FrameworkID;");

  jobject jframeworkId = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jframeworkId;
}

template <>
jobject convert(JNIEnv* env, const ExecutorID& executorId)
{
  string data;
  executorId.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // ExecutorID executorId = ExecutorID.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$ExecutorID");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$ExecutorID;");

  jobject jexecutorId = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jexecutorId;
}

template <>
jobject convert(JNIEnv* env, const TaskID& taskId)
{
  string data;
  taskId.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // TaskID taskId = TaskID.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$TaskID");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$TaskID;");

  jobject jtaskId = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jtaskId;
}

template <>
jobject convert(JNIEnv* env, const SlaveID& slaveId)
{
  string data;
  slaveId.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // SlaveID slaveId = SlaveID.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$SlaveID");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$SlaveID;");

  jobject jslaveId = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jslaveId;
}

template <>
jobject convert(JNIEnv* env, const OfferID& offerId)
{
  string data;
  offerId.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // OfferID offerId = OfferID.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$OfferID");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$OfferID;");

  jobject jofferId = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jofferId;
}

template <>
jobject convert(JNIEnv* env, const TaskState& state)
{
  jint jvalue = state;

  // TaskState state = TaskState.valueOf(value);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$TaskState");

  jmethodID valueOf =
    env->GetStaticMethodID(clazz, "valueOf",
                           "(I)Lorg/apache/mesos/Protos$TaskState;");

  jobject jstate = env->CallStaticObjectMethod(clazz, valueOf, jvalue);

  return jstate;
}

template <>
jobject convert(JNIEnv* env, const TaskDescription& task)
{
  string data;
  task.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // TaskDescription task = TaskDescription.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$TaskDescription");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$TaskDescription;");

  jobject jtask = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jtask;
}

template <>
jobject convert(JNIEnv* env, const TaskStatus& status)
{
  string data;
  status.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // TaskStatus status = TaskStatus.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$TaskStatus");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$TaskStatus;");

  jobject jstatus = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jstatus;
}

template <>
jobject convert(JNIEnv* env, const Offer& offer)
{
  string data;
  offer.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // Offer offer = Offer.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$Offer");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$Offer;");

  jobject joffer = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return joffer;
}

template <>
jobject convert(JNIEnv* env, const ExecutorInfo& executor)
{
  string data;
  executor.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // ExecutorInfo executor = ExecutorInfo.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$ExecutorInfo");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$ExecutorInfo;");

  jobject jexecutor = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jexecutor;
}

template <>
jobject convert(JNIEnv* env, const ExecutorArgs& args)
{
  string data;
  args.SerializeToString(&data);

  // byte[] data = ..;
  jbyteArray jdata = env->NewByteArray(data.size());
  env->SetByteArrayRegion(jdata, 0, data.size(), (jbyte*) data.data());

  // ExecutorArgs args = ExecutorArgs.parseFrom(data);
  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$ExecutorArgs");

  jmethodID parseFrom =
    env->GetStaticMethodID(clazz, "parseFrom",
                           "([B)Lorg/apache/mesos/Protos$ExecutorArgs;");

  jobject jargs = env->CallStaticObjectMethod(clazz, parseFrom, jdata);

  return jargs;
}

template <>
jobject convert(JNIEnv* env, const Status& status)
{
  jint jvalue = status;

  jclass clazz = FindMesosClass(env, "org/apache/mesos/Protos$Status");

  jmethodID valueOf =
    env->GetStaticMethodID(clazz, "valueOf",
                           "(I)Lorg/apache/mesos/Protos$Status;");

  jobject jstate = env->CallStaticObjectMethod(clazz, valueOf, jvalue);

  return jstate;
}


text:
#pragma once

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#include "upm.h"
#include "mraa/i2c.h"

#ifdef __cplusplus
extern "C" {
#endif

#define ABPDRRT005PG2A5_ADDRESS       0x28
#define OUTPUT_10_PERCENT_COUNT       1638
#define OUTPUT_90_PERCENT_COUNT       14746
#define ABPDRRT005PG2A5_PRESSURE_MAX  5
#define ABPDRRT005PG2A5_PRESSURE_MIN  0

/**
 * @file abpdrrt005pg2a5.h
 * @library abpdrrt005pg2a5
 * @brief C API for the ABPDRRT005PG2A5 Honeywell Pressure Sensor
 *
 * @include abpdrrt005pg2a5.c
 */

 typedef struct _abpdrrt005pg2a5_context {
    mraa_i2c_context       i2c;
    uint8_t                i2c_bus_number;
	uint8_t                address;
} *abpdrrt005pg2a5_context;

/**
 * ABPDRRT005PG2A5 Initialization function
 *
 * @param bus I2C bus to use
 * @return device context pointer
 */
abpdrrt005pg2a5_context abpdrrt005pg2a5_init(uint8_t bus, uint8_t dev_address);

/**
 * ABPDRRT005PG2A5 Close function
 *
 * @param dev abpdrrt005pg2a5_context pointer
 */
void abpdrrt005pg2a5_close(abpdrrt005pg2a5_context dev);

/**
 * Function to get the pressure in psi
 * The datasheet provides a way to calculate the pressure
 * in psi.
 *
 * @return upm_result_t UPM success/error code
 */
upm_result_t abpdrrt005pg2a5_get_pressure_psi(abpdrrt005pg2a5_context dev, float* pressure_psi);

/**
 * Function to get the pressure in pascal
 * This is calculated using a conversion function.
 *
 * @return upm_result_t UPM success/error code
 */
upm_result_t abpdrrt005pg2a5_get_pressure_pascal(abpdrrt005pg2a5_context dev, float* pressure_pascal);

#ifdef __cplusplus
}
#endif


text:
package com.instinctools.padlaboris.domain.service;

import com.instinctools.padlaboris.domain.model.MedicalLeave;
import com.instinctools.padlaboris.domain.repository.MedicalLeaveRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Default medical leave service.
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DefaultMedicalLeaveService implements MedicalLeaveService {

    private final MedicalLeaveRepository medicalLeaveRepository;

    @Override
    public MedicalLeave fetch(final Integer id) {
        return medicalLeaveRepository.findOne(id);
    }

    @Override
    public MedicalLeave create(final MedicalLeave medicalLeave) {
        return medicalLeaveRepository.save(medicalLeave);
    }

    @Override
    public void delete(final Integer id) {
        medicalLeaveRepository.delete(id);
    }

    @Override
    public List<MedicalLeave> findByStartDate(final Date startDate) {
        return medicalLeaveRepository.findByStartDate(startDate);
    }

    @Override
    public List<MedicalLeave> findAll() {
        return medicalLeaveRepository.findAll();
    }
}


text:
The Socko component has a set of traits that you can mixin to your command to enable automatic routing. At it's most basically level you would simply add the trait to the command and a route would automatically be added and your command would be executed when the route was hit by the client. In reality it is most likely that there would be a couple of functions that would be overridden to address the specific needs of your command. By default the route will use the path "_wt_internal/[COMMAND_NAME]" which in general would be modified to what you want by overriding the function ```override def path: String = "/newpath/mycommand"```. In the example you would basically have a get request route using the path "/newpath/mycommand". This document will describe the default cases for all the http methods and how you can extend the traits for specific uses.

### Http Method Traits
Below is the list of [mixin traits](../src/main/scala/com/webtrends/harness/component/socko/route/SockoRoutes.scala) which automatically add http method routes to a command simply by mixing the trait into the command.

* SockoGet
* SockoCustom
* SockoPost
* SockoDelete
* SockoOptions
* SockoHead
* SockoPut

A basic example would be to mixin your trait like below

```
class FooCommand extends Command with SockoGet {
    implicit val executionContext = context.dispatcher
    override def path: String = "/bar"
    override def commandName: String = "Foo"
    override def execute[T](bean: Option[CommandBean]): Future[CommandResponse[T]] = {
        // here is where our business logic
    }
}
```

Above is literally the simplest example for this. However this will create a command that will execute the execute function and be accessed via a Get request using the path /bar. That is all that is required. Obviously things can get more complicated and that is where you would want to extend the functionality of the Command and the routing ability of the Command. Lets go through it line by line.

1. This is the definition for your class which includes the SockoGet trait which will add the GET route
2. We are required to define the execution context as the execute function requires it
3. We are overriding the default path of /_wt_internal/Foo to be /bar instead
4. We are setting the command name which is used for various things including registering the command
5. Definition of the execute function which we would just need to fill in the details.

One other thing to note is the SockoCustom trait. This trait will allow the developer to create a complete custom route and bypass all the automatic routing functionality. This would be for specific cases where very specific Socko functionality is required. To do this you would simply override the function ```def customMatcher(event: HttpRequestEvent) : Option[mutable.HashMap[String, AnyRef]]```. Example:

```
override def customMatcher(event: HttpRequestEvent) : Option[mutable.HashMap[String, AnyRef]] = {
    Command.matchPath("example/path", event.endPoint.path) match {
      case Some(b) =>
        b.addValue(CommandBean.KeyPath, p._1)
        val bean = new SockoCommandBean(event)
        bean.appendMap(b.toMap)
        return Some(bean)
      case None => // ignore and continue in the stream
    }
}
```

One a match is found, one should determine their own behavior with customHandler, IMPORTANT: be sure to write to the event in this handler, it is up to the user to ensure the event is dealt with at this point

```
override def customHandler(bean: mutable.HashMap[String, AnyRef]) {
    val commandBean = bean.asInstanceOf[SockoCommandBean]
    commandBean.response.write(HttpResponseStatus.OK, "Handled!")
}
```

Note the function innerExecute(event), this function helps by automatically executing the execute function on the command. However this is not required, although it would be highly recommended that you pass the actual business logic off to the execute function otherwise using the Command would be fairly pointless.

### Creating the path
Creating a path within a Command is greatly simplified, and although the Path function is useful it is difficult to create a parameterized path. A String is required in the Command as the base Command trait can have no notion of the underlying transfer protocols that are used to execute it. The primary reason for Commands is to create business units that can have various transportation protocols easily added to it and switched out. However the simplicity of the RoutePath should handle the majority of use cases. In the case that it does not, the developer would be required to use the SockoCustom trait and write the route manually. The [RoutePath](../src/main/scala/com/webtrends/harness/component/socko/route/RoutePath.scala) can be used as follows in a route:

```
val bean = new CommandBean()
object PATH extends RoutePath(path, bean)
event match {
    case GET(PATH("/foo")) =>
        event.response.write("bar")
        Future { true }
    case _ => Future { false }
}
```

The RoutePath class handles two primary cases, firstly it splits a path using the '/' character as any URL would. Then it also allows users to get parameters from the URL, so a URL like '/account/1/user/2/obj/3' can be created with the string '/account/$accId/user/$userId/obj/$objId'. This will then match the URL and assume that any of the path elements starting with $ are variables. The variables will be placed in the [CommandBean](../../wookiee-lib/src/main/scala/com/webtrends/harness/command/CommandBean.scala) and can be retrieved in the Commands execute function using the key's like accId, userId and ObjId. The variables will automatically be converted to Integers if it is not a String.

### Marshalling/Unmarshalling
One important part of any Restful service or any Http driven API is marshalling and unmarshalling. How do I pull objects into my execute function and how to I push them back out. By default all marshalling and unmarshalling will be handled for the developer, and there would be no further requirement. However it handles the data in a very specific way and so may not be desirable for the developer. Below we outline the ways that marshalling and unmarshalling is handled

#### Default
By default all marshalling and unmarshalling is managed by the LiftJson library, and in this case any request bodies will be marshalled to JObject objects and unmarshalling back to JSON on the way out. If you don't want to deal with marshalling and unmarshalling and are ok with JSON, then you can simply leave as is. And you can access the JObject from the command bean by using the standard key that is used for any entities that are marshalled to JSON from the request body. You can access using the following

```
// variable bean is the CommandBean
val entity = b(CommandBean.KeyEntity).asInstanceOf[JObject]
```

Remember by default the entity is marshalled into a JObject so if we left it at that we would simply set it as such.

Unmarshalling is even easier, although by default it will just unmarshall to JSON you can pass in your objects directly to the CommandResponse and it will attempt to marshall the object appriorately. So if you have a case class defined as such ```case class Person(name:String, age:Int)``` it will marshall that object automatically to ```{"name":"value", "age":value}```. Basically you are not required to convert your object to JSON first and then send it along in the CommandResponse, you would just need to pass down the object. So in the end your code would look something like this:

```
val per = Person("Mike", 34)
CommandResponse[T](Some(per.asInstanceOf[T]))
```

#### Case Classes
We can however make things a little easier for ourselves in the case of marshalling. By default it will not automatically convert to case classes. The reason for this is that in the case of marshalling, we know ahead of time what we are passing down. However with a route we don't have the class manifest ahead of time and so to be explicit about it we need to override the unmarshall function in the SockoPut or SockoPost traits.

```
override def unmarshall[T <: AnyRef : Manifest](obj: Array[Byte]): Option[T] = {
    super.unmarshall[Person](obj).asInstanceOf[Some[T]]
}
```

By passing in the Person type into the super.unmarshall function we set the bounds for the manifest on the lift json marshaller and so force the json marshaller to attempt to marshall to that object type.

#### Custom
Custom marshalling is required in instances when JSON is not sufficient for our needs. If you look at the [example-rest](../../examples/example-rest) the [SCreate comamnd](../../examples/example-rest/src/main/scala/com/webtrends/service/sockorest/SCreate.scala) uses custom marshallers to take in a completely different structure and returns basically a sentence. The marshaller and unmarshaller are customized by overriding two functions ```override def unmarshall[T<:AnyRef:Manifest](obj:Array[Byte]) : Option[T]``` and ```override def marshallObject(obj:Any) : Array[Byte]```. I will use the examples created in the SCreate command in the example-rest, but basically a developer has free reign to build whatever type of marshaller and unmarshaller that they require if the default marshallers are not sufficient for their purposes.

```
  // Below is a custom unmarshaller if you want to use it differently
  // The Create command will use a custom unmarshaller and mimetype
  // and the Update command will use the default unmarshaller using JSON
  override def unmarshall[T <: AnyRef : Manifest](obj: Array[Byte]): Option[T] = {
    val Array(name, age) = (new String(obj)).split(":")
    Some(Person(name, Integer.parseInt(age)).asInstanceOf[T])
  }

  // Below is a custom marshaller if you want to use it differently
  // The Create command will use a custom marshaller and mimetype
  // and the Update command will use the default marshaller
  override def marshallObject(obj: Any): Array[Byte] = {
    val person = obj.asInstanceOf[Person]
    s"Socko Person: ${person.name}, ${person.age}".getBytes
  }
```

### Status Codes
Currently all successful routes will result in a 200. The Socko component has a default rejection handler that will reject a request based on things like request not being handled. A developer can extend the rejection handler by overriding the function ```protected def getRejectionHandler(event:HttpRequestEvent, e:Throwable)```
The exceptionHandler is defined as following:
```
protected def getRejectionHandler(event:HttpRequestEvent, e:Throwable) = {
    e match {
      case ce:CommandException =>
        log.debug(ce.getMessage, ce)
        event.response.write(HttpResponseStatus.BAD_REQUEST, s"Command Exception - ${ce.getMessage}\n\t${ce.toString}")
      case arg:IllegalArgumentException =>
        log.debug(arg.getMessage, arg)
        event.response.write(HttpResponseStatus.BAD_REQUEST, s"Illegal Arguments - ${arg.getMessage}\n\t${arg.toString}")
      case me:MappingException =>
        log.debug(me.getMessage, me)
        event.response.write(HttpResponseStatus.BAD_REQUEST, s"Mapping Exception - ${me.getMessage}\n\t${me.toString}")
      case ex:Exception =>
        log.debug(ex.getMessage, ex)
        event.response.write(HttpResponseStatus.INTERNAL_SERVER_ERROR, s"Server Error - ${ex.getMessage}\n\t${ex.toString}")
    }
}
```


text:
In Action
=========
Let's build the interpreter of Brainfuck_ language to demonstrate the application of Graph-talk.

The Language
------------
There are following commands:

#. '>'  move current memory pointer right.
#. '<' move memory pointer left.
#. '.' output current memory cell content.
#. ',' input data to the current memory cell.
#. '+' increase memory pointer value.
#. '–' decrease memory pointer value.
#. '[' start loop while current memory pointer is not 0, otherwise move to corresponding ']'.
#. ']' end loop.

This is pretty simple, though completely unreadable, and allows the modelling of complicated algorithms.

The Implementation
------------------
The idea is to build the graph of the parsed program and then run it. To do so, we need to put in the appropriate commands which will call corresponding Brainfuck 'virtual machine' methods. This is easy: just put the parsed commands to the complex notion to be executed one by one.

.. figure::  images/action_program.png

To build the loop, we will extract the portion of commands between '[' and ']' and run them separately while the condition is true. That means they need to be put under a separate complex notion, which in turn has to be inside the loop.

.. figure::  images/action_loop.png

In general, we add the parsed commands to the current 'top' complex notion. When the parser encounters '[' it adds a loop and a new complex 'top' notion and preserves the previous one in the stack. When ']' is found, parser does pop from the stack.

.. figure::  images/action_bf.png

The figure depicts the parsed graph of ",[-.]" program.
Simple commands, marked with the grey background just add VM call to the current top complex notion.
"Start loop" adds the new top, putting old one to the stack.
"Stop loop" pops the old top from the stack.
"Remove whitespace" notion removes whitespace by consuming it.
"Error" notion stops the process because an unknown character encountered. It is a default case for the "Command" selective notion.

When the parsing is over, the process continues to the program sub-graph and executes it.

.. _Brainfuck: http://en.wikipedia.org/wiki/Brainfuck


text:
package digitalocean

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"path/filepath"
	"testing"
)

// A MockClient manages communication with the Digital Ocean API mock.
type MockClient struct {
	Mux         *http.ServeMux
	Client      *Client
	Server      *httptest.Server
	FixturesDir string
}

// NewMockClient returns a new Digital Ocean API client mock.
func NewMockClient() *MockClient {
	client, _ := NewClient(&Option{APIKey: "test"})

	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	url, _ := url.Parse(server.URL)
	client.BaseURL = url

	cli := &MockClient{Mux: mux,
		Server:      server,
		Client:      client,
		FixturesDir: "./test-fixtures"}

	return cli
}

// Close Close Mocl
func (r *MockClient) Close() {
	r.Server.Close()
}

// ReadJSON Read json from file
func (r *MockClient) ReadJSON(filename string) string {
	text, _ := ioutil.ReadFile(filepath.Join(r.FixturesDir, filename))
	return string(text)
}

func testMethod(t *testing.T, r *http.Request, want string) {
	if got := r.Method; got != want {
		t.Errorf("Request method: %v, want %v", got, want)
	}
}

func testHeader(t *testing.T, r *http.Request, header string, want string) {
	if got := r.Header.Get(header); got != want {
		t.Errorf("Header.Get(%q) returned %s, want %s", header, got, want)
	}
}


text:
import re
from exc import *
from metadata import metadata as m
from utils import classproperty

NEST_CHARS = {
    '\'': '\'',
    '"': '"',
    '[': ']',
    '(': ')',
    '{': '}'
}
NO_SUBNEST = {'\'', '"'}

RETURN_RE = re.compile(r'^return$', flags=re.I)
RETURN_OPTS_RE = re.compile(r'^(order|skip|limit)$', flags=re.I)
ORDER_RE = re.compile(r'^order$', flags=re.I)
SKIP_RE = re.compile(r'^skip$', flags=re.I)
LIMIT_RE = re.compile(r'^limit$', flags=re.I)
SKIP_OR_LIMIT_RE = re.compile(r'^(skip|limit)$', flags=re.I)
UNION_RE = re.compile(r'^union$', flags=re.I)

def tokenize(string):
    tokens = []
    idx = 0
    token = ''
    context = []
    while idx < len(string):
        if string[idx] == '\\':
            token += string[idx] + string[idx + 1]
            idx += 2
        elif len(context) == 0:
            if string[idx].isspace():
                if len(token) > 0:
                    tokens.append(token)
                    token = ''
            else:
                if string[idx] in NEST_CHARS:
                    context.append(string[idx])
                token += string[idx]
            idx += 1
        else:
            if string[idx] == NEST_CHARS[context[-1]]:
                context.pop()
            elif context[-1] not in NO_SUBNEST and string[idx] in NEST_CHARS:
                context.append(string[idx])
            token += string[idx]
            idx += 1
    if len(token) > 0:
        tokens.append(token)
    if len(context) > 0:
        raise ValueError("unclosed nestings in query: {0}".format(' '.join(context)))
    return tokens

class Query(object):

    def __init__(self, string='', params=None):
        self.tokens = tokenize(string) if string else []
        self.params = params or {}

    @property
    def string(self):
        return ' '.join(self.tokens)

    def copy(self):
        copy = self.__class__()
        copy.tokens = [x for x in self.tokens]
        copy.params = self.params.copy()
        return copy

    def __copy__(self):
        return self.copy()

    def append(self, string, params=None):
        copy = self.copy()
        copy._append(string, params=params)
        return copy

    def _append(self, string, params=None):
        new_tokens = tokenize(string)
        return_idx = None
        union_idx = None
        for idx, token in enumerate(self.tokens):
            if RETURN_RE.match(token):
                return_idx = idx
            elif UNION_RE.match(token):
                union_idx = idx
        new_return_idx = None
        new_union_idx = None
        for idx, token in enumerate(new_tokens):
            if new_return_idx is None and RETURN_RE.match(token):
                new_return_idx = idx
            elif new_union_idx is None and UNION_RE.match(token):
                new_union_idx = idx
        if return_idx is not None and new_return_idx is None:
            if RETURN_OPTS_RE.match(new_tokens[0]):
                extra_tokens = self.tokens[return_idx:]
                self.tokens = self.tokens[:return_idx]
                if ORDER_RE.match(new_tokens[0]):
                    regex = RETURN_OPTS_RE
                elif SKIP_RE.match(new_tokens[0]):
                    regex = SKIP_OR_LIMIT_RE
                else:
                    regex = LIMIT_RE
                while extra_tokens and not regex.match(extra_tokens[0]):
                    self.tokens.append(extra_tokens.pop(0))
                self.tokens += new_tokens
            else:
                self.tokens = self.tokens[:return_idx] + new_tokens + self.tokens[return_idx:]
        elif return_idx is None or new_return_idx is None or \
             new_union_idx is not None and new_union_idx < new_return_idx:
            self.tokens += new_tokens
        else:
            self.tokens = self.tokens[:return_idx] + new_tokens
        if params is not None:
            self.params.update(params)

    def execute(self, automap=True, fast=False):
        return m.cypher(self.string, params=self.params, automap=automap, fast=fast)

    @classmethod
    def node(cls, nodecls):
        return cls(string='match (instance:{0}) return instance'.format(nodecls.clslabel))

    """
    WARNING: The methods below are very limited and provided for partial Elixir-like compatibility only
    """
    def offset(self, value):
        return self.append('skip {0}'.format(str(int(value))))

    def limit(self, value):
        return self.append('limit {0}'.format(str(int(value))))

    def all(self, automap=True, fast=False):
        return [x[0] for x in self.execute(automap=automap, fast=fast)]

    def first(self, automap=True):
        try:
            return self.limit(1).execute(automap=automap)[0][0]
        except IndexError:
            return None

    def one(self, automap=True):
        results = self.limit(2).execute(automap=automap)
        if len(results) == 1:
            return results[0][0]
        elif len(results) == 0:
            raise QueryError('No results found for one()')
        else:
            raise QueryError('Multiple results found for one()')

    def count(self):
        return self.append('return count(*)').execute(automap=False, fast=True)[0][0]


text:
<?php
/**
 * Action English lexicon topic
 *
 * @language en
 * @package modx
 * @subpackage lexicon
 */
$_lang['action'] = 'Aksi';
$_lang['action_confirm_remove'] = 'Apakah Anda yakin Anda ingin menghapus tindakan ini? Ini berpotensi bisa menghentikan pengaturan antar muka MODX.';
$_lang['action_create'] = 'Buat aksi';
$_lang['action_create_here'] = 'Buat aksi disini';
$_lang['action_desc'] = 'Aksi adalah abstraksi dari kontroler MODX. Mereka dapat digunakan untuk membuat kustom halaman pengaturan, serta mengatur menu paling atas pada pengaturan MODX.';
$_lang['action_err_create'] = 'Terjadi kesalahan saat membuat tindakan.';
$_lang['action_err_nf'] = 'Tindakan tidak ditemukan!';
$_lang['action_err_ns'] = 'Tidak ada tindakan yang ditentukan!';
$_lang['action_err_remove'] = 'Terjadi kesalahan saat menghapus tindakan.';
$_lang['action_err_save'] = 'Terjadi kesalahan saat menyimpan tindakan.';
$_lang['action_none'] = 'Tidak ada tindakan';
$_lang['action_parent_err_nf'] = 'Tindakan induk tidak ditemukan!';
$_lang['action_parent_err_ns'] = 'Induk tindakan tidak ditentukan!';
$_lang['action_place_here'] = 'Tempat tindakan di sini';
$_lang['action_remove'] = 'Menghapus tindakan';
$_lang['action_update'] = 'Perbarui tindakan';
$_lang['actions'] = 'Tindakan';
$_lang['controller'] = 'Pengawas';
$_lang['controller_err_ae'] = 'Controller sudah ada dengan jalan ini untuk ruang nama ini.';
$_lang['controller_err_nf'] = 'Controller file tidak ditemukan!';
$_lang['controller_err_ns'] = 'Tidak ada kontroler yang ditentukan!';
$_lang['controller_parent'] = 'Controller induk';
$_lang['lang_topics'] = 'Topik bahasa';
$_lang['lang_topics_desc'] = 'Ini adalah daftar rangkaian yang mewakili leksikon topik dimana tindakan ini harus memuat.';


text:
package com.jxtelecom.pds.service;

import com.jxtelecom.pds.entity.TaskEntity;

import java.util.List;
import java.util.Map;

/**
 *
 *
 * @author jxtelecom
 * @email jxtelecom@gmail.com
 * @date 2017-05-10 11:25:19
 */
public interface TaskService {

	TaskEntity queryObject(Long id);

	List<TaskEntity> queryList(Map<String, Object> map);

	int queryTotal(Map<String, Object> map);

	void save(TaskEntity task);

	void update(TaskEntity task);

	void delete(Long id);

	void deleteBatch(Long[] ids);

	void saveFromAdd(TaskEntity t);
}


text:
<!DOCTYPE html>

<title>State of the ÐApps is undergoing maintenance</title>
<meta charset="utf-8">
<meta content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name=viewport>

State of the ÐApps is undergoing maintenance

We should be up shortly! If you have any questions, please let us know at support@stateofthedapps.com


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

namespace ECS
{

public abstract class System
{
    private Context context;
    private bool reassignCachedComponents;
    private List<Component> cachedComponents;

    public Context Context
    {
        get { return context; }
        internal set { context = value; }
    }

    internal bool ReassignCachedComponents
    {
        get { return reassignCachedComponents; }
        set { reassignCachedComponents = value; }
    }

    protected List<Component> CachedComponents
    {
        get
        {
            context.RecacheCachedComponentsForSystemIfNeeded(this);

            return cachedComponents;
        }
    }

    public abstract Type ComponentType { get; }

    // for some reason C# doesn't allow properties with protected get and internal set
    // so this must be a separate method
    internal void SetCachedComponents(List<Component> cachedComponents)
    {
        this.cachedComponents = cachedComponents;
    }

    protected Component GetComponentOfEntity(int entityID)
    {
        return context.GetFirstComponentOfTypeOfEntity(ComponentType, entityID);
    }

    protected void SendEvent(Event ev)
    {
        context.SendEvent(ev);
    }

    protected void SendEvent(int entityID, object data)
    {
        context.SendEvent(new Event(this, entityID, data));
    }

    public virtual void ReceiveEvent(Event ev)
    {
    }

    public abstract void Update(object updateData);
}

public abstract class System<T> : System
    where T : Component
{
    public override Type ComponentType { get { return TypesCache<T>.Type; } }

    protected new T GetComponentOfEntity(int entityID)
    {
        return Context.GetFirstComponentOfTypeOfEntity<T>(entityID);
    }

    public override void Update(object updateData)
    {
        var cachedComponents = CachedComponents;

        if( cachedComponents != null )
        {
            for( int i = 0, count = cachedComponents.Count; i < count; i++ )
            {
                try { Update((T)cachedComponents[i], updateData); }
                catch( Exception e )
                {
                    if( Context.ErrorHandler != null )
                        Context.ErrorHandler(e);
                    else
                        throw;
                }
            }
        }
    }

    protected virtual void Update(T component, object updateData)
    {
    }
}

}


text:
layout: post
title: Creación de una imagen Windows 7 para OpenStack
category: posts
---

Disponible el [tutorial para crear una imagen Windows 7 para OpenStack](http://ualmtorres.github.io/howtos/Windows7OpenStack/). El tutorial nos muestra:

* Configuración de la máquina virtual
* Configuración de drivers VirtIO
* Configuración de Woindows 7 para OpenStack
* Instalación de Cloudbase-init
* Activación/Desactivación de números de serie para distribución de instancias.


text:
import { SyntaxKind } from "@ts-morph/common";
import { expect } from "chai";
import { CallExpression } from "../../../../compiler";
import { getInfoFromText } from "../../testHelpers";

describe(nameof(CallExpression), () => {
    describe(nameof<CallExpression>(e => e.getReturnType), () => {
        function doTest(text: string, expectedTypes: string[]) {
            const { sourceFile } = getInfoFromText(text);
            const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);
            expect(callExpressions.map(c => c.getReturnType().getText())).to.deep.equal(expectedTypes);
        }

        it("should get the call expression's return type", () => {
            doTest("const func = () => ''; const myVar = func();", ["string"]);
        });

        it("should get the call expression's return type when void", () => {
            doTest("const func = () => {}; const myVar = func();", ["void"]);
        });

        it("should get the call expression's return type when chained", () => {
            doTest("const func = () => () => 4; const myVar = func()();", ["number", "() => number"]);
        });
    });
});


text:
/**************************** sha1.c ***************************/
/***************** See RFC NNNN for details. *******************/
/* Copyright (c) 2010 IETF Trust and the persons identified as */
/* authors of the code.  All rights reserved.                  */
/* See sha.h for terms of use and redistribution.              */

/*
 *  Description:
 *      This file implements the Secure Hash Algorithm SHA-1
 *      as defined in the U.S. National Institute of Standards
 *      and Technology Federal Information Processing Standards
 *      Publication (FIPS PUB) 180-3 published in October 2008
 *      and formerly defined in its predecessors, FIPS PUB 180-1
 *      and FIP PUB 180-2.
 *
 *      A combined document showing all algorithms is available at
 *              http://csrc.nist.gov/publications/fips/
 *                     fips180-3/fips180-3_final.pdf
 *
 *      The SHA-1 algorithm produces a 160-bit message digest for a
 *      given data stream that can serve as a means of providing a
 *      "fingerprint" for a message.
 *
 *  Portability Issues:
 *      SHA-1 is defined in terms of 32-bit "words".  This code
 *      uses <stdint.h> (included via "sha.h") to define 32 and 8
 *      bit unsigned integer types.  If your C compiler does not
 *      support 32 bit unsigned integers, this code is not
 *      appropriate.
 *
 *  Caveats:
 *      SHA-1 is designed to work with messages less than 2^64 bits
 *      long. This implementation uses SHA1Input() to hash the bits
 *      that are a multiple of the size of an 8-bit octet, and then
 *      optionally uses SHA1FinalBits() to hash the final few bits of
 *      the input.
 */

#include "crypto/sha.h"
#include "crypto/sha-private.h"

/*
 *  Define the SHA1 circular left shift macro
 */
#define SHA1_ROTL(bits,word) \
                (((word) << (bits)) | ((word) >> (32-(bits))))

/*
 * Add "length" to the length.
 * Set Corrupted when overflow has occurred.
 */
static uint32_t addTemp;
#define SHA1AddLength(context, length)                     \
    (addTemp = (context)->Length_Low,                      \
     (context)->Corrupted =                                \
        (((context)->Length_Low += (length)) < addTemp) && \
        (++(context)->Length_High == 0) ? shaInputTooLong  \
                                        : (context)->Corrupted )

/* Local Function Prototypes */
static void SHA1ProcessMessageBlock(SHA1Context *context);
static void SHA1Finalize(SHA1Context *context, uint8_t Pad_Byte);
static void SHA1PadMessage(SHA1Context *context, uint8_t Pad_Byte);

/*
 *  SHA1Reset
 *
 *  Description:
 *      This function will initialize the SHA1Context in preparation
 *      for computing a new SHA1 message digest.
 *
 *  Parameters:
 *      context: [in/out]
 *          The context to reset.
 *
 *  Returns:
 *      sha Error Code.
 *
 */
int SHA1Reset(SHA1Context *context)
{
  if (!context) return shaNull;

  context->Length_High = context->Length_Low = 0;
  context->Message_Block_Index = 0;

  /* Initial Hash Values: FIPS 180-3 section 5.3.1 */
  context->Intermediate_Hash[0]   = 0x67452301;
  context->Intermediate_Hash[1]   = 0xEFCDAB89;
  context->Intermediate_Hash[2]   = 0x98BADCFE;
  context->Intermediate_Hash[3]   = 0x10325476;
  context->Intermediate_Hash[4]   = 0xC3D2E1F0;

  context->Computed   = 0;
  context->Corrupted  = shaSuccess;

  return shaSuccess;
}

/*
 *  SHA1Input
 *
 *  Description:
 *      This function accepts an array of octets as the next portion
 *      of the message.
 *
 *  Parameters:
 *      context: [in/out]
 *          The SHA context to update
 *      message_array[ ]: [in]
 *          An array of octets representing the next portion of
 *          the message.
 *      length: [in]
 *          The length of the message in message_array
 *
 *  Returns:
 *      sha Error Code.
 *
 */
int SHA1Input(SHA1Context *context,
    const uint8_t *message_array, unsigned length)
{
  if (!context) return shaNull;
  if (!length) return shaSuccess;
  if (!message_array) return shaNull;
  if (context->Computed) return context->Corrupted = shaStateError;
  if (context->Corrupted) return context->Corrupted;

  while (length--) {
    context->Message_Block[context->Message_Block_Index++] =
      *message_array;

    if ((SHA1AddLength(context, 8) == shaSuccess) &&
      (context->Message_Block_Index == SHA1_Message_Block_Size))
      SHA1ProcessMessageBlock(context);

    message_array++;
  }

  return context->Corrupted;
}

/*
 * SHA1FinalBits
 *
 * Description:
 *   This function will add in any final bits of the message.
 *
 * Parameters:
 *   context: [in/out]
 *     The SHA context to update
 *   message_bits: [in]
 *     The final bits of the message, in the upper portion of the
 *     byte. (Use 0b###00000 instead of 0b00000### to input the
 *     three bits ###.)
 *   length: [in]
 *     The number of bits in message_bits, between 1 and 7.
 *
 * Returns:
 *   sha Error Code.
 */
int SHA1FinalBits(SHA1Context *context, uint8_t message_bits,
    unsigned int length)
{
  static uint8_t masks[8] = {
      /* 0 0b00000000 */ 0x00, /* 1 0b10000000 */ 0x80,
      /* 2 0b11000000 */ 0xC0, /* 3 0b11100000 */ 0xE0,
      /* 4 0b11110000 */ 0xF0, /* 5 0b11111000 */ 0xF8,
      /* 6 0b11111100 */ 0xFC, /* 7 0b11111110 */ 0xFE
  };
  static uint8_t markbit[8] = {
      /* 0 0b10000000 */ 0x80, /* 1 0b01000000 */ 0x40,
      /* 2 0b00100000 */ 0x20, /* 3 0b00010000 */ 0x10,
      /* 4 0b00001000 */ 0x08, /* 5 0b00000100 */ 0x04,
      /* 6 0b00000010 */ 0x02, /* 7 0b00000001 */ 0x01
  };

  if (!context) return shaNull;
  if (!length) return shaSuccess;
  if (context->Corrupted) return context->Corrupted;
  if (context->Computed) return context->Corrupted = shaStateError;
  if (length >= 8) return context->Corrupted = shaBadParam;

  SHA1AddLength(context, length);
  SHA1Finalize(context,
    (uint8_t) ((message_bits & masks[length]) | markbit[length]));

  return context->Corrupted;
}

/*
 * SHA1Result
 *
 * Description:
 *   This function will return the 160-bit message digest
 *   into the Message_Digest array provided by the caller.
 *   NOTE:
 *    The first octet of hash is stored in the element with index 0,
 *      the last octet of hash in the element with index 19.
 *
 * Parameters:
 *   context: [in/out]
 *     The context to use to calculate the SHA-1 hash.
 *   Message_Digest[ ]: [out]
 *     Where the digest is returned.
 *
 * Returns:
 *   sha Error Code.
 *
 */
int SHA1Result(SHA1Context *context,
    uint8_t Message_Digest[SHA1HashSize])
{
  int i;

  if (!context) return shaNull;
  if (!Message_Digest) return shaNull;
  if (context->Corrupted) return context->Corrupted;

  if (!context->Computed)
    SHA1Finalize(context, 0x80);

  for (i = 0; i < SHA1HashSize; ++i)
    Message_Digest[i] = (uint8_t) (context->Intermediate_Hash[i>>2]
                                   >> (8 * ( 3 - ( i & 0x03 ) )));

  return shaSuccess;
}

/*
 * SHA1ProcessMessageBlock
 *
 * Description:
 *   This helper function will process the next 512 bits of the
 *   message stored in the Message_Block array.
 *
 * Parameters:
 *   context: [in/out]
 *     The SHA context to update
 *
 * Returns:
 *   Nothing.
 *
 * Comments:
 *   Many of the variable names in this code, especially the
 *   single character names, were used because those were the
 *   names used in the Secure Hash Standard.
 */
static void SHA1ProcessMessageBlock(SHA1Context *context)
{
  /* Constants defined in FIPS 180-3, section 4.2.1 */
  const uint32_t K[4] = {
      0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6
  };
  int        t;               /* Loop counter */
  uint32_t   temp;            /* Temporary word value */
  uint32_t   W[80];           /* Word sequence */
  uint32_t   A, B, C, D, E;   /* Word buffers */

  /*
   * Initialize the first 16 words in the array W
   */
  for (t = 0; t < 16; t++) {
    W[t]  = ((uint32_t)context->Message_Block[t * 4]) << 24;
    W[t] |= ((uint32_t)context->Message_Block[t * 4 + 1]) << 16;
    W[t] |= ((uint32_t)context->Message_Block[t * 4 + 2]) << 8;
    W[t] |= ((uint32_t)context->Message_Block[t * 4 + 3]);
  }

  for (t = 16; t < 80; t++)
    W[t] = SHA1_ROTL(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);

  A = context->Intermediate_Hash[0];
  B = context->Intermediate_Hash[1];
  C = context->Intermediate_Hash[2];
  D = context->Intermediate_Hash[3];
  E = context->Intermediate_Hash[4];

  for (t = 0; t < 20; t++) {
    temp = SHA1_ROTL(5,A) + SHA_Ch(B, C, D) + E + W[t] + K[0];
    E = D;
    D = C;
    C = SHA1_ROTL(30,B);
    B = A;
    A = temp;
  }

  for (t = 20; t < 40; t++) {
    temp = SHA1_ROTL(5,A) + SHA_Parity(B, C, D) + E + W[t] + K[1];
    E = D;
    D = C;
    C = SHA1_ROTL(30,B);
    B = A;
    A = temp;
  }

  for (t = 40; t < 60; t++) {
    temp = SHA1_ROTL(5,A) + SHA_Maj(B, C, D) + E + W[t] + K[2];
    E = D;
    D = C;
    C = SHA1_ROTL(30,B);
    B = A;
    A = temp;
  }

  for (t = 60; t < 80; t++) {
    temp = SHA1_ROTL(5,A) + SHA_Parity(B, C, D) + E + W[t] + K[3];
    E = D;
    D = C;
    C = SHA1_ROTL(30,B);
    B = A;
    A = temp;
  }

  context->Intermediate_Hash[0] += A;
  context->Intermediate_Hash[1] += B;
  context->Intermediate_Hash[2] += C;
  context->Intermediate_Hash[3] += D;
  context->Intermediate_Hash[4] += E;

  context->Message_Block_Index = 0;
}

/*
 * SHA1Finalize
 *
 * Description:
 *   This helper function finishes off the digest calculations.
 *
 * Parameters:
 *   context: [in/out]
 *     The SHA context to update
 *   Pad_Byte: [in]
 *     The last byte to add to the message block before the 0-padding
 *     and length. This will contain the last bits of the message
 *     followed by another single bit. If the message was an
 *     exact multiple of 8-bits long, Pad_Byte will be 0x80.
 *
 * Returns:
 *   sha Error Code.
 *
 */
static void SHA1Finalize(SHA1Context *context, uint8_t Pad_Byte)
{
  int i;
  SHA1PadMessage(context, Pad_Byte);
  /* message may be sensitive, clear it out */
  for (i = 0; i < SHA1_Message_Block_Size; ++i)
    context->Message_Block[i] = 0;
  context->Length_High = 0;     /* and clear length */
  context->Length_Low = 0;
  context->Computed = 1;
}

/*
 * SHA1PadMessage
 *
 * Description:
 *   According to the standard, the message must be padded to the next
 *   even multiple of 512 bits. The first padding bit must be a '1'.
 *   The last 64 bits represent the length of the original message.
 *   All bits in between should be 0. This helper function will pad
 *   the message according to those rules by filling the Message_Block
 *   array accordingly. When it returns, it can be assumed that the
 *   message digest has been computed.
 *
 * Parameters:
 *   context: [in/out]
 *     The context to pad
 *   Pad_Byte: [in]
 *     The last byte to add to the message block before the 0-padding
 *     and length. This will contain the last bits of the message
 *     followed by another single bit. If the message was an
 *     exact multiple of 8-bits long, Pad_Byte will be 0x80.
 *
 * Returns:
 *   Nothing.
 */
static void SHA1PadMessage(SHA1Context *context, uint8_t Pad_Byte)
{
  /*
   * Check to see if the current message block is too small to hold
   * the initial padding bits and length. If so, we will pad the
   * block, process it, and then continue padding into a second
   * block.
   */
  if (context->Message_Block_Index >= (SHA1_Message_Block_Size - 8)) {
    context->Message_Block[context->Message_Block_Index++] = Pad_Byte;
    while (context->Message_Block_Index < SHA1_Message_Block_Size)
      context->Message_Block[context->Message_Block_Index++] = 0;

    SHA1ProcessMessageBlock(context);
  } else
    context->Message_Block[context->Message_Block_Index++] = Pad_Byte;

  while (context->Message_Block_Index < (SHA1_Message_Block_Size - 8))
    context->Message_Block[context->Message_Block_Index++] = 0;

  /*
   * Store the message length as the last 8 octets
   */
  context->Message_Block[56] = (uint8_t) (context->Length_High >> 24);
  context->Message_Block[57] = (uint8_t) (context->Length_High >> 16);
  context->Message_Block[58] = (uint8_t) (context->Length_High >> 8);
  context->Message_Block[59] = (uint8_t) (context->Length_High);
  context->Message_Block[60] = (uint8_t) (context->Length_Low >> 24);
  context->Message_Block[61] = (uint8_t) (context->Length_Low >> 16);
  context->Message_Block[62] = (uint8_t) (context->Length_Low >> 8);
  context->Message_Block[63] = (uint8_t) (context->Length_Low);

  SHA1ProcessMessageBlock(context);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Contains bean overrides and new definitions for application-scope beans required for integration of RSF apps into Sakai with the
	"Entity Broker" system, when used at version 1.3 or greater (support for "EntityView" system) -->

	<bean id="sakai-EntityViewProxy" parent="RSACBridgeProxy">
		<property name="targetBeanName" value="sakai-EntityView" />
	</bean>

	<bean id="entityViewAccessRegistrar" class="org.sakaiproject.rsf.entitybroker.EntityViewAccessRegistrar">
		<property name="commonAccessHandler" ref="commonAccessProvider" />
		<property name="entityViewAccessProviderManager" ref="org.sakaiproject.entitybroker.access.EntityViewAccessProviderManager" />
	</bean>

	<bean parent="defaultViewInferrerParent">
		<property name="valueRef" value="EVVPIManager" />
	</bean>

	<bean id="EVVPIManager" class="org.sakaiproject.rsf.entitybroker.EVVPIManager" init-method="init">
		<property name="accessRegistrar" ref="entityViewAccessRegistrar" />
		<property name="sakaiEntityView" ref="sakai-EntityViewProxy" />
	</bean>

	<bean class="uk.org.ponder.springutil.ByClassTLAB">
		<property name="targetPath" value="EVVPIManager.entityViewViewParamsInferrers" />
		<property name="targetClass" value="org.sakaiproject.rsf.entitybroker.EntityViewViewParamsInferrer" />
	</bean>

</beans>


text:
package org.apache.camel.component.hl7;

import ca.uhn.hl7v2.AcknowledgmentCode;
import ca.uhn.hl7v2.ErrorCode;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import org.apache.camel.Exchange;
import org.apache.camel.support.ExpressionAdapter;
import org.apache.camel.util.ObjectHelper;

public class AckExpression extends ExpressionAdapter {

    private AcknowledgmentCode acknowledgementCode;
    private String errorMessage;
    private ErrorCode errorCode;

    public AckExpression() {
        this((AcknowledgmentCode)null, null, ErrorCode.APPLICATION_INTERNAL_ERROR);
    }

    /**
     * @deprecated use {@link #AckExpression(ca.uhn.hl7v2.AcknowledgmentCode)}
     */
    @Deprecated
    public AckExpression(AckCode acknowledgementCode) {
        this(acknowledgementCode.toAcknowledgmentCode());
    }

    /**
     * @deprecated Use {@link #AckExpression(AcknowledgmentCode, String, ErrorCode)}
     */
    @Deprecated
    public AckExpression(AckCode acknowledgementCode, String errorMessage, int errorCode) {
        this(acknowledgementCode, errorMessage, ErrorCode.errorCodeFor(errorCode));
    }

    /**
     * @deprecated Use {@link #AckExpression(AcknowledgmentCode, String, ErrorCode)}
     */
    @Deprecated
    public AckExpression(AckCode acknowledgementCode, String errorMessage, ErrorCode errorCode) {
        this(acknowledgementCode.toAcknowledgmentCode(), errorMessage, errorCode);
    }

    public AckExpression(AcknowledgmentCode acknowledgementCode) {
        this(acknowledgementCode, null, ErrorCode.APPLICATION_INTERNAL_ERROR);
    }

    public AckExpression(AcknowledgmentCode acknowledgementCode, String errorMessage, ErrorCode errorCode) {
        this.acknowledgementCode = acknowledgementCode;
        this.errorMessage = errorMessage;
        this.errorCode = errorCode;
    }

    @Override
    public Object evaluate(Exchange exchange) {
        Throwable t = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
        Message msg = exchange.getIn().getBody(Message.class);
        try {
            HL7Exception hl7e = generateHL7Exception(t);
            AcknowledgmentCode code = acknowledgementCode;
            if (t != null && code == null) {
                code = AcknowledgmentCode.AE;
            }
            return msg.generateACK(code == null ? AcknowledgmentCode.AA : code, hl7e);
        } catch (Exception e) {
            throw ObjectHelper.wrapRuntimeCamelException(e);
        }
    }

    private HL7Exception generateHL7Exception(Throwable t) {
        HL7Exception hl7Exception = null;
        if (t == null) {
            if (acknowledgementCode != null && !isSuccess(acknowledgementCode)) {
                hl7Exception = new HL7Exception(errorMessage, errorCode);
            }
        } else {
            if (t instanceof HL7Exception) {
                hl7Exception = (HL7Exception)t;
            } else {
                hl7Exception = new HL7Exception(errorMessage != null ? errorMessage : t.getMessage(),
                                                errorCode, t);
            }
        }
        return hl7Exception;
    }

    private boolean isSuccess(AcknowledgmentCode code) {
        return code.name().endsWith("A");
    }

}


text:
//
//  SocialSharingCalls.h
//  IkasGame
//
//  Created by Mikel Eizagirre on 2014-12-24.
//
//

#ifndef __IkasCocosGame__SocialSharingCalls__
#define __IkasCocosGame__SocialSharingCalls__

#include <iostream>

class SocialSharingCalls
{
public:
    static bool checkInternetConnection();

    static void sendEmail(const char *to, const char *subject, const char *message, const char *imageFilePath);
    static void openWeb(const char* direction);
    static void openMarketApp(const char *id);
    static void openMarketApps(const char *id);
    static void openTwitterProfile(std::string id, std::string username);
    static void postOnTwitter(const char *message, const char *imageFilePath);
    static void openFacebookProfile(std::string id);
};
#endif /* defined(__IkasCocosGame__SocialSharingCalls__) */


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arduino Learning #2: digitalWrite, analogWrite, and which pins are which. — Brian Wheeler</title>
    <link href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="/assets/main.css">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="/images/headshot.jpeg"/>
    <link href="/feed.xml" rel="alternate" type="application/rss+xml" title="Brian Wheeler" />
    <meta name="title" content="Arduino Learning #2: digitalWrite, analogWrite, and which pins are which. ">
    <link rel="canonical" href="http://brianw.io/blog/2014/01/21/arduino-learning-number-2-digitalwrite-analogWrite-and-which-pins-are-which">

    <meta property="og:title" content="Arduino Learning #2: digitalWrite, analogWrite, and which pins are which. "/>
    <meta property="og:url" content="http://brianw.io/blog/2014/01/21/arduino-learning-number-2-digitalwrite-analogWrite-and-which-pins-are-which"/>

    <meta property="og:description" content="Learning how to use digitalWrite and analogWrite in Arduinos."/>
    <meta name="description" content="Learning how to use digitalWrite and analogWrite in Arduinos."/>

    <meta property="og:site_name" content="Brian Wheeler">

            Home

            About

            Thoughts and stuff

                By <address>Brian Wheeler</address> —
                <time pubdate datetime="2014-21-January" title="January 21, 2014">January 21, 2014</time>

Arduino Learning #2: digitalWrite, analogWrite, and which pins are which.

Without knowing how to use the pins on the Arduino board, you basically just have a fancy battery.

Here we can see the pins. There are three sections

Digital Output

Analog Input

Power

Try and find all three sections.

Now look closely at the digital pin section. Some pins have a ~ next to them. This means that they are capable
of acting as an analog output or PWM. We can use the
pins in this section for sending out data, to do things such as control motors and LED's, write
things to a screen, or even send us a tweet when our plants need to be watered.

In the section labeled "Analog" we see there isn't a lot of variation in the markings. All these pins do is
read data. For example if you wired a circuit with a thermistor connected to you analog input, you
could very easily make a thermometer.

Under the power section we can see a few grounds, a 3.5V, a 5V, and a reset. If you know a little bit about
basic electronic circuits this should be pretty straightforward.

About analogWrite()

In your code, you can use a function called analogWrite, which will simply output a given amount of
voltage to the pin you specify. To use analogWrite, you specify an analog output pin, meaning it has a ~
next to it, and a value between 0 and 255 for the amount of output.

analogWrite() Example

Imagine there is an LED attached to pin 3.
```
// Put code inside the loop() function so that our program will keep running.
void loop() {</p>

<pre><code>// Turn on the LED
analogWrite(3, 255);

// Wait 1 second (1000) milliseconds
delay(1000);

delay(1000);
analogWrite(3, 0);
</code></pre>

<p>}
```
This code will cause the LED to turn on and off every second.

digitalWrite() Example

You probably won't be using digitalWrite unsupervised for quite some time, because it generally
requires knowledge of integrated circuits, but for your reference, you can use digitalWrite() on
any digital pin be writing

digitalWrite(pin_number, HIGH);

// OR

digitalWrite(pin_number, LOW);

HIGH and LOW are what we call constants in Arduino

        Tweet

            <address>

Written by Brian Wheeler

                Programmer, Entrepreneur, Startup Enthusiast

            </address>

        © 2015

            Brian Wheeler
            Blog ·

            About

Incorporated theme by Inc


text:
#ifndef TIMEOUTTIMER_H
#define TIMEOUTTIMER_H

#include <e32base.h>

//class MTimeOutNotify;
/*!
  @class CTimeOutTimer

  @discussion This class will notify an object after a specified timeout.
  */
class CTimeOutTimer : public CTimer
{

public:

   /*!
    @function NewL

    @discussion Create a CTimeOutTimer object
    @param aPriority priority to use for this timer
    @param aTimeOutNotify object to notify of timeout event
    @result a pointer to the created instance of CTimeOutTimer
    */
   static CTimeOutTimer* NewL(const TInt aPriority, class MTimeOutNotify& aTimeOutNotify);

   /*!
    @function NewL

    @discussion Create a CTimeOutTimer object
    @param aPriority priority to use for this timer
    @param aTimeOutNotify object to notify of timeout event
    @result a pointer to the created instance of CTimeOutTimer
    */
   static CTimeOutTimer* NewLC(const TInt aPriority, class MTimeOutNotify& aTimeOutNotify);

   /*!
    @function ~CTimeOutTimer

    @discussion Destroy the object and release all memory objects
    */
   ~CTimeOutTimer();

protected: // From CTimer

   /*!
    @function RunL

    @discussion Invoked when a timeout occurs
    */
   virtual void RunL();

private:

   /*!
    @function CTimeOutTimer

    @discussion Perform the first phase of two phase construction
    @param aPriority priority to use for this timer
    */
   CTimeOutTimer(const TInt aPriority, class MTimeOutNotify& aTimeOutNotify);

   /*!
    @function ConstructL

    @discussion Perform the second phase construction of a CTimeOutTimer
    */
   void ConstructL();

private:

   // Member variables
   class MTimeOutNotify& iNotify;

};

#endif // TIMEOUTTIMER_H


text:
declare module JSX {
	interface Element { }
	interface ElementAttributesProperty { pr1: any; pr2: any; }
	interface IntrinsicElements { }
}

interface Obj1type {
	new(n: string): {};
}
var Obj1: Obj1type;
<Obj1 x={10} />; // Error

//// [file.jsx]
var Obj1;
<Obj1 x={10}/>; // Error


text:
import django.contrib.sessions.middleware
import user_sessions.middleware

class UserSessionsMiddleware(
    user_sessions.middleware.SessionMiddleware,
    # django.contrib.sessions.middleware.SessionMiddleware,
):
    pass