text:
namespace Microsoft.Protocols.TestSuites.MS_OXCTABL
{
    using Microsoft.Protocols.TestSuites.Common;
    using Microsoft.Protocols.TestTools;

    #region Protocol rops handle

    /// <summary>
    /// This delegate is used to handle response which RopQueryRowsRequest returned
    /// </summary>
    /// <param name="queryRowFlags">A flag for the query row operation</param>
    /// <param name="bForwardRead">Identify whether to read the data forward</param>
    /// <param name="bZeroRow">Identify whether zero row returned</param>
    /// <param name="ropType">Identify rop type</param>
    /// <param name="bIsCorrectRowCount">Identify whether the correct row count data was read</param>
    /// <param name="bCursorPositionChanged">Identify whether the cursor position was changed</param>
    /// <param name="bIsLatestRopData">Identify whether the queried data equals to the last rop data</param>
    /// <param name="bIsLastSuccessRopData">Identify whether the queried row data equals to the last successful rop data</param>
    /// <param name="queryRowOrigin">Identify the cursor position returned in queryRow response</param>
    /// <param name="isRequestCountTooLarger">Identify whether the row count in the request is larger than the actual row count</param>
    public delegate void RopQueryRowsHandler(QueryRowsFlags queryRowFlags, bool bForwardRead, bool bZeroRow, TableRopType ropType, bool bIsCorrectRowCount, bool bCursorPositionChanged, bool bIsLatestRopData, bool bIsLastSuccessRopData, BookmarkType queryRowOrigin, bool isRequestCountTooLarger);

    /// <summary>
    /// This delegate is used to handle response which ResetTableRequest returned
    /// </summary>
    /// <param name="ropType">Identify rop type</param>
    /// <param name="isPreviousDataReset">Identify whether the previous data is reset</param>
    public delegate void RopResetTableHandler(TableRopType ropType, bool isPreviousDataReset);

    /// <summary>
    /// This delegate is used to handle response which RopQueryPositionRequest returned
    /// </summary>
    /// <param name="cursorPosition">Identify the current cursor position</param>
    /// <param name="isRowCount">Identify whether the right rows count is returned</param>
    public delegate void RopQueryPositionHandler(CursorPosition cursorPosition, bool isRowCount);

    /// <summary>
    /// This delegate is used to handle response which RopSeekRowRequest returned
    /// </summary>
    /// <param name="wantRowMovedCountout">Identify whether to return the actual seek row count</param>
    /// <param name="enoughRow">Identify whether there are enough row to seek</param>
    /// <param name="hasSoughtLess">Identify whether the actual seek row is less the one requested</param>
    /// <param name="isActualRowsCount">Identify whether the actual seek row is correct</param>
    public delegate void RopSeekRowHandler(bool wantRowMovedCountout, bool enoughRow, bool hasSoughtLess, bool isActualRowsCount);

    /// <summary>
    /// This delegate is used to handle response which RopSeekRowBookmarkRequest returned
    /// </summary>
    /// <param name="wantRowMovedCountout">Identify whether to return the actual seek row count</param>
    /// <param name="enoughRow">Identify whether there are enough row to seek</param>
    /// <param name="hasSoughtLess">Identify whether the actual seek row is less the one requested</param>
    /// <param name="isActualRowsCount">Identify whether the actual seek row is correct</param>
    /// <param name="rowNoLongerVisible">Identify whether the row is visible</param>
    public delegate void RopSeekRowBookmarkHandler(bool wantRowMovedCountout, bool enoughRow, bool hasSoughtLess, bool isActualRowsCount, bool rowNoLongerVisible);

    /// <summary>
    /// This delegate is used to handle response which RopSeekRowFractionalRequest returned
    /// </summary>
    /// <param name="zeroNumerator">Identify whether the Numerator is zero</param>
    /// <param name="smallDenominator">Identify whether the Numerator bigger than Denominator</param>
    /// <param name="cursorPosition">Cursor position</param>
    public delegate void RopSeekRowFractionalHandler(bool zeroNumerator, bool smallDenominator, CursorPosition cursorPosition);

    /// <summary>
    /// This delegate is used to handle response which RopFindRowRequest returned
    /// </summary>
    /// <param name="findRowFlags">Identify the flags for this operation</param>
    /// <param name="isValidRestriction">Identify whether the restriction is valid</param>
    /// <param name="HasRowData">Identify whether there are rows meet the restriction </param>
    /// <param name="isCorrectRowData">Identify whether row returned is correct</param>
    /// <param name="rowNoLongerVisible">Identify whether the row is visible</param>
    /// <param name="isLastSetColumnData">Identify whether the column data returned is the one set in the SetColumn method</param>
    public delegate void RopFindRowHandler(FindRowFlags findRowFlags, bool isValidRestriction, bool HasRowData, bool isCorrectRowData, bool rowNoLongerVisible, bool isLastSetColumnData);

    /// <summary>
    /// This delegate is used to handle response which RopExpandRowRequest returned
    /// </summary>
    /// <param name="isLastSetColumnData">Identify whether the column data returned is the one set in the SetColumn method</param>
    public delegate void RopExpandRowHandler(bool isLastSetColumnData);

    /// <summary>
    /// This delegate is used to handle response which RopGetCollapseStateRequest returned
    /// </summary>
    /// <param name="isSetCollapseStateCalled">Identify whether the SetCollapseState Rop is called</param>
    /// <param name="isCollapseStateRebuildCorrectly">Identify whether the collapse state is rebuilt successfully</param>
    public delegate void RopGetCollapseStateHandler(bool isSetCollapseStateCalled, bool isCollapseStateRebuildCorrectly);
    #endregion

    /// <summary>
    /// This interface defines the protocol adapter: IMS_OXCTABLAdapter
    /// </summary>
    public interface IMS_OXCTABLAdapter : IAdapter
    {
        #region Protocol event

        /// <summary>
        /// This event is used to handle response which RopQueryRowsRequest returned
        /// </summary>
        event RopQueryRowsHandler RopQueryRowsResponse;

        /// <summary>
        /// This event is used to handle response which RopResetTableRequest returned
        /// </summary>
        event RopResetTableHandler RopResetTableResponse;

        /// <summary>
        /// This event is used to handle response which RopQueryPositionRequest returned
        /// </summary>
        event RopQueryPositionHandler RopQueryPositionResponse;

        /// <summary>
        /// This event is used to handle response which RopSeekRowRequest returned
        /// </summary>
        event RopSeekRowHandler RopSeekRowResponse;

        /// <summary>
        /// This event is used to handle response which RopSeekRowBookmarkRequest returned
        /// </summary>
        event RopSeekRowBookmarkHandler RopSeekRowBookmarkResponse;

        /// <summary>
        /// This event is used to handle response which RopSeekRowFractionalRequest returned
        /// </summary>
        event RopSeekRowFractionalHandler RopSeekRowFractionalResponse;

        /// <summary>
        /// This event is used to handle response which RopFindRowRequest returned
        /// </summary>
        event RopFindRowHandler RopFindRowResponse;

        /// <summary>
        /// This event is used to handle response which RopExpandRowRequest returned
        /// </summary>
        event RopExpandRowHandler RopExpandRowResponse;

        /// <summary>
        /// This event is used to handle response which RopGetCollapseStateRequest returned
        /// </summary>
        event RopGetCollapseStateHandler RopGetCollapseStateResponse;
        #endregion

        #region Protocol operations
        /// <summary>
        /// This method is used to set columns for a table
        /// </summary>
        /// <param name="reqId">Identify the request ID</param>
        /// <param name="invalidPropertyTag">Indicate whether there are invalid property tags in the column set </param>
        /// <param name="newColumnSet">Indicate whether to change the current column set with new one</param>
        /// <param name="isSetColumnsAsynchronous">Indicate whether RopsetColumns Rop is to be performed asynchronously</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopSetColumns(uint reqId, bool invalidPropertyTag, bool newColumnSet, bool isSetColumnsAsynchronous);

        /// <summary>
        /// This method is used to sort table
        /// </summary>
        /// <param name="reqId">Identify the request ID</param>
        /// <param name="validHandle">Identify whether the InputHandleIndex is valid, this is used to trigger the error code in SortTable</param>
        /// <param name="multipleSortOrders">Indicate whether the sort order array contains more than one SortOrder structure</param>
        /// <param name="isMaximumCategory">Indicate whether the sort order array contains a SortOrder structure with the order set to MaximumCategory</param>
        /// <param name="allSortOrdersUsedAsCategory">Identify whether all sort orders used as category</param>
        /// <param name="allCategoryExpanded">Identify whether all categories are expanded</param>
        /// <param name="newOrder">Identify whether to change the current sort order</param>
        /// <param name="isSortTableAsynchronous">Indicate whether RopSortTable Rop is to be performed asynchronously</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopSortTable(uint reqId, bool validHandle, bool multipleSortOrders, bool isMaximumCategory, bool allSortOrdersUsedAsCategory, bool allCategoryExpanded, bool newOrder, bool isSortTableAsynchronous);

        /// <summary>
        /// This method is used to set restrict for a table
        /// </summary>
        /// <param name="reqId">Identify the request ID</param>
        /// <param name="validHandle">Identify whether the InputHandleIndex is valid, this is used to trigger the error code in Restrict</param>
        /// <param name="newRestrict">A flag identify whether new restriction is required</param>
        /// <param name="isRestrictAsynchronous">Indicate whether RopRestrict Rop is to be performed asynchronously</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopRestrict(uint reqId, bool validHandle, bool newRestrict, bool isRestrictAsynchronous);

        /// <summary>
        /// This method is used to query rows for a table
        /// </summary>
        /// <param name="queryRowFlags">A flag for the query row operation</param>
        /// <param name="forwardRead">Identify whether to read the data forward</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopQueryRows(QueryRowsFlags queryRowFlags, bool forwardRead);

        /// <summary>
        /// This method is used to Abort Rops for a table
        /// </summary>
        /// <param name="tableStatus">Identify the table status</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopAbort(out TableStatus tableStatus);

        /// <summary>
        /// This method is used to get the status for a table
        /// </summary>
        /// <param name="tableStatus">Identify the table status</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopGetStatus(out TableStatus tableStatus);

        /// <summary>
        /// This method is used to query position for a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopQueryPosition();

        /// <summary>
        /// This method is used to seek row for a table
        /// </summary>
        /// <param name="origin">Identify the origin position</param>
        /// <param name="forwardSeek">Identify whether to seek row forward</param>
        /// <param name="wantRowMovedCountout">Identify whether to return the actual moved row number</param>
        /// <param name="enoughRow">Identify whether there is enough row to seek</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopSeekRow(BookmarkType origin, bool forwardSeek, bool wantRowMovedCountout, bool enoughRow);

        /// <summary>
        /// This method is used to seek row bookmark for a table
        /// </summary>
        /// <param name="forwardSeek">Identify whether to seek bookmark forward</param>
        /// <param name="wantRowMovedCountout">Identify whether to return the actual moved row number</param>
        /// <param name="enoughRow">Identify whether there is enough row to seek</param>
        /// <returns>Table rop return values</returns>
        TableRopReturnValues RopSeekRowBookmark(bool forwardSeek, bool wantRowMovedCountout, bool enoughRow);

