text:
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace au.util.comctl {
  public delegate void FolderChangedHandler(object sender);

  /// <summary>
  /// Folder selection control
  /// </summary>
  [ToolboxBitmap(typeof(FoldernameBox), "Properties.Resources.browseFolder.png")]
  public partial class FoldernameBox : UserControl {

    #region Events
    /// <summary>
    /// Triggered whenever a different folder is selected
    /// </summary>
    public event FolderChangedHandler Changed;
    #endregion  // Events

    #region Data Members
    private string _basepath;
    private bool _stripbase;
    private bool _limitbase;
    private bool _mustExist = true;
    #endregion  // Data Members

    #region Constructor
    public FoldernameBox() {
      InitializeComponent();
    }
    #endregion  // Constructor

    #region Properties
    /// <summary>
    /// Currently selected folder
    /// </summary>
    [Description("Currently selected folder"), Category("FoldernameBox")]
    public string FolderName {
      get { return _txtFoldername.Text; }
      set {
        if(value.Length == 0)
          _txtFoldername.Text = "";
        else {
          if(_stripbase) {
            if(_mustExist && !Directory.Exists(Path.Combine(_basepath, value)))
              throw new FolderNotFoundException(Path.Combine(_basepath, value));
          } else {
            if(_limitbase && !value.StartsWith(_basepath))
              throw new PathMismatchException(_basepath, value);
            if(_mustExist && !Directory.Exists(value))
              throw new FolderNotFoundException(value);
          }
          _txtFoldername.Text = value;
          if(!_txtFoldername.Text.EndsWith(@"\"))
            _txtFoldername.Text += @"\";
        }
        if(Changed != null)
          Changed(this);
      }
    }

    /// <summary>
    /// Full path to the currently selected folder
    /// </summary>
    [Description("Full path to the currently selected folder"), Category("FoldernameBox")]
    public string FolderFullName {
      get {
        if(_stripbase)
          return Path.Combine(_basepath, _txtFoldername.Text);
        return _txtFoldername.Text;
      }
      set {
        if(value.Length == 0)
          _txtFoldername.Text = "";
        else {
          if(_limitbase && !value.StartsWith(_basepath))
            throw new PathMismatchException(_basepath, value);
          if(_mustExist && !Directory.Exists(value))
            throw new FolderNotFoundException(value);
          if(_stripbase)
            _txtFoldername.Text = FolderStripBase(value);
          else
            _txtFoldername.Text = value;
          if(!_txtFoldername.Text.EndsWith(@"\"))
            _txtFoldername.Text += @"\";
        }
        if(Changed != null)
          Changed(this);
      }
    }

    /// <summary>
    /// Gets or sets an option that controls how automatic path completion works
    /// </summary>
    [Description("Gets or sets an option that controls how automatic path completion works"), Category("FilenameBox"), DefaultValue(AutoCompleteMode.None)]
    public AutoCompleteMode AutoCompleteMode {
      get { return _txtFoldername.AutoCompleteMode; }
      set { _txtFoldername.AutoCompleteSource = (_txtFoldername.AutoCompleteMode = value) == AutoCompleteMode.None ? AutoCompleteSource.None : AutoCompleteSource.FileSystemDirectories; }
    }

    /// <summary>
    /// True if only existing folders can be selected
    /// </summary>
    [Description("True if only existing folders can be selected"), Category("FoldernameBox")]
    public bool FolderMustExist {
      get { return _mustExist; }
      set { _mustExist = value; }
    }

    /// <summary>
    /// Starting point for folder selection
    /// </summary>
    [Description("Starting point for folder selection"), Category("FoldernameBox")]
    public string BasePath {
      get { return _basepath; }
      set {
        _basepath = value;
        if(_basepath == null)
          _basepath = "";
        if(_basepath.Length > 0 && !_basepath.EndsWith(@"\"))
          _basepath += @"\";
      }
    }

    /// <summary>
    ///
    /// </summary>
    [Description("Whether the base path should be displayed to the user and returned with the foldername property"), Category("FoldernameBox")]
    public bool StripBase {
      get { return _stripbase; }
      set {
        _stripbase = value;
        if(_stripbase)
          _limitbase = true;
      }
    }

    /// <summary>
    /// Whether the selection should be limited to folders within the base path
    /// </summary>
    [Description("Whether the selection should be limited to folders within the base path"), Category("FoldernameBox")]
    public bool LimitBase {
      get { return _limitbase; }
      set {
        if(!_stripbase)
          _limitbase = value;
      }
    }

    /// <summary>
    ///
    /// </summary>
    [Description("Text to display above the browse dialog"), Category("FoldernameBox")]
    public string Description {
      get { return _dlgFolderBrowse.Description; }
      set { _dlgFolderBrowse.Description = value; }
    }

    /// <summary>
    /// Gets or sets whether the button will appear flat
    /// </summary>
    [Description("Gets or sets whether the button will appear flat"), Category("Appearance")]
    public bool FlatButton {
      get { return _btnBrowse.FlatStyle == FlatStyle.Flat; }
      set { _btnBrowse.FlatStyle = value ? _btnBrowse.FlatStyle = FlatStyle.Flat : _btnBrowse.FlatStyle = FlatStyle.Standard; }
    }

    /// <summary>
    /// True when the selected folder exists
    /// </summary>
    [Browsable(false)]
    public bool FolderExists {
      get { return Directory.Exists(FolderFullName); }
    }
    #endregion  // Properties

    private string FolderStripBase(string path) {
      path = path.Substring(_basepath.Length);
      while(path.StartsWith(@"\"))
        path = path.Substring(1);
      return path;
    }

    #region Event Handlers
    private void _btnBrowse_Click(object sender, EventArgs e) {
      if(_txtFoldername.Text.Length > 0)
        if(_stripbase)
          _dlgFolderBrowse.SelectedPath = _basepath + _txtFoldername.Text;
        else
          _dlgFolderBrowse.SelectedPath = _txtFoldername.Text;
      else
        _dlgFolderBrowse.SelectedPath = _basepath;
      _dlgFolderBrowse.ShowDialog(this);
      if(_dlgFolderBrowse.SelectedPath != _basepath) {
        if(_stripbase)
          if(_dlgFolderBrowse.SelectedPath.StartsWith(_basepath))
            _txtFoldername.Text = _dlgFolderBrowse.SelectedPath.Substring(_basepath.Length);
          else
            throw new PathMismatchException(_basepath, _dlgFolderBrowse.SelectedPath);
        else
          _txtFoldername.Text = _dlgFolderBrowse.SelectedPath;
        if(!_txtFoldername.Text.EndsWith(@"\"))
          _txtFoldername.Text += @"\";
        if(Changed != null)
          Changed(this);
      }
    }

    private void _txtFoldername_Validating(object sender, System.ComponentModel.CancelEventArgs e) {
      string foldername = _txtFoldername.Text;
      if(foldername.Length > 0) {
        if(_stripbase)
          foldername = _basepath + foldername;
        else if(_limitbase && !_txtFoldername.Text.StartsWith(_basepath)) {
          MessageBox.Show(this, string.Format(Properties.Resources.PathMismatchMessageBoxMessage, BasePath), Properties.Resources.FoldernameBoxMessageBoxCaption);
          e.Cancel = true;
        }
        if(!e.Cancel && _mustExist && !Directory.Exists(foldername)) {
          MessageBox.Show(this, string.Format(Properties.Resources.FolderNotFoundMessageBoxMessage, foldername), Properties.Resources.FoldernameBoxMessageBoxCaption);
          e.Cancel = true;
        }
        if(!e.Cancel && !foldername.EndsWith(@"\"))
          _txtFoldername.Text += @"\";
      }
      if(Changed != null)
        Changed(this);
    }

    private void FoldernameBox_EnabledChanged(object sender, EventArgs e) {
      _txtFoldername.Enabled = _btnBrowse.Enabled = Enabled;
    }
    #endregion  // event handlers
  }
}


text:
function (createSrcGroups FILE_LIST )
  # we want to get the relative path from the
  # current source dir
  string(LENGTH ${CMAKE_CURRENT_SOURCE_DIR} curDirLen)
  set(TMP_FILE_LIST ${${FILE_LIST}})

  foreach ( SOURCE ${TMP_FILE_LIST} )
    string(LENGTH ${SOURCE} fullPathLen)
    math(EXPR RelPathLen ${fullPathLen}-${curDirLen})
    string(SUBSTRING ${SOURCE} ${curDirLen} ${RelPathLen} curStr)

    string ( REGEX REPLACE "[\\/]" "\\\\" normPath ${curStr} )
    string ( REGEX MATCH "\\\\(.*)\\\\" ouput ${normPath} )
    if(NOT CMAKE_MATCH_1 STREQUAL "")
      source_group ( ${CMAKE_MATCH_1} FILES ${SOURCE} )
    endif()
  endforeach()
endfunction()

####################################################################################
# Create a UnityFile. This is a file which inlcudes all other source files.
# This is usefull, when you want a fast rebuild.
# _UNITY_FILE <= The name of the UnityFile
# _SRC_FILES <= The list of source files
####################################################################################
function(generateUnityFile _UNITY_FILE _SRC_FILES)
  set(files ${${_SRC_FILES}})
  # Generate a unique filename for the unity build translation unit
  set(unit_build_file ${CMAKE_CURRENT_BINARY_DIR}/ub_${_UNITY_FILE}.cpp)
  set_source_files_properties(${files} PROPERTIES HEADER_FILE_ONLY true)
  # Open the ub file
  FILE(WRITE ${unit_build_file} "// Unity Build generated by CMake\n")
  # Add include statement for each translation unit
  foreach(sourceFile ${files} )
    #FILE( APPEND ${unit_build_file} "#include <${CMAKE_CURRENT_SOURCE_DIR}/${sourceFile}>\n")
    FILE( APPEND ${unit_build_file} "#include \"${sourceFile}\"\n")
  endforeach()
  # Complement list of translation units with the name of ub
  set(${_UNITY_FILE} ${unit_build_file} PARENT_SCOPE)
  source_group("Generated Files" FILES ${unit_build_file})
endfunction()

####################################################################################
# Returns the name of the Directory, where the file in the FILE_PATH is located.
####################################################################################
function(getNameOfDir FILE_PATH DIR_NAME)
  get_filename_component(HAS_FILE_IN_PATH ${${FILE_PATH}} EXT)
  if (HAS_FILE_IN_PATH)
    get_filename_component(PATH_WITHOUT_FILENAME ${${FILE_PATH}} PATH)
    get_filename_component(NAME_OF_DIR  ${PATH_WITHOUT_FILENAME} NAME)
    set(${DIR_NAME} ${NAME_OF_DIR} PARENT_SCOPE)
  else()
    get_filename_component(NAME_OF_DIR ${${FILE_PATH}} NAME)
    set(${DIR_NAME} ${NAME_OF_DIR} PARENT_SCOPE)
  endif()
endfunction()

####################################################################################
# Returns relative path from the given file path; starting from CMAKE_CURRENT_SOURCE_DIR
####################################################################################

function(getRelativePath FILE_PATH RELATIVE_PATH)
  string(LENGTH ${CMAKE_CURRENT_SOURCE_DIR} CUR_DIR_LEN)
  get_filename_component(PATH_WITHOUT_FILE ${${FILE_PATH}} PATH)
  string(LENGTH ${PATH_WITHOUT_FILE} FULL_PATH_LEN)
  math(EXPR REL_PATH_LEN ${FULL_PATH_LEN}-${CUR_DIR_LEN})
  math(EXPR REL_PATH_START "${CUR_DIR_LEN}")
  string(SUBSTRING ${PATH_WITHOUT_FILE} ${REL_PATH_START} ${REL_PATH_LEN} REL_PATH)
  string(REGEX REPLACE "^/" "" out_path "${REL_PATH}")
  set(${RELATIVE_PATH} ${out_path} PARENT_SCOPE)
endfunction()

####################################################################################
# Loads a FOLDER, which should contain a FOLDER.cmake.
# In this file all source and header files should be declared.
# In this cmake files all files have to be declared relative.
# They will be read with absolut path.
# FOLDER <= The name of the folder
# _HEADER_FILES => The list of header files
# _SOURCE_FILES => The list of source files
# [OPTIONAL] 3rdArg => performs the installation of the header and source files
####################################################################################
function(loadFolder FOLDER _HEADER_FILES _SOURCE_FILES)
  set(FULL_PATH ${CMAKE_CURRENT_SOURCE_DIR}/${FOLDER}.cmake)
  include(${FULL_PATH})
  get_filename_component(ABS_PATH_TO_FILES ${FULL_PATH} PATH)
  set(shouldInstall ${ARGV3})
  set(QT_MOC_HEADERS)
  set(QT_UI_FILES)
  set(QT_QRC_FILES)

  foreach(headerFile ${HEADER_FILES} )
    if (${headerFile} MATCHES ".*.h.in$")
      string ( REGEX REPLACE ".h.in$" ".h" out_path ${headerFile} )
      configure_file(${headerFile} ${CMAKE_CURRENT_BINARY_DIR}/${out_path} @ONLY)
      set(FULL_HEADER_PATH ${ABS_PATH_TO_FILES}/${headerFile})
      getRelativePath(FULL_HEADER_PATH REL_PATH)
      set(FULL_HEADER_PATH ${CMAKE_CURRENT_BINARY_DIR}/${out_path})
      if (REL_PATH)
        string ( REGEX REPLACE "[\\/]" "\\\\" normalized_path ${REL_PATH} )
        source_group ( ${normalized_path} FILES ${FULL_HEADER_PATH} )
      endif()
      list(APPEND ALL_HPP_FILES ${FULL_HEADER_PATH})
    elseif (${headerFile} MATCHES ".*.rc.in$")
      string ( REGEX REPLACE ".rc.in$" ".rc" out_path ${headerFile} )
      configure_file(${headerFile} ${CMAKE_CURRENT_BINARY_DIR}/${out_path} @ONLY)
      source_group("Generated Files" FILES ${CMAKE_CURRENT_BINARY_DIR}/${out_path})
      list(APPEND ALL_HPP_FILES ${CMAKE_CURRENT_BINARY_DIR}/${out_path})
    elseif (${headerFile} MATCHES ".*.ui$")
        set(FULL_HEADER_PATH ${ABS_PATH_TO_FILES}/${headerFile})
        list(APPEND QT_UI_FILES ${FULL_HEADER_PATH})
        list(APPEND ALL_HPP_FILES ${FULL_HEADER_PATH})
    elseif (${headerFile} MATCHES ".*.qrc$")
        set(FULL_HEADER_PATH ${ABS_PATH_TO_FILES}/${headerFile})
        list(APPEND QT_QRC_FILES ${FULL_HEADER_PATH})
        list(APPEND ALL_HPP_FILES ${FULL_HEADER_PATH})
    else()
      set(FULL_HEADER_PATH ${ABS_PATH_TO_FILES}/${headerFile})
      file(STRINGS ${FULL_HEADER_PATH} var REGEX "Q_OBJECT")
      if(var)
         list(APPEND QT_MOC_HEADERS ${FULL_HEADER_PATH})
      endif()

      # returns the relative path, from the current source dir
      getRelativePath(FULL_HEADER_PATH REL_PATH)
      list(APPEND HEADER_LIST_OF_CUR_DIR ${FULL_HEADER_PATH})
    endif()
    # get the name of the current directory
    getNameOfDir(CMAKE_CURRENT_SOURCE_DIR DIRNAME)
    if (${shouldInstall})
      if (NOT ${FULL_HEADER_PATH} MATCHES ".*_p.h$") # we don't want to install header files which are marked as private
        install(FILES ${FULL_HEADER_PATH} DESTINATION "include/${DIRNAME}/${REL_PATH}" PERMISSIONS OWNER_READ)
      endif()
    endif()
  endforeach()

  # and now the source files
  list(APPEND QML_SOURCES)
  foreach(srcFile ${SOURCE_FILES} )
    # the source_group placement doesn't work at the moment
     if (${srcFile} MATCHES ".*.qml$")
       string(REGEX REPLACE "[\\/]" "_" qrc_resource_file ${srcFile} )
       string(REGEX REPLACE ".qml$" ".qrc" qrc_resource_file ${qrc_resource_file} )
       set(qrc_resource_file ${CMAKE_CURRENT_BINARY_DIR}/${qrc_resource_file})
       file(WRITE ${qrc_resource_file} "<!DOCTYPE RCC><RCC version=\"1.0\"><qresource prefix=\"/\"><file alias=\"${srcFile}\">${ABS_PATH_TO_FILES}/${srcFile}</file></qresource></RCC>")
       qt5_add_resources(compiled_resource_file ${qrc_resource_file})
       source_group("Generated Files" FILES ${compiled_resource_file})
       source_group("Generated Files" FILES ${qrc_resource_file})
       list(APPEND QML_SOURCES ${compiled_resource_file})
     elseif (${srcFile} MATCHES ".*.ui$")
        set(FULL_SRC_PATH ${ABS_PATH_TO_FILES}/${srcFile})
        list(APPEND QT_UI_FILES ${FULL_SRC_PATH})
        list(APPEND SOURCE_LIST_OF_CUR_DIR ${FULL_SRC_PATH})
    elseif (${srcFile} MATCHES ".*.qrc$")
        set(FULL_SRC_PATH ${ABS_PATH_TO_FILES}/${srcFile})
        list(APPEND QT_QRC_FILES ${FULL_SRC_PATH})
        list(APPEND SOURCE_LIST_OF_CUR_DIR ${FULL_SRC_PATH})
     else()
       list(APPEND SOURCE_LIST_OF_CUR_DIR ${ABS_PATH_TO_FILES}/${srcFile})
     endif()

    list(APPEND SOURCE_LIST_OF_CUR_DIR ${ABS_PATH_TO_FILES}/${srcFile})
  endforeach()

  list(APPEND QT_MOC_SOURCES)

  if (QT_MOC_HEADERS)
    qt5_wrap_cpp(QT_MOC_SOURCES ${QT_MOC_HEADERS})
    source_group("Generated Files" FILES ${QT_MOC_SOURCES})
  endif()

  list(APPEND QT_UI_SOURCES)
  if (QT_UI_FILES)
    qt5_wrap_ui(QT_UI_SOURCES ${QT_UI_FILES})
    source_group("Generated Files" FILES ${QT_UI_SOURCES})
  endif()

  list(APPEND QT_QRC_SOURCES)
  if (QT_QRC_FILES)
    qt5_add_resources(QT_QRC_SOURCES ${QT_QRC_FILES})
    source_group("Generated Files" FILES ${QT_QRC_SOURCES})
  endif()

  list(APPEND ALL_HPP_FILES ${${_HEADER_FILES}} ${HEADER_LIST_OF_CUR_DIR})
  list(APPEND ALL_CPP_FILES ${${_SOURCE_FILES}} ${SOURCE_LIST_OF_CUR_DIR} ${QT_MOC_SOURCES} ${QT_UI_SOURCES} ${QT_QRC_SOURCES} ${QML_SOURCES})
  set(${_HEADER_FILES} ${ALL_HPP_FILES} PARENT_SCOPE)
  set(${_SOURCE_FILES} ${ALL_CPP_FILES} PARENT_SCOPE)

  createSrcGroups(HEADER_LIST_OF_CUR_DIR)
  createSrcGroups(SOURCE_LIST_OF_CUR_DIR)
  message( STATUS "${FOLDER} directory included" )
endfunction()

####################################################################################
# This function checks if the current generator is used for a Viusal Studio build
# _INPUT This variable will be set to TRUE if its a Visual Studio build, otherwise to FALSE.
####################################################################################
function (is_vs_based_build _INPUT)
  if(${CMAKE_GENERATOR} MATCHES "Visual Studio")
    set(${_INPUT} TRUE PARENT_SCOPE)
  else()
    set(${_INPUT} FALSE PARENT_SCOPE)
  endif()
endfunction()

####################################################################################
# Copy a release dependency in the correct CMAKE_RUNTIME_OUTPUT_DIRECTORY
# _INPUT The full path of the dependency incl. FileName
# _OUTPUT The directory where the libraries should be installed.
# OPTIONAL: RELATIVE Path - as third argument an optional relative path can be specified
####################################################################################

function(copy_dependency_release _INPUT _OUTPUT)
  is_vs_based_build(VS_BUILD)

  # when this is a DEBUG build we dont copy the files
  if(NOT VS_BUILD)
    if(${CMAKE_BUILD_TYPE} STREQUAL Debug)
      return()
    endif()
  endif()
  # as third argument an optional relative path can be specified
  set(REL_PATH ${ARGV2})
  set(_PATH ${_INPUT})
  # make the path to normal path with / as dir separator
  string ( REGEX REPLACE "[\\/]" "/" FILE_PATH ${_PATH} )
  get_filename_component(FILE_NAME ${FILE_PATH} NAME)

  if (VS_BUILD)
    if (IS_DIRECTORY ${_INPUT})
      file(COPY ${_INPUT} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Release/${REL_PATH})
    else()
      configure_file(${FILE_PATH} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Release/${REL_PATH}/${FILE_NAME} COPYONLY)
      configure_file(${FILE_PATH} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/RelWithDebInfo/${REL_PATH}/${FILE_NAME} COPYONLY)
      configure_file(${FILE_PATH} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/MinSizeRel/${REL_PATH}/${FILE_NAME} COPYONLY)
    endif()
  else()
    if (IS_DIRECTORY ${_INPUT})
      file(COPY ${_INPUT} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${REL_PATH})
    else()
      configure_file(${FILE_PATH} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${REL_PATH}/${FILE_NAME} COPYONLY)
    endif()
  endif()

  if (IS_DIRECTORY ${_INPUT})
    install(DIRECTORY
            ${FILE_PATH}
            DESTINATION ${_OUTPUT}/${REL_PATH}
            CONFIGURATIONS Release)
  else()
    install(FILES
            ${FILE_PATH}
            DESTINATION ${_OUTPUT}/${REL_PATH}
            CONFIGURATIONS Release)
  endif()
endfunction()

####################################################################################
# Copy a debug dependency in the correct CMAKE_RUNTIME_OUTPUT_DIRECTORY
# _INPUT The full path of the dependency incl. FileName
# _OUTPUT The directory where the libraries should be installed.
# OPTIONAL: RELATIVE Path - as third argument an optional relative path can be specified
####################################################################################

function(copy_dependency_debug _INPUT _OUTPUT)
  is_vs_based_build(VS_BUILD)

  # when this is NOT a DEBUG build we dont copy the files
  if(NOT VS_BUILD)
    if(NOT ${CMAKE_BUILD_TYPE} STREQUAL Debug)
      return()
    endif()
  endif()
  # as third argument an optional relative path can be specified
  set(REL_PATH ${ARGV2})
  set(_PATH ${_INPUT})
  # make the path to normal path with / as dir separator
  string ( REGEX REPLACE "[\\/]" "////" FILE_PATH ${_PATH} )
  get_filename_component(FILE_NAME ${FILE_PATH} NAME)

  if (VS_BUILD)
    if (IS_DIRECTORY ${_INPUT})
      file(COPY ${_INPUT} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/${REL_PATH})
     else()
      configure_file(${FILE_PATH} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/${REL_PATH}/${FILE_NAME} COPYONLY)
    endif()
  else()
    if (IS_DIRECTORY ${_INPUT})
      file(COPY ${_INPUT} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${REL_PATH})
    else()
      configure_file(${FILE_PATH} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${REL_PATH}/${FILE_NAME} COPYONLY)
    endif()
  endif()

 if (IS_DIRECTORY ${_INPUT})
   install(DIRECTORY
           ${FILE_PATH}
           DESTINATION ${_OUTPUT}/${REL_PATH}
           CONFIGURATIONS Debug)
 else()
   install(FILES
           ${FILE_PATH}
           DESTINATION ${_OUTPUT}/${REL_PATH}
           CONFIGURATIONS Debug)
  endif()
endfunction()

####################################################################################
# Creates a PreCompiled Header
# _PRECOMPILED_HEADER The full path of the dependency incl. FileName
# _SRC_FILES (Only works with CPP files)
####################################################################################
function(activate_precompiled_headers _PRECOMPILED_HEADER _SOURCE_FILES)
  set(SRC_FILES ${${_SOURCE_FILES}})
  get_filename_component(pch_basename ${_PRECOMPILED_HEADER} NAME_WE)
  set(pch_abs ${CMAKE_CURRENT_SOURCE_DIR}/${_PRECOMPILED_HEADER})
  set(pch_unity ${CMAKE_CURRENT_BINARY_DIR}/${pch_basename}.cpp)

  if(MSVC)
    # First specify the name of the PCH file
    # it seems to be that nmake build cant handle the $(IntDir) variable
    if(NOT MSVC_IDE)
      set(pch_bin ${CMAKE_CURRENT_BINARY_DIR}/${pch_basename}.pch)
    else()
      set(pch_bin "$(IntDir)/${pch_basename}.pch")
    endif()
    # Generate precompiled header translation unit
    if (NOT EXISTS ${pch_unity})
      file(WRITE ${pch_unity} "// Precompiled header unity generated by CMake\n")
      file(APPEND ${pch_unity} "#include <${pch_abs}>\n")
    endif()
    # this creates the precompild header
    set_source_files_properties(${pch_unity}
                                PROPERTIES COMPILE_FLAGS "/Yc\"${pch_abs}\" /Fp\"${pch_bin}\""
                                           OBJECT_OUTPUTS "${pch_bin}")
    # Update properties of source files to use the precompiled header.
    # Additionally, force the inclusion of the precompiled header at beginning of each source file.
    set_source_files_properties(${SRC_FILES}
                                PROPERTIES COMPILE_FLAGS "/Yu\"${pch_abs}\" /FI\"${pch_abs}\" /Fp\"${pch_bin}\""
                                           OBJECT_DEPENDS "${pch_bin}")
    # Finally, update the source file collection to contain the precompiled header translation unit
    set(${_SOURCE_FILES} ${pch_unity} ${pch_abs} ${${_SOURCE_FILES}} PARENT_SCOPE)

    source_group("Generated Files" FILES ${pch_unity})
    get_filename_component(PATH_TO_PCH ${_PRECOMPILED_HEADER} DIRECTORY)
    if (PATH_TO_PCH)
        string ( REGEX REPLACE "[\\/]" "\\\\" normalized_path ${PATH_TO_PCH} )
        source_group(${normalized_path} FILES ${pch_abs})
    endif()
  endif()
endfunction()

####################################################################################
# Adds or replace a compiler option
# _OLD_OPTION The option which should be replaced
# _NEW_OPTION The new option which should be added
####################################################################################
macro( replaceCompilerOption _OLD_OPTION _NEW_OPTION)
  foreach(flag_var
          CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
          CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES ${_OLD_OPTION})
      string(REGEX REPLACE ${_OLD_OPTION} ${_NEW_OPTION} ${flag_var} "${${flag_var}}")
    else()
      set(${flag_var} "${${flag_var}} ${_NEW_OPTION}")
    endif()
   # set(${flag_var} ${${flag_var}} PARENT_SCOPE)
  endforeach()
endmacro()

####################################################################################
# enables or disables the user of RTTI for all following source files.
# _ENABLE If true, will enable RTTI, otherwise will disable RTTI.
####################################################################################
macro(enable_rtti _ENABLE)
  set(enable_rtti_opt "")
  set(disable_rtti_opt "")
  if (MSVC)
    set(enable_rtti_opt "/GR")
    set(disable_rtti_opt "/GR-")
  elseif(CMAKE_COMPILER_IS_GNUCXX )
    set(enable_rtti_opt "-frtti")
    set(disable_rtti_opt "-fno-rtti")
  elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    set(enable_rtti_opt "-frtti")
    set(disable_rtti_opt "-fno-rtti")
  else()
    message(FATAL_ERROR "Don't know how to enable/disable RTTI for this compiler.")
  endif()

  if (${_ENABLE})
    message(STATUS "Enabled: use of RTTI")
    replaceCompilerOption("${disable_rtti_opt}" "${enable_rtti_opt}")
  else()
    message(STATUS "Disabled: use of RTTI")
    replaceCompilerOption(${enable_rtti_opt} ${disable_rtti_opt})
  endif()
endmacro()

####################################################################################
# Returns the name of the used compiler.
# _COMPILER_NAME
####################################################################################
function(getCompilerName _COMPILER_NAME)
  if(MSVC_VERSION EQUAL 1400)
    set(COMPILER_NAME "vs2005")
  elseif(MSVC_VERSION EQUAL 1500)
    set(COMPILER_NAME "vs2008")
  elseif(MSVC_VERSION EQUAL 1600)
    set(COMPILER_NAME "vs2010")
  elseif(MSVC_VERSION EQUAL 1700)
    set(COMPILER_NAME "vs2012")
  elseif(MSVC_VERSION EQUAL 1800)
    set(COMPILER_NAME "vs2013")
  elseif(MSVC_VERSION EQUAL 1900)
    set(COMPILER_NAME "vs2015")
  elseif(CMAKE_COMPILER_IS_GNUCXX)
    set(COMPILER_NAME "gcc")
    if(WIN32)
      execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "-dumpversion" OUTPUT_VARIABLE GCC_VERSION_OUTPUT)
      string(REGEX REPLACE "([0-9]+\\.[0-9]+).*" "\\1" GCC_VERSION "${GCC_VERSION_OUTPUT}")
      set(COMPILER_NAME ${COMPILER_NAME}${GCC_VERSION})
    endif()
  elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
     set(COMPILER_NAME "clang")
  else()
    message(WARNING "Can not retrieve compiler name!")
    return()
  endif()

  set(${_COMPILER_NAME} ${COMPILER_NAME} PARENT_SCOPE)
endfunction()

####################################################################################
# This will install the PDB files also into the "bin" folder of the installation directory
# _TARGET_NAME The name of the target
####################################################################################

function(install_pdb_files _TARGET_NAME)
    if (MSVC)
        install(FILES $<TARGET_PDB_FILE:${_TARGET_NAME}> DESTINATION "bin" CONFIGURATIONS Debug RelWithDebInfo)
    endif()
endfunction()

####################################################################################
# Get environment variable, define it as ENV_$var and make sure backslashes are converted to forward slashes
# _COMPILER_NAME
####################################################################################
macro(getenv_path VAR)
   set(ENV_${VAR} $ENV{${VAR}})
   # replace won't work if var is blank
   if (ENV_${VAR})
     string( REGEX REPLACE "\\\\" "/" ENV_${VAR} ${ENV_${VAR}} )
   endif ()
endmacro()

macro(generateLibraryVersionVariables MAJOR MINOR PATCH PRODUCT_NAME PRODUCT_CPY_RIGHT PRODUCT_LICENSE)
  set(LIBRARY_VERSION_MAJOR ${MAJOR})
  set(LIBRARY_VERSION_MINOR ${MINOR})
  set(LIBRARY_VERSION_PATCH ${PATCH})
  set(LIBRARY_VERSION ${LIBRARY_VERSION_MAJOR}.${LIBRARY_VERSION_MINOR}.${LIBRARY_VERSION_PATCH})
  set(LIBRARY_VERSION_STR "${LIBRARY_VERSION_MAJOR}.${LIBRARY_VERSION_MINOR}.${LIBRARY_VERSION_PATCH}")
  math(EXPR LIBRARY_VERSION_CALC "${LIBRARY_VERSION_MAJOR}*1000 + ${LIBRARY_VERSION_MINOR}*100 + ${LIBRARY_VERSION_PATCH}")
  set(LIBRARY_PRODUCT_NAME ${PRODUCT_NAME})
  set(LIBRARY_COPYRIGHT ${PRODUCT_CPY_RIGHT})
  set(LIBRARY_LICENSE ${PRODUCT_LICENSE})
endmacro()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace OCA\DAV;

use OC\Files\Filesystem;
use OCA\DAV\Connector\Sabre\Directory;
use OCA\DAV\Connector\Sabre\File;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\ICollection;

/**
 * Sabre tree of nodes.
 *
 * Provides a shortcut when accessing the "files/" subtree to avoid
 * having to walk through every node and trigger unnecessary extra queries.
 */
class Tree extends \Sabre\DAV\Tree {
	/**
	 * Returns the INode object for the requested path
	 *
	 * @param string $path
	 * @return \Sabre\DAV\INode
	 * @throws NotFound
	 */
	public function getNodeForPath($path) {
		// FIXME: remove this check when we are sure that other
		// non-files endpoints work correctly

		// querying "files" directly or anything outside of it
		// will fallback to the regular implementation
		if (\strpos(\rtrim($path, '/'), 'files/') !== 0) {
			return parent::getNodeForPath($path);
		}

		$path = \trim($path, '/');
		if (isset($this->cache[$path])) {
			return $this->cache[$path];
		}

		$sections = \explode('/', $path);

		$node = $this->rootNode;
		while (\count($sections) > 0) {
			$section = \array_shift($sections);
			if (!$node instanceof ICollection) {
				throw new NotFound('Could not find node at path: ' . $path);
			}
			$node = $node->getChild($section);
			if ($node instanceof \Sabre\DAV\Tree) {
				// note: we don't cache here as the sub-tree has its own cache
				return $node->getNodeForPath(\implode('/', $sections));
			}
		}

		$this->cache[$path] = $node;
		return $node;
	}

	/**
	 * Copies a file from path to another.
	 *
	 * @param string $sourcePath      The source location
	 * @param string $destinationPath The full destination path
	 */
	public function copy($sourcePath, $destinationPath) {
		$sourceNode = $this->getNodeForPath($sourcePath);
		if ($sourceNode instanceof File
			|| $sourceNode instanceof Directory
		) {
			$hookSourcePath = $this->treePathToHookPath($sourcePath);
			$hookDestinationPath = $this->treePathToHookPath($destinationPath);
			$run = true;
			\OC_Hook::emit(
				Filesystem::CLASSNAME,
				Filesystem::signal_copy,
				[
					Filesystem::signal_param_oldpath => $hookSourcePath,
					Filesystem::signal_param_newpath => $hookDestinationPath,
					Filesystem::signal_param_run => &$run
				]
			);
			if ($run === true) {
				parent::copy($sourcePath, $destinationPath);
				\OC_Hook::emit(
					Filesystem::CLASSNAME,
					Filesystem::signal_post_copy,
					[
						Filesystem::signal_param_oldpath => $hookSourcePath,
						Filesystem::signal_param_newpath => $hookDestinationPath
					]
				);
			}
		} else {
			parent::copy($sourcePath, $destinationPath);
		}
	}

	/**
	 * @param string $treePath
	 * @return string
	 */
	private function treePathToHookPath(string $treePath) {
		$treePathArray = \explode('/', $treePath);
		$hookPathArray = \array_slice($treePathArray, 2);
		return \implode('/', $hookPathArray);
	}
}


text:
.class Lcom/android/server/smartclip/SpenGestureManagerService$3;
.super Ljava/lang/Object;
.source "SpenGestureManagerService.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/smartclip/SpenGestureManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

# direct methods
.method constructor <init>(Lcom/android/server/smartclip/SpenGestureManagerService;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 10

    const/4 v9, 0x2

    const/4 v4, 0x1

    const/4 v3, 0x0

    iget-object v5, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get5()Landroid/content/Context;

    move-result-object v6

    invoke-virtual {v6}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v6

    const-string/jumbo v7, "lock_screen_quick_note"

    const/4 v8, -0x2

    invoke-static {v6, v7, v3, v8}, Landroid/provider/Settings$Secure;->getIntForUser(Landroid/content/ContentResolver;Ljava/lang/String;II)I

    move-result v6

    if-eqz v6, :cond_0

    move v3, v4

    :cond_0
    invoke-static {v5, v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-set5(Lcom/android/server/smartclip/SpenGestureManagerService;Z)Z

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-virtual {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->keyguardOn()Z

    move-result v3

    if-eqz v3, :cond_1

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get9(Lcom/android/server/smartclip/SpenGestureManagerService;)Z

    move-result v3

    xor-int/lit8 v3, v3, 0x1

    if-eqz v3, :cond_1

    sget-object v3, Lcom/android/server/smartclip/SpenGestureManagerService;->TAG:Ljava/lang/String;

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v5, "Double tap is disable : "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v5}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get9(Lcom/android/server/smartclip/SpenGestureManagerService;)Z

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    return-void

    :cond_1
    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-wrap2(Lcom/android/server/smartclip/SpenGestureManagerService;)Z

    move-result v3

    if-eqz v3, :cond_2

    sget-object v3, Lcom/android/server/smartclip/SpenGestureManagerService;->TAG:Ljava/lang/String;

    const-string/jumbo v4, "Double tap is disabled : Screen pinning mode enabled"

    invoke-static {v3, v4}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    return-void

    :cond_2
    :try_start_0
    sget-object v3, Lcom/android/server/smartclip/SpenGestureManagerService;->TAG:Ljava/lang/String;

    const-string/jumbo v5, "Double tapped!"

    invoke-static {v3, v5}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-wrap1(Lcom/android/server/smartclip/SpenGestureManagerService;)Z

    move-result v3

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    new-instance v5, Landroid/content/Intent;

    const-string/jumbo v6, "android.intent.action.PEN_GESTURE_PENMEMO_ACTION"

    invoke-direct {v5, v6}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    invoke-static {v3, v5}, Lcom/android/server/smartclip/SpenGestureManagerService;->-set7(Lcom/android/server/smartclip/SpenGestureManagerService;Landroid/content/Intent;)Landroid/content/Intent;

    invoke-static {}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get5()Landroid/content/Context;

    move-result-object v3

    iget-object v5, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v5}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get11(Lcom/android/server/smartclip/SpenGestureManagerService;)Landroid/content/Intent;

    move-result-object v5

    sget-object v6, Landroid/os/UserHandle;->CURRENT:Landroid/os/UserHandle;

    invoke-virtual {v3, v5, v6}, Landroid/content/Context;->sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;)V

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get14(Lcom/android/server/smartclip/SpenGestureManagerService;)Landroid/telephony/TelephonyManager;

    move-result-object v3

    invoke-virtual {v3}, Landroid/telephony/TelephonyManager;->getCallState()I

    move-result v0

    const/4 v1, 0x0

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get15(Lcom/android/server/smartclip/SpenGestureManagerService;)Landroid/telephony/TelephonyManager;

    move-result-object v3

    if-eqz v3, :cond_3

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get15(Lcom/android/server/smartclip/SpenGestureManagerService;)Landroid/telephony/TelephonyManager;

    move-result-object v3

    invoke-virtual {v3}, Landroid/telephony/TelephonyManager;->getCallState()I

    move-result v1

    :cond_3
    if-eq v0, v4, :cond_4

    if-ne v0, v9, :cond_5

    :cond_4
    invoke-static {}, Lcom/android/server/smartclip/SpenGestureManagerService;->-get5()Landroid/content/Context;

    move-result-object v3

    new-instance v4, Landroid/content/Intent;

    const-string/jumbo v5, "com.samsung.intent.spengesture.DOUBLE_TAB"

    invoke-direct {v4, v5}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    invoke-virtual {v3, v4}, Landroid/content/Context;->sendBroadcast(Landroid/content/Intent;)V

    :goto_0
    return-void

    :cond_5
    if-eq v1, v4, :cond_4

    if-eq v1, v9, :cond_4

    iget-object v3, p0, Lcom/android/server/smartclip/SpenGestureManagerService$3;->this$0:Lcom/android/server/smartclip/SpenGestureManagerService;

    invoke-static {v3}, Lcom/android/server/smartclip/SpenGestureManagerService;->-wrap7(Lcom/android/server/smartclip/SpenGestureManagerService;)V
    :try_end_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    :catch_0
    move-exception v2

    invoke-virtual {v2}, Ljava/lang/Exception;->printStackTrace()V

    goto :goto_0
.end method


text:
module AirbrakeAPI
  class Base
    class << self
      def setup
      end

      def fetch(path, options)
        Client.new.get(path, options)
      end

      def deprecate(msg)
        Kernel.warn("[Deprecation] - #{msg}")
      end
    end
  end
end


text:
@interface JMCSketchViewControllerFactory : NSObject

+(JMCSketchViewController*) makeSketchViewControllerFor:(NSData*)imageData withId:(NSInteger)imageId;
+(UIImage*) makeSketchThumbnailFor:(UIImage*)sketch;

@end


text:
package net.sourceforge.pebble.web.filter;

import net.sourceforge.pebble.Constants;
import net.sourceforge.pebble.domain.AbstractBlog;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GZIPFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res,
                       FilterChain chain) throws IOException, ServletException {

      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;

      String ae = request.getHeader("Accept-Encoding");
      if (ae != null && ae.indexOf("gzip") != -1) {
        String encoding = ((AbstractBlog)request.getAttribute(Constants.BLOG_KEY)).getCharacterEncoding();
        GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response, encoding);
        chain.doFilter(req, wrappedResponse);
        wrappedResponse.finishResponse();
      } else {
        chain.doFilter(req, res);
      }
  }

  public void init(FilterConfig filterConfig) {
  }

  public void destroy() {
  }

}


text:
My experience with this sort of scaffolding is from using Rails a few years
ago and I wanted to see:
 1. how Rails has changed since I used it last
 2. what the "competition" was like these days

I muddled my way through setting up each app by skimming the docs I could
find, generally spending no more than 15-30 minutes on each, and not asking
anyone for help.

I didn't look super hard, but I was surprised by how few web frameworks
actually support Rails style scaffolding. In the end, I tested the following:

 * Rails 5.0.2
 * LoopBack 3.6.0
 * Phoenix 1.2.1
 * Sails 0.12.13
 * Kitura 1.6

The requirements were simple. To generate some sort of web app around the
following trivial models:

```
User:
  - name (string)
  - email (string)

Post:
  - title (text)
  - body (text)
  - author (User)

Comment:
  - body (text)
  - post (Post)
  - author (User)
```

That's it. I just want to see what gets done for me and how easy or painful
the generated code is as a jumping off point for building out a complete app.

Let's begin!

## Rails

Rails is where I started, so that's what I started with here.

 * [496d123a](https://github.com/rmg/scaffold-shootout/commit/496d123) - rails new rails-blog
 * [2cc35259](https://github.com/rmg/scaffold-shootout/commit/2cc3525) - rails g scaffold User name:string email:string:uniq
 * [0b233dee](https://github.com/rmg/scaffold-shootout/commit/0b233de) - rails g scaffold Post title:text body:text user:references
 * [4b71510b](https://github.com/rmg/scaffold-shootout/commit/4b71510) - rails g scaffold Comment body:text post:references user:references

The experience was basically exactly how I remembered it, except for models
becoming _slightly_ more magical. I don't really like models to have
properties that aren't documented as code in the model definition.

Ergonomics were decent, and other than the automagical model attributes, the
generated code looks relatively complete. The controllers show me where to
hang my code to override the various CRUD operations. There are trivial
templates in place for the different views, with a bonus of separate templates
for html and JSON.

I **love** the thorough documentation comments in the generated config files.

## LoopBack

I work at StrongLoop/IBM, so LoopBack was an obvious candidate. Disclaimer:
I'm one of the ones on the team who has never really touched LoopBack.

 * [d5d839a](https://github.com/rmg/scaffold-shootout/commit/d5d839a) - lb app (empty)
 * [ed4f0a5](https://github.com/rmg/scaffold-shootout/commit/ed4f0a5) - lb model Author
 * [25a6737](https://github.com/rmg/scaffold-shootout/commit/25a6737) - lb model Post
 * [89fc033](https://github.com/rmg/scaffold-shootout/commit/89fc033) - lb model Comment
 * [ca4c60a](https://github.com/rmg/scaffold-shootout/commit/ca4c60a) - lb relation (Post belongs to Author)
 * [0cb228a](https://github.com/rmg/scaffold-shootout/commit/0cb228a) - lb relation (Comment belongs to Author)
 * [950bce4](https://github.com/rmg/scaffold-shootout/commit/950bce4) - lb relation (Comment belongs to Post)

First off: ugh, I hate interactive CLIs. I want something scriptable, not a
text based wizard! There isn't really a sane way to document the options
chosen in the `lb` interview UI, so I've already forgotten what exactly I
selected.

I do recall being warned for each model that I didn't have any
datasources defined. I'm choosing to interpret that as evidence of LoopBack's
bias towards building APIs for existing databases instead of building
greenfield apps.

LoopBack (3.x) doesn't have a concept of controllers, so there are no
controllers generated. The focus is more on exposing the models via a REST-ish
API. As a side effect, there's really no "web app" as a result of the
scaffolding I generated. It _does_ have an explorer component that gives a
nice developer friendly interface to the models, but it's not really something
you can call a website.

There's a bunch of generate JSON config files (including the majority of the
model details), which I would have to dig through docs to figure out how to
modify. Actually, doing a quick scan via CLI shows that there is actually only
52 lines of actual JavaScript and 234 lines of JSON generated by all those
commands I ran. The real problem with scaffolding like this is that JSON
doesn't support comments, so I can't even submit a pull request to add
comments to the templates the generator uses.

## Phoenix

I've played with Phoenix a little while experimenting with Elixir. Elixir
feels like someone stole Ruby's wardrobe and played dress-up with Erlang and
discovered that a whole lot of it actually fits pretty darn well. Elixir was
written by an experienced Rails developer and Phoenix is a re-imagining of
Rails on top of Elixir. It is very well done.

 * [0fc813f](https://github.com/rmg/scaffold-shootout/commit/0fc813f) - mix phoenix.new phoenix_blog
 * [07de996](https://github.com/rmg/scaffold-shootout/commit/07de996) - mix phoenix.gen.html User users name:string email:string
 * [7dc08e4](https://github.com/rmg/scaffold-shootout/commit/7dc08e4) - phoenix_blog: manually add resource route
 * [a2b22c8](https://github.com/rmg/scaffold-shootout/commit/a2b22c8) - mix phoenix.gen.html Post posts title:string body:text author:references:users
 * [c603e41](https://github.com/rmg/scaffold-shootout/commit/c603e41) - phoenix_blog: manually add /posts resource route
 * [5463926](https://github.com/rmg/scaffold-shootout/commit/5463926) - mix phoenix.gen.html Comment comments body:text author:references:users post:references:posts
 * [3a762e4](https://github.com/rmg/scaffold-shootout/commit/3a762e4) - phoenix_blog: manually add /comments resource route

This scaffolding does _a lot_. The way Elixir/Erlang apps are distributed is
as standalone applications. As a result, this scaffolded app can actually be
packaged up as a self-contained tarball and deployed in almost any
environment.

The one weird bit is that I had to manually add routes for the resources that
I was able to generate by CLI. It was only one line per resource that I needed
to add, so it was relatively easy, but the instructions for doing it didn't
make it clear where in `web/router.ex` the lines were supposed to be added.
Assuming I picked the write place to put those route lines, Phoenix actually
produced what I consider the best scaffolding.

It solved my complaint about Rails having automagical model properties, so
that's cool. There are no handlers for JSON requests in this app like there
were for Rails, but that is almost certainly because I used `phoenix.gen.html`
instead of `phoenix.gen.json`.

Overall I'm quite pleased with this one.

## Sails

It rhymes with Rails, so I guess that means it is supposed to be a Rails
clone?

 * [694eb6c](https://github.com/rmg/scaffold-shootout/commit/694eb6c) - sails generate new sails-blog
 * [3b47aa0](https://github.com/rmg/scaffold-shootout/commit/3b47aa0) - sails generate model User name:string email:string
 * [a78549e](https://github.com/rmg/scaffold-shootout/commit/a78549e) - sails generate controller User create show index update delete
 * [b5b7416](https://github.com/rmg/scaffold-shootout/commit/b5b7416) - sails generate model Post title:string body:text
 * [ee3d761](https://github.com/rmg/scaffold-shootout/commit/ee3d761) - sails generate controller Post create show index update delete
 * [9dc7b93](https://github.com/rmg/scaffold-shootout/commit/9dc7b93) - sails generate model Comment body:text
 * [49435d9](https://github.com/rmg/scaffold-shootout/commit/49435d9) - sails generate controller Comment create show index update delete
 * [c3aa32f](https://github.com/rmg/scaffold-shootout/commit/c3aa32f) - sails: manually add relations to models

If it is a Rails clone it isn't a very good one. The website looks nice, and I
get the feeling that the Waterline ORM is where all the magic is at, but the
scaffolding doesn't really reflect that.

The first command generates a bunch of useful looking app-wide scaffolding
like error pages and various canned response types. Off to a great start!

The rest of the commands actually generated mostly empty files. Slightly more
useful than `touch api/models/$name.js`. Actually, if you're a whitespace
pedant like I am, the generator is actually _less_ useful than `touch` because
it produced a bunch of files without terminating newlines and _with_ lines
that contained only whitespace.

If it seems harsh to criticize the scaffolded code for whitespace problems
keep in mind that there wasn't actually much else generated to criticize.

I was feeling charitable at the end, so I spent a few minutes looking through
the docs to figure out how relations were defined. Turns out they're pretty
simple, so I added them manually.

## Swift

This one came across my desk because I had to add Swift support to our CI in
order to run the tests for `apic swiftserver`, which is basically a wrapper
for the `yo swiftserver` generator I tried out.

 * [21e837b](https://github.com/rmg/scaffold-shootout/commit/21e837b) - yo swiftserver
 * [9c7f29e](https://github.com/rmg/scaffold-shootout/commit/9c7f29e) - yo swiftserver:model User
 * [c26b651](https://github.com/rmg/scaffold-shootout/commit/c26b651) - yo swiftserver:model Post
 * [e74e523](https://github.com/rmg/scaffold-shootout/commit/e74e523) - yo swiftserver:model Comment

Nice and short. That is partially because it seems to have followed LoopBack's
pattern of a text-based wizard instead of a more script-friendly CLI.

I also encountered some compilation errors at the end of each command, but
I've dismissed them as likely something wrong with my environment. They didn't
seem to interfere with the code generation so I'm not giving any demerits for
that.

The most visible problem with the generated code is that I couldn't create the
inter-model relationships, similar to the problem I had with Sails. Unlike
Sails, however, for the life of me I couldn't figure out how to even do this
manually.

What I _do_ like about the generated Swift code is that I don't see a lot of
magic in the `Sources/Generated/*Resource.swift` files. Unfortunately, what I
see is a whole lot of code. I'm not sure if this is just boilerplate that one
has to live with in Swift/Kitura land, or if it is a feature of the generator.
I'm also a little nervous about the directory structure. Am I supposed to
modify the files under `Sources/Generated/`? Or is there some sort of workflow
for re-generating the files from something else?

# Conclusions

Ignoring my familiarity (or lack of familiarity) with the various languages,
or my ability to pester the LoopBack developers for help at any time, I'm
calling Phoenix the winner.

The scaffolded output looks to be the most useful and complete starting point
given the input, despite it having a couple manual steps.

# Suggestions For The Generator Authors

 * generated code should exemplify good code
   * comments directed at people new to the code
   * obvious places to extend functionality and hang custom code
 * interactive CLIs should not be the only option
 * it is way easier to extend scaffolded tests than to write from scratch


text:
extern void defaultSpuriousHandler(void);
extern void defaultFiqHandler(void);
extern void defaultIrqHandler(void);
extern void LowLevelInit(void);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>public\js\core\Core.Templates.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Client_Core_Core.Ajax.js

Client_Core_Core.DomManipulation.js

Client_Core_Core.js

Client_Core_Core.Mediator.js

Client_Core_Core.Socket.js

Client_Core_Core.Templates.js

Client_Core_Core.Utils.js

Client_Main.js

Client_Modules_chat.js

Client_Modules_corkboard.js

Client_Modules_friend-request.js

Client_Modules_notification.js

Client_Modules_registration.js

Client_Sandbox.js

Server_App_database.js

Server_App_Gruntfile.js

Server_App_middleware.js

Server_App_Socket.js

Server_App_Utils.js

Server_Controller_chatController.js

Server_Controller_profileController.js

Server_Controller_registrationController.js

Server_Controller_userController.js

Server_Model_userModel.js

App.js

Client_Core.js

Client_Modules.js

Client_Sandbox.js

Server_App.js

Server_Controller.js

Server_Model.js

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: public\js\core\Core.Templates.js

/**
 The Core.Templates.js provides HTML Templates for the application.

 @module Client_Core.js
 @class Client_Core_Core.Templates.js
 **/
Core.Templates = (function() {
    ///////////////////
    // public scope
    return {

        /**
         Renders a message of a corkboard message.

         @param data
         @method corkboard_message
         @returns the HTML
         **/
        corkboard_message : function(data) {
            var html =
                "<div class='corkboard-message borderd'>"
                    + "<small class='corkboard-message-details'>"
                    + "<a class='corkboard-message-user' href='/profile?userId=" + data._id + "'>"   + data.name + "</a>"
                    + "<span> wrote </span>"
                    + "<span class='corkboard-message-date'>at " + data.date + "</span>"
                    + "</small>"
                    + "<div class='corkboard-message-body'>" + data.body + "</div>" +
                    "</div>";

            return html;
        },

        /**
         Renders a message of a chat message.

         @param data
         @method chat_message
         @returns the HTML
         **/
        chat_message : function( data ) {
            var html =
                "<div class='chat-message'>"
                    + "<small class='chat-message-time'> " + data.time + "</small>"
                    + " <a class='chat-message-user' href='/profile?userId=" + data.user._id + "'>" + data.user.first_name + ":</a>"
                    + "<span class='chat-message-body'>" + data.body + "</span>" +
                    "</div>";

            return html;
        },

        /**
         Renders a friend request notification.

         @param data
         @method friend_request_notification
         @returns the HTML
         **/
        friend_request_notification : function( data ) {
            var html =
                "<span>The User</span>"
                    + "<a href='/profile?userId=" + data._id + "'>" + data.fullname + "</a>"
                    + "<span>wants to be friends with you!</span>"
                    + "<div class='friend-request-react-controls'>"
                    + "<a href='javascript:void(0)' class='accept-friend-request'  data-request-id=" + data._id + ">accept</a>"
                    + "<a href='javascript:void(0)' class='decline-friend-request' data-request-id=" + data._id + ">decline</a>" +
                    "</div>";

            return html;
        },

        /**
         Renders a friend of a user on his profile.

         @param data
         @method friend
         @returns the HTML
         **/
        friend : function(data) {
            var html = "<li><a href='/profile?userId=" + data._id + "'>" + data.fullname + "</a></li>";
            return html;
        },

        /**
         Renders a send-friend-request button.

         @method friend_status_unknown
         @returns the HTML
         **/
        friend_status_unknown : function() {
            return "<button id='send-friend-request' class='btn btn-success'>Send friend request</button>";
        },

        /**
         Renders a pending-friend-request button.

         @method friend_status_pending
         @returns the HTML
         **/
        friend_status_pending : function() {
            return "<div class='pending-friend-request'>Pending friend request</div>";
        },

        /**
         Renders a friend button as a notification that the user is already a friend.

         @method friend_status_friends
         @returns the HTML
         **/
        friend_status_friends : function() {
            return "<div class='friend'>Friends</button>";
        }
    };
}());


text:
require "missing_formula"
require "diagnostic"
require "cmd/search"
require "formula_installer"
require "tap"
require "hardware"
require "development_tools"

module Homebrew
  module_function

  def install
    raise FormulaUnspecifiedError if ARGV.named.empty?

    if ARGV.include? "--head"
      raise "Specify `--HEAD` in uppercase to build from trunk."
    end

    unless ARGV.force?
      ARGV.named.each do |name|
        next if File.exist?(name)
        if name !~ HOMEBREW_TAP_FORMULA_REGEX && name !~ HOMEBREW_CASK_TAP_CASK_REGEX
          next
        end
        tap = Tap.fetch(Regexp.last_match(1), Regexp.last_match(2))
        tap.install unless tap.installed?
      end
    end

    begin
      formulae = []

      unless ARGV.casks.empty?
        args = []
        args << "--force" if ARGV.force?
        args << "--debug" if ARGV.debug?
        args << "--verbose" if ARGV.verbose?

        ARGV.casks.each do |c|
          ohai "brew cask install #{c} #{args.join " "}"
          system("#{HOMEBREW_PREFIX}/bin/brew", "cask", "install", c, *args)
        end
      end

      # if the user's flags will prevent bottle only-installations when no
      # developer tools are available, we need to stop them early on
      FormulaInstaller.prevent_build_flags unless DevelopmentTools.installed?

      ARGV.formulae.each do |f|
        # head-only without --HEAD is an error
        if !ARGV.build_head? && f.stable.nil? && f.devel.nil?
          raise <<-EOS.undent
          #{f.full_name} is a head-only formula
          Install with `brew install --HEAD #{f.full_name}`
          EOS
        end

        # devel-only without --devel is an error
        if !ARGV.build_devel? && f.stable.nil? && f.head.nil?
          raise <<-EOS.undent
          #{f.full_name} is a devel-only formula
          Install with `brew install --devel #{f.full_name}`
          EOS
        end

        if ARGV.build_stable? && f.stable.nil?
          raise "#{f.full_name} has no stable download, please choose --devel or --HEAD"
        end

        # --HEAD, fail with no head defined
        if ARGV.build_head? && f.head.nil?
          raise "No head is defined for #{f.full_name}"
        end

        # --devel, fail with no devel defined
        if ARGV.build_devel? && f.devel.nil?
          raise "No devel block is defined for #{f.full_name}"
        end

        installed_head_version = f.latest_head_version
        new_head_installed = installed_head_version &&
                             !f.head_version_outdated?(installed_head_version, fetch_head: ARGV.fetch_head?)
        prefix_installed = f.prefix.exist? && !f.prefix.children.empty?

        if f.keg_only? && f.any_version_installed? && f.optlinked? && !ARGV.force?
          # keg-only install is only possible when no other version is
          # linked to opt, because installing without any warnings can break
          # dependencies. Therefore before performing other checks we need to be
          # sure --force flag is passed.
          if f.outdated?
            optlinked_version = Keg.for(f.opt_prefix).version
            onoe <<-EOS.undent
              #{f.full_name} #{optlinked_version} is already installed
              To upgrade to #{f.version}, run `brew upgrade #{f.name}`
            EOS
          else
            opoo <<-EOS.undent
              #{f.full_name} #{f.pkg_version} is already installed
            EOS
          end
        elsif (ARGV.build_head? && new_head_installed) || prefix_installed
          # After we're sure that --force flag is passed for linked to opt
          # keg-only we need to be sure that the version we're attempting to
          # install is not already installed.

          installed_version = if ARGV.build_head?
            f.latest_head_version
          else
            f.pkg_version
          end

          msg = "#{f.full_name} #{installed_version} is already installed"
          linked_not_equals_installed = f.linked_version != installed_version
          if f.linked? && linked_not_equals_installed
            msg = <<-EOS.undent
              #{msg}
              The currently linked version is #{f.linked_version}
              You can use `brew switch #{f} #{installed_version}` to link this version.
            EOS
          elsif !f.linked? || f.keg_only?
            msg = <<-EOS.undent
              #{msg}, it's just not linked.
              You can use `brew link #{f}` to link this version.
            EOS
          end
          opoo msg
        elsif !f.any_version_installed? && old_formula = f.old_installed_formulae.first
          msg = "#{old_formula.full_name} #{old_formula.installed_version} already installed"
          if !old_formula.linked? && !old_formula.keg_only?
            msg = <<-EOS.undent
              #{msg}, it's just not linked.
              You can use `brew link #{old_formula.full_name}` to link this version.
            EOS
          end
          opoo msg
        elsif f.migration_needed? && !ARGV.force?
          # Check if the formula we try to install is the same as installed
          # but not migrated one. If --force passed then install anyway.
          opoo <<-EOS.undent
            #{f.oldname} already installed, it's just not migrated
            You can migrate formula with `brew migrate #{f}`
            Or you can force install it with `brew install #{f} --force`
          EOS
        else
          # If none of the above is true and the formula is linked, then
          # FormulaInstaller will handle this case.
          formulae << f
        end

        # Even if we don't install this formula mark it as no longer just
        # installed as a dependency.
        next unless f.opt_prefix.directory?
        keg = Keg.new(f.opt_prefix.resolved_path)
        tab = Tab.for_keg(keg)
        unless tab.installed_on_request
          tab.installed_on_request = true
          tab.write
        end
      end

      perform_preinstall_checks

      formulae.each do |f|
        Migrator.migrate_if_needed(f)
        install_formula(f)
      end
    rescue FormulaUnreadableError, FormulaClassUnavailableError,
           TapFormulaUnreadableError, TapFormulaClassUnavailableError => e
      # Need to rescue before `FormulaUnavailableError` (superclass of this)
      # is handled, as searching for a formula doesn't make sense here (the
      # formula was found, but there's a problem with its implementation).
      ofail e.message
    rescue FormulaUnavailableError => e
      if e.name == "updog"
        ofail "What's updog?"
        return
      end

      ofail e.message
      if (reason = Homebrew::MissingFormula.reason(e.name))
        $stderr.puts reason
        return
      end

      query = query_regexp(e.name)

      ohai "Searching for similarly named formulae..."
      formulae_search_results = search_formulae(query)
      case formulae_search_results.length
      when 0
        ofail "No similarly named formulae found."
      when 1
        puts "This similarly named formula was found:"
        puts formulae_search_results
        puts "To install it, run:\n  brew install #{formulae_search_results.first}"
      else
        puts "These similarly named formulae were found:"
        puts Formatter.columns(formulae_search_results)
        puts "To install one of them, run (for example):\n  brew install #{formulae_search_results.first}"
      end

      # Do not search taps if the formula name is qualified
      return if e.name.include?("/")
      ohai "Searching taps..."
      taps_search_results = search_taps(query)
      case taps_search_results.length
      when 0
        ofail "No formulae found in taps."
      when 1
        puts "This formula was found in a tap:"
        puts taps_search_results
        puts "To install it, run:\n  brew install #{taps_search_results.first}"
      else
        puts "These formulae were found in taps:"
        puts Formatter.columns(taps_search_results)
        puts "To install one of them, run (for example):\n  brew install #{taps_search_results.first}"
      end
    end
  end

  def check_ppc
    case Hardware::CPU.type
    when :ppc
      abort <<-EOS.undent
        Sorry, Homebrew does not support your computer's CPU architecture.
        For PPC support, see: https://github.com/mistydemeo/tigerbrew
      EOS
    end
  end

  def check_writable_install_location
    raise "Cannot write to #{HOMEBREW_CELLAR}" if HOMEBREW_CELLAR.exist? && !HOMEBREW_CELLAR.writable_real?
    raise "Cannot write to #{HOMEBREW_PREFIX}" unless HOMEBREW_PREFIX.writable_real? || HOMEBREW_PREFIX.to_s == "/usr/local"
  end

  def check_development_tools
    checks = Diagnostic::Checks.new
    checks.fatal_development_tools_checks.each do |check|
      out = checks.send(check)
      next if out.nil?
      ofail out
    end
    exit 1 if Homebrew.failed?
  end

  def check_cellar
    FileUtils.mkdir_p HOMEBREW_CELLAR unless File.exist? HOMEBREW_CELLAR
  rescue
    raise <<-EOS.undent
      Could not create #{HOMEBREW_CELLAR}
      Check you have permission to write to #{HOMEBREW_CELLAR.parent}
    EOS
  end

  def perform_preinstall_checks
    check_ppc
    check_writable_install_location
    check_development_tools if DevelopmentTools.installed?
    check_cellar
  end

  def install_formula(f)
    f.print_tap_action
    build_options = f.build

    fi = FormulaInstaller.new(f)
    fi.options              = build_options.used_options
    fi.invalid_option_names = build_options.invalid_option_names
    fi.ignore_deps          = ARGV.ignore_deps?
    fi.only_deps            = ARGV.only_deps?
    fi.build_bottle         = ARGV.build_bottle?
    fi.interactive          = ARGV.interactive?
    fi.git                  = ARGV.git?
    fi.prelude
    fi.install
    fi.finish
  rescue FormulaInstallationAlreadyAttemptedError
    # We already attempted to install f as part of the dependency tree of
    # another formula. In that case, don't generate an error, just move on.
  rescue CannotInstallFormulaError => e
    ofail e.message
  end
end


text:
package org.kie.workbench.common.stunner.core.client.canvas.controls.clipboard;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Default;

import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas;
import org.kie.workbench.common.stunner.core.client.canvas.controls.AbstractCanvasControl;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.util.GraphUtils;

@ApplicationScoped
@Default
public class LocalClipboardControl
        extends AbstractCanvasControl<AbstractCanvas>
        implements ClipboardControl<Element, AbstractCanvas, ClientSession> {

    private final Set<Element> elements;
    private final Map<String, String> elementsParent;
    private final List<Command> commands;

    public LocalClipboardControl() {
        this.elements = new HashSet<>();
        this.elementsParent = new HashMap<>();
        this.commands = new ArrayList<>();
    }

    @Override
    public ClipboardControl<Element, AbstractCanvas, ClientSession> set(Element... element) {
        clear();
        elements.addAll(Arrays.stream(element).collect(Collectors.toSet()));
        elementsParent.putAll(elements.stream().filter(e -> e instanceof Node).collect(Collectors.toMap(Element::getUUID, e -> GraphUtils.getParent(e.asNode()).getUUID())));
        return this;
    }

    @Override
    public ClipboardControl<Element, AbstractCanvas, ClientSession> remove(Element... element) {
        elements.removeAll(Arrays.stream(element).collect(Collectors.toSet()));
        return this;
    }

    @Override
    public Collection<Element> getElements() {
        return elements;
    }

    @Override
    public ClipboardControl<Element, AbstractCanvas, ClientSession> clear() {
        commands.clear();
        elements.clear();
        elementsParent.clear();
        return this;
    }

    @Override
    public boolean hasElements() {
        return !elements.isEmpty();
    }

    @Override
    public String getParent(String uuid) {
        return elementsParent.get(uuid);
    }

    @Override
    public List<Command> getRollbackCommands() {
        return commands;
    }

    @Override
    public ClipboardControl<Element, AbstractCanvas, ClientSession> setRollbackCommand(Command... command) {
        commands.clear();
        commands.addAll(Stream.of(command).collect(Collectors.toList()));
        return this;
    }

    @Override
    protected void doInit() {
    }

    @Override
    protected void doDestroy() {
        clear();
    }
}


text:
// File Name: utmLib.h
//
// Written By: Danny Kent (jaus AT dannykent DOT com)
//
// Version: 3.2
//
// Date: 08/04/06
//
// Description:	This file provides an interface to the cproj library for use as a UTM conversion engine

#ifndef UTM_WRAPPER_H
#define UTM_WRAPPER_H

#include <math.h>
#include "cproj.h"
#include "pointUtm.h"
#include "pointLla.h"
#include "greatCircle.h"

#ifndef RAD_PER_DEG
#define RAD_PER_DEG D2R
#endif

#ifndef DEG_PER_RAD
#define DEG_PER_RAD R2D
#endif

#ifndef TRUE
#define TRUE 1
#endif

#ifndef FALSE
#define FALSE 0
#endif

unsigned char utmInitCheck(void);
unsigned char utmZoneCheck(PointLla pointLla);
long utmConversionInit(PointLla pointLla);

PointLla pointUtmToPointLla(PointUtm pointUtm);
PointUtm pointLlaToPointUtm(PointLla pointLla);

#endif


text:
<?php
require_once Kwf_Config::getValue('externLibraryPath.facebookPhpSdk').'/src/facebook.php';

class Kwf_Util_Facebook_FacebookZendSession extends Facebook
{
  public function __construct($config) {
    $this->session = new Kwf_Session_Namespace('facebook');
    parent::__construct($config);
    if (!empty($config['sharedSession'])) {
      $this->initSharedSession();
    }
  }
  protected function initSharedSession() {
    $cookie_name = $this->getSharedSessionCookieName();
    if (isset($_COOKIE[$cookie_name])) {
      $data = $this->parseSignedRequest($_COOKIE[$cookie_name]);
      if ($data && !empty($data['domain']) &&
          self::isAllowedDomain($this->getHttpHost(), $data['domain'])) {
        // good case
        $this->sharedSessionID = $data['id'];
        return;
      }
      // ignoring potentially unreachable data
    }
    // evil/corrupt/missing case
    $base_domain = $this->getBaseDomain();
    $this->sharedSessionID = md5(uniqid(mt_rand(), true));
    $cookie_value = $this->makeSignedRequest(
      array(
        'domain' => $base_domain,
        'id' => $this->sharedSessionID,
      )
    );
    $_COOKIE[$cookie_name] = $cookie_value;
    if (!headers_sent()) {
      $expire = time() + self::FBSS_COOKIE_EXPIRE;
      setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain);
    } else {
      // @codeCoverageIgnoreStart
      self::errorLog(
        'Shared session ID cookie could not be set! You must ensure you '.
        'create the Facebook instance before headers have been sent. This '.
        'will cause authentication issues after the first request.'
      );
      // @codeCoverageIgnoreEnd
    }
  }
  protected function setPersistentData($key, $value) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to setPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    $this->session->$session_var_name = $value;
  }

  protected function getPersistentData($key, $default = false) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to getPersistentData.');
      return $default;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    return isset($this->session->$session_var_name) ?
      $this->session->$session_var_name : $default;
  }

  protected function clearPersistentData($key) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to clearPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    unset($this->session->$session_var_name);
  }
}


text:
certificate_file=$(mktemp)

# delete temporary file on exit
trap "unlink $certificate_file" EXIT

# domain address (eg. example.org)
certificate_domain=$1

# execute only if domain is provided
if [ ! -z "$certificate_domain" ]; then
  echo "domain address: $certificate_domain"

  # download remote certificate
  echo -n | openssl s_client -connect ${certificate_domain}:443 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $certificate_file

  # get certificate size and status
  certificate_size=$(stat -f "%z" $certificate_file)
  certificate_status=$(openssl x509 -in $certificate_file -noout 2>/dev/null; echo $?)

  if [ "$certificate_size" -gt "0" ] && [ "$certificate_status" -eq "0" ]; then
    echo "certificate details: "
    openssl x509 -in $certificate_file -noout -text | awk "/X509v3 Subject Alternative Name/{getline;print}; /Subject:/ {print}" | tr -s "^ "

    # import certificate to system keychain
    sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" $certificate_file
    if [ "$?" -eq "0" ]; then
      echo "certificate imported"
    else
      echo "certificate not imported"
      exit 2
    fi
  else
    echo "certificate not downloaded or bogus"
    exit 1
  fi
fi


text:
<component name="libraryTable">
  <library name="Google App Engine SDK" type="python">
    <CLASSES>
      <root url="file://$USER_HOME$/data_science_python2.7/google-cloud-sdk/bin" />
    </CLASSES>
    <SOURCES />
  </library>
</component>


text:
<add-printer-dialog>

    <iron-icon
      hidden="[[!pendingPrinter_.isManaged]]"
      icon="cr20:domain">
    </iron-icon>
    [[getDialogTitle_(pendingPrinter_.isManaged)]]
    <printer-dialog-error error-text="[[errorText_]]">
    </printer-dialog-error>

      <cr-input class="printer-name-input"
          id="printerName"
          value="{{pendingPrinter_.printerName}}"
          on-input="onPrinterInfoChange_"
          label="$i18n{printerName}"
          aria-label="$i18n{printerName}"
          readonly="[[pendingPrinter_.isManaged]]"
          maxlength=64>
      </cr-input>

      <cr-input label="$i18n{printerAddress}"
          aria-label="$i18n{printerAddress}"
          id="printerAddress"
          on-input="onPrinterInfoChange_"
          value="{{pendingPrinter_.printerAddress}}"
          disabled="[[!isInputFieldEnabled_(networkProtocolActive_,
              pendingPrinter_.printServerUri)]]"
          maxlength=63
          readonly="[[isInputFieldReadonly_(pendingPrinter_.isManaged,
              isOnline_)]]">
      </cr-input>

          $i18n{printerProtocol}

          <select class="md-select" aria-labelledby="printerProtocol"
              value="[[pendingPrinter_.printerProtocol]]"
              on-change="onProtocolChange_"
              disabled="[[!protocolSelectEnabled_(
                  networkProtocolActive_,
                  pendingPrinter_.printServerUri,
                  pendingPrinter_.isManaged,
                  isOnline_)]]">
            <option value="ipp">
              $i18n{printerProtocolIpp}
            </option>
            <option value="ipps">
              $i18n{printerProtocolIpps}
            </option>
            <option value="http"
                disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]">
              $i18n{printerProtocolHttp}
            </option>
            <option value="https"
                disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]">
              $i18n{printerProtocolHttps}
            </option>
            <option value="socket"
                disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]">
              $i18n{printerProtocolAppSocket}
            </option>
            <option value="lpd"
                disabled="[[isAutoconfPrinter_(pendingPrinter_.*)]]">
              $i18n{printerProtocolLpd}
            </option>
            <option value="usb" disabled="[[networkProtocolActive_]]">
              $i18n{printerProtocolUsb}
            </option>
            <option value="ippusb" disabled="[[networkProtocolActive_]]">
              $i18n{printerProtocolIppUsb}
            </option>
          </select>

      <cr-input id="printerQueue" label="$i18n{printerQueue}"
          aria-label="$i18n{printerQueue}"
          value="{{pendingPrinter_.printerQueue}}"
          on-input="onPrinterInfoChange_"
          maxlength=64
          disabled="[[!isInputFieldEnabled_(networkProtocolActive_,
              pendingPrinter_.printServerUri)]]"
          readonly="[[isInputFieldReadonly_(pendingPrinter_.isManaged,
              isOnline_)]]">
      </cr-input>

      <cr-input label="$i18n{printerURI}" readonly
          aria-label="$i18n{printerURI}"
          value="[[getPrinterURI_(pendingPrinter_)]]"
          disabled="[[!isInputFieldEnabled_(networkProtocolActive_,
              pendingPrinter_.printServerUri)]]"
          readonly="[[pendingPrinter_.isManaged]]">
      </cr-input>

    <template id="makeAndModelSection" is="dom-if"
        if="[[!isAutoconfPrinter_(pendingPrinter_.*)]]">

        <cr-searchable-drop-down items="[[manufacturerList]]"
            id="printerPPDManufacturer"
            label="$i18n{printerManufacturer}"
            aria-label="$i18n{printerManufacturer}"
            value="{{pendingPrinter_.ppdManufacturer}}"
            readonly="[[isInputFieldReadonly_(pendingPrinter_.isManaged,
                isOnline_)]]"
            invalid="{{isManufacturerInvalid_}}">
        </cr-searchable-drop-down>

        <cr-searchable-drop-down items="[[modelList]]"
            id="printerPPDModel"
            label="$i18n{printerModel}"
            value="{{pendingPrinter_.ppdModel}}"
            readonly="[[isInputFieldReadonly_(pendingPrinter_.isManaged,
                isOnline_)]]"
            invalid="{{isModelInvalid_}}">
        </cr-searchable-drop-down>

          <cr-button class="ppd-button" on-click="onViewPpd_"
                     disabled="[[!isViewPpdEnabled_(printerInfoChanged_,
                         viewPpdEnabled_)]]">
            $i18n{cupsPrintersViewPpd}
          </cr-button>
          <localized-link localized-string="$i18n{selectDriver}"
                          link-url="$i18n{printingCUPSPrintPpdLearnMoreUrl}">
          </localized-link>

        <cr-input class="browse-file-input" readonly input-tabindex="-1"
            value="[[userPPD_]]" aria-labelledby="ppdLabel"
            error-message="$i18n{selectDriverErrorMessage}"
            invalid="[[invalidPPD_]]">
        </cr-input>
        <cr-button class="browse-button" on-click="onBrowseFile_"
            disabled="[[!isOnline_]]"
            aria-label="$i18n{selectDriverButtonAriaLabel}">
          $i18n{selectDriverButtonText}
        </cr-button>

    </template>

        $i18n{printerEulaNotice}

      <cr-button class="cancel-button" on-click="onCancelTap_"
          hidden="[[pendingPrinter_.isManaged]]">
        $i18n{cancel}
      </cr-button>
      <cr-button class="action-button" on-click="onSaveTap_"
          disabled="[[!canSavePrinter_(pendingPrinter_.*,
              printerInfoChanged_,
              isOnline_, isManufacturerInvalid_, isModelInvalid_)]]"
              hidden="[[pendingPrinter_.isManaged]]">
        $i18n{editPrinterButtonText}
      </cr-button>
      <cr-button class="close-button" on-click="onCancelTap_"
       hidden="[[!pendingPrinter_.isManaged]]">
       $i18n{close}
      </cr-button>

