text:
%% MASSEFresults.algorithmInfo
% Add algorithm information.
%
%% Syntax
%
%   r.algorithmInfo(algorithmNum,'name','value')
%
% |r.algorithmInfo(algorithmNum,'name','value')| adds algorithm information
% for the algorithm with number |algorithmNum| to the results set contained
% in the <help_MASSEFresults.html MASSEFresults> object |r| using the variable
% names and values contained in the |'name'| / |'value'| pair arguments.
% The following information can be stored about each algorithm:
%
% * |'algorithmLabel'|—a label for the algorithm (char array).
%
%
%

%
Copyright © 2017 University of Surrey

% Institute of Sound Recording, University of Surrey, UK

%

redpajama_set_name: RedPajamaGithub


text:
create table COMMONS_GRAPH (IDENTIFIER bigint not null identity);
alter table COMMONS_GRAPH add constraint PK_COMMONS_GRAPH_ID primary key (IDENTIFIER);

create table COMMONS_GRAPH_EDGE (IDENTIFIER bigint not null identity, SOURCE_VERTEX_CLASS varchar(255), SOURCE_VERTEX_ID bigint, TARGET_VERTEX_CLASS varchar(255), TARGET_VERTEX_ID bigint, EDGE_CLASS varchar(255), EDGE_ID bigint);
alter table COMMONS_GRAPH_EDGE add constraint PK_COMMONS_GRAPH_EDGE_ID primary key (IDENTIFIER);

create table COMMONS_GRAPH_TO_EDGES (GRAPH_ID bigint not null, EDGE_ID bigint not null unique);
alter table COMMONS_GRAPH_TO_EDGES add constraint PK_COMMONS_GPH_ID_TO_EDGES_ID primary key (GRAPH_ID, EDGE_ID);

create table COMMONS_GRAPH_TO_VERTICES (GRAPH_ID bigint not null, VERTEX_CLASS varchar(255), VERTEX_ID bigint);

create table QUERY (IDENTIFIER bigint not null identity, CONSTRAINTS_ID bigint);
alter table QUERY add constraint PK_QUERY_ID primary key (IDENTIFIER);

create table QUERY_ARITHMETIC_OPERAND (IDENTIFIER bigint not null, LITERAL varchar(255), TERM_TYPE varchar(255), DATE_LITERAL smalldatetime, TIME_INTERVAL varchar(255), DE_ATTRIBUTE_ID bigint, EXPRESSION_ID bigint);
alter table QUERY_ARITHMETIC_OPERAND add constraint PK_QRY_ARITHMETIC_OPERAND_ID primary key (IDENTIFIER);

create table QUERY_BASEEXPR_TO_CONNECTORS (BASE_EXPRESSION_ID bigint not null, CONNECTOR_ID bigint not null, POSITION integer not null);
alter table QUERY_BASEEXPR_TO_CONNECTORS add constraint PK_QRY_BASEEXP_ID_POS_TO_CONN primary key (BASE_EXPRESSION_ID, POSITION);

create table QUERY_BASE_EXPRESSION (IDENTIFIER bigint not null identity, EXPR_TYPE varchar(255) not null);
alter table QUERY_BASE_EXPRESSION add constraint PK_QUERY_BASE_EXPRESSION_ID primary key (IDENTIFIER);

create table QUERY_BASE_EXPR_OPND (BASE_EXPRESSION_ID bigint not null, OPERAND_ID bigint not null, POSITION integer not null);
alter table QUERY_BASE_EXPR_OPND add constraint PK_QRY_BASE_EXPR_ID_POS_OPND primary key (BASE_EXPRESSION_ID, POSITION);

create table QUERY_CONDITION (IDENTIFIER bigint not null identity, ATTRIBUTE_ID bigint not null, RELATIONAL_OPERATOR varchar(255));
alter table QUERY_CONDITION add constraint PK_QUERY_CONDITION_ID primary key (IDENTIFIER);

create table QUERY_CONDITION_VALUES (CONDITION_ID bigint not null, VALUE varchar(255), POSITION integer not null);
alter table QUERY_CONDITION_VALUES add constraint PK_QRY_COND_VALS_COND_ID_POS primary key (CONDITION_ID, POSITION);

create table QUERY_CONNECTOR (IDENTIFIER bigint not null identity, OPERATOR varchar(255), NESTING_NUMBER integer);
alter table QUERY_CONNECTOR add constraint PK_QUERY_CONNECTOR_ID primary key (IDENTIFIER);

create table QUERY_CONSTRAINTS (IDENTIFIER bigint not null identity, QUERY_JOIN_GRAPH_ID bigint);
alter table QUERY_CONSTRAINTS add constraint PK_QUERY_CONSTRAINTS_ID primary key (IDENTIFIER);

create table QUERY_CONSTRAINT_TO_EXPR (CONSTRAINT_ID bigint not null, EXPRESSION_ID bigint not null unique);
alter table QUERY_CONSTRAINT_TO_EXPR add constraint PK_QRY_CONST_ID_TO_EXPR_ID primary key (CONSTRAINT_ID, EXPRESSION_ID);

create table QUERY_CUSTOM_FORMULA (IDENTIFIER bigint not null, OPERATOR varchar(255), LHS_TERM_ID bigint);
alter table QUERY_CUSTOM_FORMULA add constraint PK_QUERY_CUSTOM_FORMULA_ID primary key (IDENTIFIER);

create table QUERY_EXPRESSION (IDENTIFIER bigint not null, IS_IN_VIEW BIT, IS_VISIBLE BIT, UI_EXPR_ID integer, QUERY_ENTITY_ID bigint);
alter table QUERY_EXPRESSION add constraint PK_QUERY_EXPRESSION_ID primary key (IDENTIFIER);

create table QUERY_FORMULA_RHS (CUSTOM_FORMULA_ID bigint not null, RHS_TERM_ID bigint not null, POSITION integer not null);
alter table QUERY_FORMULA_RHS add constraint PK_QRY_FORMU_ID_POS_RHS_CUST primary key (CUSTOM_FORMULA_ID, POSITION);

create table QUERY_INTER_MODEL_ASSOCIATION (IDENTIFIER bigint not null, SOURCE_SERVICE_URL text not null, TARGET_SERVICE_URL text not null, SOURCE_ATTRIBUTE_ID bigint not null, TARGET_ATTRIBUTE_ID bigint not null);
alter table QUERY_INTER_MODEL_ASSOCIATION add constraint PK_QUERY_INTER_MODEL_ASSO_ID primary key (IDENTIFIER);

create table QUERY_INTRA_MODEL_ASSOCIATION (IDENTIFIER bigint not null, DE_ASSOCIATION_ID bigint not null);
alter table QUERY_INTRA_MODEL_ASSOCIATION add constraint PK_QUERY_INTRA_MODEL_ASSO_ID primary key (IDENTIFIER);

create table QUERY_JOIN_GRAPH (IDENTIFIER bigint not null identity, COMMONS_GRAPH_ID bigint);
alter table QUERY_JOIN_GRAPH add constraint PK_QUERY_JOIN_GRAPH_ID primary key (IDENTIFIER);

create table QUERY_MODEL_ASSOCIATION (IDENTIFIER bigint not null identity);
alter table QUERY_MODEL_ASSOCIATION add constraint PK_QUERY_MODEL_ASSOCIATION_ID primary key (IDENTIFIER);

create table QUERY_OPERAND (IDENTIFIER bigint not null identity, OPND_TYPE varchar(255) not null);
alter table QUERY_OPERAND add constraint PK_QUERY_OPERAND_ID primary key (IDENTIFIER);

create table QUERY_OUTPUT_ATTRIBUTE (IDENTIFIER bigint not null identity, EXPRESSION_ID bigint, ATTRIBUTE_ID bigint not null, PARAMETERIZED_QUERY_ID bigint, POSITION integer);
alter table QUERY_OUTPUT_ATTRIBUTE add constraint PK_QUERY_OUTPUT_ATTRIBUTE_ID primary key (IDENTIFIER);

create table QUERY_OUTPUT_TERM (IDENTIFIER bigint not null identity, NAME varchar(255), TIME_INTERVAL varchar(255), TERM_ID bigint);
alter table QUERY_OUTPUT_TERM add constraint PK_QUERY_OUTPUT_TERM_ID primary key (IDENTIFIER);

create table QUERY_PARAMETER (IDENTIFIER bigint not null identity, NAME varchar(255), OBJECT_CLASS varchar(255), OBJECT_ID bigint);
alter table QUERY_PARAMETER add constraint PK_QUERY_PARAMETER_ID primary key (IDENTIFIER);

create table QUERY_PARAMETERIZED_QUERY (IDENTIFIER bigint not null, QUERY_NAME varchar(255), DESCRIPTION text);
alter table QUERY_PARAMETERIZED_QUERY add constraint PK_QRY_PARAMETERIZED_QRY_ID primary key (IDENTIFIER);

create table QUERY_QUERY_ENTITY (IDENTIFIER bigint not null identity, ENTITY_ID bigint not null);
alter table QUERY_QUERY_ENTITY add constraint PK_QUERY_QUERY_ENTITY_ID primary key (IDENTIFIER);

create table QUERY_RULE_COND (RULE_ID bigint not null, CONDITION_ID bigint not null, POSITION integer not null);
alter table QUERY_RULE_COND add constraint PK_QRY_RULE_COND_RULE_ID_POS primary key (RULE_ID, POSITION);

create table QUERY_SUBEXPR_OPERAND (IDENTIFIER bigint not null, EXPRESSION_ID bigint);
alter table QUERY_SUBEXPR_OPERAND add constraint PK_QUERY_SUBEXPR_OPERAND_ID primary key (IDENTIFIER);

create table QUERY_TO_OUTPUT_TERMS (QUERY_ID bigint not null, OUTPUT_TERM_ID bigint not null unique, POSITION integer not null);
alter table QUERY_TO_OUTPUT_TERMS add constraint PK_QRY_TO_OP_TERMS_QRY_ID_POS primary key (QUERY_ID, POSITION);

create table QUERY_TO_PARAMETERS (QUERY_ID bigint not null, PARAMETER_ID bigint not null unique, POSITION integer not null);
alter table QUERY_TO_PARAMETERS add constraint PK_QRY_TO_PARAMS_QRY_ID_POS primary key (QUERY_ID, POSITION);