        /// <summary>
        /// This method is used to seek row fractional for a table
        /// </summary>
        /// <param name="zeroNumerator">Identify whether the Numerator is zero</param>
        /// <param name="smallDenominator">Identify whether the Numerator bigger than Denominator</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopSeekRowFractional(bool zeroNumerator, bool smallDenominator);

        /// <summary>
        /// This method is used to create bookmark for a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopCreateBookmark();

        /// <summary>
        /// This method is used to query all columns for a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopQueryColumnsAll();

        /// <summary>
        /// This method is used to find row for a table
        /// </summary>
        /// <param name="findRowFlags">Identify the flags for this operation</param>
        /// <param name="origin">Identify the bookmark</param>
        /// <param name="isValidRestriction">Identify whether the restriction is valid</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopFindRow(FindRowFlags findRowFlags, BookmarkType origin, bool isValidRestriction);

        /// <summary>
        /// This method is used to free bookmark for a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopFreeBookmark();

        /// <summary>
        /// This method is used to reset a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopResetTable();

        /// <summary>
        /// This method is used to expand row for a table
        /// </summary>
        /// <param name="nonexistCategoryId">Identify whether the CategoryId row exists</param>
        /// <param name="noncollapsedCategoryId">Identify whether the CategoryId row is not collapsed</param>
        /// <param name="isMaxRowCountInvalid">Identify whether the MaxRowCount is invalid</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopExpandRow(bool nonexistCategoryId, bool noncollapsedCategoryId, bool isMaxRowCountInvalid);

        /// <summary>
        /// This method is used to Collapse row for a table
        /// </summary>
        /// <param name="nonexistCategoryId">Identify whether the CategoryId row exists</param>
        /// <param name="nonexpandedCategoryId">Identify whether the CategoryId row is not expanded</param>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopCollapseRow(bool nonexistCategoryId, bool nonexpandedCategoryId);

        /// <summary>
        /// This method is used to get collapse state for a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopGetCollapseState();

        /// <summary>
        /// This method is used to set collapse state for a table
        /// </summary>
        /// <returns>Table ROP return value</returns>
        TableRopReturnValues RopSetCollapseState();

        /// <summary>
        /// This method is used to release a table
        /// </summary>
        void RopRelease();
        #endregion

        /// <summary>
        /// This method is used to initialize the table
        /// </summary>
        /// <param name="tableType">Identify the table type</param>
        void InitializeTable(TableType tableType);

        /// <summary>
        /// Determines if the requirement is enabled or not.
        /// </summary>
        /// <param name="requirementId">The requirement Id</param>
        /// <param name="enabled">Requirement is enable or not.</param>
        void CheckRequirementEnabled(int requirementId, out bool enabled);

        /// <summary>
        /// This method is used to check whether MAPIHTTP transport is supported by SUT.
        /// </summary>
        /// <param name="isSupported">The transport is supported or not.</param>
        void CheckMAPIHTTPTransportSupported(out bool isSupported);

        /// <summary>
        /// Disconnect from the server.
        /// </summary>
        void Disconnect();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">FindClothes</string>
    <string name="action_settings">Settings</string>
    <string name="hello">随心搜</string>

</resources>

redpajama_set_name: RedPajamaGithub


text:
#ifndef __GST_AAC_PARSE_H__
#define __GST_AAC_PARSE_H__

#include <gst/gst.h>
#include <gst/base/gstbaseparse.h>

G_BEGIN_DECLS

#define GST_TYPE_AAC_PARSE \
  (gst_aac_parse_get_type())
#define GST_AAC_PARSE(obj) \
  (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_AAC_PARSE, GstAacParse))
#define GST_AAC_PARSE_CLASS(klass) \
  (G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_AAC_PARSE, GstAacParseClass))
#define GST_IS_AAC_PARSE(obj) \
  (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_AAC_PARSE))
#define GST_IS_AAC_PARSE_CLASS(klass) \
  (G_TYPE_CHECK_CLASS_TYPE((klass), GST_TYPE_AAC_PARSE))

/**
 * GstAacHeaderType:
 * @DSPAAC_HEADER_NOT_PARSED: Header not parsed yet.
 * @DSPAAC_HEADER_UNKNOWN: Unknown (not recognized) header.
 * @DSPAAC_HEADER_ADIF: ADIF header found.
 * @DSPAAC_HEADER_ADTS: ADTS header found.
 * @DSPAAC_HEADER_LOAS: LOAS header found.
 * @DSPAAC_HEADER_NONE: Raw stream, no header.
 *
 * Type header enumeration set in #header_type.
 */
typedef enum {
  DSPAAC_HEADER_NOT_PARSED,
  DSPAAC_HEADER_UNKNOWN,
  DSPAAC_HEADER_ADIF,
  DSPAAC_HEADER_ADTS,
  DSPAAC_HEADER_LOAS,
  DSPAAC_HEADER_NONE
} GstAacHeaderType;

typedef struct _GstAacParse GstAacParse;
typedef struct _GstAacParseClass GstAacParseClass;

/**
 * GstAacParse:
 *
 * The opaque GstAacParse data structure.
 */
struct _GstAacParse {
  GstBaseParse element;

  /* Stream type -related info */
  gint           object_type;
  gint           bitrate;
  gint           sample_rate;
  gint           channels;
  gint           mpegversion;
  gint           frame_samples;

  GstAacHeaderType header_type;
  GstAacHeaderType output_header_type;

  gboolean sent_codec_tag;

  gint last_parsed_sample_rate;
  gint last_parsed_channels;
};

/**
 * GstAacParseClass:
 * @parent_class: Element parent class.
 *
 * The opaque GstAacParseClass data structure.
 */
struct _GstAacParseClass {
  GstBaseParseClass parent_class;
};

GType gst_aac_parse_get_type (void);

G_END_DECLS

#endif /* __GST_AAC_PARSE_H__ */


text:
CASK_APP_LIST="macdown atom alfred iterm2 google-chrome firefox virtualbox vagrant postgres"
BREW_APP_LIST="colordiff tree homebrew/versions/maven31 gradle groovy jmeter node npm rbenv gcal"
JAVA_VERSIONS="java java7"
NVM_VERSION="v0.32.1"

# create symlinks for system settings
echo
echo "* App installations.  This will take a little while."
echo "*   Installing Homebrew..."
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
echo "*   Installing Homebrew Cask..."
    brew install caskroom/cask/brew-cask
echo "*   Setting up the previous version caskroom"
    brew tap caskroom/versions
echo "*   Installing terminal apps via brew."
    brew install $BREW_APP_LIST
echo "*   Now we'll install some binary apps: $CASK_APP_LIST"
    #brew cask install --force --appdir=/Applications $CASK_APP_LIST
    brew cask install --appdir=/Applications $CASK_APP_LIST
echo "*   Installing Java: $JAVA_VERSIONS"
    #brew cask install --force $JAVA_VERSIONS
    brew cask install $JAVA_VERSIONS
echo "*   Installing nvm"
    curl -o- https://raw.githubusercontent.com/creationix/nvm/$NVM_VERSION/install.sh | bash
echo "*   Done."

echo
echo "Symlink Setup"
echo "  Create symlink bash_profile."
    rm -f ~/.bash_profile; ln -s ~/my-env/bash_profile.sh ~/.bash_profile
echo "  Create symlink .gitconfig."
    rm -f ~/.gitconfig; ln -s ~/my-env/conf/git/gitconfig ~/.gitconfig
echo "  Create symlink ssh config."
    rm -f ~/.ssh/config; ln -s ~/my-env/conf/ssh/config ~/.ssh/config
echo "  Create maven repo symlink."
    rm -Rf ~/.m2; ln -s ~/my-env/conf/m2 ~/.m2
echo "  Create gradle symlink."
    rm -Rf ~/.gradle; ln -s ~/my-env/conf/gradle ~/.gradle
echo "  Create Intellij IDEA 'idea.vmoptions' symlink."
    rm -f ~/Library/Preferences/IntelliJIdea13/idea.vmoptions
    ln -s ~/my-env/conf/intellij-idea-14-ce/idea64.vmoptions ~/Library/Preferences/IdeaIC14/idea64.vmoptions;
echo "  Done."

echo
echo "Alfred 2 Setup"
echo "  Quitting Alfred 2 ..."
echo "  rsync Alfred 2 prefs ..."
    #Alfred 2 prefs cannot be symlinks
    osascript -e 'quit app "Alfred 2"'
    mkdir -p ~/my-env/conf/alfred2/Alfred\ 2
    rsync -r ~/Library/Application\ Support/Alfred\ 2/ ~/my-env/conf/alfred2/Alfred\ 2
    rm -Rf ~/Library/Application\ Support/Alfred\ 2;
    cp -R ~/my-env/conf/alfred2/Alfred\ 2 ~/Library/Application\ Support/Alfred\ 2;
echo "  Starting Alfred 2 ..."
    open -a /Applications/Alfred\ 2.app/Contents/MacOS/Alfred\ 2
echo "  Done."

echo
echo "Sourcing '~/.bash_profile'"
    source ~/.bash_profile
echo "  Done."

echo
echo "Install Fonts"
    # Add the custom fonts
    install_fonts ~/my-env/opt/fonts
echo "  Done."

echo
echo "Initialize Git Submodules"
    git updatesubs
echo "Done"

echo
echo
echo "Setup complete. yay."
echo


text:
package org.apache.commons.lang3.function;

import java.util.function.IntToDoubleFunction;

/**
 * A functional interface like {@link IntToDoubleFunction} that declares a {@code Throwable}.
 *
 * @param <E> Thrown exception.
 * @since 3.11
 */
@FunctionalInterface
public interface FailableIntToDoubleFunction<E extends Throwable> {

    /** NOP singleton */
    @SuppressWarnings("rawtypes")
    FailableIntToDoubleFunction NOP = t -> 0d;

    /**
     * Returns The NOP singleton.
     *
     * @param <E> Thrown exception.
     * @return The NOP singleton.
     */
    static <E extends Throwable> FailableIntToDoubleFunction<E> nop() {
        return NOP;
    }

    /**
     * Applies this function to the given argument.
     *
     * @param value the function argument
     * @return the function result
     * @throws E Thrown when the function fails.
     */
    double applyAsDouble(int value) throws E;
}


text:
require 'lib.class'

local time = require 'lib.time'
local lm = require 'lib.locales'
local eal = require 'lib.eal.manager'
local imguiInterface = require 'imgui.base'