</add-printer-dialog>


text:
from __future__ import print_function

import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
log = logging.getLogger(__name__)

from OCC.Display import OCCViewer
from OCC.Display.backend import get_qt_modules

QtCore, QtGui, QtWidgets, QtOpenGL = get_qt_modules()

class point(object):
    def __init__(self, obj=None):
        self.x = 0
        self.y = 0
        if obj is not None:
            self.set(obj)
            self.set(obj)

    def set(self, obj):
        self.x = obj.x()
        self.y = obj.y()

class qtBaseViewer(QtWidgets.QOpenGLWidget):
    def __init__(self, parent=None):
        QtWidgets.QOpenGLWidget.__init__(self, parent)
        '''format = QtGui.QSurfaceFormat()
        format.setDepthBufferSize(24)
        QtGui.QSurfaceFormat.setDefaultFormat(format)
        self.setFormat(format)'''
        self._display = None
        self._inited = False

        # enable Mouse Tracking
        self.setMouseTracking(True)
        # Strong focus
        self.setFocusPolicy(QtCore.Qt.WheelFocus)

        # required for overpainting the widget
        self.setAttribute(QtCore.Qt.WA_PaintOnScreen)
        self.setAttribute(QtCore.Qt.WA_NoSystemBackground)
        self.setAutoFillBackground(False)

    def GetHandle(self):
        ''' returns an the identifier of the GUI widget.
        It must be an integer
        '''
        win_id = self.winId()  # this returns either an int or voitptr

        if "%s"%type(win_id) == "<type 'PyCObject'>":  # PySide
            ### with PySide, self.winId() does not return an integer
            if sys.platform == "win32":
                ## Be careful, this hack is py27 specific
                ## does not work with python31 or higher
                ## since the PyCObject api was changed
                import ctypes
                ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p
                ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [
                    ctypes.py_object]
                win_id = ctypes.pythonapi.PyCObject_AsVoidPtr(win_id)
        elif type(win_id) is not int:  #PyQt4 or 5
            ## below integer cast may be required because self.winId() can
            ## returns a sip.voitptr according to the PyQt version used
            ## as well as the python version
            win_id = int(win_id)
            pass
        return win_id

    def resizeEvent(self, event):
        if self._inited:
            self._display.OnResize()

