text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using OpenTK.Graphics.OpenGL;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using SFGraphics.GLObjects.Textures;
using SFGraphics.GLObjects.Textures.TextureFormats;

namespace SmashForge
{
    public class Formats
    {
        public enum BNTXImageFormat
        {
            IMAGE_FORMAT_INVALID = 0x0,
            IMAGE_FORMAT_R8_G8_B8_A8 = 0x0b,
            IMAGE_FORMAT_R5_G6_B5 = 0x07,
            IMAGE_FORMAT_R8 = 0x02,
            IMAGE_FORMAT_R8_G8 = 0x09,
            IMAGE_FORMAT_BC1 = 0x1a,
            IMAGE_FORMAT_BC2 = 0x1b,
            IMAGE_FORMAT_BC3 = 0x1c,
            IMAGE_FORMAT_BC4 = 0x1d,
            IMAGE_FORMAT_BC5 = 0x1e,
            IMAGE_FORMAT_BC6 = 0x1f,
            IMAGE_FORMAT_BC7 = 0x20,
        };

        public enum BNTXImageTypes
        {
            UNORM = 0x01,
            SNORM = 0x02,
            SRGB = 0x06,
        };

        public static uint blk_dims(uint format)
        {
            switch (format)
            {
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC1:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC2:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC3:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC4:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC5:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC6:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC7:
                case 0x2d:
                    return 0x44;

                case 0x2e: return 0x54;
                case 0x2f: return 0x55;
                case 0x30: return 0x65;
                case 0x31: return 0x66;
                case 0x32: return 0x85;
                case 0x33: return 0x86;
                case 0x34: return 0x88;
                case 0x35: return 0xa5;
                case 0x36: return 0xa6;
                case 0x37: return 0xa8;
                case 0x38: return 0xaa;
                case 0x39: return 0xca;
                case 0x3a: return 0xcc;

                default: return 0x11;
            }
        }

        public static uint bpps(uint format)
        {
            switch (format)
            {
                case (uint)BNTXImageFormat.IMAGE_FORMAT_R8_G8_B8_A8: return 4;
                case (uint)BNTXImageFormat.IMAGE_FORMAT_R8: return 1;

                case (uint)BNTXImageFormat.IMAGE_FORMAT_R5_G6_B5:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_R8_G8:
                    return 2;

                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC1:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC4:
                    return 8;

                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC2:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC3:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC5:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC6:
                case (uint)BNTXImageFormat.IMAGE_FORMAT_BC7:
                case 0x2e:
                case 0x2f:
                case 0x30:
                case 0x31:
                case 0x32:
                case 0x33:
                case 0x34:
                case 0x35:
                case 0x36:
                case 0x37:
                case 0x38:
                case 0x39:
                case 0x3a:
                    return 16;
                default: return 0x00;
            }
        }
    }

    public class BNTX : TreeNode
    {
        //Todo: Have these 2 combined into one list
        public List<BRTI> textures = new List<BRTI>(); //For loading a list of texture instances
        public Dictionary<string, Texture> glTexByName = new Dictionary<string, Texture>();
        int BRTIOffset;

        public static int temp; //This variable is so we can get offsets from start of BNTX file
        public static byte[] BNTXFile = new byte[0];
        public string target;

        BntxEditor Editor;

        public BNTX() //Binary Texture Container
        {
            ImageKey = "nut";
            SelectedImageKey = "nut";

            ContextMenu = new ContextMenu();
            MenuItem export = new MenuItem("Export");
            ContextMenu.MenuItems.Add(export);
            export.Click += Export;
            MenuItem replace = new MenuItem("Replace");
            ContextMenu.MenuItems.Add(replace);
            replace.Click += Replace;
            MenuItem edit = new MenuItem("Edit");
            ContextMenu.MenuItems.Add(edit);
            edit.Click += OpenEditor;
        }

        private void Export(object sender, EventArgs args)
        {

            BNTX bn = this;

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "textures.bntx";

            sfd.Filter =
                    "Supported Formats|*.bntx;|" +
                    "All files(*.*)|*.*";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllBytes(sfd.FileName, BNTXFile);
            }
        }