local function decorate(cls)
  local RENDER_QUEUE_ASSET_VIEWER = 103
  cls.onCreate(function(self)
    self.meshNode = "__assetViewerContainer__"
    self.cameraName = "cn.flip.__assetViewerCamera__"
    self.container = self.render.root:getSceneNode(self.meshNode)
    self.aligner = self.render.root:getSceneNode(self.meshNode .. ".__assetViewerAligner__")
    if not self.container or not self.aligner then
      log.error("Failed to get mesh container")
      error("Failed to get mesh container")
    end
    self.camera = self.render.root:getCamera(self.cameraName)
    if not self.camera then
      log.error("Failed to get camera")
      error("Failed to get camera")
    end
    self.cameraNode = self.render.root:getSceneNode("cn")
    self.viewport = imgui.createOgreView("0x00000000")
    self.textureID = "__assetViewer__"
    local renderTarget = core:render():getRenderTarget(self.textureID)
    if not renderTarget then
      renderTarget = core:render():createRenderTarget(self.textureID, RenderTarget.Rtt, {
        autoUpdated = true,
        backgroundColor = "0x00000000",
        renderQueueSequence = {RENDER_QUEUE_ASSET_VIEWER},
        workspaceName = "assetViewer"
      });
    end
    self.viewport:setTexture(self.textureID)
    self.camera:attach(renderTarget)
  end)

  cls.onDestroy(function(self)
    if self.hasHandler then
      time.removeHandler(self.meshNode, self.onTime)
    end
  end)

  function cls:setEnabled(value)
    self.enabled = value
  end

  function cls:getSize()
    return 320, 320
  end

  function cls:run(asset)
    local meshName = asset.fullpath
    local w, h = imgui.GetContentRegionAvail()
    if w <= 0 or h <= 0 then
      return
    end

    self.viewport:render(w, h)

    if self.meshName == meshName then
      return
    end
    local meshID = "__assetViewerModel__"

    if not self.hasHandler then
      -- start rotating mesh container
      self.onTime = function(dt)
        if self.enabled then
          self.container:yaw(Radian.new(dt), OgreNode.TS_LOCAL)
        end
      end
      time.addHandler(self.meshNode, self.onTime)
      self.hasHandler = true
    end

    local renderData = self.render.props
    renderData.root.children[1].children[1].children = {{
      type = "model",
      query = "dynamic",
      mesh = meshName,
      name = meshID,
      renderQueue = RENDER_QUEUE_ASSET_VIEWER,
      workspaceName = "assetViewer",
      castShadows = false
    }}

    if pcall(function()
      self.render.props = renderData
    end) then
      self.render.position = Vector3.ZERO
      self.enabled = true
      local entity = self.aligner:getEntity(meshID)
      self.aligner.position = Vector3.ZERO
      local aabb = entity:getAabb()
      local c = self.camera:getCamera()
      local distance = aabb:getRadiusOrigin() * .7 / (c.fovy.radians * 0.5)
      local dirvec = self.cameraNode.position - Vector3.ZERO
      dirvec:normalise()
      self.aligner.position = Vector3.ZERO - aabb.center
      self.container.orientation = Quaternion.IDENTITY
      self.cameraNode.position = dirvec * distance
      self.cameraNode:lookAt(Vector3.ZERO + Vector3.new(0, self.cameraNode.position.y, 0), OgreNode.TS_WORLD)

      -- move asset viewer to some far away position to avoid clashing with real scene elements
      self.render.position = Vector3.new(100000, 100000, 100000)
    else
      self.enabled = false
    end
    self.meshName = meshName
  end

  return cls
end

eal:extend({class = {name = "__assetViewer__", requires = {render = "ogre"}}}, decorate)

-- creates asset rendering box
local function getAssetViewer()
  local id = "__assetViewer__"
  local entity = eal:getEntity(id)
  if entity then
    return entity
  end

  local e  = data:createEntity({
    id = "__assetViewer__",
    flags = {"dynamic"},
    vars = {
      class = "__assetViewer__",
      utility = true,
      enabled = false,
    },
    render = {
      root = {
        position = Vector3.ZERO,
        children = {
          {
            type = "node",
            name = "cn",
            position = Vector3.new(40, 0, 0),
            children = {
              {
                type = "node",
                name = "flip",
                rotation = Quaternion.new(0, 0, 90, 1),
                children = {
                  {
                    type = "camera",
                    name = "__assetViewerCamera__",
                    clipDistance = 0.01,
                    bgColour = "0x000000"
                  }
                }
              }
            }
          },
          {
            type = "node",
            name = "__assetViewerContainer__",
            children = {{
              type = "node",
              name = "__assetViewerAligner__"
            }}
          },
          {
            type = "node",
            rotation = Quaternion.new(0.57, 0.17, 0.75, -0.27),
            children = {{
              type = "light",
              name = "sun",
              renderQueue = RENDER_QUEUE_ASSET_VIEWER,
              direction = Vector3.new(-1, -1, -1),
              castShadows = true,
              colourShadow = "0x00000000",
              colourDiffuse = "0xFFFFFFFF",
              lightType = "directional",
              powerScale = 0
            }}
          }
        }
      }
    }
  })

  if not e then
    return nil
  end

  return eal:getEntity(e.id)
end

local function enableTextEdit(asset)
  function asset:open(assetManager)
    assetManager.scriptEditor:openFile(asset.fullpath)
  end
end

return {
  coreSystems = {
    script = {"lua"},
    movement = {"3dmovement"}
  },
  pluginsInfo = {
    OgrePlugin = {
      systems = {
        render = {"ogre"}
      },
      assets = {
        models = {
          mesh = {
            import = function(filepath, asset)
              asset.install = "models"
              local success, viewer = pcall(getAssetViewer)
              if success then
                asset.viewer = viewer
              else
                log.error("Failed to set up asset viewer " .. viewer)
              end

              asset.addToScene = function(asset, assetManager, position)
                position = position or Vector3.new(0, 0, 0)
                local textBuffer = imgui.TextBuffer(256)
                textBuffer:write("")
                local choices = {}
                choices[lm("modals.ok")] = function()
                  local sceneEditor = imguiInterface:getView("sceneEditor")
                  if sceneEditor then
                    local name = textBuffer:read()
                    local entity = {
                      render = {
                        root = {
                          position = position,
                          children = {{
                            type = "model",
                            mesh = asset.file
                          }}
                        }
                      }
                    }
                    if name ~= "" then
                      entity.id = name
                    end

                    sceneEditor:addEntity(entity)
                  end
                end
                choices[lm("modals.cancel")] = function()
                end

                assetManager.modal:show(lm("modals.create_entity.title", {asset = asset.file}), function()
                  imgui.Text(lm("modals.create_entity.desc"))
                  imgui.InputTextWithCallback(lm("modals.create_entity.entity_id"), textBuffer, 0, function() end)
                end, choices)
              end

              asset.actions = {{
                id = "addToScene",
                callback = asset.addToScene
              }}

              return true
            end
          },
        },
        scripts = {
          material = {
            import = function(filepath, asset)
              asset.install = "materials"
              enableTextEdit(asset)
              return true
            end
          },
          compositor = {
            import = function(filepath, asset)
              enableTextEdit(asset)
              asset.install = "materials"
              return true
            end
          },
          glsl = {},
          hlsl = {},
          metal = {}
        }
      }
    },
    SDLPlugin = {
      managers = {
        input = {"sdl"},
        window = {"sdl"}
      }
    },
    CEFPlugin = {
    },
    ImGUIPlugin = {
    },
    OisInputPlugin = {
      managers = {
        input = "OIS"
      }
    },
    RecastNavigationPlugin = {
      systems = {
        navigation = {"recast"}
      }
    },
    RocketUIPlugin = {
      depends = {
        OgrePlugin = "<=1.9.0"
      },
      assets = {
        scripts = {
          rcss = {
            import = function(filepath, asset)
              asset.install = "ui"
              enableTextEdit(asset)
              return true
            end
          },
          rml = {
            import = function(filepath, asset)
              asset.install = "ui"
              enableTextEdit(asset)
              return true
            end
          }
        }
      }
    }
  }
}


text:
import logging
import quantities
import os
import numpy

from rmgpy import settings

from rmgpy.molecule import Molecule
from rmgpy.quantity import Quantity
from rmgpy.solver.base import TerminationTime, TerminationConversion
from rmgpy.solver.simple import SimpleReactor
from rmgpy.solver.liquid import LiquidReactor
from rmgpy.rmg.settings import ModelSettings, SimulatorSettings
from model import CoreEdgeReactionModel

from rmgpy.scoop_framework.util import broadcast, get
from rmgpy.exceptions import InputError
################################################################################

rmg = None
speciesDict = {}

def database(
             thermoLibraries = None,
             transportLibraries = None,
             reactionLibraries = None,
             frequenciesLibraries = None,
             seedMechanisms = None,
             kineticsFamilies = 'default',
             kineticsDepositories = 'default',
             kineticsEstimator = 'rate rules',
             ):
    # This function just stores the information about the database to be loaded
    # We don't actually load the database until after we're finished reading
    # the input file
    if isinstance(thermoLibraries, str): thermoLibraries = [thermoLibraries]
    if isinstance(transportLibraries, str): transportLibraries = [transportLibraries]
    if isinstance(reactionLibraries, str): reactionLibraries = [reactionLibraries]
    if isinstance(seedMechanisms, str): seedMechanisms = [seedMechanisms]
    if isinstance(frequenciesLibraries, str): frequenciesLibraries = [frequenciesLibraries]
    rmg.databaseDirectory = settings['database.directory']
    rmg.thermoLibraries = thermoLibraries or []
    rmg.transportLibraries = transportLibraries
    # Modify reactionLibraries if the user didn't specify tuple input
    if reactionLibraries:
        index = 0
        while index < len(reactionLibraries):
            if isinstance(reactionLibraries[index],tuple):
                pass
            elif isinstance(reactionLibraries[index],str):
                reactionLibraries[index] = (reactionLibraries[index], False)
            else:
                raise TypeError('reaction libraries must be input as tuples or strings')
            index += 1
    rmg.reactionLibraries = reactionLibraries or []
    rmg.seedMechanisms = seedMechanisms or []
    rmg.statmechLibraries = frequenciesLibraries or []
    rmg.kineticsEstimator = kineticsEstimator
    if kineticsDepositories == 'default':
        rmg.kineticsDepositories = ['training']
    elif kineticsDepositories == 'all':
        rmg.kineticsDepositories = None
    else:
        if not isinstance(kineticsDepositories,list):
            raise InputError("kineticsDepositories should be either 'default', 'all', or a list of names eg. ['training','PrIMe'].")
        rmg.kineticsDepositories = kineticsDepositories

    if kineticsFamilies in ('default', 'all', 'none'):
        rmg.kineticsFamilies = kineticsFamilies
    else:
        if not isinstance(kineticsFamilies,list):
            raise InputError("kineticsFamilies should be either 'default', 'all', 'none', or a list of names eg. ['H_Abstraction','R_Recombination'] or ['!Intra_Disproportionation'].")
        rmg.kineticsFamilies = kineticsFamilies