class qtViewer3d(qtBaseViewer):
    def __init__(self, *kargs):
        qtBaseViewer.__init__(self, *kargs)
        self._drawbox = False
        self._zoom_area = False
        self._select_area = False
        self._inited = False
        self._leftisdown = False
        self._middleisdown = False
        self._rightisdown = False
        self._selection = None
        self._drawtext = True

    def InitDriver(self):
        self._display = OCCViewer.Viewer3d(self.GetHandle())
        self._display.Create()
        # background gradient
        self._display.set_bg_gradient_color(206, 215, 222, 128, 128, 128)
        # background gradient
        self._display.display_trihedron()
        self._display.SetModeShaded()
        # self._display.EnableAntiAliasing()
        self._inited = True
        # dict mapping keys to functions
        self._SetupKeyMap()
        #
        self._display.thisown = False

    def _SetupKeyMap(self):
        def set_shade_mode():
            self._display.DisableAntiAliasing()
            self._display.SetModeShaded()

        self._key_map = {ord('W'): self._display.SetModeWireFrame,
                         ord('S'): set_shade_mode,
                         ord('A'): self._display.EnableAntiAliasing,
                         ord('B'): self._display.DisableAntiAliasing,
                         ord('H'): self._display.SetModeHLR,
                         ord('F'): self._display.FitAll,
                         ord('G'): self._display.SetSelectionMode,
                         ord('P'): self._display.SetPerspectiveProjection,
                         ord('O'): self._display.SetOrthographicProjection}

    def keyPressEvent(self, event):
        code = event.key()
        if code in self._key_map:
            self._key_map[code]()
        else:
            msg = "key: {0}\nnot mapped to any function".format(code)
            log.info(msg)

    def Test(self):
        if self._inited:
            self._display.Test()

    def focusInEvent(self, event):
        if self._inited:
            self._display.Repaint()

    def focusOutEvent(self, event):
        if self._inited:
            self._display.Repaint()

    '''def paintEvent(self, event):
        print("caadfadfasd")
        if self._inited:
            self._display.Context.UpdateCurrentViewer()
            # important to allow overpainting of the OCC OpenGL context in Qt
            #self.swapBuffers()

        if self._drawbox:
            self.makeCurrent()
            painter = QtGui.QPainter(self)
            painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 0), 1))
            rect = QtCore.QRect(*self._drawbox)
            painter.drawRect(rect)
            painter.end()
            self.doneCurrent()'''

    def resizeGL(self, width, height):
        self.setupViewport(width, height)

    def ZoomAll(self, evt):
        self._display.FitAll()

    def wheelEvent(self, event):
        try:  # PyQt4/PySide
            delta = event.delta()
        except:  # PyQt5
            delta = event.angleDelta().y()
        if delta > 0:
            zoom_factor = 2
        else:
            zoom_factor = 0.5
        self._display.Repaint()
        self._display.ZoomFactor(zoom_factor)

    def dragMoveEvent(self, event):
        pass

    def mousePressEvent(self, event):
        self.setFocus()
        self.dragStartPos = point(event.pos())
        self._display.StartRotation(self.dragStartPos.x, self.dragStartPos.y)

    def mouseReleaseEvent(self, event):
        pt = point(event.pos())
        modifiers = event.modifiers()

        if event.button() == QtCore.Qt.LeftButton:
            pt = point(event.pos())
            if self._select_area:
                [Xmin, Ymin, dx, dy] = self._drawbox
                self._display.SelectArea(Xmin, Ymin, Xmin + dx, Ymin + dy)
                self._select_area = False
            else:
                # multiple select if shift is pressed
                if modifiers == QtCore.Qt.ShiftModifier:
                    self._display.ShiftSelect(pt.x, pt.y)
                else:
                    # single select otherwise
                    self._display.Select(pt.x, pt.y)
        elif event.button() == QtCore.Qt.RightButton:
            if self._zoom_area:
                [Xmin, Ymin, dx, dy] = self._drawbox
                self._display.ZoomArea(Xmin, Ymin, Xmin + dx, Ymin + dy)
                self._zoom_area = False

    def DrawBox(self, event):
        tolerance = 2
        pt = point(event.pos())
        dx = pt.x - self.dragStartPos.x
        dy = pt.y - self.dragStartPos.y
        if abs(dx) <= tolerance and abs(dy) <= tolerance:
            return
        self._drawbox = [self.dragStartPos.x, self.dragStartPos.y, dx, dy]
        self.update()

    def mouseMoveEvent(self, evt):
        pt = point(evt.pos())
        buttons = int(evt.buttons())
        modifiers = evt.modifiers()
        # ROTATE
        if (buttons == QtCore.Qt.LeftButton and
                not modifiers == QtCore.Qt.ShiftModifier):
            dx = pt.x - self.dragStartPos.x
            dy = pt.y - self.dragStartPos.y
            self._display.Rotation(pt.x, pt.y)
            self._drawbox = False
        # DYNAMIC ZOOM
        elif (buttons == QtCore.Qt.RightButton and
                  not modifiers == QtCore.Qt.ShiftModifier):
            self._display.Repaint()
            self._display.DynamicZoom(abs(self.dragStartPos.x),
                                      abs(self.dragStartPos.y), abs(pt.x),
                                      abs(pt.y))
            self.dragStartPos.x = pt.x
            self.dragStartPos.y = pt.y
            self._drawbox = False
        # PAN
        elif buttons == QtCore.Qt.MidButton:
            dx = pt.x - self.dragStartPos.x
            dy = pt.y - self.dragStartPos.y
            self.dragStartPos.x = pt.x
            self.dragStartPos.y = pt.y
            self._display.Pan(dx, -dy)
            self._drawbox = False
        # DRAW BOX
        # ZOOM WINDOW
        elif (buttons == QtCore.Qt.RightButton and
                      modifiers == QtCore.Qt.ShiftModifier):
            self._zoom_area = True
            self.DrawBox(evt)
        # SELECT AREA
        elif (buttons == QtCore.Qt.LeftButton and
                      modifiers == QtCore.Qt.ShiftModifier):
            self._select_area = True
            self.DrawBox(evt)
        else:
            self._drawbox = False
            self._display.MoveTo(pt.x, pt.y)