alter table COMMONS_GRAPH_TO_EDGES add constraint FK_COMM_GPH_TO_EDGES_GPH_ID foreign key (GRAPH_ID) references COMMONS_GRAPH;
alter table COMMONS_GRAPH_TO_EDGES add constraint FK_COMM_GPH_TO_EDGES_EDGE_ID foreign key (EDGE_ID) references COMMONS_GRAPH_EDGE;
alter table COMMONS_GRAPH_TO_VERTICES add constraint FK_COMM_GPH_TO_VRTICES_GPH_ID foreign key (GRAPH_ID) references COMMONS_GRAPH;
alter table QUERY add constraint FK_QUERY_CONSTRAINTS_ID foreign key (CONSTRAINTS_ID) references QUERY_CONSTRAINTS;
alter table QUERY_ARITHMETIC_OPERAND add constraint FK_QRY_ARITH_OPEND_IDFK_IER1 foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_ARITHMETIC_OPERAND add constraint FK_QRY_ARITH_OPEND_IDFK_IER2 foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_ARITHMETIC_OPERAND add constraint FK_QRY_ARITH_OPEND_IDFK_IER3 foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_ARITHMETIC_OPERAND add constraint FK_QRY_ARITH_OPEND_IDFK_IER4 foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_ARITHMETIC_OPERAND add constraint FK_QRY_ARITH_OPEND_IDFK_IER5 foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_ARITHMETIC_OPERAND add constraint FK_QUERY_ARITH_OPEND_EXP_ID foreign key (EXPRESSION_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_BASEEXPR_TO_CONNECTORS add constraint FK_QRY_BASEEXP_TO_CONS_CON_ID foreign key (CONNECTOR_ID) references QUERY_CONNECTOR;
alter table QUERY_BASEEXPR_TO_CONNECTORS add constraint FK_QRY_BASEEXP_ID_TO_CONS foreign key (BASE_EXPRESSION_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_BASE_EXPR_OPND add constraint FK_QRY_BASE_EXP_OPND_OPEND_ID foreign key (OPERAND_ID) references QUERY_OPERAND;
alter table QUERY_BASE_EXPR_OPND add constraint FK_QRY_BSE_EXP_OPND_BSE_EXPId foreign key (BASE_EXPRESSION_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_CONDITION_VALUES add constraint FK_QUERY_COND_VALUES_COND_ID foreign key (CONDITION_ID) references QUERY_CONDITION;
alter table QUERY_CONSTRAINTS add constraint FK_QRY_CONST_QRY_JOIN_GPH_ID foreign key (QUERY_JOIN_GRAPH_ID) references QUERY_JOIN_GRAPH;
alter table QUERY_CONSTRAINT_TO_EXPR add constraint FK_QRY_CONST_TO_EXP_CONST_ID foreign key (CONSTRAINT_ID) references QUERY_CONSTRAINTS;
alter table QUERY_CONSTRAINT_TO_EXPR add constraint FK_QRY_CONST_TO_EXPR_EXP_ID foreign key (EXPRESSION_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_CUSTOM_FORMULA add constraint FK_QUERY_CUSTOM_FORMULA_LHS_TERM_ID foreign key (LHS_TERM_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_CUSTOM_FORMULA add constraint FK_QUERY_CUSTOM_FORMULA_ID foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_EXPRESSION add constraint FK_QUERY_EXPRESSION_ID foreign key (IDENTIFIER) references QUERY_BASE_EXPRESSION;
alter table QUERY_EXPRESSION add constraint FK_QUERY_EXP_QRY_ENTITY_ID foreign key (QUERY_ENTITY_ID) references QUERY_QUERY_ENTITY;
alter table QUERY_FORMULA_RHS add constraint FK_QUERY_FORMULA_RHS_TERM_ID foreign key (RHS_TERM_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_FORMULA_RHS add constraint FK_QRY_FRM_RHS_CUST_FRM_ID foreign key (CUSTOM_FORMULA_ID) references QUERY_OPERAND;
alter table QUERY_INTER_MODEL_ASSOCIATION add constraint FK_QRY_INTER_MDL_ASSO_ID1 foreign key (IDENTIFIER) references QUERY_MODEL_ASSOCIATION;
alter table QUERY_INTRA_MODEL_ASSOCIATION add constraint FK_QRY_INTER_MDL_ASSO_ID2 foreign key (IDENTIFIER) references QUERY_MODEL_ASSOCIATION;
alter table QUERY_JOIN_GRAPH add constraint FK_QRY_JOIN_GPH_COMMON_GPH_ID foreign key (COMMONS_GRAPH_ID) references COMMONS_GRAPH;
alter table QUERY_OUTPUT_ATTRIBUTE add constraint FK_QRY_OP_ATB_PARAM_QRY_ID foreign key (PARAMETERIZED_QUERY_ID) references QUERY_PARAMETERIZED_QUERY;
alter table QUERY_OUTPUT_ATTRIBUTE add constraint FK_QRY_OUTPUT_ATB_EXP_ID foreign key (EXPRESSION_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_OUTPUT_TERM add constraint FK_QUERY_OUTPUT_TERM_TERM_ID foreign key (TERM_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_PARAMETERIZED_QUERY add constraint FK_QRY_PARAMETERIZED_QRY_ID foreign key (IDENTIFIER) references QUERY;
alter table QUERY_RULE_COND add constraint FK_QRY_RULE_COND_CONDITION_ID foreign key (CONDITION_ID) references QUERY_CONDITION;
alter table QUERY_RULE_COND add constraint FK_QUERY_RULE_COND_RULE_ID foreign key (RULE_ID) references QUERY_OPERAND;
alter table QUERY_SUBEXPR_OPERAND add constraint FK_QRY_SUBEXPR_OPERAND_ID foreign key (IDENTIFIER) references QUERY_OPERAND;
alter table QUERY_SUBEXPR_OPERAND add constraint FK_QRY_SUBEXPR_OPERAND_EXP_ID foreign key (EXPRESSION_ID) references QUERY_BASE_EXPRESSION;
alter table QUERY_TO_OUTPUT_TERMS add constraint FK_QRY_TO_OP_TRMS_OP_TRM_ID foreign key (OUTPUT_TERM_ID) references QUERY_OUTPUT_TERM;
alter table QUERY_TO_OUTPUT_TERMS add constraint FK_QRY_TO_OUTPUT_TERMS_QRY_ID foreign key (QUERY_ID) references QUERY;
alter table QUERY_TO_PARAMETERS add constraint FK_QUERY_TO_PARAMS_PARAM_ID foreign key (PARAMETER_ID) references QUERY_PARAMETER;
alter table QUERY_TO_PARAMETERS add constraint FK_QRY_TO_PARAMETERS_QRY_ID foreign key (QUERY_ID) references QUERY_PARAMETERIZED_QUERY;


text:
<?php

namespace App\Core\Presenters;

use App\Core\Transformers\CouponTransformer;
use RepositoryLab\Repository\Presenter\FractalPresenter;

/**
 * Class CouponPresenter.
 */
class CouponPresenter extends FractalPresenter
{
    /**
     * Transformer.
     *
     * @return \League\Fractal\TransformerAbstract
     */
    public function getTransformer()
    {
        return new CouponTransformer();
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;

public class FreeplayCommander : ICommandResponder
{
    #region Constructors
    static FreeplayCommander()
    {
        _freeplayDeviceType = CommonReflectedTypeInfo.FreeplayDeviceType;
        _moduleCountIncrementField = _freeplayDeviceType.GetField("ModuleCountIncrement", BindingFlags.Public | BindingFlags.Instance);
        _moduleCountDecrementField = _freeplayDeviceType.GetField("ModuleCountDecrement", BindingFlags.Public | BindingFlags.Instance);
        _timeIncrementField = _freeplayDeviceType.GetField("TimeIncrement", BindingFlags.Public | BindingFlags.Instance);
        _timeDecrementField = _freeplayDeviceType.GetField("TimeDecrement", BindingFlags.Public | BindingFlags.Instance);
        _needyToggleField = _freeplayDeviceType.GetField("NeedyToggle", BindingFlags.Public | BindingFlags.Instance);
        _hardcoreToggleField = _freeplayDeviceType.GetField("HardcoreToggle", BindingFlags.Public | BindingFlags.Instance);
        _modsOnlyToggleField = _freeplayDeviceType.GetField("ModsOnly", BindingFlags.Public | BindingFlags.Instance);
        _startButtonField = _freeplayDeviceType.GetField("StartButton", BindingFlags.Public | BindingFlags.Instance);
        _currentSettingsField = _freeplayDeviceType.GetField("currentSettings", BindingFlags.NonPublic | BindingFlags.Instance);
        _maxModuleField = _freeplayDeviceType.GetField("maxModules", BindingFlags.NonPublic | BindingFlags.Instance);
        _MAXSECONDSFIELD = _freeplayDeviceType.GetField("MAX_SECONDS_TO_SOLVE", BindingFlags.Public | BindingFlags.Static);

        _freeplaySettingsType = ReflectionHelper.FindType("Assets.Scripts.Settings.FreeplaySettings");
        _moduleCountField = _freeplaySettingsType.GetField("ModuleCount", BindingFlags.Public | BindingFlags.Instance);
        _timeField = _freeplaySettingsType.GetField("Time", BindingFlags.Public | BindingFlags.Instance);
        _isHardCoreField = _freeplaySettingsType.GetField("IsHardCore", BindingFlags.Public | BindingFlags.Instance);
        _hasNeedyField = _freeplaySettingsType.GetField("HasNeedy", BindingFlags.Public | BindingFlags.Instance);
        _onlyModsField = _freeplaySettingsType.GetField("OnlyMods", BindingFlags.Public | BindingFlags.Instance);

        _floatingHoldableType = ReflectionHelper.FindType("FloatingHoldable");
        if (_floatingHoldableType == null)
        {
            return;
        }
        _pickupTimeField = _floatingHoldableType.GetField("PickupTime", BindingFlags.Public | BindingFlags.Instance);
        _holdStateProperty = _floatingHoldableType.GetProperty("HoldState", BindingFlags.Public | BindingFlags.Instance);

        _selectableType = ReflectionHelper.FindType("Selectable");
        _handleSelectMethod = _selectableType.GetMethod("HandleSelect", BindingFlags.Public | BindingFlags.Instance);
        _onInteractEndedMethod = _selectableType.GetMethod("OnInteractEnded", BindingFlags.Public | BindingFlags.Instance);
        _childrenField = _selectableType.GetField("Children", BindingFlags.Public | BindingFlags.Instance);

        _selectableManagerType = ReflectionHelper.FindType("SelectableManager");
        if (_selectableManagerType == null)
        {
            return;
        }
        _selectMethod = _selectableManagerType.GetMethod("Select", BindingFlags.Public | BindingFlags.Instance);
        _handleInteractMethod = _selectableManagerType.GetMethod("HandleInteract", BindingFlags.Public | BindingFlags.Instance);
        _handleCancelMethod = _selectableManagerType.GetMethod("HandleCancel", BindingFlags.Public | BindingFlags.Instance);
        _setZSpinMethod = _selectableManagerType.GetMethod("SetZSpin", BindingFlags.Public | BindingFlags.Instance);
        _setControlsRotationMethod = _selectableManagerType.GetMethod("SetControlsRotation", BindingFlags.Public | BindingFlags.Instance);
        _getBaseHeldObjectTransformMethod = _selectableManagerType.GetMethod("GetBaseHeldObjectTransform", BindingFlags.Public | BindingFlags.Instance);
        _handleFaceSelectionMethod = _selectableManagerType.GetMethod("HandleFaceSelection", BindingFlags.Public | BindingFlags.Instance);

        _inputManagerType = ReflectionHelper.FindType("KTInputManager");
        if (_inputManagerType == null)
        {
            return;
        }
        _instanceProperty = _inputManagerType.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static);
        _selectableManagerProperty = _inputManagerType.GetProperty("SelectableManager", BindingFlags.Public | BindingFlags.Instance);

        _inputManager = (MonoBehaviour)_instanceProperty.GetValue(null, null);

        _multipleBombsType = ReflectionHelper.FindType("MultipleBombsAssembly.MultipleBombs");
        if (_multipleBombsType == null)
        {
            return;
        }
        _bombsCountField = _multipleBombsType.GetField("bombsCount", BindingFlags.NonPublic | BindingFlags.Instance);
        _getCurrentMaximumBombCountMethod = _multipleBombsType.GetMethod("GetCurrentMaximumBombCount", BindingFlags.Public | BindingFlags.Instance);
    }

    public FreeplayCommander(MonoBehaviour freeplayDevice, MonoBehaviour multipleBombs)
    {
        FreeplayDevice = freeplayDevice;
        MultipleBombs = multipleBombs;
        Selectable = (MonoBehaviour)FreeplayDevice.GetComponent(_selectableType);
        Debug.Log("Freeplay device: Attempting to get the Selectable list.");
        SelectableChildren = (MonoBehaviour[]) _childrenField.GetValue(Selectable);
        FloatingHoldable = (MonoBehaviour)FreeplayDevice.GetComponent(_floatingHoldableType);
        SelectableManager = (MonoBehaviour)_selectableManagerProperty.GetValue(_inputManager, null);
    }
    #endregion

    #region Interface Implementation
    public IEnumerator RespondToCommand(string userNickName, string message, ICommandResponseNotifier responseNotifier)
    {
        message = message.ToLowerInvariant();
        int holdState = (int)_holdStateProperty.GetValue(FloatingHoldable, null);

        if (holdState == 0)
        {
            if (message.Equals("drop", StringComparison.InvariantCultureIgnoreCase) ||
            message.Equals("let go", StringComparison.InvariantCultureIgnoreCase) ||
            message.Equals("put down", StringComparison.InvariantCultureIgnoreCase))
            {
                LetGoFreeplayDevice();
                yield break;
            }
        }
        else
        {
            IEnumerator holdCoroutine = HoldFreeplayDevice();
            while (holdCoroutine.MoveNext())
            {
                yield return holdCoroutine.Current;
            }
        }

        string changeHoursTo = String.Empty;
        string changeMinutesTo = String.Empty;
        string changeSecondsTo = String.Empty;
        string changeBombsTo = String.Empty;
        string changeModulesTo = String.Empty;
        bool startBomb = false;

        if (message.Equals("needy on", StringComparison.InvariantCultureIgnoreCase))
        {
            SetNeedy();
        }
        else if (message.Equals("needy off", StringComparison.InvariantCultureIgnoreCase))
        {
            SetNeedy(false);
        }
        else if (message.Equals("hardcore on", StringComparison.InvariantCultureIgnoreCase))
        {
            SetHardcore();
        }
        else if (message.Equals("hardcore off", StringComparison.InvariantCultureIgnoreCase))
        {
            SetHardcore(false);
        }
        else if (message.Equals("mods only on", StringComparison.InvariantCultureIgnoreCase))
        {
            SetModsOnly();
        }
        else if (message.Equals("mods only off", StringComparison.InvariantCultureIgnoreCase))
        {
            SetModsOnly(false);
        }
        else if (message.Equals("start", StringComparison.InvariantCultureIgnoreCase))
        {
            StartBomb();
        }
        else if (message.StartsWith("profile"))
        {
            string profile = message.Remove(0, 8).Trim();

            switch (profile)
            {
                case "single":
                case "solo":
                    changeBombsTo = "1";
                    changeHoursTo = "0";
                    changeMinutesTo = "20";
                    changeModulesTo = "11";
                    break;

                case "double":
                    changeBombsTo = "1";
                    changeHoursTo = "0";
                    changeMinutesTo = "40";
                    changeModulesTo = "23";
                    break;

                case "quadruple":
                case "quad":
                    changeBombsTo = "1";
                    changeHoursTo = "1";
                    changeMinutesTo = "20";
                    changeModulesTo = "47";
                    break;

                case "dual single":
                case "dual solo":
                    changeBombsTo = "2";
                    changeHoursTo = "0";
                    changeMinutesTo = "40";
                    changeModulesTo = "11";
                    break;

                case "dual double":
                    changeBombsTo = "2";
                    changeHoursTo = "1";
                    changeMinutesTo = "20";
                    changeModulesTo = "23";
                    break;

                case "dual quadruple":
                case "dual quad":
                    changeBombsTo = "2";
                    changeHoursTo = "2";
                    changeMinutesTo = "40";
                    changeModulesTo = "47";
                    break;
            }
        }
        else if (message.StartsWith("start"))
        {
            Match timerMatch = Regex.Match(message, "([0-9]):([0-9]{2}):([0-9]{2})");
            if (timerMatch.Success)
            {
                changeHoursTo = timerMatch.Groups[1].Value;
                changeMinutesTo = timerMatch.Groups[2].Value;
                changeSecondsTo = timerMatch.Groups[3].Value;
                message = message.Remove(timerMatch.Index, timerMatch.Length);
            }
            else
            {
                timerMatch = Regex.Match(message, "([0-9]+):([0-9]{2})");
                if (timerMatch.Success)
                {
                    changeMinutesTo = timerMatch.Groups[1].Value;
                    changeSecondsTo = timerMatch.Groups[2].Value;
                    message = message.Remove(timerMatch.Index, timerMatch.Length);
                }
            }

            Match modulesMatch = Regex.Match(message, "[0-9]+");

            while (modulesMatch.Success)
            {
                int count = 0;

                if (int.TryParse(modulesMatch.Value, out count))
                {
                    if (count <= 2)
                    {
                        changeBombsTo = modulesMatch.Value;
                    }
                    else
                    {
                        changeModulesTo = modulesMatch.Value;
                    }

                    Debug.Log(string.Format("[FreeplayCommander] Setting {1} to {0}", modulesMatch.Value,
                        count <= 2 ? "bombs" : "modules"));
                }
                message = message.Remove(modulesMatch.Index, modulesMatch.Length);
                modulesMatch = Regex.Match(message, "[0-9]+");
            }

            string messageLower = message.ToLowerInvariant();

            SetHardcore(messageLower.Contains("hardcore"));
            SetNeedy(messageLower.Contains("needy"));

            if (messageLower.Contains("vanilla"))
            {
                SetModsOnly(false);
            }
            else if (messageLower.Contains("mods"))
            {
                SetModsOnly();
            }

            startBomb = true;
        }
        else
        {
            Match timerMatch = Regex.Match(message, "^timer? ([0-9]+)(?::([0-9]{2}))(?::([0-9]{2}))$", RegexOptions.IgnoreCase);
            if (timerMatch.Success)
            {
                changeHoursTo = timerMatch.Groups[1].Value;
                changeMinutesTo = timerMatch.Groups[2].Value;
                changeSecondsTo = timerMatch.Groups[3].Value;
            }

            timerMatch = Regex.Match(message, "^timer? ([0-9]+)(?::([0-9]{2}))?$", RegexOptions.IgnoreCase);
            if (timerMatch.Success)
            {
                changeMinutesTo = timerMatch.Groups[1].Value;
                changeSecondsTo = timerMatch.Groups[2].Value;
            }

            Match bombsMatch = Regex.Match(message, "^bombs ([0-9]+)$", RegexOptions.IgnoreCase);
            if (bombsMatch.Success)
            {
                changeBombsTo = bombsMatch.Groups[1].Value;
            }

            Match modulesMatch = Regex.Match(message, "^modules ([0-9]+)$", RegexOptions.IgnoreCase);
            if (modulesMatch.Success)
            {
                changeModulesTo = modulesMatch.Groups[1].Value;
            }
        }

        if (changeMinutesTo != String.Empty)
        {
            IEnumerator setTimerCoroutine = SetBombTimer(changeHoursTo, changeMinutesTo, changeSecondsTo);
            while (setTimerCoroutine.MoveNext())
            {
                yield return setTimerCoroutine.Current;
            }
        }
        if (changeBombsTo != String.Empty)
        {
            IEnumerator setBombsCoroutine = SetBombCount(changeBombsTo);
            while (setBombsCoroutine.MoveNext())
            {
                yield return setBombsCoroutine.Current;
            }
        }
        if (changeModulesTo != String.Empty)
        {
            IEnumerator setModulesCoroutine = SetBombModules(changeModulesTo);
            while (setModulesCoroutine.MoveNext())
            {
                yield return setModulesCoroutine.Current;
            }
        }
        if (startBomb)
        {
            StartBomb();
        }

    }
    #endregion

    #region Helper Methods
    public bool IsDualBombInstalled()
    {
        bool result = MultipleBombs != null;

        if (_multipleBombsType == null)
        {
            _multipleBombsType = ReflectionHelper.FindType("MultipleBombsAssembly.MultipleBombs");
            if (_multipleBombsType == null)
            {
                return false;
            }
            _bombsCountField = _multipleBombsType.GetField("bombsCount", BindingFlags.NonPublic | BindingFlags.Instance);
            _getCurrentMaximumBombCountMethod = _multipleBombsType.GetMethod("GetCurrentMaximumBombCount", BindingFlags.Public | BindingFlags.Instance);
        }

        return result;
    }

    public IEnumerator SetBombTimer(string hours, string mins, string secs)
    {
        int hoursInt = 0;
        if (!string.IsNullOrEmpty(hours) && !int.TryParse(hours, out hoursInt))
        {
            yield break;
        }

        int minutes = 0;
        if (!int.TryParse(mins, out minutes))
        {
            yield break;
        }

        int seconds = 0;
        if (!string.IsNullOrEmpty(secs) &&
            (!int.TryParse(secs, out seconds) || seconds >= 60) )
        {
            yield break;
        }

        int timeIndex = (hoursInt * 120) + (minutes * 2) + (seconds / 30);

        //Double the available free play time. (The doubling stacks with the Multiple bombs module installed)
        float originalMaxTime = (float) _MAXSECONDSFIELD.GetValue(null);
        int maxModules = (int)_maxModuleField.GetValue(FreeplayDevice);
        int multiplier = IsDualBombInstalled() ? ((int)_getCurrentMaximumBombCountMethod.Invoke(MultipleBombs,null) * 2) - 1 : 1;
        float newMaxTime = 600f + ((maxModules - 1) * multiplier * 60);
        _MAXSECONDSFIELD.SetValue(null, newMaxTime);

        object currentSettings = _currentSettingsField.GetValue(FreeplayDevice);
        float currentTime = (float)_timeField.GetValue(currentSettings);
        int currentTimeIndex = Mathf.FloorToInt(currentTime) / 30;
        MonoBehaviour button = timeIndex > currentTimeIndex ? (MonoBehaviour)_timeIncrementField.GetValue(FreeplayDevice) : (MonoBehaviour)_timeDecrementField.GetValue(FreeplayDevice);
        MonoBehaviour buttonSelectable = (MonoBehaviour)button.GetComponent(_selectableType);

        for (int hitCount = 0; hitCount < Mathf.Abs(timeIndex - currentTimeIndex); ++hitCount)
        {
            currentTime = (float)_timeField.GetValue(currentSettings);
            SelectObject(buttonSelectable);
            yield return new WaitForSeconds(0.01f);
            if (Mathf.FloorToInt(currentTime) == Mathf.FloorToInt((float) _timeField.GetValue(currentSettings)))
                break;
        }

        //Restore original max time, just in case Multiple bombs module was NOT installed, to avoid false detection.
        _MAXSECONDSFIELD.SetValue(null, originalMaxTime);
    }

    public IEnumerator SetBombCount(string bombs)
    {
        int bombCount = 0;
        if (!int.TryParse(bombs, out bombCount))
        {
            yield break;
        }

        if (!IsDualBombInstalled())
        {
            yield break;
        }

        int currentBombCount = (int) _bombsCountField.GetValue(MultipleBombs);
        MonoBehaviour buttonSelectable = bombCount > currentBombCount ? SelectableChildren[3] : SelectableChildren[2];

        for (int hitCount = 0; hitCount < Mathf.Abs(bombCount - currentBombCount); ++hitCount)
        {
            int lastBombCount = (int)_bombsCountField.GetValue(MultipleBombs);
            SelectObject(buttonSelectable);
            yield return new WaitForSeconds(0.01f);
            if (lastBombCount == (int)_bombsCountField.GetValue(MultipleBombs))
                yield break;
        }

        //SelectObject(bombCount <= 1 ? SelectableChildren[2] : SelectableChildren[3]);
    }

    public IEnumerator SetBombModules(string mods)
    {
        int moduleCount = 0;
        if (!int.TryParse(mods, out moduleCount))
        {
            yield break;
        }

        object currentSettings = _currentSettingsField.GetValue(FreeplayDevice);
        int currentModuleCount = (int)_moduleCountField.GetValue(currentSettings);
        MonoBehaviour button = moduleCount > currentModuleCount ? (MonoBehaviour)_moduleCountIncrementField.GetValue(FreeplayDevice) : (MonoBehaviour)_moduleCountDecrementField.GetValue(FreeplayDevice);
        MonoBehaviour buttonSelectable = (MonoBehaviour)button.GetComponent(_selectableType);

        for (int hitCount = 0; hitCount < Mathf.Abs(moduleCount - currentModuleCount); ++hitCount)
        {
            int lastModuleCount = (int)_moduleCountField.GetValue(currentSettings);
            SelectObject(buttonSelectable);
            yield return new WaitForSeconds(0.01f);
            if (lastModuleCount == (int)_moduleCountField.GetValue(currentSettings))
                yield break;
        }
    }

    public void SetNeedy(bool on = true)
    {
        object currentSettings = _currentSettingsField.GetValue(FreeplayDevice);
        bool hasNeedy = (bool)_hasNeedyField.GetValue(currentSettings);
        if (hasNeedy != on)
        {
            MonoBehaviour needyToggle = (MonoBehaviour)_needyToggleField.GetValue(FreeplayDevice);
            SelectObject( (MonoBehaviour)needyToggle.GetComponent(_selectableType) );

        }
    }

    public void SetHardcore(bool on = true)
    {
        object currentSettings = _currentSettingsField.GetValue(FreeplayDevice);
        bool isHardcore = (bool)_isHardCoreField.GetValue(currentSettings);
        if (isHardcore != on)
        {
            MonoBehaviour hardcoreToggle = (MonoBehaviour)_hardcoreToggleField.GetValue(FreeplayDevice);
            SelectObject( (MonoBehaviour)hardcoreToggle.GetComponent(_selectableType) );
        }
    }

    public void SetModsOnly(bool on = true)
    {
        object currentSettings = _currentSettingsField.GetValue(FreeplayDevice);
        bool onlyMods = (bool)_onlyModsField.GetValue(currentSettings);
        if (onlyMods != on)
        {
            MonoBehaviour modsToggle = (MonoBehaviour)_modsOnlyToggleField.GetValue(FreeplayDevice);
            SelectObject( (MonoBehaviour)modsToggle.GetComponent(_selectableType) );
        }
    }

    public void StartBomb()
    {
        MonoBehaviour startButton = (MonoBehaviour)_startButtonField.GetValue(FreeplayDevice);
        SelectObject( (MonoBehaviour)startButton.GetComponent(_selectableType) );
    }

    public IEnumerator HoldFreeplayDevice()
    {
        int holdState = (int)_holdStateProperty.GetValue(FloatingHoldable, null);

        if (holdState != 0)
        {
            SelectObject(Selectable);

            float holdTime = (float)_pickupTimeField.GetValue(FloatingHoldable);
            IEnumerator forceRotationCoroutine = ForceHeldRotation(holdTime);
            while (forceRotationCoroutine.MoveNext())
            {
                yield return forceRotationCoroutine.Current;
            }
        }
    }

    public void LetGoFreeplayDevice()
    {
        int holdState = (int)_holdStateProperty.GetValue(FloatingHoldable, null);
        if (holdState == 0)
        {
            DeselectObject(Selectable);
        }
    }

    private void SelectObject(MonoBehaviour selectable)
    {
        _handleSelectMethod.Invoke(selectable, new object[] { true });
        _selectMethod.Invoke(SelectableManager, new object[] { selectable, true });
        _handleInteractMethod.Invoke(SelectableManager, null);
        _onInteractEndedMethod.Invoke(selectable, null);
    }

    private void DeselectObject(MonoBehaviour selectable)
    {
        _handleCancelMethod.Invoke(SelectableManager, null);
    }

    private IEnumerator ForceHeldRotation(float duration)
    {
        Transform baseTransform = (Transform)_getBaseHeldObjectTransformMethod.Invoke(SelectableManager, null);

        float initialTime = Time.time;
        while (Time.time - initialTime < duration)
        {
            Quaternion currentRotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);

            _setZSpinMethod.Invoke(SelectableManager, new object[] { 0.0f });
            _setControlsRotationMethod.Invoke(SelectableManager, new object[] { baseTransform.rotation * currentRotation });
            _handleFaceSelectionMethod.Invoke(SelectableManager, null);
            yield return null;
        }

        _setZSpinMethod.Invoke(SelectableManager, new object[] { 0.0f });
        _setControlsRotationMethod.Invoke(SelectableManager, new object[] { baseTransform.rotation * Quaternion.Euler(0.0f, 0.0f, 0.0f) });
        _handleFaceSelectionMethod.Invoke(SelectableManager, null);
    }
    #endregion

    #region Readonly Fields
    public readonly MonoBehaviour FreeplayDevice = null;
    public readonly MonoBehaviour Selectable = null;
    public readonly MonoBehaviour[] SelectableChildren = null;
    public readonly MonoBehaviour FloatingHoldable = null;
    private readonly MonoBehaviour SelectableManager = null;
    private readonly MonoBehaviour MultipleBombs = null;
    #endregion

    #region Private Static Fields
    private static Type _freeplayDeviceType = null;
    private static FieldInfo _moduleCountIncrementField = null;
    private static FieldInfo _moduleCountDecrementField = null;
    private static FieldInfo _timeIncrementField = null;
    private static FieldInfo _timeDecrementField = null;
    private static FieldInfo _needyToggleField = null;
    private static FieldInfo _hardcoreToggleField = null;
    private static FieldInfo _modsOnlyToggleField = null;
    private static FieldInfo _startButtonField = null;
    private static FieldInfo _currentSettingsField = null;
    private static FieldInfo _maxModuleField = null;
    private static FieldInfo _MAXSECONDSFIELD = null;

    private static Type _freeplaySettingsType = null;
    private static FieldInfo _moduleCountField = null;
    private static FieldInfo _timeField = null;
    private static FieldInfo _isHardCoreField = null;
    private static FieldInfo _hasNeedyField = null;
    private static FieldInfo _onlyModsField = null;

    private static Type _floatingHoldableType = null;
    private static FieldInfo _pickupTimeField = null;
    private static PropertyInfo _holdStateProperty = null;

    private static Type _selectableType = null;
    private static MethodInfo _handleSelectMethod = null;
    private static MethodInfo _onInteractEndedMethod = null;
    private static FieldInfo _childrenField = null;

    private static Type _selectableManagerType = null;
    private static MethodInfo _selectMethod = null;
    private static MethodInfo _handleInteractMethod = null;
    private static MethodInfo _handleCancelMethod = null;
    private static MethodInfo _setZSpinMethod = null;
    private static MethodInfo _setControlsRotationMethod = null;
    private static MethodInfo _getBaseHeldObjectTransformMethod = null;
    private static MethodInfo _handleFaceSelectionMethod = null;

    private static Type _inputManagerType = null;
    private static PropertyInfo _instanceProperty = null;
    private static PropertyInfo _selectableManagerProperty = null;

    private static MonoBehaviour _inputManager = null;

    private static Type _multipleBombsType = null;
    private static FieldInfo _bombsCountField = null;
    private static MethodInfo _getCurrentMaximumBombCountMethod = null;

    #endregion
}


text:
package goStrongswanVici

import (
	"fmt"
	"strconv"
)

//from list-sa event
type IkeSa struct {
	Uniqueid        string               `json:"uniqueid"` //called ike_id in terminate() argument.
	Version         string               `json:"version"`
	State           string               `json:"state"` //had saw: ESTABLISHED
	Local_host      string               `json:"local-host"`
	Local_id        string               `json:"local-id"`
	Remote_host     string               `json:"remote-host"`
	Remote_id       string               `json:"remote-id"`
	Remote_xauth_id string               `json:"remote-xauth-id"` //client username
	Initiator       string               `json:"initiator"`
	Initiator_spi   string               `json:"initiator-spi"`
	Responder_spi   string               `json:"responder-spi"`
	Encr_alg        string               `json:"encr-alg"`
	Encr_keysize    string               `json:"encr-keysize"`
	Integ_alg       string               `json:"integ-alg"`
	Integ_keysize   string               `json:"integ-keysize"`
	Prf_alg         string               `json:"prf-alg"`
	Dh_group        string               `json:"dh-group"`
	Established     string               `json:"established"`
	Rekey_time      string               `json:"rekey-time"`
	Reauth_time     string               `json:"reauth-time"`
	Remote_vips     []string             `json:"remote-vips"`
	Child_sas       map[string]Child_sas `json:"child-sas"` //key means child-sa-name(conn name in ipsec.conf)
}

type Child_sas struct {
	Reqid         string   `json:"reqid"`
	State         string   `json:"state"` //had saw: INSTALLED
	Mode          string   `json:"mode"`  //had saw: TUNNEL
	Protocol      string   `json:"protocol"`
	Encap         string   `json:"encap"`
	Spi_in        string   `json:"spi-in"`
	Spi_out       string   `json:"spi-out"`
	Cpi_in        string   `json:"cpi-in"`
	Cpi_out       string   `json:"cpi-out"`
	Encr_alg      string   `json:"encr-alg"`
	Encr_keysize  string   `json:"encr-keysize"`
	Integ_alg     string   `json:"integ-alg"`
	Integ_keysize string   `json:"integ-keysize"`
	Prf_alg       string   `json:"prf-alg"`
	Dh_group      string   `json:"dh-group"`
	Esn           string   `json:"esn"`
	Bytes_in      string   `json:"bytes-in"` //bytes into this machine
	Packets_in    string   `json:"packets-in"`
	Use_in        string   `json:"use-in"`
	Bytes_out     string   `json:"bytes-out"` // bytes out of this machine
	Packets_out   string   `json:"packets-out"`
	Use_out       string   `json:"use-out"`
	Rekey_time    string   `json:"rekey-time"`
	Life_time     string   `json:"life-time"`
	Install_time  string   `json:"install-time"`
	Local_ts      []string `json:"local-ts"`
	Remote_ts     []string `json:"remote-ts"`
}

func (s *Child_sas) GetBytesIn() uint64 {
	num, err := strconv.ParseUint(s.Bytes_in, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

func (s *Child_sas) GetBytesOut() uint64 {
	num, err := strconv.ParseUint(s.Bytes_out, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

// To be simple, list all clients that are connecting to this server .
// A client is a sa.
// Lists currently active IKE_SAs
func (c *ClientConn) ListSas(ike string, ike_id string) (sas []map[string]IkeSa, err error) {
	sas = []map[string]IkeSa{}
	var eventErr error
	//register event
	err = c.RegisterEvent("list-sa", func(response map[string]interface{}) {
		sa := &map[string]IkeSa{}
		err = ConvertFromGeneral(response, sa)
		if err != nil {
			fmt.Printf("list-sa event error: %s\n", err)
			eventErr = err
			return
		}
		sas = append(sas, *sa)
		//fmt.Printf("event %#v\n", response)
	})
	if err != nil {
		return
	}
	if eventErr != nil {
		return
	}

	inMap := map[string]interface{}{}
	if ike != "" {
		inMap["ike"] = ike
	}
	if ike_id != "" {
		inMap["ike_id"] = ike_id
	}
	_, err = c.Request("list-sas", inMap)
	if err != nil {
		return
	}
	//fmt.Printf("request finish %#v\n", sas)
	err = c.UnregisterEvent("list-sa")
	if err != nil {
		return
	}
	return
}

//a vpn conn in the strongswan server
type VpnConnInfo struct {
	IkeSa
	Child_sas
	IkeSaName   string //looks like conn name in ipsec.conf, content is same as ChildSaName
	ChildSaName string //looks like conn name in ipsec.conf
}

func (c *VpnConnInfo) GuessUserName() string {
	if c.Remote_xauth_id != "" {
		return c.Remote_xauth_id
	}
	if c.Remote_id != "" {
		return c.Remote_id
	}
	return ""
}

// a helper method to avoid complex data struct in ListSas
// if it only have one child_sas ,it will put it into info.Child_sas
func (c *ClientConn) ListAllVpnConnInfo() (list []VpnConnInfo, err error) {
	sasList, err := c.ListSas("", "")
	if err != nil {
		return
	}
	list = make([]VpnConnInfo, len(sasList))
	for i, sa := range sasList {
		info := VpnConnInfo{}
		if len(sa) != 1 {
			fmt.Printf("[vici.ListAllVpnConnInfo] warning: len(sa)[%d]!=1\n", len(sa))
		}
		for ikeSaName, ikeSa := range sa {
			info.IkeSaName = ikeSaName
			info.IkeSa = ikeSa
			//if len(ikeSa.Child_sas) != 1 {
			//	fmt.Println("[vici.ListAllVpnConnInfo] warning: len(ikeSa.Child_sas)[%d]!=1", len(ikeSa.Child_sas))
			//}
			for childSaName, childSa := range ikeSa.Child_sas {
				info.ChildSaName = childSaName
				info.Child_sas = childSa
				break
			}
			break
		}
		if len(info.IkeSa.Child_sas) == 1 {
			info.IkeSa.Child_sas = nil
		}
		list[i] = info
	}
	return
}


text:
<?php

namespace Magento\Sales\Controller\AbstractController;

use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Registry;

class OrderLoader implements OrderLoaderInterface
{
    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $orderFactory;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $registry;

    /**
     * @var OrderViewAuthorizationInterface
     */
    protected $orderAuthorization;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    protected $url;

    /**
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param OrderViewAuthorizationInterface $orderAuthorization
     * @param Registry $registry
     * @param \Magento\Framework\UrlInterface $url
     */
    public function __construct(
        \Magento\Sales\Model\OrderFactory $orderFactory,
        OrderViewAuthorizationInterface $orderAuthorization,
        Registry $registry,
        \Magento\Framework\UrlInterface $url
    ) {
        $this->orderFactory = $orderFactory;
        $this->orderAuthorization = $orderAuthorization;
        $this->registry = $registry;
        $this->url = $url;
    }

    /**
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return bool
     */
    public function load(RequestInterface $request, ResponseInterface $response)
    {
        $orderId = (int)$request->getParam('order_id');
        if (!$orderId) {
            $request->initForward();
            $request->setActionName('noroute');
            $request->setDispatched(false);
            return false;
        }

        $order = $this->orderFactory->create()->load($orderId);

        if ($this->orderAuthorization->canView($order)) {
            $this->registry->register('current_order', $order);
            return true;
        }
        $response->setRedirect($this->url->getUrl('*/*/history'));
        return false;
    }
}


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Util.Webs.Controllers;
using Util.Webs.Razors;

namespace Util.Samples.Apis.Tools {
    /// <summary>
    /// 初始化Razor控制器
    /// </summary>
    public class InitRazorController : WebApiControllerBase {
        /// <summary>
        /// Razor静态Html生成器
        /// </summary>
        public IRazorHtmlGenerator RazorHtmlGenerator { get; set; }

        /// <summary>
        /// 初始化一个<see cref="InitRazorController"/>类型的实例
        /// </summary>
        public InitRazorController( IRazorHtmlGenerator razorHtmlGenerator ) {
            RazorHtmlGenerator = razorHtmlGenerator;
        }

        /// <summary>
        /// 初始化路由
        /// </summary>
        [Route( "/api/init" )]
        [HttpPost]
        public async Task<IActionResult> Init() {
            await RazorHtmlGenerator.Generate();
            return new JsonResult( "" );
        }
    }
}


text:
#include <aws/glue/model/GetSchemaByDefinitionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetSchemaByDefinitionRequest::GetSchemaByDefinitionRequest() :
    m_schemaIdHasBeenSet(false),
    m_schemaDefinitionHasBeenSet(false)
{
}

Aws::String GetSchemaByDefinitionRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_schemaIdHasBeenSet)
  {
   payload.WithObject("SchemaId", m_schemaId.Jsonize());

  }

  if(m_schemaDefinitionHasBeenSet)
  {
   payload.WithString("SchemaDefinition", m_schemaDefinition);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetSchemaByDefinitionRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSGlue.GetSchemaByDefinition"));
  return headers;

}


text:
import * as React from "react";
import {NodeModel} from "../Common";
import {DiagramEngine} from "../DiagramEngine";

export interface NodeProps {
	node:NodeModel;
	children?: any;
	diagramEngine: DiagramEngine
}

export interface NodeState {
}

/**
 * @author Dylan Vorster
 */
export class NodeWidget extends React.Component<NodeProps, NodeState> {

	constructor(props: NodeProps) {
		super(props);
		this.state = {
		}
	}

	shouldComponentUpdate(){
		return this.props.diagramEngine.canEntityRepaint(this.props.node);
	}

	render() {
		return (
			React.DOM.div({
				'data-nodeid': this.props.node.id,
				className: 'node' + (this.props.node.isSelected()?' selected':''),
				style:{
					top: this.props.node.y,
					left: this.props.node.x,
				}},
				React.cloneElement(this.props.children,{})
			)
		);
	}
}


text:
Scene::Scene()
{
	InitScene();
	//std::vector<std::unique_ptr<Primitive>> sceneObject;
}
void Scene::InitScene()
{
	//Create a default scene with some stuff in it
	mainCamera = new Camera();

	vec3 light_position(0.0f, -2.0f, -1.0f);
	lightSource = new Light(light_position, Color(255.0f,255.0f,255.0f), 1.0f);

	//Sphere *scene_sphere = new Sphere(vec3(-1.5f, -0.2f, 2.0f), 0.4f, sphereMaterial1);//green
	//Sphere *scene_sphere2 = new Sphere(vec3(-0.7f, -0.8f, 4.0f), 0.5f, sphereMaterial2);//maroon
	//Plane *ground_plane = new Plane(vec3(0.0f, 1.0f, 0.0f),-1.0f,planeMaterial);//gray
	//Triangle *big_triangle = new Triangle(vec3(1.0f,0.0f,2.5f), vec3(0.0f, -1.0f, 2.5f), vec3(-1.0f, 0.0f, 2.5f),triangleMat);//gray

	//sceneObject.push_back(scene_sphere);
	//sceneObject.push_back(scene_sphere2);
	//sceneObject.push_back(ground_plane);
	////sceneObject.push_back(std::unique_ptr<Triangle>(big_triangle));

}
void Scene::addRenderObject(RenderObject* renderObject)
{
	sceneObject.push_back(renderObject);
}

void Scene::deleteRenderObject(RenderObject* renderObject)
{
	for (std::vector<RenderObject*>::iterator itRenderObjects(sceneObject.begin()), itEnd(sceneObject.end());
	itRenderObjects != itEnd;
		)
	{
		if (*itRenderObjects == renderObject)
		{
			delete(*itRenderObjects);
			itRenderObjects = sceneObject.erase(itRenderObjects);
			itEnd = sceneObject.end();
		}
		else
		{
			++itRenderObjects;
		}
	}
}

void Scene::ClearRenderObjects()
{
	for (std::vector<RenderObject*>::iterator itRenderObjects(sceneObject.begin()), itEnd(sceneObject.end());
	itRenderObjects != itEnd;
		)
	{
		delete(*itRenderObjects);
		itRenderObjects = sceneObject.erase(itRenderObjects);
		itEnd = sceneObject.end();
	}
}


text:
from os.path import join as pjoin

# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 1
_version_micro = ''  # use '' for first of series, number for 1 and above
_version_extra = 'dev'
# _version_extra = ''  # Uncomment this for full releases

# Construct full version string from these.
_ver = [_version_major, _version_minor]
if _version_micro:
    _ver.append(_version_micro)
if _version_extra:
    _ver.append(_version_extra)

__version__ = '.'.join(map(str, _ver))

CLASSIFIERS = ["Development Status :: 3 - Alpha",
               "Environment :: Console",
               "Intended Audience :: Science/Research",
               "License :: OSI Approved :: MIT License",
               "Operating System :: OS Independent",
               "Programming Language :: Python",
               "Topic :: Scientific/Engineering"]

# Description should be a one-liner:
description = "arghphot: arghhh! Photometry"
# Long description will go up on the pypi page
long_description = """
arghphot
========

Arghhh! Photometry.

.. _README: https://github.com/balbinot/arghphot/blob/master/README.md

License
=======
``arghphot`` is licensed under the terms of the MIT license. See the file
"LICENSE" for information on the history of this software, terms & conditions
for usage, and a DISCLAIMER OF ALL WARRANTIES.

All trademarks referenced herein are property of their respective holders.

Copyright (c) 2016--, Eduardo Balbinot, University of Surrey
"""

NAME = "arghphot"
MAINTAINER = "Eduardo Balbinot"
MAINTAINER_EMAIL = "e.balbinot@surrey.ac.uk"
DESCRIPTION = description
LONG_DESCRIPTION = long_description
URL = "http://github.com/balbinot/arghphot"
DOWNLOAD_URL = ""
LICENSE = "MIT"
AUTHOR = "Eduardo Balbinot"
AUTHOR_EMAIL = "e.balbinot@surrey.ac.uk"
PLATFORMS = "OS Independent"
MAJOR = _version_major
MINOR = _version_minor
MICRO = _version_micro
VERSION = __version__
PACKAGES = ['arghphot',
            'arghphot.tests']
PACKAGE_DATA = {'arghphot': [pjoin('data', '*')]}
REQUIRES = ["numpy", "astropy", "ccdproc"]


text:
from office365.runtime.client_value_object import ClientValueObject

class SharePointIds(ClientValueObject):
    """The SharePointIds resource groups the various identifiers for an item stored in a SharePoint site or OneDrive
    for Business into a single structure. """


text:
var FANTASMA1 = function (key,game,startpos){

    this.game = game;
    this.key = key;
    //Parametros de this

    this.velocidad = 60;
    this.estaMuriendo = false;
    this.tiempoAtaque = 0;
    this.startPos = startpos;
    this.nombre = "fantasma1";
    this.timer = 0;
    this.ataque = false;
    this.huir = true;
    //Damos los valores a this del mismo mundo que del mundo game que pasamos

    this.gridsize = game.gridsize;
    this.safetile = game.safetile;

    //Creamos los diferentes puntos de navegacion

    this.marcador = new Phaser.Point(0,0);
    this.curva = new Phaser.Point(0,0);
    this.treshold = 6;

    this.direcciones = [ null, null, null, null, null];
    this.contrarios = [ Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.DOWN, Phaser.UP ];

    this.actual = Phaser.NONE;
    this.girando = Phaser.NONE;
    this.quieroIr = Phaser.NONE;
    this.score = 0;
    this.keyPressTimer = 0;
    this.KEY_COOLING_DOWN_TIME = 750;

    //Ahora creamos el sprite this

    this.sprite = this.game.add.sprite(this.startPos.x, this.startPos.y, key, 0);

    //Podemos escalar a this, para que se vea más grande

    this.sprite.anchor.setTo(0.5);

    ///////ANIMACIONES DE this////////

    this.sprite.animations.add('derecha', [11], 10, true);
    this.sprite.animations.add('arriba', [9], 10, true);
    this.sprite.animations.add('abajo', [10], 10, true);
    this.sprite.animations.add('izquierda', [8], 10, true);//Queremos que se repita en bucle.
    this.sprite.animations.add('huir', [16, 17], 10, true);
    this.sprite.animations.add('morir', [20], 10, true);

    //////////////////////////////////

    this.game.physics.arcade.enable(this.sprite);
    this.sprite.body.setSize(16, 16, 0, 0);
    this.sprite.play('derecha');

    //Llamamos al prototipo de this, que tendrá la función de mover.

    this.mover(Phaser.RIGHT);

};
FANTASMA1.prototype.updateCounter = function() {

        this.tiempoAtaque++;

    }

FANTASMA1.prototype.volver = function(){

    this.game.scoreF -= 50;
    this.score -= 50;
    this.sprite.x = this.startPos.x;
    this.sprite.y = this.startPos.y;
    this.mover(Phaser.RIGHT);

};

FANTASMA1.prototype.mover = function (direccion) {

    var velocidad = this.velocidad;

    if (direccion === Phaser.NONE) {
        this.sprite.body.velocity.x = this.sprite.body.velocity.y = 0;
        return;
    }

    if (direccion === Phaser.LEFT || direccion === Phaser.UP)
    {
        velocidad = -velocidad;
    }
    if (direccion === Phaser.LEFT || direccion === Phaser.RIGHT)
    {
        this.sprite.body.velocity.x = velocidad;
    }
    else
    {
        this.sprite.body.velocity.y = velocidad;
    }
    //  Reset the scale and angle (FANTASMA1 is facing to the right in the sprite sheet)
    if(!this.game.pacman.ataque&& !this.game.pacman2.ataque){

        this.sprite.play('derecha');
        if (direccion === Phaser.LEFT)
        {

            this.sprite.play('izquierda');
        }
        else if (direccion === Phaser.UP)
        {
            this.sprite.play('arriba');
        }
        else if (direccion === Phaser.DOWN)
        {
            this.sprite.play('abajo');
        }

    }else{

        this.sprite.play('huir');
    }

    this.actual = direccion;

};

FANTASMA1.prototype.atacar = function(){

    console.log("ataque");
    this.game.scoreF += 150;
    this.score += 150;

}
FANTASMA1.prototype.update = function() {

        if(this.game.tiempo < this.game.final && this.game.totaldots > 0){

            this.game.physics.arcade.collide(this.sprite, this.game.layer);
            this.game.physics.arcade.overlap(this.sprite, this.game.dots, this.comerDot, null, this);
            this.game.physics.arcade.overlap(this.sprite, this.game.pills, this.comerPill, null, this);
            if(!this.ataque){

                this.game.physics.arcade.overlap(this.sprite,this.game.pacman.sprite, this.volver,null,this);
                this.game.physics.arcade.overlap(this.sprite,this.game.pacman2.sprite, this.volver,null,this);

            }

            if(this.ataque){

                if(this.tiempoAtaque < 10000){

                    this.game.physics.arcade.overlap(this.sprite,this.game.pacman.sprite,this.atacar,null,this);
                    this.game.physics.arcade.overlap(this.sprite,this.game.pacman2.sprite,this.atacar,null,this);
                    var that = this;
                    this.timer.loop(1000,that.updateCounter,this);
                    this.timer.start();
                    //console.log("Tiempo" + this.tiempoAtaque);

                }else{

                    this.ataque = false;
                    //this.huir = true;
                    this.timer.destroy();
                    this.tiempoAtaque = 0;
                    //console.log("Modo normal");

                }

            }

            //this.game.physics.arcade.overlap(this.sprite,this.game.pacman2.sprite,this.volver,null,this);
            this.marcador.x = this.game.math.snapToFloor(Math.floor(this.sprite.x), this.gridsize) / this.gridsize;
            this.marcador.y = this.game.math.snapToFloor(Math.floor(this.sprite.y), this.gridsize) / this.gridsize;

            if(this.marcador.x < 0){//Si llega al borde sin borde, sale por el otro lado

                this.sprite.x = this.game.map.widthInPixels - 1;

            }

            if(this.marcador.x >= this.game.map.width){

                this.sprite.x = 1;

            }

            //Ahora nos creamos las direcciones.

            this.direcciones[1] = this.game.map.getTileLeft(this.game.layer.index, this.marcador.x, this.marcador.y);
            this.direcciones[2] = this.game.map.getTileRight(this.game.layer.index, this.marcador.x, this.marcador.y);
            this.direcciones[3] = this.game.map.getTileAbove(this.game.layer.index, this.marcador.x, this.marcador.y);
            this.direcciones[4] = this.game.map.getTileBelow(this.game.layer.index, this.marcador.x, this.marcador.y);

            //this.comprobarTeclas();

            if(this.girando !== Phaser.NONE){

                this.girar();

            }

        }else{

            this.mover(Phaser.NONE);
            if(!this.estaMuriendo){

                this.estaMuriendo = true;
                this.sprite.play('morir');

            }

        }

    };

FANTASMA1.prototype.comprobarTeclas = function(){

    if (this.game.cursors.left.isDown ||
        this.game.cursors.right.isDown ||
        this.game.cursors.up.isDown ||
        this.game.cursors.down.isDown) {
        this.keyPressTimer = this.game.time.time + this.KEY_COOLING_DOWN_TIME;
    }

    if(this.game.cursors.left.isDown && this.actual !== Phaser.LEFT){

        this.quieroIr = Phaser.LEFT;

    }else if(this.game.cursors.right.isDown && this.actual !== Phaser.RIGHT){

        this.quieroIr = Phaser.RIGHT;

    }

    else if(this.game.cursors.up.isDown && this.actual !== Phaser.UP){

        this.quieroIr = Phaser.UP;

    }

    else if(this.game.cursors.down.isDown && this.actual !== Phaser.DOWN){

        this.quieroIr = Phaser.DOWN;

    }

    if (this.game.time.time > this.keyPressTimer)
    {
        //  This forces them to hold the key down to turn the corner
        this.girando = Phaser.NONE;
        this.quieroIr = Phaser.NONE;
    } else {

        this.comprobarDireccion(this.quieroIr);
    }

};

FANTASMA1.prototype.comerDot = function(FANTASMA1,dot){

    dot.kill();

    this.game.scoreF += 100;
    this.score += 100;
    this.game.totaldots--; //COMPROBAR SI LAURA LO LLAMA ASÍ EN LA FUNCION GENERAL.

};

FANTASMA1.prototype.comerPill = function(FANTASMA1, pill){

    pill.kill();

    //this.huir = false;
    this.ataque = true;
    this.timer = this.game.time.create(false);

    this.game.numPills--;

};

//Ahora entramos en la función de giro

FANTASMA1.prototype.girar = function(){

    var sx = Math.floor(this.sprite.x);
    var sy = Math.floor(this.sprite.y);

    //Tenemos que tener en cuenta que, debido al rápido movimiento de FANTASMA1, deberemos tener cuidado, porque muchas veces
    //entre la pulsación y cuando se puede realizar el giro, FANTASMA1 ya puede haber pasado la zona de giro.

    if(!this.game.math.fuzzyEqual(sx, this.curva.x, this.treshold) || !this.game.math.fuzzyEqual(sy, this.curva.y, this.treshold))
    {
        return false;
    }

    //Tenemos que alinear el grid donde nos movemos con las posiciones del sprite de FANTASMA1

    this.sprite.x = this.curva.x;
    this.sprite.y = this.curva.y;

    this.sprite.body.reset(this.curva.x, this.curva.y);
    this.mover(this.girando);
    this.girando = Phaser.NONE;
    return true;

};

//Debemos comprobar si se puede girar en la dirección que se le ha pedido

FANTASMA1.prototype.comprobarDireccion = function(girarA){

    //console.log("Queremos girar a:" + girarA);
    if(this.girando === girarA || this.direcciones[girarA] === null || this.direcciones[girarA].index !== this.safetile){ //Estamos comprobando que no puede girar hacia la direccion que quiere porque ya está en esa direccion, o no puede.

        return;

    }

    if(this.actual === this.contrarios[girarA]){

        this.mover(girarA);
        this.keyPressTimer = this.game.time.time;

    }else{

        this.girando = girarA;
        this.curva.x = (this.marcador.x * this.gridsize) + (this.gridsize / 2);
        this.curva.y = (this.marcador.y * this.gridsize) + (this.gridsize / 2);
        this.quieroIr = Phaser.NONE;

    }

};


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>octant.ocean.velocity</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package octant ::
        Package ocean ::
        Module velocity

Module velocity

source code

velocity class.py

Created by Rob Hetland on 2007-01-13. Copyright (c) 2007 Texas A&M
  Univsersity. All rights reserved.

Version:
        1.3.0.dev6329

    Classes

        nc_velocity

    Variables

        ALLOW_THREADS = 1

        BUFSIZE = 10000

        CLIP = 0

        ERR_CALL = 3

        ERR_DEFAULT = 0

        ERR_DEFAULT2 = 2084

        ERR_IGNORE = 0

        ERR_LOG = 5

        ERR_PRINT = 4

        ERR_RAISE = 2

        ERR_WARN = 1

        FLOATING_POINT_SUPPORT = 1

        FPE_DIVIDEBYZERO = 1

        FPE_INVALID = 8

        FPE_OVERFLOW = 2

        FPE_UNDERFLOW = 4

        False_ = False

        Inf = inf

        Infinity = inf

        MAXDIMS = 32

        NAN = nan

        NINF = -inf

        NZERO = -0.0

        NaN = nan

        PINF = inf

        PZERO = 0.0

        RAISE = 2

        SHIFT_DIVIDEBYZERO = 0

        SHIFT_INVALID = 9

        SHIFT_OVERFLOW = 3

        SHIFT_UNDERFLOW = 6

        ScalarType = (<type 'int'>, <type 'float'>, <type 'complex'>, ...

        True_ = True

        UFUNC_BUFSIZE_DEFAULT = 10000

        UFUNC_PYVALS_NAME = 'UFUNC_PYVALS'

        WRAP = 1

        absolute = <ufunc 'absolute'>

        add = <ufunc 'add'>

        arccos = <ufunc 'arccos'>

        arccosh = <ufunc 'arccosh'>

        arcsin = <ufunc 'arcsin'>

        arcsinh = <ufunc 'arcsinh'>

        arctan = <ufunc 'arctan'>

        arctan2 = <ufunc 'arctan2'>

        arctanh = <ufunc 'arctanh'>

        bitwise_and = <ufunc 'bitwise_and'>

        bitwise_not = <ufunc 'invert'>

        bitwise_or = <ufunc 'bitwise_or'>

        bitwise_xor = <ufunc 'bitwise_xor'>

        c_ = <numpy.lib.index_tricks.CClass object at 0x78f1b0>

        cast = <code title="{<type 'numpy.int64'>: <function <lambda> at 0x1028bf0>, <type 'numpy.\
int16'>: <function <lambda> at 0x1028c30>, <type 'numpy.void'>: <funct\
ion <lambda> at 0x1028c70>, <type 'numpy.complex128'>: <function <lamb\
da> at 0x1028cb0>, <type 'numpy.int32'>: <function <lambda> at 0x1028c\
f0>, <type 'numpy.uint32'>: <function <lambda> at 0x1028d30>, <type 'n\
umpy.unicode_'>: <function <lambda> at 0x1028d70>, <type 'numpy.comple\
x64'>: <function <lambda> at 0x1028db0>, <type 'numpy.int32'>: <functi\
on <lambda> at 0x1028df0>, <type 'numpy.uint32'>: <function <lambda> a\
...">{<type 'numpy.int64'>: <function <lambda> at 0x1028bf0>...

        ceil = <ufunc 'ceil'>

        conj = <ufunc 'conjugate'>

        conjugate = <ufunc 'conjugate'>

        cos = <ufunc 'cos'>

        cosh = <ufunc 'cosh'>

        deg2rad = <ufunc 'deg2rad'>

        degrees = <ufunc 'degrees'>

        divide = <ufunc 'divide'>

        e = 2.71828182846

        equal = <ufunc 'equal'>

        exp = <ufunc 'exp'>

        exp2 = <ufunc 'exp2'>

        expm1 = <ufunc 'expm1'>

        fabs = <ufunc 'fabs'>

        floor = <ufunc 'floor'>

        floor_divide = <ufunc 'floor_divide'>

        fmax = <ufunc 'fmax'>

        fmin = <ufunc 'fmin'>

        fmod = <ufunc 'fmod'>

        frexp = <ufunc 'frexp'>

        greater = <ufunc 'greater'>

        greater_equal = <ufunc 'greater_equal'>

        hypot = <ufunc 'hypot'>

        index_exp = <numpy.lib.index_tricks.IndexExpression object at ...

        inf = inf

        infty = inf

        invert = <ufunc 'invert'>

        isfinite = <ufunc 'isfinite'>

        isinf = <ufunc 'isinf'>

        isnan = <ufunc 'isnan'>

        ldexp = <ufunc 'ldexp'>

        left_shift = <ufunc 'left_shift'>

        less = <ufunc 'less'>

        less_equal = <ufunc 'less_equal'>

        little_endian = True

        log = <ufunc 'log'>

        log10 = <ufunc 'log10'>

        log1p = <ufunc 'log1p'>

        logaddexp = <ufunc 'logaddexp'>

        logaddexp2 = <ufunc 'logaddexp2'>

        logical_and = <ufunc 'logical_and'>

        logical_not = <ufunc 'logical_not'>

        logical_or = <ufunc 'logical_or'>

        logical_xor = <ufunc 'logical_xor'>

        maximum = <ufunc 'maximum'>

        mgrid = <numpy.lib.index_tricks.nd_grid object at 0x6bfcf0>

        minimum = <ufunc 'minimum'>

        mod = <ufunc 'remainder'>

        modf = <ufunc 'modf'>

        multiply = <ufunc 'multiply'>

        nan = nan

        nbytes = <code title="{<type 'numpy.int64'>: 8, <type 'numpy.int16'>: 2, <type 'numpy.void'>\
: 0, <type 'numpy.complex128'>: 16, <type 'numpy.int32'>: 4, <type 'nu\
mpy.uint32'>: 4, <type 'numpy.unicode_'>: 0, <type 'numpy.complex64'>:\
 8, <type 'numpy.int32'>: 4, <type 'numpy.uint32'>: 4, <type 'numpy.st\
ring_'>: 0, <type 'numpy.float128'>: 16, <type 'numpy.uint16'>: 2, <ty\
pe 'numpy.object_'>: 4, <type 'numpy.float64'>: 8, <type 'numpy.int8'>\
: 1, <type 'numpy.uint8'>: 1, <type 'numpy.bool_'>: 1, <type 'numpy.fl\
oat32'>: 4, <type 'numpy.uint64'>: 8, <type 'numpy.complex256'>: 32}">{<type 'numpy.int64'>: 8, <type 'numpy.int16'>: 2, <t...

        negative = <ufunc 'negative'>

        newaxis = None

        not_equal = <ufunc 'not_equal'>

        ogrid = <numpy.lib.index_tricks.nd_grid object at 0x6c5490>

        ones_like = <ufunc 'ones_like'>

        pi = 3.14159265359

        power = <ufunc 'power'>

        r_ = <numpy.lib.index_tricks.RClass object at 0x6c50f0>

        rad2deg = <ufunc 'rad2deg'>

        radians = <ufunc 'radians'>

        reciprocal = <ufunc 'reciprocal'>

        remainder = <ufunc 'remainder'>

        right_shift = <ufunc 'right_shift'>

        rint = <ufunc 'rint'>

        s_ = <numpy.lib.index_tricks.IndexExpression object at 0x78f270>

        sctypeDict = {0: <type 'numpy.bool_'>, 1: <type 'numpy.int8'>,...

        sctypeNA = {'?': 'Bool', 'B': 'UInt8', 'Bool': <type 'numpy.bo...

        sctypes = {'complex': [<type 'numpy.complex64'>, <type 'numpy....

        sign = <ufunc 'sign'>

        signbit = <ufunc 'signbit'>

        sin = <ufunc 'sin'>

        sinh = <ufunc 'sinh'>

        sqrt = <ufunc 'sqrt'>

        square = <ufunc 'square'>

        subtract = <ufunc 'subtract'>

        tan = <ufunc 'tan'>

        tanh = <ufunc 'tanh'>

        true_divide = <ufunc 'true_divide'>

        trunc = <ufunc 'trunc'>

        typeDict = {0: <type 'numpy.bool_'>, 1: <type 'numpy.int8'>, 2...

        typeNA = {'?': 'Bool', 'B': 'UInt8', 'Bool': <type 'numpy.bool...

        typecodes = {'All': '?bhilqpBHILQPfdgFDGSUVO', 'AllFloat': 'fd...

    Variables Details

ScalarType

Value:

(<type 'int'>,
 <type 'float'>,
 <type 'complex'>,
 <type 'long'>,
 <type 'bool'>,
 <type 'str'>,
 <type 'unicode'>,
 <type 'buffer'>,
...

cast

Value:

{<type 'numpy.int64'>: <function <lambda> at 0x1028bf0>, <type 'numpy.
int16'>: <function <lambda> at 0x1028c30>, <type 'numpy.void'>: <funct
ion <lambda> at 0x1028c70>, <type 'numpy.complex128'>: <function <lamb
da> at 0x1028cb0>, <type 'numpy.int32'>: <function <lambda> at 0x1028c
f0>, <type 'numpy.uint32'>: <function <lambda> at 0x1028d30>, <type 'n
umpy.unicode_'>: <function <lambda> at 0x1028d70>, <type 'numpy.comple
x64'>: <function <lambda> at 0x1028db0>, <type 'numpy.int32'>: <functi
on <lambda> at 0x1028df0>, <type 'numpy.uint32'>: <function <lambda> a
...

index_exp

Value:

<numpy.lib.index_tricks.IndexExpression object at 0x78f230>

nbytes

Value:

{<type 'numpy.int64'>: 8, <type 'numpy.int16'>: 2, <type 'numpy.void'>
: 0, <type 'numpy.complex128'>: 16, <type 'numpy.int32'>: 4, <type 'nu
mpy.uint32'>: 4, <type 'numpy.unicode_'>: 0, <type 'numpy.complex64'>:
 8, <type 'numpy.int32'>: 4, <type 'numpy.uint32'>: 4, <type 'numpy.st
ring_'>: 0, <type 'numpy.float128'>: 16, <type 'numpy.uint16'>: 2, <ty
pe 'numpy.object_'>: 4, <type 'numpy.float64'>: 8, <type 'numpy.int8'>
: 1, <type 'numpy.uint8'>: 1, <type 'numpy.bool_'>: 1, <type 'numpy.fl
oat32'>: 4, <type 'numpy.uint64'>: 8, <type 'numpy.complex256'>: 32}

sctypeDict

Value:

{0: <type 'numpy.bool_'>,
 1: <type 'numpy.int8'>,
 2: <type 'numpy.uint8'>,
 3: <type 'numpy.int16'>,
 4: <type 'numpy.uint16'>,
 5: <type 'numpy.int32'>,
 6: <type 'numpy.uint32'>,
 7: <type 'numpy.int32'>,
...

sctypeNA

Value:

{'?': 'Bool',
 'B': 'UInt8',
 'Bool': <type 'numpy.bool_'>,
 'Complex128': <type 'numpy.complex256'>,
 'Complex32': <type 'numpy.complex64'>,
 'Complex64': <type 'numpy.complex128'>,
 'D': 'Complex64',
 'F': 'Complex32',
...

sctypes

Value:

{'complex': [<type 'numpy.complex64'>,
             <type 'numpy.complex128'>,
             <type 'numpy.complex256'>],
 'float': [<type 'numpy.float32'>,
           <type 'numpy.float64'>,
           <type 'numpy.float128'>],
 'int': [<type 'numpy.int8'>,
         <type 'numpy.int16'>,
...

typeDict

Value:

{0: <type 'numpy.bool_'>,
 1: <type 'numpy.int8'>,
 2: <type 'numpy.uint8'>,
 3: <type 'numpy.int16'>,
 4: <type 'numpy.uint16'>,
 5: <type 'numpy.int32'>,
 6: <type 'numpy.uint32'>,
 7: <type 'numpy.int32'>,
...

typeNA

Value:

{'?': 'Bool',
 'B': 'UInt8',
 'Bool': <type 'numpy.bool_'>,
 'Complex128': <type 'numpy.complex256'>,
 'Complex32': <type 'numpy.complex64'>,
 'Complex64': <type 'numpy.complex128'>,
 'D': 'Complex64',
 'F': 'Complex32',
...

typecodes

Value:

{'All': '?bhilqpBHILQPfdgFDGSUVO',
 'AllFloat': 'fdgFDG',
 'AllInteger': 'bBhHiIlLqQpP',
 'Character': 'c',
 'Complex': 'FDG',
 'Float': 'fdg',
 'Integer': 'bhilqp',
 'UnsignedInteger': 'BHILQP'}

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1
    on Mon Apr 20 11:56:30 2009

      http://epydoc.sourceforge.net


text:
local Linear, parent = torch.class('nn.Linear', 'nn.Module')

function Linear:__init(inputSize, outputSize, bias)
   parent.__init(self)
   local bias = ((bias == nil) and true) or bias
   self.weight = torch.Tensor(outputSize, inputSize)
   self.gradWeight = torch.Tensor(outputSize, inputSize)
   if bias then
      self.bias = torch.Tensor(outputSize)
      self.gradBias = torch.Tensor(outputSize)
   end
   self:reset()
end

function Linear:noBias()
   self.bias = nil
   self.gradBias = nil
   return self
end

function Linear:reset(stdv)
   if stdv then
      stdv = stdv * math.sqrt(3)
   else
      stdv = 1./math.sqrt(self.weight:size(2))
   end
   if nn.oldSeed then
      for i=1,self.weight:size(1) do
         self.weight:select(1, i):apply(function()
            return torch.uniform(-stdv, stdv)
         end)
      end
      if self.bias then
         for i=1,self.bias:nElement() do
            self.bias[i] = torch.uniform(-stdv, stdv)
         end
      end
   else
      self.weight:uniform(-stdv, stdv)
      if self.bias then self.bias:uniform(-stdv, stdv) end
   end
   return self
end

local function updateAddBuffer(self, input)
   local nframe = input:size(1)
   self.addBuffer = self.addBuffer or input.new()
   if self.addBuffer:nElement() ~= nframe then
      self.addBuffer:resize(nframe):fill(1)
   end
end

function Linear:updateOutput(input)
   if input:dim() == 1 then
      self.output:resize(self.weight:size(1))
      if self.bias then self.output:copy(self.bias) else self.output:zero() end
      self.output:addmv(1, self.weight, input)
   elseif input:dim() == 2 then
      local nframe = input:size(1)
      local nElement = self.output:nElement()
      self.output:resize(nframe, self.weight:size(1))
      if self.output:nElement() ~= nElement then
         self.output:zero()
      end
      updateAddBuffer(self, input)
      self.output:addmm(0, self.output, 1, input, self.weight:t())
      if self.bias then self.output:addr(1, self.addBuffer, self.bias) end
   else
      error('input must be vector or matrix')
   end

   return self.output
end

function Linear:updateGradInput(input, gradOutput)
   if self.gradInput then

      local nElement = self.gradInput:nElement()
      self.gradInput:resizeAs(input)
      if self.gradInput:nElement() ~= nElement then
         self.gradInput:zero()
      end
      if input:dim() == 1 then
         self.gradInput:addmv(0, 1, self.weight:t(), gradOutput)
      elseif input:dim() == 2 then
         self.gradInput:addmm(0, 1, gradOutput, self.weight)
      end

      return self.gradInput
   end
end

function Linear:accGradParameters(input, gradOutput, scale)
   scale = scale or 1
   if input:dim() == 1 then
      self.gradWeight:addr(scale, gradOutput, input)
      if self.bias then self.gradBias:add(scale, gradOutput) end
   elseif input:dim() == 2 then
      self.gradWeight:addmm(scale, gradOutput:t(), input)
      if self.bias then
         -- update the size of addBuffer if the input is not the same size as the one we had in last updateGradInput
         updateAddBuffer(self, input)
         self.gradBias:addmv(scale, gradOutput:t(), self.addBuffer)
      end
   end
end

function Linear:sharedAccUpdateGradParameters(input, gradOutput, lr)
   -- we do not need to accumulate parameters when sharing:
   self:defaultAccUpdateGradParameters(input, gradOutput, lr)
end

function Linear:clearState()
   if self.addBuffer then self.addBuffer:set() end
   return parent.clearState(self)
end

function Linear:__tostring__()
  return torch.type(self) ..
      string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1)) ..
      (self.bias == nil and ' without bias' or '')
end


text:
{% extends 'common/base.html' %}
{% import "macros/_patination.html" as page_macros %}
{% block content %}
    {% for article in articles.items %}

{{ article.title|title }}

             {{ moment(article.timestamp).format('LL') }}
             {{ article.author.username }}

{{ article.body_html|striptags|truncate(length=200, killwords=False, end="......") }}

             {{ article.category_name }}

            {% for tagged in article.taggeds %}
                 {{ tagged.name }}
            {% endfor %}

        阅读全文 >>

    {% endfor %}

    {{ page_macros.pagination_widget(articles, '.index') }}

{% endblock %}


text:
<?php

use Mockery as m;
use Basset\Asset;
use Basset\Collection;
use Illuminate\Support\Collection as IlluminateCollection;

class CollectionTest extends PHPUnit_Framework_TestCase {

    public function tearDown()
    {
        m::close();
    }

    public function setUp()
    {
        $this->collection = new Collection($this->directory = m::mock('Basset\Directory'), 'foo');
    }

    public function testGetIdentifierOfCollection()
    {
        $this->assertEquals('foo', $this->collection->getIdentifier());
    }

    public function testGetDefaultDirectory()
    {
        $this->assertEquals($this->directory, $this->collection->getDefaultDirectory());
    }

    public function testGetExtensionFromGroup()
    {
        $this->assertEquals('css', $this->collection->getExtension('stylesheets'));
        $this->assertEquals('js', $this->collection->getExtension('javascripts'));
    }

    public function testGettingCollectionAssetsWithDefaultOrdering()
    {
        $this->directory->shouldReceive('getAssets')->andReturn($expected = new IlluminateCollection(array(
            $this->getAssetInstance('bar.css', 'path/to/bar.css', 'stylesheets', 1),
            $this->getAssetInstance('baz.css', 'path/to/baz.css', 'stylesheets', 2)
        )));

        $this->assertEquals($expected->all(), $this->collection->getAssets('stylesheets')->all());
    }

    public function testGettingCollectionWithMultipleAssetGroupsReturnsOnlyRequestedGroup()
    {
        $this->directory->shouldReceive('getAssets')->andReturn(new IlluminateCollection(array(
            $assets[] = $this->getAssetInstance('foo.css', 'path/to/foo.css', 'stylesheets', 1),
            $assets[] = $this->getAssetInstance('bar.js', 'path/to/bar.js', 'javascripts', 2),
            $assets[] = $this->getAssetInstance('baz.js', 'path/to/baz.js', 'javascripts', 3),
            $assets[] = $this->getAssetInstance('qux.css', 'path/to/qux.css', 'stylesheets', 4)
        )));

        $expected = array(0 => $assets[0], 3 => $assets[3]);
        $this->assertEquals($expected, $this->collection->getAssets('stylesheets')->all());
    }

    public function testGettingCollectionAssetsWithCustomOrdering()
    {
        $this->directory->shouldReceive('getAssets')->andReturn(new IlluminateCollection(array(
            $assets[] = $this->getAssetInstance('foo.css', 'path/to/foo.css', 'stylesheets', 1), // Becomes 2nd
            $assets[] = $this->getAssetInstance('bar.css', 'path/to/bar.css', 'stylesheets', 2), // Becomes 4th
            $assets[] = $this->getAssetInstance('baz.css', 'path/to/baz.css', 'stylesheets', 1), // Becomes 1st
            $assets[] = $this->getAssetInstance('qux.css', 'path/to/qux.css', 'stylesheets', 4), // Becomes 5th
            $assets[] = $this->getAssetInstance('zin.css', 'path/to/zin.css', 'stylesheets', 3)  // Becomes 3rd
        )));

        $expected = array($assets[2], $assets[0], $assets[4], $assets[1], $assets[3]);
        $this->assertEquals($expected, $this->collection->getAssets('stylesheets')->all());
    }

    public function testGettingCollectionRawAssets()
    {
        $this->directory->shouldReceive('getAssets')->andReturn(new IlluminateCollection(array(
            $assets[] = $this->getAssetInstance('foo.css', 'path/to/foo.css', 'stylesheets', 1),
            $assets[] = $this->getAssetInstance('bar.css', 'path/to/bar.css', 'stylesheets', 2)
        )));

        $assets[1]->raw();

        $this->assertEquals(array(1 => $assets[1]), $this->collection->getAssetsOnlyRaw('stylesheets')->all());
    }

    public function getAssetInstance($relative, $absolute, $group, $order)
    {
        $asset = new Asset(m::mock('Illuminate\Filesystem\Filesystem'), m::mock('Basset\Factory\FactoryManager'), 'testing', $absolute, $relative);

        return $asset->setOrder($order)->setGroup($group);
    }

}


text:
"""Implement the rules of release package build rule."""
import logging
import os
import subprocess
import zipfile

import mool.shared_utils as su

def zip_all_currdir(params):
  """Zip all contents of current directory to target file."""
  assert 1 == len(params)
  target_file = params[0]
  tmp_file = target_file + '.tmp'
  with zipfile.ZipFile(tmp_file, 'w') as zip_obj:
    for root, _, files in os.walk('.'):
      for file_path in files:
        zip_obj.write(os.path.join(root, file_path))
  subprocess.check_call(['mv', tmp_file, target_file])

def unzip_all_currdir(file_path):
  """Unzip the given file in current directory."""
  with zipfile.ZipFile(file_path) as zip_obj:
    zip_obj.extractall()

def _check_and_get_outfile(rule_details):
  """Check that user is trying to pack rules with only one out files."""
  out_files = rule_details[su.OUT_KEY]
  if isinstance(out_files, list):
    if len(out_files) == 1:
      return out_files[0]
    msg = ('Rule {} is emitting multiple out files. Rules with multiple out'
           ' files are not allowed in release package rule!'
           ).format(rule_details[su.NAME_KEY])
    raise su.Error(msg)
  return out_files

class ReleasePackage(object):
  """Pre-release test and packaging module."""
  @classmethod
  def _setup_deps(cls, rule_details, details_map):
    """Setup all dependencies."""
    all_dep_paths = rule_details[su.ALL_DEP_PATHS_KEY][:]
    for rule_symbol in rule_details[su.PACKAGE_MODULES_KEY]:
      all_dep_paths.append(_check_and_get_outfile(details_map[rule_symbol]))
    rule_details[su.ALL_DEP_PATHS_KEY] = sorted(list(set(all_dep_paths)))

  @classmethod
  def _setup_tests(cls, rule_details, details_map):
    """Setup all tests."""
    test_commands = []
    for rule_symbol in rule_details.get(su.PACKAGE_TESTS_KEY, []):
      test_commands.append(['echo', 'Testing', rule_symbol])
      test_commands.extend(details_map[rule_symbol][su.TEST_COMMANDS_KEY])
    rule_details[su.RELEASE_TEST_COMMANDS_KEY] = test_commands

  @classmethod
  def _setup_linking(cls, rule_details, details_map):
    """Setup linking final output."""
    link_commands = [[su.CHANGE_CURR_DIR, rule_details[su.WDIR_KEY]]]
    possible_prefixes = su.prefix_transform([su.BUILD_OUT_DIR])
    extract_in_zip = rule_details.get(su.EXTRACT_IN_ZIP, [])
    for rule_symbol in rule_details.get(su.PACKAGE_MODULES_KEY, []):
      if rule_symbol in extract_in_zip:
        continue
      src_file = details_map[rule_symbol][su.OUT_KEY]
      dst_file = su.get_relative_path(possible_prefixes, src_file)
      link_commands.append(su.get_mkdir_command(os.path.dirname(dst_file)))
      link_commands.append(su.get_copy_command(src_file, dst_file, True))
    for rule_symbol in extract_in_zip:
      link_commands.append([su.EXTRACT_ARCHIVE_IN_CURRDIR,
                            details_map[rule_symbol][su.OUT_KEY]])
    link_commands.append(
        [su.CREATE_ARCHIVE_ALL_CURRDIR, rule_details[su.OUT_KEY]])
    rule_details[su.LINK_COMMANDS_KEY] = link_commands

  @classmethod
  def setup(cls, rule_details, details_map):
    """Full setup of the rule."""
    out_file = rule_details[su.NAME_KEY] + '.zip'
    su.init_rule_common(rule_details, out_file, [])
    rule_details[su.POSSIBLE_PREFIXES_KEY] = su.prefix_transform([])
    cls._setup_deps(rule_details, details_map)
    cls._setup_tests(rule_details, details_map)
    cls._setup_linking(rule_details, details_map)

  @classmethod
  def build_commands(cls, rule_details):
    """Generate build command line."""
    logging.info('Emitting %s at %s', rule_details[su.TYPE_KEY],
                 su.log_normalize(rule_details[su.OUT_KEY]))
    directory_list = [rule_details[su.OUTDIR_KEY]]
    command_list = [su.get_mkdir_command(d) for d in directory_list]
    command_list.extend(rule_details[su.RELEASE_TEST_COMMANDS_KEY])
    command_list.extend(rule_details[su.LINK_COMMANDS_KEY])
    return command_list


text:
package com.moneybender.proxy.subscribers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.moneybender.proxy.ProxySettings;
import com.moneybender.proxy.publishers.PacketHeader;
import com.moneybender.proxy.publishers.SubscriberManager;

public class AbstractSubscriberTest {

	private SubscriberManager manager;

	@Before
	public void setUp() throws Exception {
		manager = new SubscriberManager(ProxySettings.DEFAULT_REQUEST_PORT,
			ProxySettings.DEFAULT_RESPONSE_PORT, ProxySettings.DEFAULT_DUPLEX_PORT);
	}

	@After
	public void tearDown() throws Exception {
		if(manager != null){
			manager.close();
		}
	}

	@Test
	public void testGetPayload() throws Exception {

		AbstractSubscriber subscriber = new AbstractSubscriber() {

			@Override
			protected void processPacket(PacketHeader header, byte[] payload, OutputStream out) throws IOException {
			}

		};

		String payload = "AVeryLargeInvertebrate";
		byte[] buffer = payload.getBytes();
		ByteArrayInputStream payloadStream = new ByteArrayInputStream(buffer);

		PacketHeader header = new PacketHeader();
		header.setDataLength(payloadStream.available());

		manager.publishRequest(header, buffer);
		Thread.sleep(100);

		byte[] payloadReceived = subscriber.getPayload(header, payloadStream);
		Assert.assertTrue(payloadReceived.length > 0);
		Assert.assertEquals(payload, new String(payloadReceived));
	}

}


text:
Reports Serializable classes whose serialVersionUID field.
is not declared private static final long.

Powered by InspectionGadgets


text:
================================================================================
VAppIPAssignmentInfo
================================================================================

.. describe:: Property of

    :py:class:`~pyvisdk.do.vm_config_info.VmConfigInfo`,
    :py:class:`~pyvisdk.do.vm_config_spec.VmConfigSpec`

.. describe:: Since

    vSphere API 4.0

.. describe:: Extends

    :py:class:`~pyvisdk.mo.dynamic_data.DynamicData`

.. class:: pyvisdk.do.v_app_ip_assignment_info.VAppIPAssignmentInfo

    .. py:attribute:: ipAllocationPolicy

        Specifies how IP allocation should be managed by the VI platform. This is typically specified by the deployer. The set of valid options for the policy is based on the capabilities of the vApp software, as specified by the supportedAllocationSchemes property.

    .. py:attribute:: ipProtocol

        Specifies the chosen IP protocol for this deployment. This must be one of the values in the supportedIpProtocol field.

    .. py:attribute:: supportedAllocationScheme

        Specifies the IP allocation schemes supported by the guest software.

    .. py:attribute:: supportedIpProtocol

        Specifies the IP protocols supported by the guest software.


text:
module Zermelo

  class LockNotAcquired < StandardError; end

  module Locks

    class RedisLock

      # Adapted from https://github.com/mlanett/redis-lock,
      # now covers locking multiple keys at once

      attr_accessor :expires_at, :life, :sleep_in_ms

      def initialize
        @owner_value = Thread.current.object_id
        @life        = 60
        @timeout     = 10
        @sleep_in_ms = 125
      end

      def lock(*record_klasses, &block)
        @keys = record_klasses.map{|k| k.send(:class_key) }.sort.map{|k| "#{k}::lock" }
        do_lock_with_timeout(@timeout) or raise Zermelo::LockNotAcquired.new(@keys.join(", "))
        result = true
        if block
          begin
            result = (block.arity == 1) ? block.call(self) : block.call
          # rescue Exception => e
          #   puts e.message
          #   puts e.backtrace.join("\n")
          #   raise e
          ensure
            release_lock
          end
        end
        result
      end

      def extend_life( new_life )
        do_extend( new_life ) or raise Zermelo::LockNotAcquired.new(@keys.join(", "))
      end

      def unlock
        release_lock
      end

      private

      def full_keys
        @full_keys ||= @keys.map {|k| ["#{k}:owner", "#{k}:expiry"] }.flatten
      end

      def owner_keys
        @owner_keys ||= @keys.map {|k| "#{k}:owner" }
      end

      def expiry_keys
        @expiry_keys ||= @keys.map {|k| "#{k}:expiry" }
      end

      def do_lock_with_timeout( timeout )
        locked = false
        with_timeout(timeout) { locked = do_lock }
        locked
      end

      # @returns true if locked, false otherwise
      def do_lock( tries = 3 )
        # We need to set both owner and expire at the same time
        # If the existing lock is stale, we delete it and try again once

        locked = nil

        loop do
          new_xval = Time.now.to_i + @life

          lock_keyvals = @keys.map {|k| ["#{k}:owner",  @owner_value,
                                         "#{k}:expiry", new_xval] }.flatten

          result = Zermelo.redis.msetnx(*lock_keyvals)

          if [1, true].include?(result)
            # log :debug, "do_lock() success"
            @expires_at = new_xval
            locked = true
            break
          else
            # log :debug, "do_lock() failed"
            # consider the possibility that this lock is stale
            tries -= 1
            next if tries > 0 && stale_key?
            locked = false
            break
          end
        end
        locked
      end

      def do_extend( new_life )
        # We use watch and a transaction to ensure we only change a lock we own
        # The transaction fails if the watched variable changed
        # Use my_owner = oval to make testing easier.
        new_xval = Time.now.to_i + new_life
        extended = false
        with_watch( *owner_keys  ) do
          owners = Zermelo.redis.mget( *owner_keys )
          if owners == ([@owner_value.to_s] * owner_keys.size)
            result = Zermelo.redis.multi do |multi|
              multi.mset( *(expiry_keys.zip( [new_xval] * expiry_keys.size)) )
            end
            if result == ['OK']
              # log :debug, "do_extend() success"
              @expires_at = new_xval
              extended = true
            end
          end
        end
        extended
      end

      # Only actually deletes it if we own it.
      # There may be strange cases where we fail to delete it, in which case expiration will solve the problem.
      def release_lock
        released = false
        with_watch( *full_keys ) do
          owners = Zermelo.redis.mget( *owner_keys )
          if owners == ([@owner_value.to_s] * owner_keys.size)
            result = Zermelo.redis.multi do |multi|
              multi.del(*full_keys)
            end
            if result && (result.size == 1) && (result.first == full_keys.size)
              released = true
            end
          end
        end
        released
      end

      def stale_key?
        # Check if expiration exists and is it stale?
        # If so, delete it.
        # watch() all keys so we can detect if they change while we do this
        # multi() will fail if keys have changed after watch()
        # Thus, we snapshot consistency at the time of watch()
        # Note: inside a watch() we get one and only one multi()
        now = Time.now.to_i
        stale = false
        with_watch( *full_keys ) do

          owners_expires = Zermelo.redis.mget(full_keys)

          if owners_expires.each_slice(2).all? {|owner, expire| is_deletable?( owner, expire, now)}
            result = Zermelo.redis.multi do |multi|
              multi.del(*full_keys)
            end
            # If anything changed then multi() fails and returns nil
            if result && (result.size == 1) && (result.first == owner_keys.size)
              # log :info, "Deleted stale key from #{owner}"
              stale = true
            end
          end
        end # watch
        stale
      end

      def locked?
        now = Time.now.to_i
        owners_expires = Zermelo.redis.mget(full_keys)
        owners_expires && (owners_expires.size == (@keys.size * 2)) &&
          owners_expires.each_slice(2).all? {|owner, expiration| is_locked?(owner, expiration, now)}
      end

      # returns true if the lock exists and is owned by the given owner
      def is_locked?(owner, expiration, now)
        (owner == @owner_value) && ! is_deletable?(owner, expiration, now)
      end

      # returns true if this is a broken or expired lock
      def is_deletable?( owner, expiration, now)
        expiration = expiration.to_i
        (owner || (expiration > 0)) && (!owner || (expiration < now))
      end

      def with_watch( *args, &block )
        Zermelo.redis.watch( *args )
        begin
          block.call
        ensure
          Zermelo.redis.unwatch
        end
      end

      # Calls block until it returns true or times out.
      # @param block should return true if successful, false otherwise
      # @returns true if successful, false otherwise
      def with_timeout( timeout, &block )
        expire = Time.now + timeout.to_f
        sleepy = @sleep_in_ms / 1000.to_f()
        # this looks inelegant compared to while Time.now < expire, but does not oversleep
        ret = nil
        loop do
          if block.call
            ret = true
            break
          end
          if (Time.now + sleepy) > expire
            ret = false
            break
          end
          sleep(sleepy)
          # might like a different strategy, but general goal is not use 100% cpu while contending for a lock.
        end
        ret
      end

    end

  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<meta name="copyright" content="(C) Copyright 2014" />
<meta name="DC.rights.owner" content="(C) Copyright 2014" />
<meta name="DC.Type" content="topic" />
<meta name="DC.Title" content="test 2" />
<meta name="DC.Relation" scheme="URI" content="t1.html" />
<meta name="DC.Format" content="XHTML" />
<meta name="DC.Identifier" content="test2" />
<link rel="stylesheet" type="text/css" href="commonltr.css" />
<title>test 2</title>

test 2

 content

Parent topic: test 1


text:
#include "RakPeerInterface.h"
#include "RakSleep.h"
#include "RakThread.h"
#include "RakNetworkFactory.h"
#include <stdio.h>
#include "../SQLite3Plugin/ServerOnly/sqlite3.h"
#include "GetTime.h"
#include "RakString.h"
#include "jpeglib.h"

using namespace RakNet;

struct my_error_mgr {
	struct jpeg_error_mgr pub;	/* "public" fields */
};

METHODDEF(void) my_error_exit (j_common_ptr cinfo);

//
//	to handle fatal errors.
//	the original JPEG code will just exit(0). can't really
//	do that in Windows....
//

METHODDEF(void) my_error_exit (j_common_ptr cinfo)
{
}

void main(void)
{
	printf("Add images to SQLite database and read back to measure performance.\n");

	// Create a database, and tell the plugin about it
	sqlite3 *database;
	// Here :memory: means create the database in memory only.
	// Normally the first parameter refers to a path on the disk to the database file
	if (sqlite3_open_v2("C:\\EchoChamber\\sqliteDb", &database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0)!=SQLITE_OK)
		return;

	char *errorMsg;
	sqlite3_exec(database, "CREATE TABLE Images (imageId_pk integer PRIMARY KEY, imageData bytea);", 0, 0, &errorMsg);
	if (errorMsg)
	{
		printf(errorMsg);
		sqlite3_free(errorMsg);
		return;
	}

	printf("Opening image\n");
	const char *imgPath1="c:\\temp\\img1.jpg";
	const char *imgPath2="c:\\temp\\img2.jpg";
	FILE *fp = fopen(imgPath1, "rb");
	unsigned fileLength1;
	fseek(fp, 0, SEEK_END);
	fileLength1 = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	char *fileBuff1 = (char *) malloc(fileLength1);
	fread(fileBuff1, 1, fileLength1, fp);
	fclose(fp);

	fp = fopen(imgPath2, "rb");
	unsigned fileLength2;
	fseek(fp, 0, SEEK_END);
	fileLength2 = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	char *fileBuff2 = (char *) malloc(fileLength2);
	fread(fileBuff2, 1, fileLength2, fp);
	fclose(fp);

	static const int numInsertions=100;
	printf("Adding image to database %i times\n", numInsertions);

	sqlite3_stmt *statement;
	if (sqlite3_prepare_v2(
		database,
		"INSERT INTO Images (imageData) VALUES (?);",
		-1,
		&statement,
		0
		)!=SQLITE_OK)
		return;

	unsigned int i;
	int rc;
	for (i=0; i < numInsertions; i++)
	{
		if ((i&1)==0)
		{
			if (sqlite3_bind_blob(statement, 1, fileBuff1, fileLength1, 0)!=SQLITE_OK)
				return;
		}
		else
		{
			if (sqlite3_bind_blob(statement, 1, fileBuff2, fileLength2, 0)!=SQLITE_OK)
				return;
		}

		rc = sqlite3_step(statement);
		if (rc!=SQLITE_DONE && rc!=SQLITE_OK)
			return;

		sqlite3_reset(statement);
	}

	sqlite3_finalize(statement);

	// 4 animations 25 FPS = 100 images per second
	if (sqlite3_prepare_v2(
		database,
		"SELECT imageData FROM Images;",
		-1,
		&statement,
		0
		)!=SQLITE_OK)
		return;

	// Execute first time
	printf("Reading 100 images\n");
	RakNetTimeMS startTime=RakNet::GetTimeMS();
	rc = sqlite3_step(statement);
	RakNetTimeMS endTime=RakNet::GetTimeMS();
	printf("Statement execution took %i milliseconds\n", endTime-startTime);
	printf("Processing row ");
	unsigned int rowCount=1;
	while (rc==SQLITE_ROW)
	{
		const void *readImageDataFromDb = sqlite3_column_blob(statement, 0);
		int lengthOfImageData = sqlite3_column_bytes(statement, 0);

		struct jpeg_decompress_struct cinfo;
		struct my_error_mgr jerr;
		cinfo.err = jpeg_std_error(&jerr.pub);
		jerr.pub.error_exit = my_error_exit;
		jpeg_create_decompress(&cinfo);
		jpeg_memory_src(&cinfo, (const JOCTET *) readImageDataFromDb, lengthOfImageData);
		(void) jpeg_read_header(&cinfo, TRUE);
		JDIMENSION width = cinfo.image_width;
		JDIMENSION height = cinfo.image_height;
		jpeg_destroy_decompress(&cinfo);

		printf("%i ", rowCount++);

		rc = sqlite3_step(statement);
	}
	if (rc==SQLITE_ERROR)
		return;
	RakNetTimeMS endTime2=RakNet::GetTimeMS();

	sqlite3_reset(statement);
	printf("\n");
	printf("Processing took %i milliseconds\n", endTime2-endTime);
	printf("Total time is %i milliseconds\n", endTime2-startTime);

	sqlite3_finalize(statement);

	free(fileBuff1);
	free(fileBuff2);
	sqlite3_close(database);

	printf("Press enter to quit\n");
	char str[256];
	gets(str);
	return;
}