def species(label, structure, reactive=True):
    logging.debug('Found {0} species "{1}" ({2})'.format('reactive' if reactive else 'nonreactive', label, structure.toSMILES()))
    spec, isNew = rmg.reactionModel.makeNewSpecies(structure, label=label, reactive=reactive)
    if not isNew:
        raise InputError("Species {0} is a duplicate of {1}. Species in input file must be unique".format(label,spec.label))
    # Force RMG to add the species to edge first, prior to where it is added to the core, in case it is found in
    # any reaction libraries along the way
    rmg.reactionModel.addSpeciesToEdge(spec)
    rmg.initialSpecies.append(spec)
    speciesDict[label] = spec

def SMARTS(string):
    return Molecule().fromSMARTS(string)

def SMILES(string):
    return Molecule().fromSMILES(string)

def InChI(string):
    return Molecule().fromInChI(string)

def adjacencyList(string):
    return Molecule().fromAdjacencyList(string)

# Reaction systems
def simpleReactor(temperature,
                  pressure,
                  initialMoleFractions,
                  terminationConversion=None,
                  terminationTime=None,
                  sensitivity=None,
                  sensitivityThreshold=1e-3
                  ):
    logging.debug('Found SimpleReactor reaction system')

    for value in initialMoleFractions.values():
        if value < 0:
            raise InputError('Initial mole fractions cannot be negative.')

    for spec in initialMoleFractions:
            initialMoleFractions[spec] = float(initialMoleFractions[spec])

    totalInitialMoles = sum(initialMoleFractions.values())
    if totalInitialMoles != 1:
        logging.warning('Initial mole fractions do not sum to one; normalizing.')
        logging.info('')
        logging.info('Original composition:')
        for spec, molfrac in initialMoleFractions.iteritems():
            logging.info("{0} = {1}".format(spec,molfrac))
        for spec in initialMoleFractions:
            initialMoleFractions[spec] /= totalInitialMoles
        logging.info('')
        logging.info('Normalized mole fractions:')
        for spec, molfrac in initialMoleFractions.iteritems():
            logging.info("{0} = {1}".format(spec,molfrac))

    T = Quantity(temperature)
    P = Quantity(pressure)

    termination = []
    if terminationConversion is not None:
        for spec, conv in terminationConversion.iteritems():
            termination.append(TerminationConversion(speciesDict[spec], conv))
    if terminationTime is not None:
        termination.append(TerminationTime(Quantity(terminationTime)))
    if len(termination) == 0:
        raise InputError('No termination conditions specified for reaction system #{0}.'.format(len(rmg.reactionSystems)+2))

    sensitiveSpecies = []
    if sensitivity:
        if isinstance(sensitivity, str): sensitivity = [sensitivity]
        for spec in sensitivity:
            sensitiveSpecies.append(speciesDict[spec])
    system = SimpleReactor(T, P, initialMoleFractions, termination, sensitiveSpecies, sensitivityThreshold)
    rmg.reactionSystems.append(system)

# Reaction systems
def liquidReactor(temperature,
                  initialConcentrations,
                  terminationConversion=None,
                  terminationTime=None,
                  sensitivity=None,
                  sensitivityThreshold=1e-3,
                  constantSpecies=None):

    logging.debug('Found LiquidReactor reaction system')
    T = Quantity(temperature)
    for spec,conc in initialConcentrations.iteritems():
        concentration = Quantity(conc)
        # check the dimensions are ok
        # convert to mol/m^3 (or something numerically nice? or must it be SI)
        initialConcentrations[spec] = concentration.value_si
    termination = []
    if terminationConversion is not None:
        for spec, conv in terminationConversion.iteritems():
            termination.append(TerminationConversion(speciesDict[spec], conv))
    if terminationTime is not None:
        termination.append(TerminationTime(Quantity(terminationTime)))
    if len(termination) == 0:
        raise InputError('No termination conditions specified for reaction system #{0}.'.format(len(rmg.reactionSystems)+2))

    sensitiveSpecies = []
    if sensitivity:
        for spec in sensitivity:
            sensitiveSpecies.append(speciesDict[spec])

    ##chatelak: check the constant species exist
    if constantSpecies is not None:
        logging.debug('  Generation with constant species:')
        for constantSpecie in constantSpecies:
            logging.debug("  {0}".format(constantSpecie))
            if not speciesDict.has_key(constantSpecie):
                raise InputError('Species {0} not found in the input file'.format(constantSpecie))

    system = LiquidReactor(T, initialConcentrations, termination, sensitiveSpecies, sensitivityThreshold,constantSpecies)
    rmg.reactionSystems.append(system)

def simulator(atol, rtol, sens_atol=1e-6, sens_rtol=1e-4):
    rmg.simulatorSettingsList.append(SimulatorSettings(atol, rtol, sens_atol, sens_rtol))

def solvation(solvent):
    # If solvation module in input file, set the RMG solvent variable
    if not isinstance(solvent,str):
        raise InputError("solvent should be a string like 'water'")
    rmg.solvent = solvent

def model(toleranceMoveToCore=None, toleranceMoveEdgeReactionToCore=numpy.inf,toleranceKeepInEdge=0.0, toleranceInterruptSimulation=1.0,
          toleranceMoveEdgeReactionToSurface=numpy.inf, toleranceMoveSurfaceSpeciesToCore=numpy.inf, toleranceMoveSurfaceReactionToCore=numpy.inf,
          toleranceMoveEdgeReactionToSurfaceInterrupt=None,
          toleranceMoveEdgeReactionToCoreInterrupt=None, maximumEdgeSpecies=1000000, minCoreSizeForPrune=50,
          minSpeciesExistIterationsForPrune=2, filterReactions=False, ignoreOverallFluxCriterion=False,
          maxNumSpecies=None,maxNumObjsPerIter=1,terminateAtMaxObjects=False,toleranceThermoKeepSpeciesInEdge=numpy.inf,dynamicsTimeScale=(0.0,'sec')):
    """
    How to generate the model. `toleranceMoveToCore` must be specified.
    toleranceMoveReactionToCore and toleranceReactionInterruptSimulation refers to an additional criterion for forcing an edge reaction to be included in the core
    by default this criterion is turned off
    Other parameters are optional and control the pruning.
    ignoreOverallFluxCriterion=True will cause the toleranceMoveToCore to be only applied
    to the pressure dependent network expansion and not movement of species from edge to core
    """
    if toleranceMoveToCore is None:
        raise InputError("You must provide a toleranceMoveToCore value. It should be less than or equal to toleranceInterruptSimulation which is currently {0}".format(toleranceInterruptSimulation))
    if toleranceMoveToCore > toleranceInterruptSimulation:
        raise InputError("toleranceMoveToCore must be less than or equal to toleranceInterruptSimulation, which is currently {0}".format(toleranceInterruptSimulation))

    rmg.modelSettingsList.append(ModelSettings(toleranceMoveToCore, toleranceMoveEdgeReactionToCore,toleranceKeepInEdge, toleranceInterruptSimulation,
          toleranceMoveEdgeReactionToSurface, toleranceMoveSurfaceSpeciesToCore, toleranceMoveSurfaceReactionToCore,
          toleranceMoveEdgeReactionToSurfaceInterrupt,toleranceMoveEdgeReactionToCoreInterrupt, maximumEdgeSpecies, minCoreSizeForPrune,
          minSpeciesExistIterationsForPrune, filterReactions, ignoreOverallFluxCriterion, maxNumSpecies, maxNumObjsPerIter,terminateAtMaxObjects,
          toleranceThermoKeepSpeciesInEdge,Quantity(dynamicsTimeScale)))

def quantumMechanics(
                    software,
                    method,
                    fileStore = None,
                    scratchDirectory = None,
                    onlyCyclics = False,
                    maxRadicalNumber = 0,
                    ):
    from rmgpy.qm.main import QMCalculator
    rmg.quantumMechanics = QMCalculator(software = software,
                                        method = method,
                                        fileStore = fileStore,
                                        scratchDirectory = scratchDirectory,
                                        onlyCyclics = onlyCyclics,
                                        maxRadicalNumber = maxRadicalNumber,
                                        )

def pressureDependence(
                       method,
                       temperatures,
                       pressures,
                       maximumGrainSize = 0.0,
                       minimumNumberOfGrains = 0,
                       interpolation = None,
                       maximumAtoms=None,
                       ):

    from rmgpy.cantherm.pdep import PressureDependenceJob

    # Setting the pressureDependence attribute to non-None enables pressure dependence
    rmg.pressureDependence = PressureDependenceJob(network=None)

    # Process method
    rmg.pressureDependence.method = method

    # Process interpolation model
    if isinstance(interpolation, str):
        interpolation = (interpolation,)
    if interpolation[0].lower() not in ("chebyshev","pdeparrhenius"):
        raise InputError("Interpolation model must be set to either 'Chebyshev' or 'PDepArrhenius'.")
    rmg.pressureDependence.interpolationModel = interpolation

    # Process temperatures
    Tmin, Tmax, Tunits, Tcount = temperatures
    rmg.pressureDependence.Tmin = Quantity(Tmin, Tunits)
    rmg.pressureDependence.Tmax = Quantity(Tmax, Tunits)
    rmg.pressureDependence.Tcount = Tcount
    rmg.pressureDependence.generateTemperatureList()

    # Process pressures
    Pmin, Pmax, Punits, Pcount = pressures
    rmg.pressureDependence.Pmin = Quantity(Pmin, Punits)
    rmg.pressureDependence.Pmax = Quantity(Pmax, Punits)
    rmg.pressureDependence.Pcount = Pcount
    rmg.pressureDependence.generatePressureList()

    # Process grain size and count
    rmg.pressureDependence.maximumGrainSize = Quantity(maximumGrainSize)
    rmg.pressureDependence.minimumGrainCount = minimumNumberOfGrains

    # Process maximum atoms
    rmg.pressureDependence.maximumAtoms = maximumAtoms

    rmg.pressureDependence.activeJRotor = True
    rmg.pressureDependence.activeKRotor = True
    rmg.pressureDependence.rmgmode = True

def options(name='Seed', generateSeedEachIteration=False, saveSeedToDatabase=False, units='si', saveRestartPeriod=None,
            generateOutputHTML=False, generatePlots=False, saveSimulationProfiles=False, verboseComments=False,
            saveEdgeSpecies=False, keepIrreversible=False, wallTime='00:00:00:00'):
    rmg.name = name
    rmg.generateSeedEachIteration=generateSeedEachIteration
    rmg.saveSeedToDatabase=saveSeedToDatabase
    rmg.units = units
    rmg.saveRestartPeriod = Quantity(saveRestartPeriod) if saveRestartPeriod else None
    if generateOutputHTML:
        logging.warning('Generate Output HTML option was turned on. Note that this will slow down model generation.')
    rmg.generateOutputHTML = generateOutputHTML
    rmg.generatePlots = generatePlots
    rmg.saveSimulationProfiles = saveSimulationProfiles
    rmg.verboseComments = verboseComments
    if saveEdgeSpecies:
        logging.warning('Edge species saving was turned on. This will slow down model generation for large simulations.')
    rmg.saveEdgeSpecies = saveEdgeSpecies
    rmg.keepIrreversible = keepIrreversible
    rmg.wallTime = wallTime