text:
/**
 * Writes a user's GTM accounts to the sheet.
 */
function writeGtmAccountsToSheet() {
  checkRelease();
  const accounts = listGTMResources('accounts');
  if (accounts.length > 0) {
    const formattedAccounts = accounts.reduce((arr, account) => {
      arr.push([account.name, account.path]);
      return arr;
    }, []);
    writeToSheet(formattedAccounts, 'gtmWorkspace', 'accounts list');
  }
}

/**
 * Writes a user's GTM containers to the sheet.
 */
function writeSelectedGtmContainersToSheet() {
  const accounts = getDataFromSheet('gtmWorkspace', 'accounts list');
  const selectedAccounts = accounts.filter(account => account[2]);
  const containers = listGTMResources('containers', selectedAccounts[0][1]);
  if (containers.length > 0) {
    const formattedContainers = containers.reduce((arr, container) => {
      arr.push([container.name, container.path]);
      return arr;
    }, []);
    writeToSheet(formattedContainers, 'gtmWorkspace', 'containers list');
  }
}

/**
 * Writes a user's GTM workspaces to the sheet.
 */
function writeSelectedGtmWorkspacesToSheet() {
  const containers = getDataFromSheet('gtmWorkspace', 'containers list');
  const selectedContainers = containers.filter(container => container[2]);
  const workspaces = listGTMResources('workspaces', selectedContainers[0][1]);
  if (workspaces.length > 0) {
    const formattedWorkspaces = workspaces.reduce((arr, workspace) => {
      arr.push([workspace.name, workspace.path]);
      return arr;
    }, []);
    writeToSheet(formattedWorkspaces, 'gtmWorkspace', 'workspaces list');
  }
}