        private void Replace(object sender, EventArgs args)
        {
            BNTX bn = this;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter =
                    "Supported Formats|*.bntx;|" +
                    "All files(*.*)|*.*";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                byte[] newBntx = File.ReadAllBytes(ofd.FileName);

                FileData f = new FileData(newBntx);
                f.endian = Endianness.Little;

                bn.Nodes.Clear();
                bn.Read(f);
            }
        }

        private void OpenEditor(object sender, EventArgs args)
        {
            Editor = new BntxEditor(this);
            Editor.Text = Parent.Text + "\\" + Text;
            MainForm.Instance.AddDockedControl(Editor);
        }
        public void ReadBNTXFile(string data) //For single BNTX files
        {
            FileData f = new FileData(data);
            f.endian = Endianness.Little;

            Read(f);
        }
        public void ReadBNTXFile(byte[] data) //For single BNTX files
        {
            FileData f = new FileData(data);
            f.endian = Endianness.Little;

            Read(f);
        }

        public void RefreshGlTexturesByName()
        {
            glTexByName.Clear();

            foreach (BRTI tex in Nodes)
            {
                Texture2D tex2d = BRTI.CreateTexture2D(tex.texture);
                tex.texture.display = tex2d;
                tex.display = tex.texture.display;

                glTexByName.Add(tex.Text, tex2d);

            }
        }

        public void Read(FileData f)
        {
            textures.Clear();

            BFRES b = new BFRES();

            temp = f.Pos();

            f.Skip(8); //Magic
            int Version = f.ReadInt();
            int ByteOrderMark = f.ReadShort();
            int FormatRevision = f.ReadShort();
            Text = f.ReadString(f.ReadInt() + temp, -1);
            f.Skip(2);
            int strOffset = f.ReadShort();
            int relocOffset = f.ReadInt();
            int FileSize = f.ReadInt();
            target = f.ReadString(f.Pos(), 4); //NX
            f.Skip(4);
            int TexturesCount = f.ReadInt();
            int InfoPtrsOffset = f.ReadInt();
            int DataBlockOffset = f.ReadInt();
            int DictOffset = f.ReadInt();
            int strDictSize = f.ReadInt();

            Text = Text + ".bntx";

            BNTXFile = f.GetSection(temp, FileSize);

            for (int i = 0; i < TexturesCount; i++)
            {
                f.Seek(InfoPtrsOffset + temp + i * 8);
                BRTIOffset = f.ReadInt();

                f.Seek(BRTIOffset + temp);

                //  textures.Add(new BRTI(f));
                BRTI texture = new BRTI();
                texture.Read(f, this);

                textures.Add(texture);

            }
            Nodes.AddRange(textures.ToArray());
        }
        public void Save()
        {

            foreach (BRTI info in textures)
            {
                TegraX1Swizzle.Surface surf = info.surf;

                int alignment = 0;

                if (surf.tileMode == 1)
                    alignment = 1;
                else
                    alignment = 512;

                uint blk_dim = Formats.blk_dims(surf.format >> 8);
                uint blkWidth = blk_dim >> 4;
                uint blkHeight = blk_dim & 0xF;

                uint bpp = Formats.bpps(surf.format >> 8);

                for (int y = 0; y < info.texture.mipmaps.Count; ++y)
                {

                }

                for (int y = 0; y < info.texture.mipmaps.Count; ++y)
                {

                }
            }
        }
    }

    public class BRTI : TreeNode //Binary Texture Info
    {
        public TegraX1Swizzle.Surface surf;

        public BRTI_Texture texture = new BRTI_Texture();
        public byte DataType;
        public byte[] result_;

        public int Width, Height;
        public Texture display;
        public uint format;
        public uint blkWidth, blkHeight, bpp;

        public override string ToString()
        {
            return Text;
        }

        public void Read(FileData f, BNTX bntx) //Docs thanks to AboodXD!!
        {
            ImageKey = "texture";
            SelectedImageKey = "texture";

            f.Skip(4);

            int BRTISize1 = f.ReadInt();
            long BRTISize2 = f.ReadInt64();
            surf = new TegraX1Swizzle.Surface();
            ushort Flags = (ushort)f.ReadShort();
            surf.dim = (sbyte)f.ReadByte();
            surf.tileMode = (sbyte)f.ReadByte();
            surf.swizzle = (ushort)f.ReadShort();
            surf.numMips = (ushort)f.ReadShort();
            uint numSamples = (uint)f.ReadInt();
            surf.format = (uint)f.ReadInt();
            DataType = (byte)(surf.format & 0xFF);
            uint accessFlags = (uint)f.ReadInt();
            surf.width = f.ReadInt();
            surf.height = f.ReadInt();
            surf.depth = f.ReadInt();
            int FaceCount = f.ReadInt();
            surf.sizeRange = f.ReadInt();
            uint unk38 = (uint)f.ReadInt();
            uint unk3C = (uint)f.ReadInt();
            uint unk40 = (uint)f.ReadInt();
            uint unk44 = (uint)f.ReadInt();
            uint unk48 = (uint)f.ReadInt();
            uint unk4C = (uint)f.ReadInt();
            surf.imageSize = f.ReadInt();
            surf.alignment = f.ReadInt();
            int ChannelType = f.ReadInt();
            int TextureType = f.ReadInt();
            Text = f.ReadString((int)f.ReadInt64() + BNTX.temp + 2, -1);
            long ParentOffset = f.ReadInt64();
            long PtrsOffset = f.ReadInt64();

            format = surf.format;

            surf.data = new List<byte[]>();

            uint blk_dim = Formats.blk_dims(surf.format >> 8);
            blkWidth = blk_dim >> 4;
            blkHeight = blk_dim & 0xF;

            f.Seek((int)PtrsOffset + BNTX.temp);
            long firstMipOffset = f.ReadInt64();
            surf.data.Add(f.GetSection((int)firstMipOffset + BNTX.temp, surf.imageSize));
            for (int mipLevel = 1; mipLevel < surf.numMips; mipLevel++)
            {
                long dataOff = f.ReadInt64();
                surf.data.Add(f.GetSection((int)dataOff + BNTX.temp, (int)firstMipOffset + surf.imageSize - (int)dataOff));
                //    Debug.WriteLine($"{Name} Height {surf.height}wdith = {surf.width}allignment = {surf.alignment}blkwidth = {blkWidth}blkheight = {blkHeight}blkdims = {blk_dim} format = {surf.format} datatype = {DataType} dataoffset = {dataOff}");
            }
            bpp = Formats.bpps(surf.format >> 8);

            int target = 0;
            if (bntx.target == "NX  ")
                target = 1;

            int blockHeightLog2 = surf.sizeRange & 7;

            int linesPerBlockHeight = (1 << blockHeightLog2) * 8;
            int blockHeightShift = 0;

            for (int mipLevel = 0; mipLevel < surf.numMips; mipLevel++)
            {
                uint width = (uint)Math.Max(1, surf.width >> mipLevel);
                uint height = (uint)Math.Max(1, surf.height >> mipLevel);

                uint size = TegraX1Swizzle.DIV_ROUND_UP(width, blkWidth) * TegraX1Swizzle.DIV_ROUND_UP(height, blkHeight) * bpp;

                if (TegraX1Swizzle.pow2_round_up(TegraX1Swizzle.DIV_ROUND_UP(height, blkWidth)) < linesPerBlockHeight)
                    blockHeightShift += 1;

                byte[] result = TegraX1Swizzle.deswizzle(width, height, blkWidth, blkHeight, target, bpp, (uint)surf.tileMode, (uint)surf.alignment, Math.Max(0, blockHeightLog2 - blockHeightShift), surf.data[mipLevel], 0);
                //Create a copy and use that to remove uneeded data
                result_ = new byte[size];
                Array.Copy(result, 0, result_, 0, size);
                texture.mipmaps.Add(result_);
            }

            LoadFormats(texture, surf.format, 0, surf.width, surf.height);

            texture.width = surf.width;
            texture.height = surf.height;

            Width = surf.width;
            Height = surf.height;
        }

        private void LoadFormats(BRTI_Texture texture, uint format, int mipLevel, int width, int height)
        {
            switch (format >> 8)
            {
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_BC1):
                    texture.pixelInternalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt1Ext;
                    break;
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_BC2):
                    if (DataType == (byte)Formats.BNTXImageTypes.UNORM)
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt3Ext;
                    else if (DataType == (byte)Formats.BNTXImageTypes.SRGB)
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedSrgbAlphaS3tcDxt3Ext;
                    else
                        throw new Exception("Unsupported data type for BC2");
                    break;
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_BC3):
                    if (DataType == (byte)Formats.BNTXImageTypes.UNORM)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt5Ext;
                    }
                    else if (DataType == (byte)Formats.BNTXImageTypes.SRGB)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedSrgbAlphaS3tcDxt5Ext;
                    }
                    else
                        throw new Exception("Unsupported data type for BC3");
                    break;
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_BC4):
                    if (DataType == (byte)Formats.BNTXImageTypes.UNORM)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedRedRgtc1;
                    }
                    else if (DataType == (byte)Formats.BNTXImageTypes.SNORM)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedSignedRedRgtc1;
                    }
                    else
                        throw new Exception("Unsupported data type for BC4");
                    break;
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_BC5):
                    if (DataType == (byte)Formats.BNTXImageTypes.UNORM)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedRgRgtc2;
                    }
                    else if (DataType == (byte)Formats.BNTXImageTypes.SNORM)
                    {
                        //    texture.pixelInternalFormat = PixelInternalFormat.CompressedRgRgtc2;

                        byte[] fixBC5 = DDS_Decompress.DecompressBC5(texture.mipmaps[mipLevel], width, height, true);
                        texture.mipmaps[mipLevel] = fixBC5;
                        texture.pixelInternalFormat = PixelInternalFormat.Rgba;
                        texture.pixelFormat = OpenTK.Graphics.OpenGL.PixelFormat.Rgba;
                    }
                    else
                        Console.WriteLine("Unsupported data type for BC5");
                    break;
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_BC7):
                    if (DataType == (byte)Formats.BNTXImageTypes.UNORM || DataType == (byte)Formats.BNTXImageTypes.SRGB)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.CompressedRgbaBptcUnorm;
                    }
                    break;
                case ((uint)Formats.BNTXImageFormat.IMAGE_FORMAT_R8_G8_B8_A8):
                    if (DataType == (byte)Formats.BNTXImageTypes.UNORM || DataType == (byte)Formats.BNTXImageTypes.SRGB)
                    {
                        texture.pixelInternalFormat = PixelInternalFormat.Rgba;
                        texture.pixelFormat = OpenTK.Graphics.OpenGL.PixelFormat.Rgba;
                    }
                    else
                        throw new Exception("Unsupported data type for R8_G8_B8_A8");
                    break;
            }
        }
        public class BRTI_Texture
        {
            public List<byte[]> mipmaps = new List<byte[]>();
            public int width, height;
            public Texture display;
            public PixelInternalFormat pixelInternalFormat;
            public OpenTK.Graphics.OpenGL.PixelFormat pixelFormat;
            public int mipMapCount; //temp till i add mip maps.
            public PixelType pixelType = PixelType.UnsignedByte;

        }

        public static Texture2D CreateTexture2D(BRTI_Texture tex, int surfaceIndex = 0)
        {
            bool compressedFormatWithMipMaps = SFGraphics.GLObjects.Textures.TextureFormats.TextureFormatTools.IsCompressed(tex.pixelInternalFormat);

            if (compressedFormatWithMipMaps)
            {
                if (tex.mipMapCount > 1)
                {
                    Texture2D texture = new Texture2D();
                    texture.LoadImageData(tex.width, tex.height, tex.mipmaps,
                        (InternalFormat)tex.pixelInternalFormat);
                    return texture;
                }
                else
                {
                    // Only load the first level and generate the rest.
                    Texture2D texture = new Texture2D();
                    texture.LoadImageData(tex.width, tex.height, tex.mipmaps[0], (InternalFormat)tex.pixelInternalFormat);
                    return texture;
                }
            }
            else
            {
                // Uncompressed.
                Texture2D texture = new Texture2D();
                texture.LoadImageData(tex.width, tex.height, tex.mipmaps[0],
                    new TextureFormatUncompressed(tex.pixelInternalFormat, tex.pixelFormat, tex.pixelType));
                return texture;
            }
        }

        public static int LoadBitmap(Bitmap image)
        {
            int texID = GL.GenTexture();

            GL.BindTexture(TextureTarget.Texture2D, texID);

            BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
                OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

            image.UnlockBits(data);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, 2);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

            return texID;
        }

        public unsafe void ExportAsImage(BRTI_Texture t, Texture tex, string path)
        {
            Bitmap bitmap = new Bitmap(t.width, t.height);
            System.Drawing.Imaging.BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, t.width, t.height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            tex.Bind();
            GL.GetTexImage(TextureTarget.Texture2D, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0);

            bitmap.UnlockBits(bitmapData);
            bitmap.Save(path);
        }
    }

}


text:
package org.draegisoft.sonny.test

import org.draegisoft.sonny._

import java.io._

import org.scalatest._

import scala.util.parsing.input.CharSequenceReader

import TestValues._

class CssParserSpec extends CssParser with FlatSpecLike with Matchers{

  "The parser" should "parse valid css correctly" in {
    implicit val parserToTest = parseCss
    parsing(testCss) should equal (testSheet)
  }

  private def assertFail[T](input: String)(implicit p: Parser[T]) = {
    an [IllegalArgumentException] should be thrownBy { parsing(input)(p)}
  }