def generatedSpeciesConstraints(**kwargs):

    validConstraints = [
        'allowed',
        'maximumCarbonAtoms',
        'maximumOxygenAtoms',
        'maximumNitrogenAtoms',
        'maximumSiliconAtoms',
        'maximumSulfurAtoms',
        'maximumHeavyAtoms',
        'maximumRadicalElectrons',
        'maximumSingletCarbenes',
        'maximumCarbeneRadicals',
        'allowSingletO2',
        'maximumIsotopicAtoms'
    ]

    for key, value in kwargs.items():
        if key not in validConstraints:
            raise InputError('Invalid generated species constraint {0!r}.'.format(key))

        rmg.speciesConstraints[key] = value

def thermoCentralDatabase(host,
                        port,
                        username,
                        password,
                        application):

    from rmgpy.data.thermo import ThermoCentralDatabaseInterface
    rmg.thermoCentralDatabase = ThermoCentralDatabaseInterface(host,
                                                            port,
                                                            username,
                                                            password,
                                                            application)

################################################################################

def setGlobalRMG(rmg0):
    """
    sets the global variable rmg to rmg0. This is used to allow for unittesting
    of above methods
    """
    global rmg
    rmg = rmg0

def readInputFile(path, rmg0):
    """
    Read an RMG input file at `path` on disk into the :class:`RMG` object
    `rmg`.
    """
    global rmg, speciesDict

    full_path = os.path.abspath(os.path.expandvars(path))
    try:
        f = open(full_path)
    except IOError, e:
        logging.error('The input file "{0}" could not be opened.'.format(full_path))
        logging.info('Check that the file exists and that you have read access.')
        raise e

    logging.info('Reading input file "{0}"...'.format(full_path))
    logging.info(f.read())
    f.seek(0)# return to beginning of file

    setGlobalRMG(rmg0)
    rmg.reactionModel = CoreEdgeReactionModel()
    rmg.initialSpecies = []
    rmg.reactionSystems = []
    speciesDict = {}

    global_context = { '__builtins__': None }
    local_context = {
        '__builtins__': None,
        'True': True,
        'False': False,
        'database': database,
        'species': species,
        'SMARTS': SMARTS,
        'SMILES': SMILES,
        'InChI': InChI,
        'adjacencyList': adjacencyList,
        'simpleReactor': simpleReactor,
        'liquidReactor': liquidReactor,
        'simulator': simulator,
        'solvation': solvation,
        'model': model,
        'quantumMechanics': quantumMechanics,
        'pressureDependence': pressureDependence,
        'options': options,
        'generatedSpeciesConstraints': generatedSpeciesConstraints,
        'thermoCentralDatabase': thermoCentralDatabase
    }

    try:
        exec f in global_context, local_context
    except (NameError, TypeError, SyntaxError), e:
        logging.error('The input file "{0}" was invalid:'.format(full_path))
        logging.exception(e)
        raise
    finally:
        f.close()

    rmg.speciesConstraints['explicitlyAllowedMolecules'] = []
    broadcast(rmg.speciesConstraints, 'speciesConstraints')

    # convert keys from species names into species objects.
    for reactionSystem in rmg.reactionSystems:
        reactionSystem.convertInitialKeysToSpeciesObjects(speciesDict)

    if rmg.quantumMechanics:
        rmg.quantumMechanics.setDefaultOutputDirectory(rmg.outputDirectory)
        rmg.quantumMechanics.initialize()
    broadcast(rmg.quantumMechanics, 'quantumMechanics')

    logging.info('')

################################################################################

def readThermoInputFile(path, rmg0):
    """
    Read an thermo estimation input file at `path` on disk into the :class:`RMG` object
    `rmg`.
    """

    global rmg, speciesDict

    full_path = os.path.abspath(os.path.expandvars(path))
    try:
        f = open(full_path)
    except IOError, e:
        logging.error('The input file "{0}" could not be opened.'.format(full_path))
        logging.info('Check that the file exists and that you have read access.')
        raise e

    logging.info('Reading input file "{0}"...'.format(full_path))

    rmg = rmg0
    rmg.reactionModel = CoreEdgeReactionModel()
    rmg.initialSpecies = []
    rmg.reactionSystems = []
    speciesDict = {}

    global_context = { '__builtins__': None }
    local_context = {
        '__builtins__': None,
        'True': True,
        'False': False,
        'database': database,
        'species': species,
        'SMARTS': SMARTS,
        'SMILES': SMILES,
        'InChI': InChI,
        'solvation': solvation,
        'adjacencyList': adjacencyList,
        'quantumMechanics': quantumMechanics,
    }

    try:
        exec f in global_context, local_context
    except (NameError, TypeError, SyntaxError), e:
        logging.error('The input file "{0}" was invalid:'.format(full_path))
        logging.exception(e)
        raise
    finally:
        f.close()

    if rmg.quantumMechanics:
        rmg.quantumMechanics.setDefaultOutputDirectory(rmg.outputDirectory)
        rmg.quantumMechanics.initialize()
    broadcast(rmg.quantumMechanics, 'quantumMechanics')

    logging.info('')

################################################################################

def saveInputFile(path, rmg):
    """
    Save an RMG input file at `path` on disk from the :class:`RMG` object
    `rmg`.
    """

    f = open(path, 'w')

    # Databases
    f.write('database(\n')
    #f.write('    "{0}",\n'.format(rmg.databaseDirectory))
    f.write('    thermoLibraries = {0!r},\n'.format(rmg.thermoLibraries))
    f.write('    reactionLibraries = {0!r},\n'.format(rmg.reactionLibraries))
    f.write('    seedMechanisms = {0!r},\n'.format(rmg.seedMechanisms))
    f.write('    kineticsDepositories = {0!r},\n'.format(rmg.kineticsDepositories))
    f.write('    kineticsFamilies = {0!r},\n'.format(rmg.kineticsFamilies))
    f.write('    kineticsEstimator = {0!r},\n'.format(rmg.kineticsEstimator))
    f.write(')\n\n')

    # Species
    for species in rmg.initialSpecies:
        f.write('species(\n')
        f.write('    label = "{0}",\n'.format(species.label))
        f.write('    reactive = {0},\n'.format(species.reactive))
        f.write('    structure = adjacencyList(\n')
        f.write('"""\n')
        f.write(species.molecule[0].toAdjacencyList())
        f.write('"""),\n')
        f.write(')\n\n')

    # Reaction systems
    for system in rmg.reactionSystems:
        if rmg.solvent:
            f.write('liquidReactor(\n')
            f.write('    temperature = ({0:g},"{1!s}"),\n'.format(system.T.getValue(),system.T.units))
            f.write('    initialConcentrations={\n')
            for species, conc in system.initialConcentrations.iteritems():
                f.write('        "{0!s}": ({1:g},"{2!s}"),\n'.format(species.label,conc.getValue(),conc.units))
        else:
            f.write('simpleReactor(\n')
            f.write('    temperature = ({0:g},"{1!s}"),\n'.format(system.T.getValue(),system.T.units))
            # Convert the pressure from SI pascal units to bar here
            # Do something more fancy later for converting to user's desired units for both T and P..
            f.write('    pressure = ({0:g},"{1!s}"),\n'.format(system.P.getValue(),system.P.units))
            f.write('    initialMoleFractions={\n')
            for species, molfrac in system.initialMoleFractions.iteritems():
                f.write('        "{0!s}": {1:g},\n'.format(species.label, molfrac))
        f.write('    },\n')

        # Termination criteria
        conversions = ''
        for term in system.termination:
            if isinstance(term, TerminationTime):
                f.write('    terminationTime = ({0:g},"{1!s}"),\n'.format(term.time.getValue(),term.time.units))

            else:
                conversions += '        "{0:s}": {1:g},\n'.format(term.species.label, term.conversion)
        if conversions:
            f.write('    terminationConversion = {\n')
            f.write(conversions)
            f.write('    },\n')

        # Sensitivity analysis
        if system.sensitiveSpecies:
            sensitivity = []
            for item in system.sensitiveSpecies:
                sensitivity.append(item.label)
            f.write('    sensitivity = {0},\n'.format(sensitivity))
            f.write('    sensitivityThreshold = {0},\n'.format(system.sensitivityThreshold))

        f.write(')\n\n')

    if rmg.solvent:
        f.write("solvation(\n    solvent = '{0!s}'\n)\n\n".format(rmg.solvent))

    # Simulator tolerances
    f.write('simulator(\n')
    f.write('    atol = {0:g},\n'.format(rmg.absoluteTolerance))
    f.write('    rtol = {0:g},\n'.format(rmg.relativeTolerance))
    f.write('    sens_atol = {0:g},\n'.format(rmg.sensitivityAbsoluteTolerance))
    f.write('    sens_rtol = {0:g},\n'.format(rmg.sensitivityRelativeTolerance))
    f.write(')\n\n')

    # Model
    f.write('model(\n')
    f.write('    toleranceMoveToCore = {0:g},\n'.format(rmg.fluxToleranceMoveToCore))
    f.write('    toleranceKeepInEdge = {0:g},\n'.format(rmg.fluxToleranceKeepInEdge))
    f.write('    toleranceInterruptSimulation = {0:g},\n'.format(rmg.fluxToleranceInterrupt))
    f.write('    maximumEdgeSpecies = {0:d},\n'.format(rmg.maximumEdgeSpecies))
    f.write('    minCoreSizeForPrune = {0:d},\n'.format(rmg.minCoreSizeForPrune))
    f.write('    minSpeciesExistIterationsForPrune = {0:d},\n'.format(rmg.minSpeciesExistIterationsForPrune))
    f.write('    filterReactions = {0:d},\n'.format(rmg.filterReactions))
    f.write(')\n\n')

    # Pressure Dependence
    if rmg.pressureDependence:
        f.write('pressureDependence(\n')
        f.write('    method = {0!r},\n'.format(rmg.pressureDependence.method))
        f.write('    maximumGrainSize = ({0:g},"{1!s}"),\n'.format(rmg.pressureDependence.grainSize.getValue(),rmg.pressureDependence.grainSize.units))
        f.write('    minimumNumberOfGrains = {0},\n'.format(rmg.pressureDependence.grainCount))
        f.write('    temperatures = ({0:g},{1:g},"{2!s}",{3:d}),\n'.format(
            rmg.pressureDependence.Tmin.getValue(),
            rmg.pressureDependence.Tmax.getValue(),
            rmg.pressureDependence.Tmax.units,
            rmg.pressureDependence.Tcount,
        ))
        f.write('    pressures = ({0:g},{1:g},"{2!s}",{3:d}),\n'.format(
            rmg.pressureDependence.Pmin.getValue(),
            rmg.pressureDependence.Pmax.getValue(),
            rmg.pressureDependence.Pmax.units,
            rmg.pressureDependence.Pcount,
        ))
        f.write('    interpolation = {0},\n'.format(rmg.pressureDependence.interpolationModel))
        f.write('    maximumAtoms = {0}, \n'.format(rmg.pressureDependence.maximumAtoms))
        f.write(')\n\n')

    # Quantum Mechanics
    if rmg.quantumMechanics:
        f.write('quantumMechanics(\n')
        f.write('    software = {0!r},\n'.format(rmg.quantumMechanics.settings.software))
        f.write('    method = {0!r},\n'.format(rmg.quantumMechanics.settings.method))
        # Split paths created by QMSettings
        if rmg.quantumMechanics.settings.fileStore:
            f.write('    fileStore = {0!r},\n'.format(os.path.split(rmg.quantumMechanics.settings.fileStore)[0]))
        else:
            f.write('    fileStore = None,\n')
        if rmg.quantumMechanics.settings.scratchDirectory:
            f.write('    scratchDirectory = {0!r},\n'.format(os.path.split(rmg.quantumMechanics.settings.scratchDirectory)[0]))
        else:
            f.write('    scratchDirectory = None,\n')
        f.write('    onlyCyclics = {0},\n'.format(rmg.quantumMechanics.settings.onlyCyclics))
        f.write('    maxRadicalNumber = {0},\n'.format(rmg.quantumMechanics.settings.maxRadicalNumber))
        f.write(')\n\n')

    # Species Constraints
    if rmg.speciesConstraints:
        f.write('generatedSpeciesConstraints(\n')
        for constraint, value in sorted(rmg.speciesConstraints.items(), key=lambda constraint: constraint[0]):
            if value is not None: f.write('    {0} = {1},\n'.format(constraint,value))
        f.write(')\n\n')

    # Options
    f.write('options(\n')
    f.write('    units = "{0}",\n'.format(rmg.units))
    if rmg.saveRestartPeriod:
        f.write('    saveRestartPeriod = ({0},"{1}"),\n'.format(rmg.saveRestartPeriod.getValue(), rmg.saveRestartPeriod.units))
    else:
        f.write('    saveRestartPeriod = None,\n')
    f.write('    generateOutputHTML = {0},\n'.format(rmg.generateOutputHTML))
    f.write('    generatePlots = {0},\n'.format(rmg.generatePlots))
    f.write('    saveSimulationProfiles = {0},\n'.format(rmg.saveSimulationProfiles))
    f.write('    saveEdgeSpecies = {0},\n'.format(rmg.saveEdgeSpecies))
    f.write('    keepIrreversible = {0},\n'.format(rmg.keepIrreversible))
    f.write('    verboseComments = {0},\n'.format(rmg.verboseComments))
    f.write('    wallTime = {0},\n'.format(rmg.wallTime))
    f.write(')\n\n')

    f.close()