/**
 * Gets the selected workspace path from the GTM Workspace sheet.
 * return {string} The selected workspace path.
 */
function getSelectedWorkspacePath() {
  const workspaces = getDataFromSheet('gtmWorkspace', 'workspaces list');
  const selectedWorkspace = workspaces.filter(workspace => workspace[2]);
  if (selectedWorkspace.length == 0) {
    ui.alert(messageText.missingGTMWorkspace);
    return '';
  } else {
   return selectedWorkspace[0][1];
  }
}

/**
 * Gets the selected workspace name from the GTM Workspace sheet.
 * return {string} The selected workspace name.
 */
function getSelectedWorkspaceName() {
  const workspaces = getDataFromSheet('gtmWorkspace', 'workspaces list');
  const selectedWorkspace = workspaces.filter(workspace => workspace[2]);
  if (selectedWorkspace.length == 0) {
    ui.alert(messageText.missingGTMWorkspace);
    return '';
  } else {
   return selectedWorkspace[0][0];
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: karlvaniseghem
 * Date: 19/09/15
 * Time: 22:12
 */

namespace Bakgat\Notos\Domain\Model\Descriptive;

interface TagRepository
{
    /**
     * Gets all tags
     * @return mixed
     */
    public function all();

    /**
     * Get all tags used in another table of type
     *
     * @param $type
     * @return mixed
     */
    public function allOfType($type);

    /**
     * Add a tag
     * @param Tag $tag
     * @return mixed
     */
    public function add(Tag $tag);

    /**
     * Updates a tag
     *
     * @param Tag $tag
     * @return mixed
     */
    public function update(Tag $tag);

    /**
     * Removes a tag
     *
     * @param Tag $tag
     * @return mixed
     */
    public function remove(Tag $tag);

    /**
     * Finds a tag by it's name
     *
     * @param TagName $name
     * @return Tag
     */
    public function tagOfName(TagName $name);

    /**
     * Finds a tag by it's name or create one
     *
     * @param TagName $name
     * @return Tag
     */
    public function tagOfNameOrCreate(TagName $name);

}


text:
'use strict';

// Fizz buzz module config
angular.module('fizz-buzz').run(['Menus',
	function(Menus) {
		// Config logic
		// ...
		Menus.addMenuItem('topbar', 'FizzBuzz', 'fizz-buzz', 'item', '/fizz-buzz', true);
	}
]);


text:
'''An opengl demo for PyQt5
test on Windows with Python3.6
'''

import array

from PyQt5 import QtGui

vertexShaderCode = '''#version 410

layout(location=0) in vec4 position;
layout(location=1) in vec4 color;

out vec4 theColor;

void main()
{
    gl_Position = position;
    theColor = color;
}
'''

fragmentShaderCode = '''#version 410

in vec4 theColor;

out vec4 outColor;

void main()
{
    outColor = theColor;
}
'''

class Triangle(QtGui.QOpenGLWindow):

    def __init__(self, parent=None):
        super(Triangle, self).__init__(QtGui.QOpenGLWindow.NoPartialUpdate, parent)

        format_ = QtGui.QSurfaceFormat()
        format_.setRenderableType(QtGui.QSurfaceFormat.OpenGL)
        format_.setProfile(QtGui.QSurfaceFormat.CoreProfile)
        # PyQt5 5.8.2 only has 4.1.0 opengl binding
        format_.setVersion(4, 1)
        self.setFormat(format_)

        self.gl = None
        self.program = QtGui.QOpenGLShaderProgram()
        self.vao = QtGui.QOpenGLVertexArrayObject()

    def __del__(self):
        self.program.deleteLater()
        self.vao.destroy()

    def initializeGL(self):
        self.gl = self.context().versionFunctions()
        self.gl.initializeOpenGLFunctions()
        #
        self.printContextInformation()
        #

        self.program.create()
        self.program.addShaderFromSourceCode(QtGui.QOpenGLShader.Vertex, vertexShaderCode)
        self.program.addShaderFromSourceCode(QtGui.QOpenGLShader.Fragment, fragmentShaderCode)
        self.program.link()
        assert self.program.isLinked()

        vertexData = array.array('f', [
            # position
            0.0, 0.5, 0.0, 1.0,
            0.5, -0.366, 0.0, 1.0,
            -0.5, -0.366, 0.0, 1.0,
            # colors
            1.0, 0.0, 0.0, 1.0,
            0.0, 1.0, 0.0, 1.0,
            0.0, 0.0, 1.0, 1.0
        ])

        vertexMem = memoryview(vertexData)

        vbo = QtGui.QOpenGLBuffer()
        vbo.create()
        vbo.setUsagePattern(vbo.StaticDraw)
        vbo.bind()
        # vbo.allocate(vertexData, vertexData.buffer_info()[1]*vertexData.itemsize)
        vbo.allocate(vertexData, vertexMem.nbytes)

        self.vao.create()
        self.vao.bind()
        vbo.bind()
        self.program.bind()

        self.program.enableAttributeArray(0)
        self.program.setAttributeBuffer(0, self.gl.GL_FLOAT, 0, 4, 0)

        self.program.enableAttributeArray(1)
        self.program.setAttributeBuffer(1, self.gl.GL_FLOAT, 12*vertexMem.itemsize, 4, 0)

        self.vao.release()
        self.program.release()
        vbo.destroy()

    # def resizeGL(self, w, h):
    #     super(Triangle, self).resizeGL(w, h)

    def paintGL(self):
        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT)
        self.gl.glClearColor(0.0, 0.0, 0.0, 1.0)
        self.program.bind()
        self.vao.bind()

        self.gl.glDrawArrays(self.gl.GL_TRIANGLES, 0, 3)

        self.program.release()
        self.vao.release()

    def printContextInformation(self):
        glType = 'OpenGL ES' if self.context().isOpenGLES() else "OpenGL"
        glVersion = self.gl.glGetString(self.gl.GL_VERSION)

        print('{} : {}'.format(glType, glVersion))

if __name__ == '__main__':
    import sys

    app = QtGui.QGuiApplication(sys.argv)

    window = Triangle()
    window.setTitle('PyQt5 Opengl demo')
    window.resize(1280, 720)
    window.show()

    sys.exit(app.exec_())