  private def parsing[T](s: String)(implicit p: Parser[T]): T = {
    val phraseParser = phrase(p)
    val input = new CharSequenceReader(s)

    phraseParser(input) match {
      case Success(t, _) => t
      case NoSuccess(msg, _) =>
        throw new IllegalArgumentException(
          "Could not parse '%s'%n%s".format(s,msg)
        )
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package gw.internal.gosu.ir.transform.statement;

import gw.internal.gosu.parser.statements.ContinueStatement;
import gw.internal.gosu.ir.transform.TopLevelTransformationContext;
import gw.lang.ir.IRStatement;
import gw.lang.ir.statement.IRContinueStatement;

/**
 */
public class ContinueStatementTransformer extends AbstractStatementTransformer<ContinueStatement>
{
  public static IRStatement compile( TopLevelTransformationContext cc, ContinueStatement stmt )
  {
    ContinueStatementTransformer gen = new ContinueStatementTransformer( cc, stmt );
    return gen.compile();
  }

  private ContinueStatementTransformer( TopLevelTransformationContext cc, ContinueStatement stmt )
  {
    super( cc, stmt );
  }

  @Override
  protected IRStatement compile_impl()
  {
    return new IRContinueStatement();
  }
}


text:
function TestFile() {}

TestFile.prototype = new Entity();

TestFile.prototype.getSaveText = function() {
  // First line is file description
  var descr = this.getPageDescription();

  return (descr !== undefined ? descr : "") + "\n" +
        $("#osbitools .test_file_name").html().replace(/
/g, "\n");
};

/**
 * Load entity metadata into GUI
 * Use this.data variable to access loaded data
 *
 */
TestFile.prototype.onLoadData = function() {
  // First line is description
  var pos = this.data.entity.indexOf("\n");

  // Check if last quotes in place
  var idx = this.data.entity.charAt(this.data.entity.length - 1) == '"' ? 1 : 0;
  this.setPageDescription(this.data.entity.substr(idx, pos));

  // Trim first and last double quotes
  this.initBodyCtx(this.data.entity.substring(pos + 1,
                          this.data.entity.length - idx));
  this.showEntityPropWin();

  return true;
};

TestFile.prototype.onBodyInit = function(src) {
  this.url = src;
  this.initBodyCtx(this.dname + ":" + get_file_name_from_url(src));

  return true;
};

TestFile.prototype.initBodyCtx = function(msg) {
  var me = this;
  this.body_ctx.html('
' +
                    msg.replace(/\n/g, "
") + '
');

  var text = $("#osbitools .test_file_name");

  // Add drag&drop for body context
  this.body_ctx.droppable({
    drop: function(event, ui) {
      if (!WEB_APP.base.DST_HANDLED)
        return false;
      me.appendBodyCtx(text, WEB_APP.base.DST_SRC);
      text.removeClass("dotted-border-ready");
      text.addClass("dotted-border");
    },
    over: function(event, ui) {
      if (WEB_APP.base.DST_HANDLED) {
        text.removeClass("dotted-border");
        text.addClass("dotted-border-ready");
      }
    },
    out: function() {
      if (WEB_APP.base.DST_HANDLED) {
        text.removeClass("dotted-border-ready");
        text.addClass("dotted-border");
      }
    }
  });
};

TestFile.prototype.appendBodyCtx = function(text, src) {
  text.html(text.html() + "
" +
                this.dname + ":" + get_file_name_from_url(src));

  this.clearSaved(true);
  return true;
};

TestFile.prototype.onPreview = function(url, name, params) {
  alert(ts("LL_HAS_NO_PREVIEW"));
};


text:
import cookie from 'react-cookie'
import ReactTooltip from 'react-tooltip'

const toggleShowAdminLinks = (setCookie = true) => (dispatch, getState) => {
  if (setCookie) {
    if (!getState().liveAdmin.showAdminLinks) {
      cookie.save('liveAdminShowAdminLinks', 1, { path: '/' })
    }
    else {
      cookie.remove('liveAdminShowAdminLinks', { path: '/' })
    }
  }
  setTimeout(() => ReactTooltip.rebuild(), 0)
  dispatch({
    type: 'TOGGLE_SHOW_ADMIN_LINKS'
  })
}

export default toggleShowAdminLinks


text:
package hu.diveino.droid.model.database;

import hu.diveino.droid.util.TypeConverter;

public class LogbookEntry {

    private Integer numberOfDives;
    private Integer loggedDiveHours;
    private Integer loggedDiveMinutes;
    private Double maxDepth;
    private String lastDiveDateTime;    //yyyy-MM-dd HH:mm

    private String lastDiveDate;        //yyyy-MM-dd
    private String lastDiveTime;        //HH:mm

    public LogbookEntry(Integer numberOfDives,
                        Integer loggedDiveHours, Integer loggedDiveMinutes,
                        Double maxDepth, String lastDiveDateTime) {

        this.numberOfDives = numberOfDives;
        this.loggedDiveHours = loggedDiveHours;
        this.loggedDiveMinutes = loggedDiveMinutes;
        this.maxDepth = maxDepth;
        this.lastDiveDateTime = lastDiveDateTime;

        this.lastDiveDate = "";
        this.lastDiveTime = "";
        if (this.lastDiveDateTime != null) {
            String[] splitDiveDateTime = this.lastDiveDateTime.split(" ");
            if (splitDiveDateTime.length >= 2) {
                this.lastDiveDate = splitDiveDateTime[0];
                this.lastDiveTime = splitDiveDateTime[1];
            }
        }
    }

    public Integer getNumberOfDives() {
        return numberOfDives;
    }

    public String getNumberOfDivesText() {
        return TypeConverter.convertIntegerToText(this.numberOfDives);
    }

    public Integer getLoggedDiveHours() {
        return loggedDiveHours;
    }

    public String getLoggedDiveHoursText() {
        return TypeConverter.convertIntegerToTwoCharacterText(this.loggedDiveHours);
    }

    public Integer getLoggedDiveMinutes() {
        return loggedDiveMinutes;
    }

    public String getLoggedDiveMinutesText() {
        return TypeConverter.convertIntegerToTwoCharacterText(this.loggedDiveMinutes);
    }

    public Double getMaxDepth() {
        return maxDepth;
    }

    public String getMaxDepthText() {
        return TypeConverter.convertDoubleToText(this.maxDepth);
    }

    public String getLastDiveDateTime() {
        return lastDiveDateTime;
    }

    public String getLastDiveDate() {
        return lastDiveDate;
    }

    public String getLastDiveTime() {
        return lastDiveTime;
    }
}


text:
def prompt(message)
  puts "=> #{message}"
end

def valid_number?(input)
  /\d/.match(input) && /^\d*\.?\d*$/.match(input)
end

def another_calculation?
  loop do
    answer = gets.chomp.downcase
    break true if %w(y yes).include?(answer)
    break false if %w(n no).include?(answer)
    prompt("Please enter 'y' or 'n'.")
  end
end

# def valid_number?(num)
prompt "Welcome to Mortgage Calculator. Please enter your name:"

name = ''
loop do
  name = gets.chomp
  if name.empty?
    prompt "Make sure to use a valid name."
  else
    break
  end
end

prompt "Hi #{name}!"

prompt <<-MSG
To calculate your fixed monthly repayment amount, we need the following details:

(1) The loan amount;
(2) The Annual Percentage Rate; and
(3) The loan duration

Let's get started!
MSG

loop do # main loop
  # Loan Amount
  loan_amt = ''
  loop do
    prompt "Please enter your loan amount (in dollars):"
    loan_amt = gets.chomp
    if valid_number?(loan_amt)
      break
    else
      prompt "Not a valid loan amount. Please try again."
    end
  end

  loan_amt = loan_amt.to_f

  # Annual Percentage Rate
  apr = ''
  loop do
    prompt "Please enter the Annual Percentage Rate (APR) (in %)"
    apr = gets.chomp
    if valid_number?(apr)
      break
    else
      prompt "Not a valid APR. Please try again."
    end
  end

  mpr = apr.to_f / 12 / 100

  # Loan Duration
  loan_durn_yrs = ''
  loop do
    prompt "Please enter the loan duration (in years)"
    loan_durn_yrs = gets.chomp
    if valid_number?(loan_durn_yrs)
      break
    else
      prompt "Not a valid loan duration. Please try again."
    end
  end

  loan_durn_mths = loan_durn_yrs.to_i * 12
  mthly_rpt = loan_amt * (mpr * (1 + mpr)**loan_durn_mths) / \
              ((1 + mpr)**loan_durn_mths - 1)
  mthly_rpt_2dp = sprintf("%.2f", mthly_rpt)
  wkly_rpt =  loan_amt * (mpr * (1 + mpr)**loan_durn_mths) / \
              ((1 + mpr)**loan_durn_mths - 1)
  wkly_rpt_2dp = sprintf("%.2f", wkly_rpt * 12 / 52)

  prompt "Calculating your interest repayment..."
  prompt <<-MSG
  Your fixed monthly repayment amount is:
  $#{mthly_rpt_2dp} per month; or
  $#{wkly_rpt_2dp} per week."
  MSG
  prompt("Perform another calculation? (y/n)")
  break unless another_calculation?
end

prompt "Thanks for using Mortgage Calculator. Good bye!"


text:
package org.dizitart.no2.exceptions;

/**
 * Exception thrown when a database security error occurs.
 *
 * @since 1.0
 * @author Anindya Chatterjee.
 */
public class SecurityException extends NitriteException {
    /**
     * Instantiates a new {@link SecurityException}.
     *
     * @param errorMessage the error message
     */
    public SecurityException(ErrorMessage errorMessage) {
        super(errorMessage);
    }
}


text:
<readable><title>661749711_6f408dad62</title><content>
A dog jumps to catch a red ball outside .
a small shaggy dog plays with a red ball on the grass .
A Yorkie trying to catch a red toy .
little dog is jumping up to catch a red ball in its mouth .
The dog jumps up to catch the red ball .
</content></readable>


text:
<?php

//$Id$

import('submission.trackDirector.TrackDirectorSubmission');

class DirectorSubmission extends TrackDirectorSubmission {

	/**
	 * Constructor.
	 */
	function DirectorSubmission() {
		parent::TrackDirectorSubmission();
	}
}

?>


text:
# Stepwise refinement of code
*Author: Kasper B. Graversen*
<ArticleHeaderUrls/><Categories Tags="Refactoring, Code_Readability">
</Categories>

*We all know that code left alone rot over time. Yet it is hard to get the time to solely change code for the purpose of changing it. And when you do get the time, it is hard to find the inclination and energy to really dig in.*

*A technique I often employ to accommodate these problems, is to step-wise refine the code while reading it during the implementation of change requests or adding features.*

Please show your support by sharing and voting:

<SocialShareButtons>
</SocialShareButtons>

Table of Content

   * [1. Introduction](#introduction)
   * [2. Hands on the code](#hands-on-the-code)
   * [3. Adding notes](#adding-notes)
   * [4. Removing notes](#removing-notes)
   * [5. Extract to private method repeatedly...](#extract-to-private-method-repeatedly)
   * [6. Extract to public method](#extract-to-public-method)
   * [7. Inline method](#inline-method)
   * [8. Conclusions](#conclusions)

## 1. Introduction

This article chronicles a real session of reading and step-wise refining a piece of code from the beginning.

 Let me stress, that the refinements are made in small and safe increments. Each of which denotes a safe place to stop. Safety is of utmost importance. When you are afraid of making change in the fear of breaking something, you refrain from making them.

Aside from safety, making changes in small increments has the added benefit, that you can be interrupted by say an emergency situation without much harm. Since the code is lefter better than it was, it can be shipped. We can always return to the code days or months later. With a half-done improvement left days or months is typically work lost. Certainly, it requires extra work, and possibly extra tests to ensure that nothing is broken.

## 2. Hands on the code

The other day I was grokking some code for the [StatePrinter project](https://github.com/kbilsted/StatePrinter). I was at a point where the internal circuitry  of the project was in need of rewiring due to new features.  I fell upon the following code which judging from the name, parameters and return type converts a `Type` into a list of fields. But is that really what the method is doing? This code is by no means magic, it is the bread-and-butter for project. Hence we are interested in proper naming and/or separation of concerns.

```
public List<SanitiedFieldInfo> GetFields(Type type)
{
    var fields = new HarvestHelper().GetFields(type);

    var res = new List<SanitiedFieldInfo>();
    foreach (var field in fields)
    {
        switch (field.FieldInfo.MemberType)
        {
            case MemberTypes.Field:
                if ((field.FieldInfo as FieldInfo).IsPublic)
                    res.Add(field);
                break;
            case MemberTypes.Property:
                var propertyInfo = (PropertyInfo) field.FieldInfo;
                if (propertyInfo.GetGetMethod(false) != null)
                    res.Add(field);
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
    return res.ToList();
}
```

After a one-pass trawl over the code, we realize that the method does two distinct things. It gets a list of fields from some reflection-wrapper, then filters away all non-public entries. After having read the code, the empty line between `fields` and `res`  (line 2 and 4) was a dead give-away of these two concerns.  While adding empty lines to show a switch of focus is best practice, it is not guaranteed that the next reader will have the same understanding - especially if he is not aware of that convention.

## 3. Adding notes

If I have difficulties reading code, maybe due to lack of experience with that part of the code base, or lack of domain knowledge, I sometimes add notes to the code. I annotate the code using comments with my first impression understanding as I go along. Now I don't want to document every single line, just highlight the main themes. This is meant as a light-weight process, I'm definitely not documenting parameters or whether a method may thrown an exception for example.  The result is:

```
public List<SanitiedFieldInfo> GetFields(Type type)
{
    var fields = new HarvestHelper().GetFields(type);

    // Filter
    var res = new List<SanitiedFieldInfo>();
    ...
}
```

Naturally, in a small piece of code like this, the number of concerns are limited. Only two things are going on. Gathering data, and filtering. Notice that I didn't bother inserting a comment for the first line. I find it hard to properly document a one-liner. If I ever feel the need to do so, I'd rather rename the method being called. Only document what is not self-explanatory.

Now, the story might as well end here. If we assume that my mental notes are correct, we have left the code a little better than how we found it. *"But we haven't changed anything"*, you argue. Well, to the compiler we didn't, but for the next reader of the code we did. We made clear to two sub processes of the method. And that has value.  Thinking about it, comments have some nice properties:

1. They are guaranteed not to change the behaviour of the code. Are you changing production code, or are you really close to a release deadline, likely you do not want to rock the boat unnecessarily.
2. They serve as excellent bookmarks for later refactorings (made by you or some other person).

Now, there are some pitfalls as well.

1. My notes could be wrong, after all they are my first impressions.
2. Later changes made to the code is not guaranteed change the documentation, this is especially true when merging in branches where there are no conflicts.
3. I value the principle of *"don't document the obvious"*, so avoid that

... This is why most of the time I don't stop here.

Let us pause for a moment reflect on our deeds. Are we cheating management by improving something we are not paid to improve? No. The time-consumer here is *not* inserting the comments or figuring out how to word them. It is to read and understand the logic of the code. Remember, code is read many times more often than (re-)written.

## 4. Removing notes
To best combat the problem of documentation gradually drifting from the code, we remove comment altogether!  One way to remove a comment this is to apply the "Extract method" refactoring pattern. Below we remove the comment `// filter` and replace it with a method `Filter()`.

```
public List<SanitiedFieldInfo> GetFields(Type type)
{
    var fields = new HarvestHelper().GetFields(type);

    return Filter(fields);
}
```
and this

```
List<SanitiedFieldInfo> Filter(List<SanitiedFieldInfo> fields)
{
    var res = new List<SanitiedFieldInfo>();
    foreach (var field in fields)
    {
        switch (field.FieldInfo.MemberType)
        {
            case MemberTypes.Field:
            ...
```

Applying the "Extract method" refactoring may not always be a viable solution. For example,  when the extracted method takes many arguments, say 8. In such cases, and depending on the source code layout, we may spend 8-10 lines calling the method, and a similar amount of lines on defining the parameter list of the function.  Assuming the code we are extracting to a method is less than 8 lines of code, we are replacing a one-liner comment with roughly 20 lines of code for the method call and the method definition. This may instead lead to cluttering the overview and hurt readability.

Large classes is another example where the code does not lend itself to such refactorings. With a very large class, you now have to mentally juggle all the state and logic of the class along with only being able to read fragments of the code (a method). A first stab on such a code base, it is likely beneficial to separating the class into several classes.

Naturally, the rules here are not set in store. Once I was faced with code that had so many nested scopes that extracting into methods was the only conceivable way to ensure that new requirements were added correctly. Go with your gut-feeling.

## 5. Extract to private method repeatedly...

Now that we have understood the overall motivation for the `Filter()` method, we can focus our mental energy on the `res` variable. Clearly it is the result of the execution since it is being returned. I've come to appreciate more and more, to extract the body of looping constructs. The reason being that we separate the traversal of steps from the execution in each step. Typically the two are unrelated.

This is somewhat comparable to why I favour using a `foreach` over a `for`. With the `foreach` I do not have to concern myself with the indexing variable. Is it modified in the loop body? Is it always incremented by 1? etc.

When we extract the method body we get

```
List<SanitiedFieldInfo> Filter(List<SanitiedFieldInfo> fields)
{
    var res = new List<SanitiedFieldInfo>();
    foreach (var field in fields)
        AddFieldIfPublic(field, res);

    return res;
}

void AddFieldIfPublic(SanitiedFieldInfo field, List<SanitiedFieldInfo> res)
{
    switch (field.FieldInfo.MemberType)
    {
        case MemberTypes.Field:
            if ((field.FieldInfo as FieldInfo).IsPublic)
               res.Add(field);
            break;
        case MemberTypes.Property:
          var propertyInfo = (PropertyInfo)field.FieldInfo;
          if (propertyInfo.GetGetMethod(false) != null)
             res.Add(field);
          break;
        default:
            throw new ArgumentOutOfRangeException();
    }
}
```

## 6. Extract to public method

We realize after further scrutiny that if there is a match, we add the current field to the `res` list. And that for each invocation of the method a maximum of one element (the field) is added. Hence it is a filter. We have a common pattern for doing filtering. It is called LINQ. There are three advantages by using LINQ in the code.

1. We use a common and easily recognizable implementation strategy. When people read `Where` they have a good idea as what is going on.
2. We are forced to separate out the "business logic" from the actual filtering (which is the reusable bit LINQ provides).
3. Without LINQ, we are free to perform any kind of changes to the list. With LINQ we are tied into just filtering.

This lock-in provides a lot of readability. The reader will never ponder *"what is going on in this loop, some advanced mutation I bet"*. With LINQ we have less freedom as to what we can do - ultimately  liberatting many potential detours in the readers mind.

The result is

```
List<SanitiedFieldInfo> Filter(List<SanitiedFieldInfo> fields)
{
    return fields.Where(IsPublic).ToList();
}

bool IsPublic(SanitiedFieldInfo field)
{
    switch (field.FieldInfo.MemberType)
    {
        case MemberTypes.Field:
            if ((field.FieldInfo as FieldInfo).IsPublic)
                return true;
            break;
        case MemberTypes.Property:
            var propertyInfo = (PropertyInfo)field.FieldInfo;
            if (propertyInfo.GetGetMethod(false) != null)
                return true;
            break;
        default:
          throw new ArgumentOutOfRangeException();
    }
    return false;
}
```

## 7. Inline method

Finally, we realize that the `Filter()` is a simple call to `Where` and hence we might as well apply the refactoring pattern "In-line method".

The final result is

```
public List<SanitiedFieldInfo> GetFields(Type type)
{
    var fields = new HarvestHelper().GetFields(type);

    return fields.Where(IsPublic).ToList();
}

bool IsPublic(SanitiedFieldInfo field)
{
    switch (field.FieldInfo.MemberType)
    {
        case MemberTypes.Field:
            if ((field.FieldInfo as FieldInfo).IsPublic)
                return true;
            break;
        case MemberTypes.Property:
            var propertyInfo = (PropertyInfo)field.FieldInfo;
            if (propertyInfo.GetGetMethod(false) != null)
                return true;
            break;
        default:
            throw new ArgumentOutOfRangeException();
    }
    return false;
}
```

## 8. Conclusions
The article in summary form

* By step-wise refining the code, we make the intentions of the code clearer.
* By constantly separating code into smaller parts we reduce the possibility of mistakes and enable reuse of code.
* We always seize the chance to in-line methods when we realize we have created too small methods.
* By using LINQ we boost readability.

Notice that we did not jump directly from the first version of the code to the last. By doing simple step-wise refinements, we ensure that each step is safe. Preferably, we take each step with automated tests as the safety net.

I hope you are inspired to do safe refactorings the next time you have to understand a tangled piece of code. Simple refactorings like these do not take a lot of time, and they make life for you easier as your understanding shapes the code. Also it makes it easier to next reader too. So everyone benefits.

A point we haven't touched upon is how distributed version control systems directly support this way of working. Every time we have completed a small step, we can issue a commit. Then, before pushing, we can combine the change sets into one. See `git reset --soft head~xx` or `hg combine xx` for further information on combining commits.

Please show your support by sharing and voting:
<SocialShareButtons>
</SocialShareButtons>

<CommentText>
</CommentText>


text:
class Ai: public ActorComponent
{
public:
	virtual void Act(Actor *owner) = 0;
	virtual ~Ai(){}
protected:
	Ai(const char *componentSecondaryType);
	const char* componentSecondaryType;
};

class PlayerControlledAi: public Ai
{
public:
	static const char *type;
	PlayerControlledAi(): Ai(type)
	{}
	~PlayerControlledAi(){}
	void Act(Actor *owner){}
};

#endif


text:
Для установки docker системы в linux mint можно использовать скрипт, приведенный ниже.
Его необходимо сохранить (например, script.sh).
Далее сделать файл скрипта исполняемым (если он еще таковым не является):
'chmod +x script.sh'
Запускаем скрипт, указывая путь до него:
'path/to/script.sh'
Если скрипт находится в текущей директории, то нужно указать ./ перед именем файла скрипта:
'./script.sh'
Можно запустить скрипт, непосредственно указывая интерпретатор sh:
'sh script.sh'

```
#!/usr/bin/env bash

# https://docs.docker.com/install/linux/docker-ce/ubuntu/
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable"
sudo apt-get update
sudo apt-get install docker-ce

# https://docs.docker.com/compose/install/
sudo curl -L https://github.com/docker/compose/releases/download/1.20.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

# https://docs.docker.com/install/linux/linux-postinstall/
sudo groupadd docker
sudo usermod -aG docker $USER
```

Актуальная версия скрипта [тут]:https://gist.github.com/dweldon/39ca0536168a92815a56df44eb55a337

Пример установки docker контейнера с postgres:

1. установка docker контейнера с postgres:
   `docker run --name some-postgres -e POSTGRES_PASSWORD=password -d postgres`

2. Вывести список запущенных контейнеров можно командой:
   `docker ps`
   После выполнения команды в консоли в столбце NAMES отображается имя контейнера "some-postgres"

3. Запуск консоли psql происходит следующей командой
   `docker exec -ti <имя контейнера> psql -U postgres`

После ввода команды появляется приглашение консоли psql


text:
function do_plot_unconditional_forecasts(mycast,m)

vnames=m.endogenous;

nvars=numel(vnames);

figure('name','unconditional forecasts');

for ivar=1:nvars

    subplot(nvars,1,ivar);

    plot(mycast.(vnames{ivar}),'linewidth',2);

    ylabel(vnames{ivar});

end

tmp=set([mycast.ygap mycast.pi mycast.FFR],'varnames',{'ygap','pi','FFR'});

disp('********** Unconditional forecasts ***********');
display(tmp)

end


text:
cask 'astropad-studio' do
  version '3.3.0'
  sha256 '55d6d08f5b70a1ffd89dd5864312bddc3c3df1784a848d0ba408dff1dec775fd'

  # s3.amazonaws.com/astropad.com was verified as official when first introduced to the cask
  url "https://s3.amazonaws.com/astropad.com/downloads/AstropadStudio-#{version}.dmg"
  appcast 'https://astropad.com/downloads/studio-sparkle.xml'
  name 'Astropad Studio'
  homepage 'https://astropad.com/'

  app 'Astropad Studio.app'

  uninstall quit: 'com.astro-hq.AstropadStudioMac'

  zap trash: [
               '~/Library/Caches/Astropad',
               '~/Library/Caches/com.astro-hq.AstropadStudioMac',
               '~/Library/Preferences/com.astro-hq.AstropadStudioMac.plist',
               '~/Library/Saved Application State/com.astro-hq.AstropadStudioMac.savedState',
             ]
end


text:
import { AutomatonWithGUI } from '../../AutomatonWithGUI';
import { BezierNode, FxDefinition, FxSection } from '@fms-cat/automaton';
import { ChannelStatusCode } from '../../ChannelWithGUI';
import { Action as ContextAction } from './store';
import { CurveStatusCode } from '../../CurveWithGUI';
import { GUISettings, defaultGUISettings } from '../../types/GUISettings';
import { Reducer } from 'redux';
import { Status } from '../../types/Status';
import { WithBypass } from '../../types/WithBypass';
import { WithID } from '../../types/WithID';
import { arraySetDelete } from '../utils/arraySet';
import { binarySearch } from '../utils/binarySearch';
import { jsonCopy } from '../../utils/jsonCopy';
import { produce } from 'immer';
import { reorderArray } from '../../utils/reorderArray';
import type { StateChannelItem } from '../../types/StateChannelItem';

// == state ========================================================================================
export interface State {
  instance?: AutomatonWithGUI;
  fxDefinitions: { [ name: string ]: FxDefinition };
  channelNames: string[];
  channels: {
    [ name: string ]: {
      value: number;
      length: number;
      status: Status<ChannelStatusCode> | null;
      items: { [ id: string ]: StateChannelItem };
      sortedItems: StateChannelItem[];
    };
  };
  curves: {
    [ name: string ]: {
      status: Status<CurveStatusCode> | null;
      length: number;
      path: string;
      nodes: { [ id: string ]: BezierNode & WithID };
      fxs: { [ id: string ]: FxSection & WithBypass & WithID };
    };
  };
  curvesPreview: {
    [ name: string ]: {
      time: number | null;
      value: number | null;
      itemTime: number | null;
      itemSpeed: number | null;
      itemOffset: number | null;
    };
  };
  labels: { [ name: string ]: number };
  loopRegion: { begin: number; end: number } | null;
  isPlaying: boolean;
  time: number;
  length: number;
  resolution: number;
  shouldSave: boolean;
  guiSettings: GUISettings;
}

export const initialState: Readonly<State> = {
  channelNames: [],
  channels: {},
  curves: {},
  curvesPreview: {},
  labels: {},
  loopRegion: null,
  fxDefinitions: {},
  isPlaying: false,
  time: 0.0,
  length: 1.0,
  resolution: 10.0,
  shouldSave: false,
  guiSettings: jsonCopy( defaultGUISettings )
};

// == action =======================================================================================
export type Action = {
  type: 'Automaton/SetInstance';
  automaton: AutomatonWithGUI;
} | {
  type: 'Automaton/AddFxDefinition';
  name: string;
  fxDefinition: FxDefinition;
} | {
  type: 'Automaton/CreateChannel';
  channel: string;
  index: number;
} | {
  type: 'Automaton/RemoveChannel';
  channel: string;
} | {
  type: 'Automaton/ReorderChannels';
  index: number;
  length: number;
  newIndex: number;
} | {
  type: 'Automaton/UpdateChannelValue';
  channel: string;
  value: number;
} | {
  type: 'Automaton/UpdateChannelLength';
  channel: string;
  length: number;
} | {
  type: 'Automaton/UpdateChannelStatus';
  channel: string;
  status: Status<ChannelStatusCode> | null;
} | {
  type: 'Automaton/UpdateChannelItem';
  channel: string;
  id: string;
  item: StateChannelItem;
} | {
  type: 'Automaton/RemoveChannelItem';
  channel: string;
  id: string;
} | {
  type: 'Automaton/CreateCurve';
  curveId: string;
  length: number;
  path: string;
} | {
  type: 'Automaton/RemoveCurve';
  curveId: string;
} | {
  type: 'Automaton/UpdateCurvePath';
  curveId: string;
  path: string;
} | {
  type: 'Automaton/UpdateCurveLength';
  curveId: string;
  length: number;
} | {
  type: 'Automaton/UpdateCurveStatus';
  curveId: string;
  status: Status<CurveStatusCode> | null;
} | {
  type: 'Automaton/UpdateCurvePreviewTimeValue';
  curveId: string;
  time: number;
  value: number;
  itemTime: number;
  itemSpeed: number;
  itemOffset: number;
} | {
  type: 'Automaton/UpdateCurveNode';
  curveId: string;
  id: string;
  node: BezierNode & WithID;
} | {
  type: 'Automaton/RemoveCurveNode';
  curveId: string;
  id: string;
} | {
  type: 'Automaton/UpdateCurveFx';
  curveId: string;
  id: string;
  fx: FxSection & WithBypass & WithID;
} | {
  type: 'Automaton/RemoveCurveFx';
  curveId: string;
  id: string;
} | {
  type: 'Automaton/UpdateCurveLength';
  curveId: string;
  length: number;
} | {
  type: 'Automaton/SetLabel';
  name: string;
  time: number;
} | {
  type: 'Automaton/DeleteLabel';
  name: string;
} | {
  type: 'Automaton/SetLoopRegion';
  loopRegion: { begin: number; end: number } | null;
} | {
  type: 'Automaton/UpdateIsPlaying';
  isPlaying: boolean;
} | {
  type: 'Automaton/UpdateTime';
  time: number;
} | {
  type: 'Automaton/ChangeLength';
  length: number;
} | {
  type: 'Automaton/ChangeResolution';
  resolution: number;
} | {
  type: 'Automaton/SetShouldSave';
  shouldSave: boolean;
} | {
  type: 'Automaton/UpdateGUISettings';
  settings: GUISettings;
};

// == reducer ======================================================================================
export const reducer: Reducer<State, ContextAction> = ( state = initialState, action ) => {
  return produce( state, ( newState: State ) => {
    if ( action.type === 'Reset' ) {
      newState.channelNames = [];
      newState.channels = {};
      newState.curves = {};
      newState.curvesPreview = {};
      newState.labels = {};
      newState.loopRegion = null;
      newState.fxDefinitions = {};
      newState.isPlaying = false;
      newState.time = 0.0;
      newState.length = 1.0;
      newState.resolution = 10.0;
      newState.shouldSave = false;
      newState.guiSettings = jsonCopy( defaultGUISettings );
    } else if ( action.type === 'Automaton/SetInstance' ) {
      newState.instance = action.automaton;
    } else if ( action.type === 'Automaton/AddFxDefinition' ) {
      newState.fxDefinitions[ action.name ] = action.fxDefinition;
    } else if ( action.type === 'Automaton/CreateChannel' ) {
      newState.channelNames.splice( action.index, 0, action.channel );

      newState.channels[ action.channel ] = {
        value: 0.0,
        length: 1.0,
        status: null,
        items: {},
        sortedItems: [],
      };
    } else if ( action.type === 'Automaton/RemoveChannel' ) {
      arraySetDelete( newState.channelNames, action.channel );
      delete newState.channels[ action.channel ];
    } else if ( action.type === 'Automaton/ReorderChannels' ) {
      reorderArray( newState.channelNames, action.index, action.length )( action.newIndex );
    } else if ( action.type === 'Automaton/UpdateChannelValue' ) {
      newState.channels[ action.channel ].value = action.value;
    } else if ( action.type === 'Automaton/UpdateChannelLength' ) {
      newState.channels[ action.channel ].length = action.length;
    } else if ( action.type === 'Automaton/UpdateChannelStatus' ) {
      newState.channels[ action.channel ].status = action.status;
    } else if ( action.type === 'Automaton/UpdateChannelItem' ) {
      let shouldInsert = false;
      const timeExisting = newState.channels[ action.channel ].items[ action.id ]?.time;

      if ( timeExisting == null ) {
        shouldInsert = true;
      } else {
        const indexExisting = binarySearch(
          newState.channels[ action.channel ].sortedItems,
          ( item ) => item.time < timeExisting
        );

        if ( timeExisting !== action.item.time ) {
          newState.channels[ action.channel ].sortedItems.splice( indexExisting, 1 );
          shouldInsert = true;
        } else {
          newState.channels[ action.channel ].sortedItems[ indexExisting ] = action.item;
        }
      }

      if ( shouldInsert ) {
        const indexToInsert = binarySearch(
          newState.channels[ action.channel ].sortedItems,
          ( item ) => item.time < action.item.time
        );
        newState.channels[ action.channel ].sortedItems.splice( indexToInsert, 0, action.item );
      }

      newState.channels[ action.channel ].items[ action.id ] = action.item;
    } else if ( action.type === 'Automaton/RemoveChannelItem' ) {
      const timeExisting = newState.channels[ action.channel ].items[ action.id ]?.time;

      if ( timeExisting != null ) {
        const indexToRemove = binarySearch(
          newState.channels[ action.channel ].sortedItems,
          ( item ) => item.time < timeExisting
        );
        newState.channels[ action.channel ].sortedItems.splice( indexToRemove, 1 );
      }

      delete newState.channels[ action.channel ].items[ action.id ];
    } else if ( action.type === 'Automaton/CreateCurve' ) {
      newState.curves[ action.curveId ] = {
        status: null,
        length: action.length,
        path: action.path,
        nodes: {},
        fxs: {}
      };
      newState.curvesPreview[ action.curveId ] = {
        time: null,
        value: null,
        itemTime: null,
        itemSpeed: null,
        itemOffset: null,
      };
    } else if ( action.type === 'Automaton/RemoveCurve' ) {
      delete newState.curves[ action.curveId ];
    } else if ( action.type === 'Automaton/UpdateCurvePath' ) {
      newState.curves[ action.curveId ].path = action.path;
    } else if ( action.type === 'Automaton/UpdateCurveLength' ) {
      newState.curves[ action.curveId ].length = action.length;
    } else if ( action.type === 'Automaton/UpdateCurveStatus' ) {
      newState.curves[ action.curveId ].status = action.status;
    } else if ( action.type === 'Automaton/UpdateCurvePreviewTimeValue' ) {
      newState.curvesPreview[ action.curveId ].time = action.time;
      newState.curvesPreview[ action.curveId ].value = action.value;
      newState.curvesPreview[ action.curveId ].itemTime = action.itemTime;
      newState.curvesPreview[ action.curveId ].itemSpeed = action.itemSpeed;
      newState.curvesPreview[ action.curveId ].itemOffset = action.itemOffset;
    } else if ( action.type === 'Automaton/UpdateCurveNode' ) {
      newState.curves[ action.curveId ].nodes[ action.id ] = jsonCopy( action.node );
    } else if ( action.type === 'Automaton/RemoveCurveNode' ) {
      delete newState.curves[ action.curveId ].nodes[ action.id ];
    } else if ( action.type === 'Automaton/UpdateCurveFx' ) {
      newState.curves[ action.curveId ].fxs[ action.id ] = jsonCopy( action.fx );
    } else if ( action.type === 'Automaton/RemoveCurveFx' ) {
      delete newState.curves[ action.curveId ].fxs[ action.id ];
    } else if ( action.type === 'Automaton/SetLabel' ) {
      newState.labels[ action.name ] = action.time;
    } else if ( action.type === 'Automaton/DeleteLabel' ) {
      delete newState.labels[ action.name ];
    } else if ( action.type === 'Automaton/SetLoopRegion' ) {
      newState.loopRegion = action.loopRegion;
    } else if ( action.type === 'Automaton/UpdateIsPlaying' ) {
      newState.isPlaying = action.isPlaying;
    } else if ( action.type === 'Automaton/UpdateTime' ) {
      newState.time = action.time;
    } else if ( action.type === 'Automaton/ChangeLength' ) {
      newState.length = action.length;
    } else if ( action.type === 'Automaton/ChangeResolution' ) {
      newState.resolution = action.resolution;
    } else if ( action.type === 'Automaton/SetShouldSave' ) {
      newState.shouldSave = action.shouldSave;
    } else if ( action.type === 'Automaton/UpdateGUISettings' ) {
      newState.guiSettings = action.settings;
    }
  } );
};


text:
/**
 * Autogenerated by Thrift Compiler (0.9.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

namespace Apache.Cassandra
{
  ///
  /// The ConsistencyLevel is an enum that controls both read and write
  /// behavior based on the ReplicationFactor of the keyspace.  The
  /// different consistency levels have different meanings, depending on
  /// if you're doing a write or read operation.
  ///
  /// If W + R > ReplicationFactor, where W is the number of nodes to
  /// block for on write, and R the number to block for on reads, you
  /// will have strongly consistent behavior; that is, readers will
  /// always see the most recent write. Of these, the most interesting is
  /// to do QUORUM reads and writes, which gives you consistency while
  /// still allowing availability in the face of node failures up to half
  /// of <ReplicationFactor>. Of course if latency is more important than
  /// consistency then you can use lower values for either or both.
  ///
  /// Some ConsistencyLevels (ONE, TWO, THREE) refer to a specific number
  /// of replicas rather than a logical concept that adjusts
  /// automatically with the replication factor.  Of these, only ONE is
  /// commonly used; TWO and (even more rarely) THREE are only useful
  /// when you care more about guaranteeing a certain level of
  /// durability, than consistency.
  ///
  /// Write consistency levels make the following guarantees before reporting success to the client:
  ///   ANY          Ensure that the write has been written once somewhere, including possibly being hinted in a non-target node.
  ///   ONE          Ensure that the write has been written to at least 1 node's commit log and memory table
  ///   TWO          Ensure that the write has been written to at least 2 node's commit log and memory table
  ///   THREE        Ensure that the write has been written to at least 3 node's commit log and memory table
  ///   QUORUM       Ensure that the write has been written to <ReplicationFactor> / 2 + 1 nodes
  ///   LOCAL_QUORUM Ensure that the write has been written to <ReplicationFactor> / 2 + 1 nodes, within the local datacenter (requires NetworkTopologyStrategy)
  ///   EACH_QUORUM  Ensure that the write has been written to <ReplicationFactor> / 2 + 1 nodes in each datacenter (requires NetworkTopologyStrategy)
  ///   ALL          Ensure that the write is written to <ReplicationFactor> nodes before responding to the client.
  ///
  /// Read consistency levels make the following guarantees before returning successful results to the client:
  ///   ANY          Not supported. You probably want ONE instead.
  ///   ONE          Returns the record obtained from a single replica.
  ///   TWO          Returns the record with the most recent timestamp once two replicas have replied.
  ///   THREE        Returns the record with the most recent timestamp once three replicas have replied.
  ///   QUORUM       Returns the record with the most recent timestamp once a majority of replicas have replied.
  ///   LOCAL_QUORUM Returns the record with the most recent timestamp once a majority of replicas within the local datacenter have replied.
  ///   EACH_QUORUM  Returns the record with the most recent timestamp once a majority of replicas within each datacenter have replied.
  ///   ALL          Returns the record with the most recent timestamp once all replicas have replied (implies no replica may be down)..
  ///
  public enum ConsistencyLevel
  {
    ONE = 1,
    QUORUM = 2,
    LOCAL_QUORUM = 3,
    EACH_QUORUM = 4,
    ALL = 5,
    ANY = 6,
    TWO = 7,
    THREE = 8,
  }
}


text:
local require = require

local canvas            = require "hs.canvas"

local fcp               = require "cp.apple.finalcutpro"
local i18n              = require "cp.i18n"

local mod = {}

--- plugins.finalcutpro.touchbar.widgets.zoom.widget() -> `hs._asm.undocumented.touchbar.item`
--- Function
--- The Widget
---
--- Parameters:
---  * None
---
--- Returns:
---  * A `hs._asm.undocumented.touchbar.item`
function mod.widget()

    local canvasWidth, canvasHeight = 250, 30

    local widgetCanvas = canvas.new{x = 0, y = 0, h = 30, w = canvasWidth}

    widgetCanvas[#widgetCanvas + 1] = {
        id               = "background",
        type             = "rectangle",
        action           = "strokeAndFill",
        strokeColor      = { white = 1 },
        fillColor        = { hex = "#1d1d1d", alpha = 1 },
        roundedRectRadii = { xRadius = 5, yRadius = 5 },
    }

    widgetCanvas[#widgetCanvas + 1] = {
        id                  = "startLine",
        type                = "segments",
        coordinates         = {
            {x = 0, y = canvasHeight/2},
            {x = canvasWidth / 2, y = canvasHeight/2} },
        action              = "stroke",
        strokeColor         = { hex = "#5051e7", alpha = 1 },
        strokeWidth         = 1.5,
    }

    widgetCanvas[#widgetCanvas + 1] = {
        id                  = "endLine",
        type                = "segments",
        coordinates         = {
            {x = canvasWidth / 2, y = canvasHeight/2},
            {x = canvasWidth, y = canvasHeight/2} },
        action              = "stroke",
        strokeColor         = { white = 1.0 },
        strokeWidth         = 1.5,
    }

    widgetCanvas[#widgetCanvas + 1] = {
        id                  = "circle",
        type                = "circle",
        radius              = 10,
        action              = "strokeAndFill",
        fillColor           = { hex = "#414141", alpha = 1 },
        strokeWidth         = 1.5,
        center              = { x = canvasWidth / 2, y = canvasHeight / 2 },
    }

    widgetCanvas:canvasMouseEvents(true, true, false, true)
        :mouseCallback(function(o,m,i,x,y) -- luacheck: ignore

            if not fcp.isFrontmost() or not fcp.timeline:isShowing() then return end

            widgetCanvas.circle.center = {
                x = x,
                y = canvasHeight / 2,
            }

            widgetCanvas.startLine.coordinates = {
                {x = 0, y = canvasHeight/2},
                {x = x, y = canvasHeight/2},
            }

            widgetCanvas.endLine.coordinates = {
                { x = x, y = canvasHeight / 2 },
                { x = canvasWidth, y = canvasHeight / 2 },
            }

            if m == "mouseDown" or m == "mouseMove" then
                local appearance = fcp.timeline.toolbar.appearance
                if appearance then
                    appearance:show().zoomAmount:setValue(x/(canvasWidth/10))
                end
            elseif m == "mouseUp" then
                local appearance = fcp.timeline.toolbar.appearance
                if appearance then
                    appearance:hide()
                end
            end
    end)

    mod.item = mod._manager.touchbar().item.newCanvas(widgetCanvas, "zoomSlider")
        :canvasClickColor{ alpha = 0.0 }

    return mod.item

end

--- plugins.finalcutpro.touchbar.widgets.zoom.init() -> nil
--- Function
--- Initialise the module.
---
--- Parameters:
---  * None
---
--- Returns:
---  * None
function mod.init(manager)
    mod._manager = manager

    local params = {
        group = "fcpx",
        text = i18n("zoomSlider"),
        subText = i18n("zoomSliderDescription"),
        item = mod.widget,
    }
    manager.widgets:new("zoomSlider", params)

    return mod

end

local plugin = {
    id              = "finalcutpro.touchbar.widgets.zoom",
    group           = "finalcutpro",
    dependencies    = {
        ["core.touchbar.manager"] = "manager",
    }
}

function plugin.init(deps)
    --------------------------------------------------------------------------------
    -- Only load plugin if Final Cut Pro is supported:
    --------------------------------------------------------------------------------
    if not fcp:isSupported() then return end

    local manager = deps.manager
    if manager.supported() then
        return mod.init(manager)
    end
end

return plugin


text:
package php.runtime.lang.exception;

import php.runtime.Memory;
import php.runtime.annotation.Reflection;
import php.runtime.annotation.Reflection.BaseType;
import php.runtime.annotation.Reflection.Final;
import php.runtime.annotation.Reflection.Name;
import php.runtime.annotation.Reflection.Signature;
import php.runtime.common.HintType;
import php.runtime.common.Modifier;
import php.runtime.env.Environment;
import php.runtime.exceptions.support.ErrorType;
import php.runtime.lang.BaseException;
import php.runtime.lang.exception.BaseBaseException;
import php.runtime.memory.LongMemory;
import php.runtime.reflection.ClassEntity;

@BaseType
@Name("Error")
@Signature(root = true, value =
        {
                @Reflection.Arg(value = "message", modifier = Modifier.PROTECTED, type = HintType.STRING),
                @Reflection.Arg(value = "code", modifier = Modifier.PROTECTED, type = HintType.INT),
                @Reflection.Arg(value = "previous", modifier = Modifier.PROTECTED, type = HintType.OBJECT),
                @Reflection.Arg(value = "trace", modifier = Modifier.PRIVATE, type = HintType.ARRAY),
                @Reflection.Arg(value = "file", modifier = Modifier.PROTECTED, type = HintType.STRING),
                @Reflection.Arg(value = "line", modifier = Modifier.PROTECTED, type = HintType.INT),
                @Reflection.Arg(value = "position", modifier = Modifier.PROTECTED, type = HintType.INT)
        }
)
public class BaseError extends BaseBaseException implements BaseThrowable {
    protected ErrorType errorType = ErrorType.E_CORE_ERROR;

    public BaseError(Environment env) {
        super(env);
    }

    public BaseError(Environment env, ErrorType errorType) {
        super(env);
        this.errorType = errorType;
    }

    public BaseError(Environment env, ClassEntity clazz) {
        super(env, clazz);
        errorType = ErrorType.E_ERROR;
    }

    @Signature
    public Memory getErrorType() {
        return LongMemory.valueOf(errorType.value);
    }

    @Signature({
            @Reflection.Arg(value = "message", optional = @Reflection.Optional(value = "", type = HintType.STRING)),
            @Reflection.Arg(value = "code", optional = @Reflection.Optional(value = "0", type = HintType.INT)),
            @Reflection.Arg(value = "previous", nativeType = BaseThrowable.class, optional = @Reflection.Optional(value = "NULL"))
    })
    public Memory __construct(Environment env, Memory... args) {
        clazz.refOfProperty(props, "message").assign(args[0].toString());
        if (args.length > 1)
            clazz.refOfProperty(props, "code").assign(args[1].toLong());

        if (args.length > 2)
            clazz.refOfProperty(props, "previous").assign(args[2]);

        return Memory.NULL;
    }

    @Final
    @Override
    @Signature
    public Memory getMessage(Environment env, Memory... args) {
        return super.getMessage(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getCode(Environment env, Memory... args) {
        return super.getCode(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getLine(Environment env, Memory... args) {
        return super.getLine(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getPosition(Environment env, Memory... args) {
        return super.getPosition(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getFile(Environment env, Memory... args) {
        return super.getFile(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getTrace(Environment env, Memory... args) {
        return super.getTrace(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getPrevious(Environment env, Memory... args) {
        return super.getPrevious(env, args);
    }

    @Override
    @Signature
    public Memory __toString(Environment env, Memory... args) {
        return super.__toString(env, args);
    }

    @Final
    @Override
    @Signature
    public Memory getTraceAsString(Environment env, Memory... args) {
        return super.getTraceAsString(env, args);
    }

    @Signature
    private Memory __clone(Environment env, Memory... args) {
        return Memory.NULL;
    }
}


text:
Now that Helm is installed and the repository has been added, install Workflow with a native ingress by running:

```
$ helm install deis/workflow --namespace deis --set global.experimental_native_ingress=true,controller.platform_domain=deis.com
```

Where `controller.platform_domain` is a **required** parameter that is traditionally not required for Workflow that is explained in the next section. In this example we are using `deis.com` for `$hostname`.

Helm will install a variety of Kubernetes resources in the `deis` namespace.
Wait for the pods that Helm launched to be ready. Monitor their status by running:

```
$ kubectl --namespace=deis get pods
```

You should also notice that several Kubernetes ingresses has been installed on your cluster. You can view it by running:

```
$ kubectl get ingress --namespace deis
```

Depending on the order in which the Workflow components initialize, some pods may restart. This is common during the
installation: if a component's dependencies are not yet available, that component will exit and Kubernetes will
automatically restart it.

Here, it can be seen that the controller, builder and registry all took a few loops waiting for minio before they were able to start:

```
$ kubectl --namespace=deis get pods
NAME                          READY     STATUS    RESTARTS   AGE
deis-builder-hy3xv            1/1       Running   5          5m
deis-controller-g3cu8         1/1       Running   5          5m
deis-database-rad1o           1/1       Running   0          5m
deis-logger-fluentd-1v8uk     1/1       Running   0          5m
deis-logger-fluentd-esm60     1/1       Running   0          5m
deis-logger-sm8b3             1/1       Running   0          5m
deis-minio-4ww3t              1/1       Running   0          5m
deis-registry-asozo           1/1       Running   1          5m
deis-workflow-manager-68nu6   1/1       Running   0          5m
```

## Install a Kubernetes Ingress Controller

Now that Workflow has been deployed with the `global.experimental_native_ingress` flag set to `true`, we will need a Kubernetes ingress controller in place to begin routing traffic.

Here is an example of how to use [traefik](https://traefik.io/) as an ingress controller for Workflow. Of course, you are welcome to use any controller you wish.

```
$ helm install stable/traefik --name ingress --namespace kube-system
```

## Configure DNS

The experimental ingress feature requires a user to set up a hostname, and assumes the `deis.$host` convention.

We need to point the `*.$host` record to the public IP address of your ingress controller. You can get the public IP using the following command. A wildcard entry is necessary here as apps will use the same rule after they are deployed.

```
$ kubectl get svc ingress-traefik --namespace kube-system
NAME              CLUSTER-IP   EXTERNAL-IP      PORT(S)                      AGE
ingress-traefik   10.0.25.3    138.91.243.152   80:31625/TCP,443:30871/TCP   33m
```

Additionally, we need to point the `deis-builder.$host` record to the public IP address of the [Builder][].

```
$ kubectl get svc deis-builder --namespace deis
NAME           CLUSTER-IP     EXTERNAL-IP     PORT(S)          AGE
deis-builder   10.0.165.140   40.86.182.187   2222:32488/TCP   33m
```

If we were using `deis.com` as a hostname, we would need to create the following A DNS records.

| Name                         | Type          | Value          |
| ---------------------------- |:-------------:| --------------:|
| *.deis.com                   | A             | 138.91.243.152 |
| deis-builder.deis.com        | A             | 40.86.182.187  |

Once all of the pods are in the `READY` state, and `deis.$host` resolves to the external IP found above, Workflow is up and running!

After installing Workflow, [register a user and deploy an application](../quickstart/deploy-an-app.md).

##### Feedback

While this feature is experimental we welcome feedback on the issue. We would like to learn more about use cases, and user experience. Please [open a new issue](https://github.com/deis/workflow/issues/new) for feedback.

[builder]: ../understanding-workflow/components.md#builder


text:
#import "SalesforceOAuthPlugin.h"
#import "CDVPlugin+SFAdditions.h"
#import <SalesforceSDKCore/SFJsonUtils.h>
#import <SalesforceSDKCore/SFUserActivityMonitor.h>
#import <SalesforceSDKCore/NSDictionary+SFAdditions.h>
#import <SalesforceSDKCore/SFAuthenticationManager.h>
#import <SalesforceSDKCore/SFSDKWebUtils.h>
#import "SFHybridViewController.h"

// ------------------------------------------
// Private methods interface
// ------------------------------------------
@interface SalesforceOAuthPlugin()

- (void)authenticate:(CDVInvokedUrlCommand*)command getCachedCredentials:(BOOL)getCachedCredentials;

/**
 Method to be called when the OAuth process completes.
 @param authDict The NSDictionary containing the authentication data.
 @param callbackId The plugin callback ID associated with the request.
 */
- (void)authenticationCompletion:(NSDictionary *)authDict callbackId:(NSString *)callbackId;

/**
 Creates an error dictionary to send back in an auth error case.
 @param error The OAuth error that occurred.
 @param authInfo The OAuth info associated with the auth attempt.
 @return An NSDictionary of error information.
 */
+ (NSDictionary *)authErrorDictionaryFromError:(NSError *)error authInfo:(SFOAuthInfo *)authInfo;

@end

// ------------------------------------------
// Main implementation
// ------------------------------------------
@implementation SalesforceOAuthPlugin

#pragma mark - Cordova plugin methods and helpers

- (void)getAuthCredentials:(CDVInvokedUrlCommand *)command
{
    [self log:SFLogLevelDebug format:@"getAuthCredentials: arguments: %@", command.arguments];
    /* NSString* jsVersionStr = */[self getVersion:@"getAuthCredentials" withArguments:command.arguments];
    [self authenticate:command getCachedCredentials:YES];
}

- (void)authenticate:(CDVInvokedUrlCommand*)command
{
    [self log:SFLogLevelDebug format:@"authenticate: arguments: %@", command.arguments];
    /* NSString* jsVersionStr = */[self getVersion:@"authenticate" withArguments:command.arguments];
    [self authenticate:command getCachedCredentials:NO];
}

- (void)logoutCurrentUser:(CDVInvokedUrlCommand *)command
{
    [self log:SFLogLevelDebug format:@"logoutCurrentUser: arguments: %@", command.arguments];
    /* NSString* jsVersionStr = */[self getVersion:@"logoutCurrentUser" withArguments:command.arguments];
    [[SFAuthenticationManager sharedManager] logout];
}

- (void)getAppHomeUrl:(CDVInvokedUrlCommand *)command
{
    [self log:SFLogLevelDebug format:@"getAppHomeUrl: arguments: %@", command.arguments];
    NSString* callbackId = command.callbackId;
    /* NSString* jsVersionStr = */[self getVersion:@"getAppHomeUrl" withArguments:command.arguments];
    NSURL *url = ((SFHybridViewController *)self.viewController).appHomeUrl;
    NSString *urlString = (url == nil ? @"" : [url absoluteString]);
    [self log:SFLogLevelDebug format:@"AppHomeURL: %@",urlString];
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:urlString];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}

- (void)authenticate:(CDVInvokedUrlCommand*)command getCachedCredentials:(BOOL)getCachedCredentials
{
    [self log:SFLogLevelDebug msg:@"authenticate:getCachedCredentials:"];
    NSString* callbackId = command.callbackId;
    SFOAuthPluginAuthSuccessBlock completionBlock = ^(SFOAuthInfo *authInfo, NSDictionary *authDict) {
        [self authenticationCompletion:authDict callbackId:callbackId];
    };
    SFOAuthFlowFailureCallbackBlock failureBlock = ^(SFOAuthInfo *authInfo, NSError *error) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                      messageAsDictionary:[[self class] authErrorDictionaryFromError:error authInfo:authInfo]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
    };

    SFHybridViewController *hybridVc = (SFHybridViewController *)self.viewController;
    if (getCachedCredentials) {
        [hybridVc getAuthCredentialsWithCompletionBlock:completionBlock failureBlock:failureBlock];
    } else {
        [hybridVc authenticateWithCompletionBlock:completionBlock failureBlock:failureBlock];
    }
}

+ (NSDictionary *)authErrorDictionaryFromError:(NSError *)error authInfo:(SFOAuthInfo *)authInfo
{
    NSMutableDictionary *authDict = [NSMutableDictionary dictionary];
    authDict[@"Domain"] = error.domain;
    authDict[@"Code"] = @(error.code);
    authDict[@"Description"] = error.localizedDescription;
    if ((error.userInfo)[@"error"] != nil)
        authDict[@"Type"] = (error.userInfo)[@"error"];
    authDict[@"AuthInfo"] = [authInfo description];
    return authDict;
}

#pragma mark - Salesforce.com login helpers

- (void)authenticationCompletion:(NSDictionary *)authDict callbackId:(NSString *)callbackId
{
    [self log:SFLogLevelDebug msg:@"authenticationCompletion: Authentication flow succeeded. Initiating post-auth configuration."];
    // Call back to the client with the authentication credentials.
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:authDict];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}

@end


text:
project="DOCES - Unity"

echo "Compilando $project para ambientes webGL"
/Applications/Unity/Unity.app/Contents/MacOS/Unity \
  -batchmode \
  -nographics \
  -silent-crashes \
  -logFile ${PWD}/unity.log \
  -projectPath "${PWD}/DOCES - Unity" \
  -buildTarget WebGL "${PWD}/Build/Web"  \
  -quit

  #-buildOSXUniversalPlayer "${PWD}/game.app" \

echo 'Logs do processo de compilacao'
cat ${PWD}/unity.log


text:
class BitVectorTest : public testing::Test {
 protected:
  // This function is called before each test.
  virtual void SetUp() {
  }

  // This function is called after each test.
  virtual void TearDown() {
  }
};

TEST_F(BitVectorTest, DefaultConstructor) {
  marisa2::grimoire::BitVector bit_vector;
  ASSERT_FALSE(static_cast<bool>(bit_vector));
  ASSERT_EQ(0U, bit_vector.size());
  ASSERT_EQ(0U, bit_vector.num_1s());
  ASSERT_EQ(0U, bit_vector.num_0s());
}

TEST_F(BitVectorTest, Map) {
  // TODO
}

TEST_F(BitVectorTest, Read) {
  // TODO
}

TEST_F(BitVectorTest, Write) {
  // TODO
}

TEST_F(BitVectorTest, PushBack) {
  marisa2::Error error;
  marisa2::grimoire::BitVector bit_vector;

  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  ASSERT_EQ(1U, bit_vector.size());

  error = bit_vector.push_back(false);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  ASSERT_EQ(2U, bit_vector.size());

  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  ASSERT_EQ(3U, bit_vector.size());

  ASSERT_TRUE(bit_vector[0]);
  ASSERT_FALSE(bit_vector[1]);
  ASSERT_TRUE(bit_vector[2]);
}

TEST_F(BitVectorTest, Build) {
  marisa2::Error error;
  marisa2::grimoire::BitVector bit_vector;

  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  error = bit_vector.push_back(false);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();

  error = bit_vector.build();
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  ASSERT_EQ(MARISA2_ENABLE_RANK, bit_vector.flags());

  ASSERT_EQ(2U, bit_vector.num_1s());
  ASSERT_EQ(1U, bit_vector.num_0s());

  ASSERT_EQ(bit_vector.num_1s(), bit_vector.rank_1(bit_vector.size()));
  ASSERT_EQ(bit_vector.num_0s(), bit_vector.rank_0(bit_vector.size()));
}

TEST_F(BitVectorTest, Rank) {
  marisa2::Error error;
  marisa2::grimoire::BitVector bit_vector;

  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  error = bit_vector.push_back(false);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();

  error = bit_vector.build();
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  ASSERT_EQ(MARISA2_ENABLE_RANK, bit_vector.flags());

  ASSERT_EQ(0U, bit_vector.rank_1(0));
  ASSERT_EQ(1U, bit_vector.rank_1(1));
  ASSERT_EQ(1U, bit_vector.rank_1(2));
  ASSERT_EQ(2U, bit_vector.rank_1(3));

  ASSERT_EQ(0U, bit_vector.rank_0(0));
  ASSERT_EQ(0U, bit_vector.rank_0(1));
  ASSERT_EQ(1U, bit_vector.rank_0(2));
  ASSERT_EQ(1U, bit_vector.rank_0(3));
}

TEST_F(BitVectorTest, Select) {
  marisa2::Error error;
  marisa2::grimoire::BitVector bit_vector;

  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  error = bit_vector.push_back(false);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  error = bit_vector.push_back(true);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();

  error = bit_vector.build(MARISA2_ENABLE_SELECT_1 | MARISA2_ENABLE_SELECT_0);
  ASSERT_EQ(MARISA2_NO_ERROR, error.code()) << error.message();
  ASSERT_EQ(MARISA2_ENABLE_RANK | MARISA2_ENABLE_SELECT_1 |
            MARISA2_ENABLE_SELECT_0, bit_vector.flags());

  // TODO
}


text:
<?php
class Users extends LGB_Controller {

	/**
	 * 出発させる
	 * @params
	 * @return
	 */
	public function questGo() {
		$data = array();

		$user_id = $this->input->get_post('user_id', TRUE);
		$quest_data = $this->input->get_post('quest_select', TRUE);
		$userData = new UserData();
		$userData->userQuestGo($user_id, $quest_data);

		// 更新したデータを返す
		$data = $userData->getUser($user_id);

                $this->output->set_output(json_encode($data));
                $this->output->_display();
		exit;
	}

	/**
	 * ユーザーデータ取得
	 * @param int (user_id)
	 * @return array (user data)
	 */
	public function getUserData(){
		$user_id = $this->input->get_post('id', TRUE);
		$user_data = new UserData();
		$data = $user_data->getUser($user_id);

		$this->output->set_output(json_encode($data));
		$this->output->_display();
		exit;
	}
}


text:
.. _tethys_settings_cmd:

settings command
****************

Customize the settings of the Tethys Portal.

.. argparse::
   :module: tethys_cli
   :func: tethys_command_parser
   :prog: tethys
   :path: settings