def getInput(name):
    """
    Returns the RMG input object that corresponds
    to the parameter name.

    First, the module level is queried. If this variable
    is empty, the broadcasted variables are queried.
    """
    global rmg

    if rmg:
        if name == 'speciesConstraints':
            return rmg.speciesConstraints
        elif name == 'quantumMechanics':
            return rmg.quantumMechanics
        elif name == 'thermoCentralDatabase':
            return rmg.thermoCentralDatabase
        else:
            raise Exception('Unrecognized keyword: {}'.format(name))
    else:
        try:
            obj = get(name)
            if obj:
                return obj
            else:
                raise Exception
        except Exception, e:
            logging.debug("Did not find a way to obtain the variable for {}.".format(name))
            raise e

    raise Exception('Could not get variable with name: {}'.format(name))


text:
import subprocess
import os.path
import shutil
import time
import json

from gii.core         import *

from gii.qt           import *
from gii.qt.IconCache import getIcon
from gii.qt.helpers   import addWidgetWithLayout, QColorF, unpackQColor
from gii.qt.dialogs   import requestString, alertMessage, requestColor
from gii.qt.controls.GenericTreeWidget import GenericTreeWidget

from gii.qt.controls.PropertyEditor  import PropertyEditor

from gii.AssetEditor  import AssetEditorModule

from gii.moai.MOAIEditCanvas import MOAIEditCanvas
from gii.moai import _LuaObject

from PyQt4  import QtCore, QtGui, QtOpenGL
from PyQt4.QtCore import Qt

from mock import getMockClassName
##----------------------------------------------------------------##

def _getModulePath( path ):
	import os.path
	return os.path.dirname( __file__ ) + '/' + path

def _fixDuplicatedName( names, name, id = None ):
	if id:
		testName = name + '_%d' % id
	else:
		id = 0
		testName = name
	#find duplicated name
	if testName in names:
		return _fixDuplicatedName( names, name, id + 1)
	else:
		return testName

##----------------------------------------------------------------##
class Box(object):
	def __init__(self):
		self.items = []

##----------------------------------------------------------------##

class ParticleEditor( AssetEditorModule ):
	"""docstring for ParticleEditor"""
	def __init__(self):
		super(ParticleEditor, self).__init__()
		self.editingAsset  = None
		self.editingConfig = None
		self.editingState  = None

		self.emitters = Box()
		self.emitters.items=[]

		self.states = Box()
		self.states.items=[]
		self.scriptModifyFlag = 0

	def getName(self):
		return 'particle_editor'

	def getDependency(self):
		return [ 'qt', 'mock' ]

	def onLoad(self):
		self.windowTitle = 'Particle System Editor'
		self.container = self.requestDocumentWindow('MockParticleEditor',
				title       = 'Particle System Editor',
				size        = (500,300),
				minSize     = (500,300),
				# allowDock = False
			)

		self.tool = self.addToolBar( 'particle_editor', self.container.addToolBar() )
		self.addTool( 'particle_editor/save',   label = 'Save', icon = 'save' )
		self.addTool( 'particle_editor/----' )
		self.addTool( 'particle_editor/add_state',   label = '+ State' )
		self.addTool( 'particle_editor/add_emitter', label = '+ Emitter' )
		self.addTool( 'particle_editor/remove',      label = 'Delete', icon = 'remove' )
		self.addTool( 'particle_editor/update',      label = 'Update', icon = 'refresh' )
		self.addTool( 'particle_editor/----' )
		self.addTool( 'particle_editor/start_preview', icon = 'play' )
		self.addTool( 'particle_editor/stop_preview', icon = 'stop' )

		self.window = window = self.container.addWidgetFromFile(
			_getModulePath('ParticleEditor2.ui')
		)
		self.canvas = addWidgetWithLayout(
			MOAIEditCanvas( window.containerPreview )
		)
		self.tree = addWidgetWithLayout(
			ParticleTreeWidget( window.containerTree, multiple_selection = False, editable = False )
			)
		self.tree.module = self

		self.propEditor = addWidgetWithLayout(
			PropertyEditor( window.containerProperty )
			)

		window.textScriptRender.textChanged.connect( self.onScriptModified )
		window.textScriptInit.textChanged.connect( self.onScriptModified )
		self.window.panelScript.setEnabled( False )

		self.propEditor.propertyChanged.connect( self.onPropertyChanged )

	def onStart( self ):
		self.canvas.loadScript( _getModulePath('ParticleEditor.lua') )
		# self.canvas.setDelegateEnv( 'editor', self )

	def onSetFocus( self ):
		self.container.show()
		self.container.raise_()
		self.container.activateWindow()
		self.container.setFocus()

	def openAsset( self, node ):
		self.setFocus()
		if self.editingAsset == node: return
		self.checkScriptTimer = self.container.startTimer( 3, self.checkScript )

		self.container.setDocumentName( node.getNodePath() )
		self.editingAsset  = node

		self.canvas.makeCurrent()
		self.editingConfig = self.canvas.safeCallMethod( 'preview', 'open', node.getPath() )

		self.tree.rebuild()
		self.tree.setAllExpanded( True )

	def saveAsset( self ):
		if not self.editingAsset: return
		self.canvas.safeCallMethod( 'preview', 'save', self.editingAsset.getAbsFilePath() )

	def closeAsset( self ):
		self.checkScriptTimer.stop()

	def changeState( self, state ):
		self.editingState = state
		if state:
			self.window.panelScript.setEnabled( True )
			self.window.textScriptRender.setPlainText( state.renderScript )
			self.window.textScriptInit.setPlainText( state.initScript )
			self.refreshScriptTitle()
		else:
			self.window.panelScript.setEnabled( False )

	def changeSelection( self, selection ):
		self.propEditor.setTarget( selection )
		self.canvas.safeCallMethod( 'preview', 'changeSelection', selection )

	def refreshScriptTitle( self ):
		state = self.editingState
		self.window.labelStateName.setText( 'current editing state script: <%s>' % state.name )
		# if not state: return
		# tabParent = self.window.panelScript
		# idx = tabParent.indexOf( self.window.tabInit )
		# tabParent.setTabText( idx, 'Init Script <%s>' % state.name )
		# idx = tabParent.indexOf( self.window.tabRender )
		# tabParent.setTabText( idx, 'Render Script <%s>' % state.name )

	def onScriptModified( self ):
		self.scriptModifyFlag = 1

	def checkScript( self ):
		if self.scriptModifyFlag == 0:
			self.canvas.safeCallMethod(
				'preview',
				'updateScript',
				self.window.textScriptInit.toPlainText(),
				self.window.textScriptRender.toPlainText()
			 )
		if self.scriptModifyFlag >= 0:
			self.scriptModifyFlag -= 1

	def onPropertyChanged( self, obj, field, value ):
		if field == 'name':
			self.tree.refreshNodeContent( obj )
			if obj == self.editingState:
				self.refreshScriptTitle()
		else:
			self.canvas.safeCallMethod( 'preview', 'update', obj, field, value )

	def onTool( self, tool ):
		if tool.name == 'update':
			if self.editingAsset:
				self.canvas.safeCallMethod( 'preview', 'rebuildSystem' )

		elif tool.name == 'add_state':
			if self.editingAsset:
				stConfig = self.canvas.safeCallMethod( 'preview', 'addState' )
				if stConfig:
					self.tree.addNode( stConfig )
					self.tree.selectNode( stConfig )
					self.tree.editNode( stConfig )

		elif tool.name == 'add_emitter':
			if self.editingAsset:
				emConfig = self.canvas.safeCallMethod( 'preview', 'addEmitter' )
				if emConfig:
					self.tree.addNode( emConfig )
					self.tree.selectNode( emConfig )
					self.tree.editNode( emConfig )

		elif tool.name == 'remove':
			pass

		elif tool.name == 'save':
			self.saveAsset()

		elif tool.name == 'start_preview':
			self.canvas.safeCallMethod( 'preview', 'startPreview' )

		elif tool.name == 'stop_preview':
			self.canvas.safeCallMethod( 'preview', 'stopPreview' )

##----------------------------------------------------------------##
class ParticleTreeWidget( GenericTreeWidget ):
	def getHeaderInfo( self ):
		return [ ('Name', -1) ]

	def getRootNode( self ):
		return self.module

	def saveTreeStates( self ):
		pass

	def loadTreeStates( self ):
		pass

	def getNodeParent( self, node ): # reimplemnt for target node
		if node == self.module:
			return None

		if node == self.module.editingConfig:
			return self.module

		if node in [ self.module.emitters, self.module.states ]:
			return self.module.editingConfig

		clas = node.getClassName( node )
		if clas == 'ParticleEmitterConfig':
			return self.module.emitters

		if clas == 'ParticleStateConfig':
			return self.module.states

		return node.parent

	def getNodeChildren( self, node ):
		config = self.module.editingConfig
		if node == self.module:
			if config:
				return [ config ]
			else:
				return []

		if node == config:
			return [ self.module.emitters, self.module.states ] #virtual nodes

		if node == self.module.emitters:
			return [ item for item in config.emitters.values() ]

		if node == self.module.states:
			return [ item for item in config.states.values() ]

		return []

	def updateItemContent( self, item, node, **option ):
		if node == self.module: return

		if node == self.module.emitters:
			item.setText( 0, 'Emitters' )
			item.setIcon( 0, getIcon('folder') )
		elif node == self.module.states:
			item.setText( 0, 'States' )
			item.setIcon( 0, getIcon('folder') )
		elif node == self.module.editingConfig:
			item.setText( 0, 'Particle System' )
			item.setIcon( 0, getIcon('particle') )
		elif node.getClassName( node ) in [ 'ParticleEmitterConfig', 'ParticleStateConfig' ]:
			item.setText( 0, node.name )
			item.setIcon( 0, getIcon('obj') )
		else:
			item.setText( 0, '' )
			item.setIcon( 0, getIcon('obj') )

	def onItemSelectionChanged(self):
		for selection in self.getSelection():
			self.module.changeSelection( selection )
			break

	def onItemChanged( self, item, col ):
		node = self.getNodeByItem( item )
		# app.getModule('layer_manager').changeLayerName( layer, item.text(0) )

	# def onItemActivated( self, item, col ):
	# 	node = self.getNodeByItem( item )
	# 	if isinstance( node, _LuaObject ):
	# 		clas = node.getClassName( node )
	# 		if clas == 'ParticleStateConfig':
	# 			self.module.changeState( node )
	# 		elif clas == 'ParticleEmitterConfig':
	# 			self.module.canvas.safeCallMethod( 'preview', 'activateEmitter', node )
##----------------------------------------------------------------##

##----------------------------------------------------------------##

ParticleEditor().register()
##----------------------------------------------------------------##


text:
export * from './src/component/date-format.component';
export * from './src/component/mat/mat-date-format.component';
export * from './src/mock/date-format.model.mock';
export * from './src/mock/date-format.validator.mock';
export * from './src/model/date-format.enum';
export * from './src/model/date-format.model';
export * from './src/validator/date-format.validator';
export * from './src/module';


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin.Testing;
using Swashbuckle.Application;
using Xunit;

namespace Microsoft.Azure.Mobile.Server.Swagger.Test
{
    public class SwaggerUiConfigExtensionsTests
    {
        [Fact]
        public async Task SwaggerUiDocs()
        {
            // Arrange
            TestServer server = SwashbuckleHelper.CreateSwaggerServer(null, c =>
            {
                c.MobileAppUi();
            });

            string o2cExpected = GetResourceString("Microsoft.Azure.Mobile.Server.Swagger.o2c.html");
            string oauthExpected = GetResourceString("Microsoft.Azure.Mobile.Server.Swagger.swagger-oauth.js");

            // Act
            var o2cResponse = await server.HttpClient.GetAsync("http://localhost/swagger/ui/o2c-html");
            var oauthResponse = await server.HttpClient.GetAsync("http://localhost/swagger/ui/lib/swagger-oauth-js");

            string o2c = await o2cResponse.Content.ReadAsStringAsync();
            string oauth = await oauthResponse.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(o2cExpected, o2c);
            Assert.Equal(oauthExpected, oauth);
        }

        [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This code is resilient to this scenario")]
        private static string GetResourceString(string resourceName)
        {
            string resourceText;

            using (Stream stream = typeof(SwaggerUiConfigExtensions).Assembly.GetManifestResourceStream(resourceName))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    resourceText = reader.ReadToEnd();
                }
            }

            return resourceText;
        }
    }
}


text:
<?php

$l['forum_management'] = "Gestion du forum";
$l['forum_management_desc'] = "Cette section vous permet de gérer les sections et les forums. Vous pouvez gérer les permissions de forum et également les modérateurs assignés à un forum. Si vous modifiez l'ordre d'affichage d'un ou plusieurs forums ou sections, assurez-vous de soumettre le formulaire au bas de cette page.";
$l['add_forum'] = "Ajouter un forum";
$l['add_forum_desc'] = "Ici vous pouvez ajouter un nouveau forum ou une nouvelle section. Vous pouvez aussi en définir les permissions initiales.";
$l['copy_forum'] = "Copier le forum";
$l['copy_forum_desc'] = "Ici vous pouvez copier les paramètres ou les permissions d'un forum existant vers un autre ou vers un nouveau forum.";
$l['forum_permissions'] = "Permissions";
$l['forum_permissions_desc'] = "Ici vous pouvez modifier toutes les permissions d'un groupe individuel pour un forum unique";
$l['view_forum'] = "Voir le forum";
$l['view_forum_desc'] = "Ici vous pouvez voir les sous-forums, éditer rapidement les permissions et ajouter des modérateurs à votre forum.";
$l['add_child_forum'] = "Ajouter un sous-forum";
$l['edit_forum_settings'] = "Éditer les paramètres du forum";
$l['edit_forum_settings_desc'] = "Ici vous pouvez éditer les paramètres et les permissions d'un forum existant.";
$l['edit_forum'] = "Éditer le forum";
$l['edit_mod'] = "Éditer un modérateur";
$l['edit_mod_desc'] = "Ici vous pouvez modifier les paramètres d'un modérateur particulier.";
$l['forum_moderators'] = "Modérateurs du forum";
$l['forum_permissions2'] = "Permissions du forum";
$l['more_subforums'] = "et {1} davantage.";

$l['manage_forums'] = "Gérer les forums";
$l['forum'] = "Forum";
$l['order'] = "Ordre";

$l['edit_forum'] = "Éditer forum";
$l['subforums'] = "Sous-forums";
$l['moderators'] = "Modérateurs";
$l['permissions'] = "Permissions";
$l['add_child_forum'] = "Ajouter un sous-forum";
$l['delete_forum'] = "Supprimer forum";

$l['sub_forums'] = "Sous-forums";
$l['update_forum_orders'] = "Enregistrer l'ordre des forums";
$l['update_forum_permissions'] = "Enregistrer les permissions du forum";
$l['reset'] = "Réinitialiser";
$l['in_forums'] = "Forums dans \"{1}\"";
$l['forum_permissions_in'] = "Permissions du forum \"{1}\"";
$l['moderators_assigned_to'] = "Modérateurs assignés à \"{1}\"";
$l['edit_permissions'] = "Éditer les permissions";
$l['set_permissions'] = "Définir les permissions";
$l['using_custom_perms'] = "Utiliser les permissions personnalisées";
$l['using_default_perms'] = "Utiliser les permissions par défaut";
$l['clear_custom_perms'] = "Effacer les permissions personnalisées";
$l['set_custom_perms'] = "Attribuer les permissions personnalisées";

$l['permissions_use_group_default'] = "Utiliser les paramètres par défaut du groupe";
$l['permissions_group'] = "Groupe";
$l['permissions_canview'] = "Peut voir ?";
$l['permissions_canpostthreads'] = "Peut poster des messages ?";
$l['permissions_canpostreplys'] = "Peut poster des réponses ?";
$l['permissions_canpostpolls'] = "Peut poster des sondages ?";
$l['permissions_canuploadattachments'] = "Peut uploader des pièces jointes ?";
$l['permissions_all'] = "Tout ?";

$l['overview_allowed_actions'] = "Vue d'ensemble: des actions permises";
$l['overview_disallowed_actions'] = "Vue d'ensemble: des actions non permises";
$l['perm_drag_canview'] = "• Vue";
$l['perm_drag_canpostthreads'] = "• Discussions";
$l['perm_drag_canpostreplys'] = "• Réponses";
$l['perm_drag_canpostpolls'] = "• Sondages";
$l['moderator_permissions'] = "Permissions modérateur";
$l['forum_desc'] = "Forum que le modérateur gère.";
$l['edit_mod_for'] = "Éditer les options de modération de \"{1}\"";
$l['can_edit_posts'] = "Peut éditer les messages ?";
$l['can_delete_posts'] = "Peut supprimer les messages ?";
$l['can_view_ips'] = "Peut voir les IPs ?";
$l['can_open_close_threads'] = "Peut ouvrir/fermer les discussions ?";
$l['can_manage_threads'] = "Peut gérer les discussions (diviser, déplacer, copier, fusionner) ?";
$l['can_move_to_other_forums'] = "Peut déplacer les discussions vers un autre forum que cet utilisateur ne peut pas modérer ?";
$l['save_mod'] = "Enregistrer le modérateur";

$l['no_forums'] = "Aucun forum n'a été trouvé.";
$l['no_moderators'] = "Aucun modérateur n'a été trouvé.";

$l['success_forum_disporder_updated'] = "Mise à jour des ordres d'affichage du forum réussie.";
$l['success_forum_deleted'] = "Suppression du forum sélectionné réussie.";
$l['success_moderator_deleted'] = "Suppression du modérateur sélectionné réussie.";
$l['success_forum_permissions_updated'] = "Mise à jour des permissions du forum réussie.";
$l['success_forum_updated'] = "Mise à jour des paramètres du forum réussie.";
$l['success_moderator_updated'] = "Mise à jour du modérateur sélectionné réussie.";
$l['success_custom_permission_cleared'] = "Les permissions personnalisées pour ce forum ont été efacées.";

$l['error_invalid_forum'] = "Sélectionnez un forum valide.";
$l['error_invalid_moderator'] = "Sélectionnez un modérateur valide à supprimer.";
$l['error_invalid_fid'] = "ID Forum sélectionné invalide.";
$l['error_forum_parent_child'] = "Vous ne pouvez pas définir comme parent de ce forum un de ses propres sous-forums.";
$l['error_forum_parent_itself'] = "Le forum parent ne peut pas être le forum lui-même.";
$l['error_incorrect_moderator'] = "Sélectionnez un modérateur valide.";

$l['confirm_moderator_deletion'] = "Êtes-vous sûr de vouloir supprimer ce modérateur de ce forum ?";
$l['confirm_forum_deletion'] = "Êtes-vous sûr de vouloir supprimer ce forum ?";
$l['confirm_clear_custom_permission'] = "Êtes-vous sûr de vouloir effacer cette permission personnalisée ?";

$l['create_a'] = "Créer un";
$l['create_a_desc'] = "Sélectionnez le type de forum que vous créez - un forum où on peut poster, ou une section qui contient d'autres forums.";
$l['forum'] = "Forum";
$l['category'] = "Section";
$l['title'] = "Titre";
$l['description'] = "Description";
$l['save_forum'] = "Enregistrer le forum";
$l['parent_forum'] = "Forum parent";
$l['parent_forum_desc'] = "Le forum qui contient ce forum. Les sections n'ont pas de forum parent - dans ce cas, sélectionnez 'Aucun' - cependant, les sections peuvent être définies comme ayant un forum parent.";
$l['none'] = "Aucun";
$l['display_order'] = "Ordre d'affichage";

$l['show_additional_options'] = "Afficher les options supplémentaires";
$l['hide_additional_options'] = "Cacher les options supplémentaires";
$l['additional_forum_options'] = "Options supplémentaires du forum";
$l['forum_link'] = "Lien du forum";
$l['forum_link_desc'] = "Pour faire un forum de redirection vers un autre emplacement, entrez l'URL de destination vers laquelle vous voulez rediriger. L'entrée d'une URL dans ce champ supprimera la fonctionnalité du forum; cependant, les permissions y resteront définies.";
$l['forum_password'] = "Mot de passe du forum";
$l['forum_password_desc'] = "Pour protéger davantage ce forum, vous pouvez choisir un mot de passe qui devra être entré pour y accéder. Note : Les groupes d'utilisateurs ont encore besoin des permissions d'accès à ce forum.";
$l['access_options'] = "Options d'accès";
$l['forum_is_active'] = "Le forum est actif ?";
$l['forum_is_active_desc'] = "Si désélectionné, ce forum ne sera pas montré aux utilisateurs et n'\"existera\" pas.";
$l['forum_is_open'] = "Le forum est ouvert ?";
$l['forum_is_open_desc'] = "Si désélectionné, les utilisateurs ne seront pas en mesure de participer au forum, indépendamment des permissions.";

$l['copy_to_new_forum'] = "Copier vers un nouveau forum";
$l['source_forum'] = "Forum source";
$l['source_forum_desc'] = "Forum où récupérer les paramètres et/ou permissions.";
$l['destination_forum'] = "Forum de destination";
$l['destination_forum_desc'] = "Forum où copier les paramètres et/ou permissions.";
$l['new_forum_settings'] = "Paramètres du nouveau forum";
$l['copy_settings_and_properties'] = "Copier paramètres et propriétés forum";
$l['copy_settings_and_properties_desc'] = "Ne s'applique que si le forum destination existe.";
$l['copy_user_group_permissions'] = "Copier permissions groupe utilisateur";
$l['copy_user_group_permissions_desc'] = "Utilisez CTRL pour sélectionner plusieurs groupes.";

$l['moderation_options'] = "Options de modération";
$l['mod_new_posts'] = "Oui, modérer nouveaux messages";
$l['mod_new_threads'] = "Oui, modérer nouvelles discussions";
$l['mod_new_attachments'] = "Oui, modérer nouvelles pièces jointes";
$l['mod_after_edit'] = "Oui, modérer après édition";
$l['override_user_style'] = "Oui, ignorer le style sélectionné de l'utilisateur";
$l['style_options'] = "Options style";
$l['forum_specific_style'] = "Style spécifique au forum :";
$l['use_default'] = "Utiliser défaut";
$l['dont_display_rules'] = "Ne pas afficher les règles pour ce forum";
$l['display_rules_inline'] = "Affichage des règles pour ce forum dans le listing de la discussion";
$l['display_rules_link'] = "Afficher un lien sur les règles pour ce forum";
$l['display_method'] = "Méthode d'affichage :";
$l['rules'] = "Règles :";
$l['forum_rules'] = "Règles du forum";
$l['name'] = "Nom";
$l['username'] = "Nom d'utilisateur";
$l['moderator_username_desc'] = "Le nom d'utilisateur du modérateur à ajouter";
$l['add_user_as_moderator'] = "Ajouter un modérateur";
$l['usergroup'] = "Groupe d'utilisateurs";
$l['add_usergroup_as_moderator'] = "Ajouter un groupe d'utilisateurs comme modérateurs";
$l['moderator_usergroup_desc'] = "Titre du groupe d'utilisateurs à ajouter";
$l['add_usergroup_moderator'] = "Ajouter un modérateur de groupe d'utilisateurs";
$l['add_user_moderator'] = "Ajouter Modérateur(s)";

$l['default_view_options'] = "Options de visualisation par défaut";
$l['default_date_cut'] = "Date limite par défaut :";
$l['default_sort_by'] = "Tri par défaut :";
$l['default_sort_order'] = "Ordre de Tri par défaut :";

$l['board_default'] = "Paramètres du forum";

$l['datelimit_1day'] = "Dernier jour";
$l['datelimit_5days'] = "5 derniers jours";
$l['datelimit_10days'] = "10 derniers jours";
$l['datelimit_20days'] = "20 derniers jours";
$l['datelimit_50days'] = "50 derniers jours";
$l['datelimit_75days'] = "75 derniers jours";
$l['datelimit_100days'] = "100 derniers jours";
$l['datelimit_lastyear'] = "Année dernière";
$l['datelimit_beginning'] = "Le début";

$l['sort_by_subject'] = "Titre des discussions";
$l['sort_by_lastpost'] = "Date du dernier message";
$l['sort_by_starter'] = "Créateur de la discussion";
$l['sort_by_started'] = "Date de création de la discussion";
$l['sort_by_rating'] = "Notation de la discussion";
$l['sort_by_replies'] = "Nombre de réponses";
$l['sort_by_views'] = "Nombre d'affichages";

$l['sort_order_asc'] = "Croissant";
$l['sort_order_desc'] = "Décroissant";

$l['misc_options'] = "Options diverses";
$l['allow_html'] = "Oui, autoriser le HTML";
$l['allow_mycode'] = "Oui, autoriser le MyCode";
$l['allow_smilies'] = "Oui, autoriser les smileys";
$l['allow_img_code'] = "Oui, autoriser les balises [img] (requiert que MyCode soit activé)";
$l['allow_video_code'] = "Oui, autoriser le code [video] dans les messages (requiert que MyCode soit activé)";
$l['allow_post_icons'] = "Oui, autoriser les icônes de message";
$l['allow_thread_ratings'] = "Oui, autoriser la notation des discussions";
$l['show_forum_jump'] = "Oui, voir dans le menu 'Aller à'";
$l['use_postcounts'] = "Oui, faire en sorte que les messages dans ce forum comptent dans les statistiques de messages d'utilisateurs";

$l['use_permissions'] = "Utiliser les permissions";
$l['use_permissions_desc'] = "Sélectionnez les permissions que vous voulez utiliser pour ce groupe d'utilisateurs - permissions héritées (supprime des permissions personnalisées) ou permissions personnalisées.";
$l['inherit_permissions'] = "Utiliser les permissions du groupe d'utilisateurs ou hériter les permissionqs des forums parents";
$l['custom_permissions'] = "Utiliser les permissions personnalisées (ci-dessus)";
$l['custom_permissions_for'] = "Permissions personnalisées pour";

$l['inherited_permission'] = "héritée";
$l['custom_permission'] = "personnalisée";
$l['save_permissions'] = "Enregistrer les permissions du forum ";

$l['error_missing_title'] = "Vous devez entrer un titre.";
$l['error_no_parent'] = "Vous devez sélectionner un forum parent.";
$l['error_not_empty'] = "Les forums avec des discussions ne peuvent être convertis en catégories.";

$l['success_forum_added'] = "Forum créé.";
$l['success_moderator_added'] = "Le modérateur a été ajouté à ce forum.";
$l['success_forum_permissions_saved'] = "Les permissions du forum ont été enregistrées.";
$l['success_forum_copied'] = "Le forum sélectionné a été copié.";

$l['error_moderator_already_added'] = "L'utilisateur/groupe sélectionné est déjà modérateur de ce forum.";
$l['error_moderator_not_found'] = "Le nom d'utilisateur/groupe n'a pas été trouvé.";
$l['error_new_forum_needs_name'] = "Vous devez donner un nom à votre forum.";
$l['error_invalid_source_forum'] = "Forum source invalide.";
$l['error_invalid_destination_forum'] = "Forum destination invalide.";

$l['group_viewing'] = "Regardant";
$l['group_posting_rating'] = "Postant/Notant";
$l['group_editing'] = "Éditant";
$l['group_polls'] = "Sondages";
$l['group_misc'] = "Divers";

$l['viewing_field_canview'] = "Peut voir le forum ?";
$l['viewing_field_canviewthreads'] = "Peut voir les discussions dans le forum ?";
$l['viewing_field_canonlyviewownthreads'] = "Peut uniquement voir ses propres discussions ?";
$l['viewing_field_candlattachments'] = "Peut télécharger les pièces jointes ?";

$l['posting_rating_field_canpostthreads'] = "Peut poster des discussions ?";
$l['posting_rating_field_canpostreplys'] = "Peut poster des réponses ?";
$l['posting_rating_field_canpostattachments'] = "Peut poster des pièces jointes ?";
$l['posting_rating_field_canratethreads'] = "Peut noter des discussions ?";

$l['editing_field_caneditposts'] = "Peut éditer ses propres messages ?";
$l['editing_field_candeleteposts'] = "Peut supprimer ses propres messages ?";
$l['editing_field_candeletethreads'] = "Peut supprimer ses propres discussions ?";
$l['editing_field_caneditattachments'] = "Peut éditer ses propres pièces jointes ?";

$l['polls_field_canpostpolls'] = "Peut poster des sondages ?";
$l['polls_field_canvotepolls'] = "Peut voter dans les sondages ?";

$l['misc_field_cansearch'] = "Peut rechercher dans le forum ?";

?>


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Documentz.DTOs;
using Microsoft.AspNetCore.Mvc;
using Documentz.Models;
using Documentz.Services;

namespace Documentz.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class StoredItemController : Controller
    {
        private IStoredItemService StoredItemService { get; }

        public StoredItemController(IStoredItemService storedItemService) => StoredItemService = storedItemService;

        // GET: api/StoredItem
        [HttpGet]
        [ActionName("Get")]
        public async Task<IEnumerable<IStoredItem>> GetAsync()
        {
            return await StoredItemService.GetAllItemsAsync();
        }

        // GET: api/StoredItem/5
        [HttpGet("{id}", Name = "Get")]
        public async Task<IActionResult> GetAsync(string id)
        {
            IStoredItem storedItem = await StoredItemService.GetItemAsync(id);

            if (storedItem == null)
            {
                return NotFound();
            }
            return Ok(storedItem);
        }

        // POST: api/StoredItem
        [HttpPost(Name = "Post")]
        public async Task<IActionResult> PostAsync([FromBody]StoredItemDTO item)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var createdItem = await StoredItemService.AddItemAsync(item);
            return Created($"/api/storeditem/{createdItem.Id}", createdItem);
        }

        // PUT: api/StoredItem/5
        [HttpPut("{id}", Name = "Put")]
        public async Task<IActionResult> PutAsync(string id, [FromBody]StoredItemDTO value)
        {
            await StoredItemService.UpdateItemAsync(id, value);
            return Ok();
        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}", Name = "Delete")]
        public async void DeleteAsync(string id)
        {
            await StoredItemService.DeleteItemAsync(id);
        }
    }
}