text:
Two rules were changed from [feross/standard](https://github.com/feross/standard):

### Use 2 spaces for indentation

  eslint: [`indent`](http://eslint.org/docs/rules/indent)

  ```js
  function hello (name) {
    console.log('hi', name)
  }
  ```

  [qb-standard recommends 4 spaces](recommended-style.md)

### Use camelcase when naming variables and functions

  eslint: [`camelcase`](http://eslint.org/docs/rules/camelcase)

  ```js
    function my_function () { }    // ✗ avoid
    function myFunction () { }     // ✓ ok

    var my_var = 'hello'           // ✗ avoid
    var myVar = 'hello'            // ✓ ok
  ```

  [qb-standard recommends snake_case for some names](recommended-style.md)

# Rules not kept

The following rules from [feross/standard](https://github.com/feross/standard)
were decided to be not quite impactful enough keep:

### Wrap conditional assignments with additional parentheses

  This makes it clear that the expression is intentionally an assignment (`=`) rather than a typo for equality (`===`).

  eslint: [`no-cond-assign`](http://eslint.org/docs/rules/no-cond-assign)

  ```js
  // ✓ ok
  while ((m = text.match(expr))) {
      // ...
  }

  // ✗ avoid
  while (m = text.match(expr)) {
      // ...
  }
  ```

Why not enforced?  100% line and branch coverage will almost certainly catch such mistakes.

### Trailing commas not allowed

  eslint: [`comma-dangle`](http://eslint.org/docs/rules/comma-dangle)

  ```js
    var obj = {
        message: 'hello',   // ✗ avoid
    }
  ```

Why not enforced?

Trailing commas don't cause a safety concern outside of IE8 and there are
consistency and ease-of-use benefits in using them to manage vertical lists.

Here's an example of trailing commas helping reduce diff-noise:

Let's say this object:

```js
var info = {
    first_name: "Stanley",
    last_name: "Peabody",
    address: "2015 U.S. Highway Route 22, Fimblebuck, New Jersey, 03252-2355"
}
```

... is changed to this:

```js
var info = {
    first_name: "Stanley",
    last_name: "Peabody",
    address: "2015 U.S. Highway Route 22, Fimblebuck, New Jersey, 03252-2355",
    cell_phone: "377-232-0333"
}
```

The diff shows:

```
--- a/doc/t.js
+++ b/doc/t.js
@@ -1,5 +1,6 @@
 var info = {
     first_name: "Stanley",
     last_name: "Peabody",
-    address: "2015 U.S. Highway Route 22, Fimblebuck, New Jersey, 03252-2355"
+    address: "2015 U.S. Highway Route 22, Fimblebock, New Jersey, 03252-2355",
+    cell_phone: "377-232-0333"
 }
```

So cell_phone was added...

Did you notice that Fimblebuck changed spelling too?  If changing
that line was dangerous to our system, we could easily have overlooked it in
a review.  If we had used dangling commas, the spelling change
would have been much more obvious.

So we leave use of dangling commas a author judgement call and suggest that if you
see them in someone else's file, to **not** help "clean them up".  They might be intentional.

### Commas should have a space after them.

  eslint: [`comma-spacing`](http://eslint.org/docs/rules/comma-spacing)

  ```js
  // ✓ ok
  var list = [1, 2, 3, 4]
  function greet (name, options) { ... }
  ```

  ```js
  // ✗ avoid
  var list = [1,2,3,4]
  function greet (name,options) { ... }
  ```

  Why not enforced?  Very long lists might be better to cram into smaller space.
  Not a safety or significant readability concern.

### For var declarations, write each declaration in its own statement.

  eslint: [`one-var`](http://eslint.org/docs/rules/one-var)

  ```js
  // ✓ ok
  var silent = true
  var verbose = true

  // ✗ avoid
  var silent = true, verbose = true

  // ✗ avoid
  var silent = true,
      verbose = true
  ```
  Why not enforced?   Not a safety or significant readability concern.

### Add spaces inside single line blocks

  eslint: [`block-spacing`](http://eslint.org/docs/rules/block-spacing)

  ```js
    function foo () {return true}    // ✗ avoid
    function foo () { return true }  // ✓ ok
  ```

  Why not enforced?  Not a safety or significant readability concern.

### No label statements

  eslint: [`no-labels`](http://eslint.org/docs/rules/no-labels)

  ```js
  label:
      while (true) {
          break label     // ✗ avoid
      }
  ```

  Why not enforced?  Some high-performance code is clearer with label use.  Inappropriate
  use is a judgement call.

### Do not use multiple spaces except for indentation

  eslint: [`no-multi-spaces`](http://eslint.org/docs/rules/no-multi-spaces)

  ```js
  const id =    1234    // ✗ avoid
  const id = 1234       // ✓ ok
  ```
   Why not enforced?   Not a significant readability or safety concern.  Agree it can
   be annoying when over-applied, but in some cases, alignment can help readability:

```js
  var padright = function (s, l) { while(s.length < l) s = s + ' '; return s }
  var padleft =  function (s, l) { while(s.length < l) s = ' ' + s; return s }
```

   Probably best to leave up to author's judgement.

redpajama_set_name: RedPajamaGithub


text:
package sarama

import "encoding/binary"

// LengthField implements the PushEncoder and PushDecoder interfaces for calculating 4-byte lengths.
type lengthField struct {
	startOffset int
	length      int32
}

func (l *lengthField) decode(pd packetDecoder) error {
	var err error
	l.length, err = pd.getInt32()
	if err != nil {
		return err
	}
	if l.length > int32(pd.remaining()) {
		return ErrInsufficientData
	}
	return nil
}

func (l *lengthField) saveOffset(in int) {
	l.startOffset = in
}

func (l *lengthField) reserveLength() int {
	return 4
}

func (l *lengthField) run(curOffset int, buf []byte) error {
	binary.BigEndian.PutUint32(buf[l.startOffset:], uint32(curOffset-l.startOffset-4))
	return nil
}

func (l *lengthField) check(curOffset int, buf []byte) error {
	if int32(curOffset-l.startOffset-4) != l.length {
		return PacketDecodingError{"length field invalid"}
	}

	return nil
}

type varintLengthField struct {
	startOffset int
	length      int64
}

func (l *varintLengthField) decode(pd packetDecoder) error {
	var err error
	l.length, err = pd.getVarint()
	return err
}

func (l *varintLengthField) saveOffset(in int) {
	l.startOffset = in
}

func (l *varintLengthField) adjustLength(currOffset int) int {
	oldFieldSize := l.reserveLength()
	l.length = int64(currOffset - l.startOffset - oldFieldSize)

	return l.reserveLength() - oldFieldSize
}

func (l *varintLengthField) reserveLength() int {
	var tmp [binary.MaxVarintLen64]byte
	return binary.PutVarint(tmp[:], l.length)
}

func (l *varintLengthField) run(curOffset int, buf []byte) error {
	binary.PutVarint(buf[l.startOffset:], l.length)
	return nil
}

func (l *varintLengthField) check(curOffset int, buf []byte) error {
	if int64(curOffset-l.startOffset-l.reserveLength()) != l.length {
		return PacketDecodingError{"length field invalid"}
	}

	return nil
}


text:
package org.apache.mina.core.filterchain;

/**
 * A {@link RuntimeException} which is thrown when {@link IoFilter#init()}
 * or {@link IoFilter#onPostAdd(IoFilterChain, String, org.apache.mina.core.filterchain.IoFilter.NextFilter)}
 * failed.
 *
 * @author Apache MINA Project
 */
public class IoFilterLifeCycleException extends RuntimeException {
    private static final long serialVersionUID = -5542098881633506449L;

    public IoFilterLifeCycleException() {
    }

    public IoFilterLifeCycleException(String message) {
        super(message);
    }

    public IoFilterLifeCycleException(String message, Throwable cause) {
        super(message, cause);
    }

    public IoFilterLifeCycleException(Throwable cause) {
        super(cause);
    }
}


text:
'use strict';

var Promise  = require('../ext/promise');
var chalk    = require('chalk');
var Task     = require('../models/task');
var fs       = require('fs');

module.exports = Task.extend({
  run: function(options, updateInfo) {
    this.ui.write(chalk.yellow('\nA new version of ember-cli is available (' +
      updateInfo.newestVersion + ').\n'));

    var updatePrompt = {
      type: 'confirm',
      name: 'answer',
      message: 'Are you sure you want to update ember-cli?',
      choices: [
        { key: 'y', name: 'Yes, update', value: 'yes' },
        { key: 'n', name: 'No, cancel', value: 'no' }
      ]
    };

    return this.ui.prompt(updatePrompt).then(function(response) {
      if (response.answer === true) {
        this.runNpmUpdate(updateInfo.newestVersion);
      }
    }.bind(this));
  },
  init: function() {
    this.npm = this.npm || require('npm');
    this.loadNPM = Promise.denodeify(this.npm.load);
  },

  runNpmUpdate: function(newestVersion) {
    this.ui.pleasantProgress.start(chalk.green('Updating ember-cli'), chalk.green('.'));

    this.loadNPM({
      loglevel: 'silent',
      global: true
    })
    .then(function(npm) {
      return Promise.denodeify(npm.commands.install)(['ember-cli']);
    }.bind(this))
    .then(function() {
      // update project's package.json file manually
      var packageFilePath = this.project.root + '/package.json';

      if (!fs.existsSync(packageFilePath)) {
        this.ui.write('There was an error locating your package.json file.');
        return false;
      }

      var fileContent = fs.readFileSync(packageFilePath);
      var jsonContent = JSON.parse(fileContent);

      jsonContent.devDependencies['ember-cli'] = newestVersion;
      fs.writeFileSync(packageFilePath, JSON.stringify(jsonContent, null, 2));
      this.ui.write(chalk.green('\n✓ ember-cli was successfully updated!\n'));
      this.showEmberInitPrompt();
    }.bind(this))
    .catch(function() {
      this.ui.write('There was an error – possibly a permissions issue. You ' +
        'may need to manually run ' +
        chalk.green('npm install -g ember-cli') + '.\n');
    }.bind(this))
    .finally(function() {
      this.ui.pleasantProgress.stop();
    }.bind(this));
  },

  showEmberInitPrompt: function() {
    this.ui.write('To complete the update, you need to run ' +
      chalk.green('ember init') + ' in your project directory.\n');

    var initPrompt = {
      type: 'confirm',
      name: 'answer',
      message: 'Would you like to run ' + chalk.green('ember init') + ' now?',
      choices: [
        { key: 'y', name: 'Yes', value: 'yes' },
        { key: 'n', name: 'No', value: 'no' }
      ]
    };

    return this.ui.prompt(initPrompt).then(function(response) {
      if (response.answer === true) {
        var InitCommand = this.commands.Init;

        var initCommand = new InitCommand({
          ui: this.ui,
          analytics: this.analytics,
          tasks: this.tasks,
          project: this.project
        });

        initCommand.run({}, []);
      }
    }.bind(this));
  }

});


text:
#include "umlPortHandler.h"

#include "editor/nodeElement.h"
#include "editor/private/borderChecker.h"

UmlPortHandler::UmlPortHandler(NodeElement * const node)
		: mNode(node), mBelongsToHorizontalBorders(true)
{
}

void UmlPortHandler::handleMoveEvent(const bool leftPressed
		, QPointF &pos, const QPointF &scenePos
		, NodeElement *&parentNode)
{
	if (!mNode || !leftPressed) {
		return;
	}

	if (pos == QPointF(0,0)) {
		pos = mNode->pos();
	}

	QGraphicsItem* const item = mNode->scene()->items(scenePos).value(1);
	NodeElement* const actionItem = dynamic_cast<NodeElement * const>(item);
	const BorderChecker actionItemBorderChecker(actionItem);
	QPointF posInItem = QPointF(0, 0);
	if (actionItem && ((actionItem == parentNode) || (!parentNode))) {
		posInItem = actionItem->mapFromScene(scenePos);

		const bool checkLowerBorder = actionItemBorderChecker.checkLowerBorder(posInItem);
		const bool checkUpperBorder = actionItemBorderChecker.checkUpperBorder(posInItem);
		const bool checkRightBorder = actionItemBorderChecker.checkRightBorder(posInItem);
		const bool checkLeftBorder = actionItemBorderChecker.checkLeftBorder(posInItem);
		const bool checkBorders = checkLowerBorder || checkUpperBorder
			|| checkRightBorder || checkLeftBorder;

		if (checkBorders) {
			mNode->setParentItem(actionItem);
			parentNode = actionItem;
			pos = mNode->pos();
			mBelongsToHorizontalBorders = checkLowerBorder || checkUpperBorder;
		} else {
			handleHorizontalBorders(actionItem, parentNode, pos, posInItem);
		}
	} else if (parentNode) {
			mNode->setPos(pos);
			if (parentNode) {
				posInItem = parentNode->mapFromScene(scenePos);
				handleHorizontalBorders(parentNode, parentNode, pos, posInItem);
			}
	}
}

void UmlPortHandler::handleHorizontalBorders(
		const NodeElement * const tmpNode, const NodeElement * const parentNode
		, const QPointF &pos, const QPointF &posInItem) const
{
	QPointF newPos = pos;
	const BorderChecker parentNodeBorderChecker(parentNode);
	if (mBelongsToHorizontalBorders) {
		// tmpNode->borderValues()[0] == xHor of tmpNode. (mXHor field of BorderChecker(tmpNode))
		if (parentNodeBorderChecker.checkNoBorderY(posInItem, tmpNode->borderValues()[0])) {
			newPos.setX(posInItem.x());
		}
	} else {
		// tmpNode->borderValues()[3] == yVert of tmpNode. (mYVert field of BorderChecker(tmpNode))
		if (parentNodeBorderChecker.checkNoBorderX(posInItem, tmpNode->borderValues()[3])) {
			newPos.setY(posInItem.y());
		}
	}
	mNode->setPos(newPos);
}


text:
include(CMakeParseArguments)

#--------------------------------------------------------------------
# Creates a inviwo module
macro(ivw_module project_name)
    project(${project_name} ${ARGN})
endmacro()

#--------------------------------------------------------------------
# Retrieve all enabled modules as a list
function(ivw_retrieve_all_modules module_list)
    set(${module_list} ${ivw_all_registered_modules} PARENT_SCOPE)
endfunction()

#--------------------------------------------------------------------
# Determine application dependencies.
# Creates a list of enabled modules in executable directory if runtime
# module loading is enabled. Otherwise sets the registration macros and
# adds module dependencies
# Example: ivw_configure_application_module_dependencies(inviwo ${list_of_modules})
# The list of modules is usually fetched from ivw_retrieve_all_modules
function(ivw_configure_application_module_dependencies target)
    if(IVW_CFG_RUNTIME_MODULE_LOADING)
        # Specify which modules to load at runtime (all will be loaded if the file does not exist)
        ivw_create_enabled_modules_file(${target} ${ARGN})
        target_compile_definitions(${target} PUBLIC IVW_RUNTIME_MODULE_LOADING)
        # Dependencies to build before this project when they are changed.
        # Needed if modules are loaded at runtime since they should be built
        # when this project is set as startup project
        ivw_mod_name_to_alias(dep_targets ${ARGN})
        add_dependencies(${target} ${dep_targets})
    else()
        ivw_mod_name_to_reg(reg_targets ${ARGN})
        target_compile_definitions(${target} PUBLIC ${reg_targets})
        ivw_mod_name_to_alias(dep_targets ${ARGN})
        target_link_libraries(${target} PUBLIC ${dep_targets})
    endif()
endfunction()

function(ivw_private_filter_dependency_list retval module)
    set(the_list "")
    if(ARGN)
        foreach(item ${ARGN})
            string(REGEX MATCH "(^Inviwo.*.Module$)" found_item ${item})
            if(found_item)
                list(APPEND the_list ${item})
            else()
                string(TOLOWER ${module} l_module)
                message(WARNING "Found dependency: \"${item}\", "
                    "which is not an Inviwo module in depends.cmake for module: \"${module}\". "
                    "Incorporate non Inviwo module dependencies using regular target_link_libraries. "
                    "For example: target_link_libraries(inviwo-module-${l_module} PUBLIC ${item})")
            endif()
        endforeach()
    endif()
    set(${retval} ${the_list} PARENT_SCOPE)
endfunction()

function(ivw_private_check_dependency_list retval modules_var module)
    set(the_list "")
    if(ARGN)
        foreach(item ${ARGN})
            string(TOUPPER ${item} u_item)
            list(FIND ${modules_var} ${u_item} found)
            if(NOT ${found} EQUAL -1)
                list(APPEND the_list ${item})
            else()
                message(WARNING "Found dependency: \"${item}\", in depends.cmake for"
                    " module: \"${module}\". But no such Inviwo module was registered.")
            endif()
        endforeach()
    endif()
    set(${retval} ${the_list} PARENT_SCOPE)
endfunction()

function(ivw_private_setup_module_data)
    set(options CORE)
    set(oneValueArgs DIR BASE NAME GROUP)
    set(multiValueArgs "")
    cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

    set(dir ${ARG_DIR})
    set(name ${ARG_NAME})
    set(module_path ${ARG_BASE})
    ivw_dir_to_mod_dep(mod ${dir})
    ivw_dir_to_mod_prefix(opt ${dir})           # OpenGL -> IVW_MODULE_OPENGL
    ivw_dir_to_module_taget_name(target ${dir}) # OpenGL -> inviwo-module-opengl

    ivw_private_get_ivw_module_include_path(${module_path}/${dir} includePrefix includePath orgName)
    # includePrefix -> inviwo/opengl
    # includePath -> ... inviwo/modules/opengl/include/inviwo/opengl
    # orgName -> inviwo

    # Get the classname with the right casing
    if(${ARG_CORE})
        set(class "InviwoCore")
        set(alias "inviwo::core")
        set(target "inviwo-core")
        set(header "inviwo/core/common/inviwocore.h")
        set(api "IVW_CORE_API")
        set(includePrefix "inviwo/core")
        set(includePath "${module_path}/${dir}/inviwo/core")
        set(orgName "inviwo")
        set(apiDefineInc "inviwo/core/common/inviwocoredefine.h")
        set(sharedLibInc "inviwo/core/common/coremodulesharedlibrary.h")
        set(sharedLibCpp ${CMAKE_BINARY_DIR}/modules/${dir}/src/common/${dir}modulesharedlibrary.cpp)
    else()
        set(class "${name}Module")
        set(alias "inviwo::module::${dir}")
        set(header "${includePrefix}/${dir}module.h")
        string(TOUPPER "${name}" u_module)
        set(api "IVW_MODULE_${u_module}_API")
        set(apiDefineInc ${includePrefix}/${dir}moduledefine.h)
        set(sharedLibInc ${includePrefix}/${dir}modulesharedlibrary.h)
        set(sharedLibCpp ${CMAKE_BINARY_DIR}/modules/${dir}/src/${dir}modulesharedlibrary.cpp)
    endif()
    set(sharedLibHpp ${CMAKE_BINARY_DIR}/modules/${dir}/include/${sharedLibInc})

    # Get module version
    ivw_private_get_ivw_module_version(${module_path}/${dir}/CMakeLists.txt version)
    set("${mod}_name"         "${name}"               CACHE INTERNAL "Module name")
    set("${mod}_dir"          "${dir}"                CACHE INTERNAL "Module dir")
    set("${mod}_base"         "${module_path}"        CACHE INTERNAL "Module base")
    set("${mod}_path"         "${module_path}/${dir}" CACHE INTERNAL "Module path")
    set("${mod}_group"        "${ARG_GROUP}"          CACHE INTERNAL "Module group")
    set("${mod}_opt"          "${opt}"                CACHE INTERNAL "Module cmake option")
    set("${mod}_target"       "${target}"             CACHE INTERNAL "Module target")
    set("${mod}_alias"        "${alias}"              CACHE INTERNAL "Module alias")
    set("${mod}_class"        "${class}"              CACHE INTERNAL "Module class")
    set("${mod}_modName"      "Inviwo${name}Module"   CACHE INTERNAL "Module mod name")
    set("${mod}_version"      "${version}"            CACHE INTERNAL "Module version")
    set("${mod}_header"       "${header}"             CACHE INTERNAL "Module header")
    set("${mod}_incPrefix"    "${includePrefix}"      CACHE INTERNAL "Module include Prefix")
    set("${mod}_incPath"      "${includePath}"        CACHE INTERNAL "Module include Path")
    set("${mod}_orgName"      "${orgName}"            CACHE INTERNAL "Module Org Name")
    set("${mod}_api"          "${api}"                CACHE INTERNAL "API Macro")
    set("${mod}_apiDefineInc" "${apiDefineInc}"       CACHE INTERNAL "API header include")
    set("${mod}_sharedLibInc" "${sharedLibInc}"       CACHE INTERNAL "Shared lib include")
    set("${mod}_sharedLibCpp" "${sharedLibCpp}"       CACHE INTERNAL "Shared lib Source")
    set("${mod}_sharedLibHpp" "${sharedLibHpp}"       CACHE INTERNAL "Shared lib Header")

    # Check of there is a depends.cmake
    # Optionally defines: dependencies, aliases, protected, EnableByDefault
    # Save dependencies to INVIWO<NAME>MODULE_dependencies
    # Save aliases to INVIWO<NAME>MODULE_aliases
    # Save protected to INVIWO<NAME>MODULE_protected
    # Save EnableByDefault to INVIWO<NAME>MODULE_EnableByDefault
    set(dependencies "")
    set(aliases "")
    set(protected OFF)
    set(EnableByDefault OFF)
    if(EXISTS "${${mod}_path}/depends.cmake")
        include(${${mod}_path}/depends.cmake)
    endif()

    # set by ivw_add_build_module_dependency to enable non modules to force modules to build
    if(DEFINED ${mod}_enableExternal)
        set(EnableByDefault ${${mod}_enableExternal})
    endif()

    if(${ARG_CORE})
        set("${mod}_dependencies"    ${dependencies} CACHE INTERNAL "Module dependencies")
        set("${mod}_protected"       ON              CACHE INTERNAL "Protected Module")
        set("${mod}_enableByDefault" ON              CACHE INTERNAL "Enable module by default")
    else()
        set("${mod}_dependencies"   "InviwoCoreModule;${dependencies}" CACHE INTERNAL "Module dependencies")
        set("${mod}_protected"       ${protected}                      CACHE INTERNAL "Protected Module")
        set("${mod}_enableByDefault" ${EnableByDefault}                CACHE INTERNAL "Enable module by default")
    endif()
    set("${mod}_aliases" ${aliases} CACHE INTERNAL "Module aliases")
    unset(dependencies)
    unset(aliases)
    unset(protected)

    # Check if there is a readme.md of the module.
    # In that case set to INVIWO<NAME>MODULE_description
    if(EXISTS "${${mod}_path}/readme.md")
        file(READ "${${mod}_path}/readme.md" description)
        # truncate description since some readme files are quite substantial
        string(LENGTH "${description}" desc_len)
        if(desc_len GREATER 250)
            string(SUBSTRING "${description}" 0 250 description)
            string(JOIN "" description "${description}" "...")
        endif()
        # encode linebreaks, i.e. '\n', and semicolon in description for
        # proper handling in CMAKE
        encodeLineBreaks(cdescription ${description})
        set("${mod}_description" ${cdescription} CACHE INTERNAL "Module description")
    endif()
endfunction()

#--------------------------------------------------------------------
# Register modules
# Generate module options (which was not specified before) and,
# Sort directories based on dependencies inside directories
# defines:  (example project_name = OpenGL)
# INVIWOOPENGLMODULE_description  -> </readme.md>
# INVIWOOPENGLMODULE_dependencies -> </depends.cmake::dependencies>
#
function(ivw_register_modules retval)
    # Collect all modules and information
    set(modules "")

    ivw_dir_to_mod_dep(mod core)
    list(APPEND modules ${mod})
    ivw_private_setup_module_data(CORE NAME "Core" GROUP "" DIR "core" BASE ${IVW_SOURCE_DIR})
    ivw_add_module_option_to_cache(${mod} ON)

    foreach(module_path ${IVW_MODULE_DIR} ${IVW_EXTERNAL_MODULES})
        get_filename_component(group_name ${module_path} NAME)
        set(group_name "modules-${group_name}")

        # Check of there is a meta.cmake
        # Optionally defines: group_name
        if(EXISTS "${module_path}/meta.cmake")
            include("${module_path}/meta.cmake")
        endif()

        string(STRIP ${module_path} module_path)
        if(NOT EXISTS ${module_path})
             message("External module path does not exist: '${module_path}'")
             continue()
        endif()
        if(NOT IS_DIRECTORY ${module_path})
             message("External module path is not a directory: '${module_path}'")
             continue()
        endif()

        file(GLOB dirs RELATIVE ${module_path} ${module_path}/[^.]*)
        foreach(dir ${dirs})
            ivw_dir_to_mod_dep(mod ${dir})
            list(FIND modules ${mod} found)
            if(NOT ${found} EQUAL -1)
                message("Module with name ${dir} already added at ${${mod}_path}")
                continue()
            endif()
            ivw_private_is_valid_module_dir(${module_path} ${dir} valid)
            if(${valid})
                ivw_debug_message(STATUS "register module: ${dir}")
                list(APPEND modules ${mod})
                ivw_private_get_ivw_module_name(${module_path}/${dir}/CMakeLists.txt name)
                ivw_private_get_ivw_module_version(${module_path}/${dir}/CMakeLists.txt version)
                ivw_private_setup_module_data(
                    NAME ${name}
                    GROUP ${group_name}
                    VERSION ${version}
                    DIR ${dir}
                    BASE ${module_path}
                )
            endif()
        endforeach()
    endforeach()

    # Add modules to cmake cache
    foreach(mod ${modules})
        ivw_add_module_option_to_cache(${mod} ${${mod}_enableByDefault})
    endforeach()

    # Find aliases
    set(aliases "")
    foreach(mod ${modules})
        foreach(alias ${${mod}_aliases})
            list(APPEND aliases ${alias})
            if(DEFINED alias_${alias}_mods)
                list(APPEND alias_${alias}_mods ${mod})
            else()
                set(alias_${alias}_mods ${mod})
            endif()
        endforeach()
    endforeach()

    # Substitute aliases
    foreach(mod ${modules})
        set(new_dependencies "")
        foreach(dependency ${${mod}_dependencies})
            list(FIND aliases ${dependency} found)
            if(NOT ${found} EQUAL -1)
                if(DEFINED ${${mod}_opt}_${dependency})
                    list(APPEND new_dependencies ${${${mod}_opt}_${dependency}})
                else()
                    # Find the best substitute
                    list(GET ${alias_${dependency}_mods} 0 new_mod)
                    set(new_dep ${${new_mod}_modName})
                    foreach(alias_mod ${alias_${dependency}_mods})
                        set(new_dep ${${alias_mod}_modName})
                        if(${${alias_mod}_opt}}) # if substitution is enabled we stick with that one.
                            break()
                        endif()
                    endforeach()
                    list(APPEND new_dependencies ${new_dep})
                    set(${${mod}_opt}_${dependency} "${new_dep}" CACHE STRING "Dependency")
                endif()
                set(alias_names "")
                foreach(alias_mod ${alias_${dependency}_mods})
                    list(APPEND alias_names ${${alias_mod}_modName})
                endforeach()
                set_property(CACHE ${${mod}_opt}_${dependency} PROPERTY STRINGS ${alias_names})
            else()
                list(APPEND new_dependencies ${dependency})
            endif()
        endforeach()
        # Validate that there only are module dependencies
        ivw_private_filter_dependency_list(new_dependencies ${${mod}_name} ${new_dependencies})
        ivw_private_check_dependency_list(new_dependencies modules ${${mod}_name} ${new_dependencies})
        set("${mod}_dependencies" ${new_dependencies} CACHE INTERNAL "Module dependencies")
        ivw_mod_name_to_mod_dep(udependencies ${new_dependencies})
        set("${mod}_udependencies" ${udependencies} CACHE INTERNAL "Module uppercase dependencies")
    endforeach()

    # Add module versions dependencies
    foreach(mod ${modules})
        set(dependencies_version "")
        foreach(dependency ${${mod}_dependencies})
            ivw_mod_name_to_mod_dep(dep ${dependency})
            list(FIND modules ${dep} found)
            if(NOT ${found} EQUAL -1)
                list(GET modules ${found} module)
                list(APPEND dependencies_version ${${module}_version})
            else()
                # Dependency was not found, not an inviwo module...
                # We do not take responsibility for external library versions.
                # Distribute the dependency along with the library!
                # ivw_message("${${mod}_name}: ${dependency} dependency not found")
            endif()
        endforeach()
        set("${mod}_dependenciesversion" ${dependencies_version} CACHE INTERNAL "Module dependency versions")
    endforeach()

    # Sort modules by dependencies
    ivw_topological_sort(modules _udependencies sorted_modules)

    # enable dependencies
    ivw_reverse_list_copy(sorted_modules rev_sorted_modules)
    foreach(mod ${rev_sorted_modules})
        if(${${mod}_opt})
            foreach(dep ${${mod}_udependencies})
                if(NOT ${${dep}_opt})
                    ivw_add_module_option_to_cache(${dep} ON FORCE)
                    message(STATUS "${${dep}_opt} was set to build, "
                        "due to dependency towards module ${${mod}_name}")
                endif()
            endforeach()
        endif()
    endforeach()

    ivw_copy_if(enabled_sorted_modules LIST sorted_modules EVAL PROJECTOR _opt)

    # Generate module registration file
    ivw_private_generate_module_registration_files(enabled_sorted_modules)

    # Add enabled modules in sorted order
    set(ivw_module_names "")
    foreach(mod IN LISTS enabled_sorted_modules)
        message(STATUS "create module: ${${mod}_name}")
        if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.16.0)
            list(APPEND CMAKE_MESSAGE_INDENT "    ")
        endif()
        add_subdirectory(${${mod}_path} ${IVW_BINARY_DIR}/modules/${${mod}_dir})
        list(APPEND ivw_module_names ${${mod}_modName})
        ivw_private_generate_module_registration_file(${mod})
        if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.16.0)
            list(POP_BACK CMAKE_MESSAGE_INDENT)
        endif()
    endforeach()

    # Save list of modules
    set(ivw_all_registered_modules ${ivw_module_names} CACHE INTERNAL "All registered inviwo modules")

    set(${retval} ${sorted_modules} PARENT_SCOPE)
endfunction()

#--------------------------------------------------------------------
# Set module to build by default if value is true
# Example ivw_enable_modules_if(IVW_INTEGRATION_TESTS GLFW Base)
# Needs to be called before ivw_register_modules
function(ivw_enable_modules_if value)
    if(NOT ${value})
        return()
    endif()
    foreach(dir IN LISTS ARGN)
        ivw_dir_to_mod_dep(mod ${dir})
        ivw_dir_to_mod_prefix(opt ${dir})
        if(DEFINED ${mod}_opt)
            if(NOT ${${mod}_opt})
                ivw_add_module_option_to_cache(${mod} ON FORCE)
                message(STATUS "${dir} was set to on, due to dependency from ${value}")
            endif()
        elseif(DEFINED ${opt})
             set(${opt} ON CACHE BOOL "Build inviwo module ${dir}" FORCE)
             message(STATUS "${dir} was set to on, due to dependency from ${value}")
        elseif(NOT ${mod}_enableExternal)
            set("${mod}_enableExternal" ON CACHE INTERNAL "Enable module for external dependency" FORCE)
            message(STATUS "${dir} was set to on, due to dependency from ${value}")
        endif()
    endforeach()
endfunction()

#--------------------------------------------------------------------
# Set module build option to true
function(ivw_enable_module the_module)
    ivw_dir_to_mod_dep(mod ${the_module})
    ivw_add_module_option_to_cache(${mod} ON)
endfunction()

#--------------------------------------------------------------------
# Creates source group structure recursively
function(ivw_group group_name)
    set(options "")
    set(oneValueArgs "BASE")
    set(multiValueArgs "")
    cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

    ivw_dir_to_mod_dep(mod ${PROJECT_NAME})

    if(ARG_BASE AND IS_ABSOLUTE ${ARG_BASE})
        set(base ${ARG_BASE})
    elseif(ARG_BASE AND NOT IS_ABSOLUTE ${ARG_BASE})
         set(base ${CMAKE_CURRENT_SOURCE_DIR}/${ARG_BASE})
    elseif(group_name STREQUAL "Header Files" AND ${mod}_incPath)
        set(base "${${mod}_incPath}")
    elseif(group_name STREQUAL "Header Files" AND  EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/include")
        set(base "${CMAKE_CURRENT_SOURCE_DIR}/include")
    elseif(group_name STREQUAL "Source Files" AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src")
        set(base "${CMAKE_CURRENT_SOURCE_DIR}/src")
    elseif(group_name STREQUAL "Test Files" AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/unittests")
        set(base "${CMAKE_CURRENT_SOURCE_DIR}/tests/unittests")
     elseif(group_name STREQUAL "Shader Files" AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/glsl")
        set(base "${CMAKE_CURRENT_SOURCE_DIR}/glsl")
    else()
        set(base "${CMAKE_CURRENT_SOURCE_DIR}")
    endif()

    source_group(TREE ${base} PREFIX ${group_name} FILES ${ARG_UNPARSED_ARGUMENTS})
endfunction()

#--------------------------------------------------------------------
# Creates VS folder structure
function(ivw_folder target folder_name)
    set_target_properties(${target} PROPERTIES FOLDER ${folder_name})
endfunction()

#--------------------------------------------------------------------
# Creates project module from name
# This it called from the inviwo module CMakeLists.txt
# that is included from ivw_register_modules.
function(ivw_create_module)
    set(options "NO_PCH" "QT")
    set(oneValueArgs "VERSION" "GROUP")
    set(multiValueArgs "")
    cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/include)
        set(LEGACY false)
    else()
        set(LEGACY true)
    endif()

    if(ARG_QT)
        set(qt "QT")
    else()
        set(qt "")
    endif()

    string(TOLOWER ${PROJECT_NAME} l_project_name)
    ivw_dir_to_mod_dep(mod ${l_project_name})  # opengl -> INVIWOOPENGLMODULE

    set(cmake_files "${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt")
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/depends.cmake")
        list(APPEND cmake_files "${CMAKE_CURRENT_SOURCE_DIR}/depends.cmake")
    endif()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/readme.md")
        list(APPEND cmake_files "${CMAKE_CURRENT_SOURCE_DIR}/readme.md")
    endif()
    source_group("CMake Files" FILES ${cmake_files})

    # Add module class files
    set(mod_class_files
        # Add module creation function for dll/so loading
        ${CMAKE_CURRENT_BINARY_DIR}/src/${l_project_name}modulesharedlibrary.cpp
        ${CMAKE_CURRENT_BINARY_DIR}/include/${${mod}_incPrefix}/${l_project_name}modulesharedlibrary.h
        $<$<BOOL:${LEGACY}>:${CMAKE_CURRENT_SOURCE_DIR}/${l_project_name}module.h>
        $<$<BOOL:${LEGACY}>:${CMAKE_CURRENT_SOURCE_DIR}/${l_project_name}module.cpp>
        $<$<BOOL:${LEGACY}>:${CMAKE_CURRENT_SOURCE_DIR}/${l_project_name}moduledefine.h>
    )

    remove_duplicates(ivw_unique_mod_files ${ARG_UNPARSED_ARGUMENTS} ${mod_class_files} ${cmake_files})

    # Create library
    add_library(${${mod}_target} ${ivw_unique_mod_files})
    add_library(${${mod}_alias} ALIAS ${${mod}_target})

    get_filename_component(base_parent ${${mod}_base} PATH)
    target_include_directories(${${mod}_target} PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include>
        $<INSTALL_INTERFACE:include>
        $<$<BOOL:${LEGACY}>:${${mod}_base}>
        $<$<BOOL:${LEGACY}>:${base_parent}>
    )

    # Define standard properties
    ivw_define_standard_definitions(${${mod}_opt} ${${mod}_target})
    ivw_define_standard_properties(${${mod}_target} ${qt})

    # Add dependencies from depends.cmake and InviwoCore
    ivw_mod_name_to_alias(ivw_dep_targets ${${mod}_dependencies})
    target_link_libraries(${${mod}_target} PUBLIC ${ivw_dep_targets})

    # Optimize compilation with pre-compilied headers
    if(NOT ARG_NO_PCH)
        ivw_compile_optimize_on_target(${${mod}_target})
    endif()

    # Add stuff to the installer
    ivw_default_install_targets(${${mod}_target})
    ivw_private_install_module_dirs()

    ivw_make_unittest_target("${${mod}_dir}" "${${mod}_target}")

    if(ARG_GROUP)
        ivw_folder(${${mod}_target} "${ARG_GROUP}")
    else()
        ivw_folder(${${mod}_target} "${${mod}_group}")
    endif()

endfunction()

#--------------------------------------------------------------------
# Add all external projects specified in cmake string IVW_EXTERNAL_PROJECTS
function(ivw_add_external_projects)
    foreach(project_root_path ${IVW_EXTERNAL_PROJECTS})
        string(STRIP ${project_root_path} project_root_path)
        get_filename_component(FOLDER_NAME ${project_root_path} NAME)
        add_subdirectory(${project_root_path} ${CMAKE_CURRENT_BINARY_DIR}/ext_${FOLDER_NAME})
    endforeach()
endfunction()


text:
import mongoose from '../stores/mongoose'
import { Schema } from 'mongoose'

const applicationSchema = new Schema({
  icon: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 16
  },
  category: { type: Schema.Types.ObjectId, ref: 'Category' },
  totalVote: { type: Number, default: 0 },
  voteCount: { type: Number, default: 0 },
  developerName: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 16
  },
  description: {
    type: String,
    required: true
  },
  versions: [{
    version: {
      type: String,
      required: true
    },
    changelog: {
      type: String,
      required: true
    },
    publishDate: {
      type: Date,
      default: new Date()
    }
  }],
  screenshots: [String],
  qrcode: {
    type: String,
    required: true
  }
}, {
  versionKey: false
})

const Application = mongoose.model('Application', applicationSchema)

export default Application


text:
package com.intellij.refactoring.actions;

import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.SyntheticElement;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.rename.RenameHandlerRegistry;

public class RenameElementAction extends BaseRefactoringAction {

  public RenameElementAction() {
    setInjectedContext(true);
  }

  public boolean isAvailableInEditorOnly() {
    return false;
  }

  public boolean isEnabledOnElements(PsiElement[] elements) {
    if (elements.length != 1) return false;

    PsiElement element = elements[0];
    return element instanceof PsiNamedElement && !(element instanceof SyntheticElement);
  }

  public RefactoringActionHandler getHandler(DataContext dataContext) {
    return RenameHandlerRegistry.getInstance().getRenameHandler(dataContext);
  }

  protected boolean isEnabledOnDataContext(DataContext dataContext) {
    return RenameHandlerRegistry.getInstance().hasAvailableHandler(dataContext);
  }

  protected boolean isAvailableForLanguage(Language language) {
    return true;
  }
}


text:
namespace scm {
namespace gl_classic {

class context_format;

class __scm_export(gl_core) context_base : boost::noncopyable
{
public:
    typedef scm::shared_ptr<void>   handle;

public:
    context_base();
    virtual ~context_base();

    virtual void            cleanup() = 0;

    virtual bool            make_current(bool current = true) const = 0;

    const context_format&   format() const;
    const handle&           context_handle() const;
    const handle&           device_handle() const;

    virtual bool            empty() const;

protected:
    context_format          _context_format;

    handle                  _device_handle;  // win/WGL: HDC, linux/GLX: Display*
    handle                  _context_handle;

};

} // namespace gl_classic
} // namespace scm

#include <scm/core/utilities/platform_warning_enable.h>

#endif // SCM_GL_CONTEXT_BASE_H_INCLUDED


text:
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''

---

**Enhancement/feature description**
[A clear and concise description of what the problem is. Ex. I'm always frustrated when ...]

**Steps which explain the enhancement/feature**
1. [First Step]
2. [Second Step]
3. [Other Steps...]

**Current and suggested behavior**
[Describe current and suggested behavior here]

**Why would the enhancement be useful to most users**
[Explain why the enhancement would be useful to most users]

**Screenshots and GIFs**
![Screenshots and GIFs which demonstrate the steps or part of TableFilter  the enhancement suggestion is related to](url)

**Additional context**
[Add any other context or screenshots about the feature request here.]

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**TableFilter Version:** [Enter TableFilter version here]
**Browser and version:** [Enter Browser name and version here]
**OS and version:** [Enter OS name and version here]
**Device:** [e.g. iPhone6]


text:
module ActiveScaffold::Bridges
  class DatePicker < ActiveScaffold::DataStructures::Bridge
    autoload :Helper, 'active_scaffold/bridges/date_picker/helper'
    def self.install
      require File.join(File.dirname(__FILE__), "date_picker/ext.rb")
    end
    def self.install?
      ActiveScaffold.js_framework == :jquery && jquery_ui_included?
    end
    def self.jquery_ui_included?
      Jquery::Rails.const_defined?('JQUERY_UI_VERSION') || Jquery.const_defined?('Ui')
    end
    def self.localization
      "jQuery(function($){
  if (typeof($.datepicker) === 'object') {
    #{Helper.date_options_for_locales}
    $.datepicker.setDefaults($.datepicker.regional['#{::I18n.locale}']);
  }
  if (typeof($.timepicker) === 'object') {
    #{Helper.datetime_options_for_locales}
    $.timepicker.setDefaults($.timepicker.regional['#{::I18n.locale}']);
  }
});\n"
    end
  end
end


text:
"use strict";
var url = "http://localhost:5000";
function rentEquipmentPost(arr, email, dateFrom, dateTo) {
  var equipdets = {
      method: "POST",
      headers: {
          'content-type': 'application/json'
      },
      body: JSON.stringify({
          equipments : arr,
          email : email,
          dateFrom : dateFrom,
          dateTo : dateTo
      })
  }
  fetch(url+"/equipment/checkout", equipdets)
  .then(function(res){
      if(res.ok){
          //login to profile
          //displaySuccess();
          location.href = "../HTML/profile.html?email=" + email;
          console.log("request sent!");
      }
      else{
          //alert incorrect
          console.log("incorrect");
      }
  })
  .catch(function(err){
      console.log("POST request failed", err);
  });
}

function getAllEquip(){
    var equip = {
        method : "GET"
    }
    fetch(url+"/equipments", equip)
    .then(function(res){
      if(res.ok) {
        res.json().then(function(data){
          for (var i = 0; i < data.length; i++) {
            var equip = data[i];
            var label= document.createElement("label");
            var description = document.createTextNode(equip.name);
            var checkbox = document.createElement("input");

            checkbox.type = "checkbox";    // make the element a checkbox
            checkbox.id = equip.category;  // give it id
            checkbox.value = equip.name;   // make its value

            label.appendChild(checkbox);   // add the box to the element
            label.appendChild(description);// add the description to the element

            console.log("" + equip.category);

            // add the label element to your div
            document.getElementById("" + equip.category).appendChild(label);
          }
            //console.log(data);
            //var json = JSON.parse(data);
            //console.log(json);
            //console.log(data[0].name);
        })
      }
      else {
        console.log("incorrect username/password");
      }
    })
    .catch(function(err){
        console.log("GET request failed", err);
    });
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Console\Output;

use PhpCsFixer\Differ\DiffConsoleFormatter;
use PhpCsFixer\Error\Error;
use PhpCsFixer\Linter\LintingException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * @author SpacePossum
 *
 * @internal
 */
final class ErrorOutput
{
    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var bool
     */
    private $isDecorated;

    public function __construct(OutputInterface $output)
    {
        $this->output = $output;
        $this->isDecorated = $output->isDecorated();
    }

    /**
     * @param string  $process
     * @param Error[] $errors
     */
    public function listErrors($process, array $errors)
    {
        $this->output->writeln(['', sprintf(
            'Files that were not fixed due to errors reported during %s:',
            $process
        )]);

        $showDetails = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE;
        $showTrace = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG;
        foreach ($errors as $i => $error) {
            $this->output->writeln(sprintf('%4d) %s', $i + 1, $error->getFilePath()));
            $e = $error->getSource();
            if (!$showDetails || null === $e) {
                continue;
            }

            $class = sprintf('[%s]', \get_class($e));
            $message = $e->getMessage();
            $code = $e->getCode();
            if (0 !== $code) {
                $message .= " ({$code})";
            }

            $length = max(\strlen($class), \strlen($message));
            $lines = [
                '',
                $class,
                $message,
                '',
            ];

            $this->output->writeln('');

            foreach ($lines as $line) {
                if (\strlen($line) < $length) {
                    $line .= str_repeat(' ', $length - \strlen($line));
                }

                $this->output->writeln(sprintf('      <error>  %s  </error>', $this->prepareOutput($line)));
            }

            if ($showTrace && !$e instanceof LintingException) { // stack trace of lint exception is of no interest
                $this->output->writeln('');
                $stackTrace = $e->getTrace();
                foreach ($stackTrace as $trace) {
                    if (isset($trace['class'], $trace['function']) && \Symfony\Component\Console\Command\Command::class === $trace['class'] && 'run' === $trace['function']) {
                        $this->output->writeln('      [ ... ]');

                        break;
                    }

                    $this->outputTrace($trace);
                }
            }

            if (Error::TYPE_LINT === $error->getType() && 0 < \count($error->getAppliedFixers())) {
                $this->output->writeln('');
                $this->output->writeln(sprintf('      Applied fixers: <comment>%s</comment>', implode(', ', $error->getAppliedFixers())));

                $diff = $error->getDiff();
                if (!empty($diff)) {
                    $diffFormatter = new DiffConsoleFormatter(
                        $this->isDecorated,
                        sprintf(
                            '<comment>      ---------- begin diff ----------</comment>%s%%s%s<comment>      ----------- end diff -----------</comment>',
                            PHP_EOL,
                            PHP_EOL
                        )
                    );

                    $this->output->writeln($diffFormatter->format($diff));
                }
            }
        }
    }

    private function outputTrace(array $trace)
    {
        if (isset($trace['class'], $trace['type'], $trace['function'])) {
            $this->output->writeln(sprintf(
                '      <comment>%s</comment>%s<comment>%s()</comment>',
                $this->prepareOutput($trace['class']),
                $this->prepareOutput($trace['type']),
                $this->prepareOutput($trace['function'])
            ));
        } elseif (isset($trace['function'])) {
            $this->output->writeln(sprintf('      <comment>%s()</comment>', $this->prepareOutput($trace['function'])));
        }

        if (isset($trace['file'])) {
            $this->output->writeln(sprintf('        in <info>%s</info> at line <info>%d</info>', $this->prepareOutput($trace['file']), $trace['line']));
        }
    }

    /**
     * @param string $string
     *
     * @return string
     */
    private function prepareOutput($string)
    {
        return $this->isDecorated
            ? OutputFormatter::escape($string)
            : $string
        ;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testng-results skipped="0" failed="1" total="1" passed="0">
  <reporter-output>
  </reporter-output>
  <suite name="Default suite" duration-ms="6103" started-at="2015-07-01T06:25:21Z" finished-at="2015-07-01T06:25:27Z">
    <groups>
    </groups>
    <test name="Default test" duration-ms="6103" started-at="2015-07-01T06:25:21Z" finished-at="2015-07-01T06:25:27Z">
      <class name="com.example.tests.ContactModificationTests">
        <test-method status="PASS" signature="setUp()[pri:0, instance:com.example.tests.ContactModificationTests@19bf37e3]" name="setUp" is-config="true" duration-ms="5679" started-at="2015-07-01T09:25:21Z" finished-at="2015-07-01T09:25:27Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- setUp -->
        <test-method status="FAIL" signature="modifySomeContact()[pri:0, instance:com.example.tests.ContactModificationTests@19bf37e3]" name="modifySomeContact" duration-ms="230" started-at="2015-07-01T09:25:27Z" finished-at="2015-07-01T09:25:27Z">
          <exception class="java.lang.NullPointerException">
            <full-stacktrace>
              <![CDATA[java.lang.NullPointerException
	at com.example.tests.ContactModificationTests.modifySomeContact(ContactModificationTests.java:24)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
	at org.testng.internal.Invoker.invokeMethod(Invoker.java:648)
	at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:834)
	at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1142)
	at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:124)
	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
	at org.testng.TestRunner.privateRun(TestRunner.java:771)
	at org.testng.TestRunner.run(TestRunner.java:621)
	at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
	at org.testng.SuiteRunner.run(SuiteRunner.java:259)
	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1176)
	at org.testng.TestNG.runSuitesLocally(TestNG.java:1101)
	at org.testng.TestNG.run(TestNG.java:1009)
	at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
	at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
	at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
]]>
            </full-stacktrace>
          </exception> <!-- java.lang.NullPointerException -->
          <reporter-output>
          </reporter-output>
        </test-method> <!-- modifySomeContact -->
        <test-method status="PASS" signature="tearDown()[pri:0, instance:com.example.tests.ContactModificationTests@19bf37e3]" name="tearDown" is-config="true" duration-ms="181" started-at="2015-07-01T09:25:27Z" finished-at="2015-07-01T09:25:27Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- tearDown -->
      </class> <!-- com.example.tests.ContactModificationTests -->
    </test> <!-- Default test -->
  </suite> <!-- Default suite -->
</testng-results>


text:
class Homeroom < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged
  validates :name, uniqueness: true
  validates :slug, uniqueness: true
  has_many :students
  belongs_to :educator
end


text:
class Collmex::Api::Accbal < Collmex::Api::Line
  SPECIFICATION =
  [
  { name: :satzart, type: :string, const: "ACCBAL" },
  { name: :kontonummer, type: :integer },
  { name: :kontoname, type: :string },
  { name: :saldo, type: :currency },
  ]
end


text:
<?xml version='1.0' encoding='UTF-8'?>
<package version="0.1" uuid="d">
  <names>
    <name lang="en_US">d</name>
  </names>
  <supportedLanguages>
    <language>en_US</language>
  </supportedLanguages>
  <requirements>
    <naoqiRequirement minVersion="1.22"/>
    <robotRequirement model="NAO"/>
  </requirements>
</package>


text:
package com.twosigma.beakerx.doclet;

import java.util.List;

public class ClassInspect {
    String className;
    String fullName;
    String javadoc;
    List<MethodInspect> methods;
    List<MethodInspect> constructors;

    public ClassInspect(String className, String fullName, String javadoc) {
        this.className = className;
        this.fullName = fullName;
        this.javadoc = javadoc;
    }

    public String getClassName() {
        return className;
    }

    public String getFullName() {
        return fullName;
    }

    public String getJavadoc() {
        return javadoc;
    }

    public List<MethodInspect> getMethods() {
        return methods;
    }

    public void setMethods(List<MethodInspect> methods) {
        this.methods = methods;
    }

    public List<MethodInspect> getConstructors() {
        return constructors;
    }

    public void setConstructors(List<MethodInspect> constructors) {
        this.constructors = constructors;
    }
}


text:
using UnrealBuildTool;
using System.IO;

public class OVRLipSync : ModuleRules
{
    private string ModulePath
    {
        get { return ModuleDirectory; }
    }

    private string ThirdPartyPath
    {
        get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); }
    }

    private string BinariesPath
    {
        get { return Path.GetFullPath(Path.Combine(ModulePath, "../../Binaries/")); }
    }

	public OVRLipSync(TargetInfo Target)
	{

		PublicIncludePaths.AddRange(
			new string[] {
				"OVRLipSync/Public"
				// ... add public include paths required here ...
			}
			);

		PrivateIncludePaths.AddRange(
			new string[] {
				"OVRLipSync/Private",
				// ... add other private include paths required here ...
			}
			);

		PublicDependencyModuleNames.AddRange(
			new string[]
			{
				"Core",
				"Projects",
                "CoreUObject",
                "Engine",
                "InputCore",
                "RHI",
                "Voice",
                "OnlineSubsystem",
                "OnlineSubsystemUtils"
				// ... add other public dependencies that you statically link with here ...
			}
			);

		PrivateDependencyModuleNames.AddRange(
			new string[]
			{
				// ... add private dependencies that you statically link with here ...
                "Core",
                "Projects",
                "CoreUObject",
                "Engine",
                "InputCore",
                "RHI",
                "Voice",
                "OnlineSubsystem",
                "OnlineSubsystemUtils"
            }
			);

		DynamicallyLoadedModuleNames.AddRange(
			new string[]
			{
				// ... add any modules that your module loads dynamically here ...
			}
			);

        LoadOVRLipSyncLib(Target);
	}

    public bool LoadOVRLipSyncLib(TargetInfo Target)
    {
        bool isLibrarySupported = false;

        if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32))
        {
            isLibrarySupported = true;

            string PlatformString = (Target.Platform == UnrealTargetPlatform.Win64) ? "x64" : "x32";

            if (Target.Platform == UnrealTargetPlatform.Win64)
            {
                PublicDelayLoadDLLs.Add("OVRLipSync_x64.dll");
                RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(BinariesPath, "Win64", "OVRLipSync_x64.dll")));
            }
            else
            {
                PublicDelayLoadDLLs.Add("OVRLipSync.dll");
                RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(BinariesPath, "Win32", "OVRLipSync.dll")));
            }
        }

        return isLibrarySupported;
    }
}


text:
package com.tonicsystems.jarjar.classpath;

import java.io.InputStream;
import java.io.IOException;
import javax.annotation.Nonnull;

public abstract class ClassPathResource {

    @Nonnull
    public abstract String getArchiveName();

    @Nonnull
    public abstract String getName();

    public abstract long getLastModifiedTime();

    @Nonnull
    public abstract InputStream openStream() throws IOException;

    @Override
    public String toString() {
        return getArchiveName() + "!" + getName();
    }

}


text:
layout: index
title: More things to do with objects
---

Giving and Using objects
------------------------

After a player has taken an object, they can give that object to, or use it on, other objects in the game.

For example, after picking up some flowers, a player can give them to a character called "Susan" by typing "give flowers to susan".

"Give" and "Use" are set up in exactly the same way – the only difference is whether the player types "give ... to ..." or "use ... on ...".

In this example, we are going to revive the corpse of Bob in the lounge, using a [heart defibrillator](http://en.wikipedia.org/wiki/Defibrillation). First, we need to alter the setup of Bob so that we give a correct description whether he is dead or alive. To do this, we are going to use an **object flag**.

An object flag is simply a way of accessing a boolean attribute of an object (a boolean attribute can only be either "true" or "false"). You can use it to mark certain things as "done", and is a common way to track the progress of a game.

It is good practice to give flags meaningful names, and to have them start off (or false). For Bob, we will call the flag "alive".

So, using the defibrillator on Bob is going to add a flag called "alive" to Bob. In the "look at" description, we'll check whether Bob has his "alive" flag set. If so, we'll print "Bob is sitting up, appearing to feel somewhat under the weather", and if not, we'll print the old description "Bob is lying on the floor, a lot more still than usual."

Updating the description
------------------------

Getting the correct description to display is very similar to the "watch" example in the [Using scripts](using_scripts.html) section.

Change Bob's "look at" description to "Run script", and add an "if" command.

For the expression, choose "object has flag". Then select "Bob" and enter the flag name "alive". Add the descriptions above for "then" and "else" messages.

![](../images/Use1.png "Use1.png")

Using the defibrillator
-----------------------

Now, add a "defibrillator" object to the lounge. Enter a description like "A heart defibrillator can magically revive a dead person, if all those hospital dramas are to be believed."

Go to the _Inventory_ tab and tick "Object can be taken".

Now go back to Bob. We need to turn on "Use/Give", so on his "Features" tab, tick the "Use/Give:..." check box. His _Use/Give_ tab should now appear.

Go to the "Use (other object) on this" section of the new "Use/Give" tab, and choose "Handle objects individually".

![](../images/Use2.png "Use2.png")

A list will appear in the "Use" section. Here you can add the objects that can be used on Bob, with a script for each. Click "Add" and type "defibrillator".

A Script Editor window will now pop up. In this script, we want to print a message to tell the player what's happening, and also set the "alive" flag on Bob.

So, add a "print a message" script and type something like "Miraculously, the defibrillator lived up to its promise, and Bob is now alive again. He says his head feels kind of fuzzy."

Now add a "Set object flag" command. Choose Bob from the objects list, and enter the flag name "alive".

![](../images/Use3.png "Use3.png")

Close the Script Editor window. Now run the game. Look at Bob, then type "use defibrillator on bob", then look at Bob again. Verify that you see the correct text in each case.

Notice what happens when you type "use defibrillator on bob" a second time - you get the same response again. You should know how to fix this now - update your "use defibrillator on bob" script to check for the "alive" flag. Update this now (if you are struggling, just move on to the next section, where it will be revealed!).

Using Functions
---------------

It would be good if we could get the same effect just by typing "use defibrillator". There are a couple of things we could do here, from the defibrillator _Use/Give_ tab, under "Use (on its own)":

-   we can tick "Display menu of objects this can be used on". This will allow the player to select Bob to use the defibrillator on.
-   we can choose "Run script" from the Action list, to automatically defibrillate Bob.

The first option is definitely the easiest, but the second option allows us to demonstrate the use of functions.

Of course, we could simply copy the script we created in the section above, and paste it into the defibrillator's "use this object (on its own)" script. However, if we then wanted to make an update to one script, we would have to update the other one as well.

The best way to resolve this is to make both our existing "use defibrillator on Bob", and our new "use defibrillator" point to the same script. The way to do this is to set up a **function**.

Functions provide a way for you to set up scripts that can be called from anywhere in your game, so you don't have to keep copying and pasting or re-entering the script.

Let's create one now to store the script commands we use to resuscitate Bob. We can then set both "use defibrillator on bob" and "use defibrillator" to call this function.

First, go to Bob's _Use/Give_ tab, and double click "defibrillator" in the "Use" table to bring up the Script Editor. Hold down the shift key and select all script lines, then click the Cut button to move this script to the clipboard. Now close the window.

Now add a new function (right click the tree, or use the Add menu), and call it "revive bob". For the script, click the Paste button.

![](../images/Functionrevive.png "Functionrevive.png")

Now we just need to update "use defibrillator on bob" and create "use defibrillator", to make them call this function. Go back to Bob's use/give tab, and double-click to edit the defibrillator script again.

Add a "call function" script, and enter the name "revive bob". Now close the window.

Now we're kind of back where we started - if you run the game and type "use defibrillator on bob", it calls the "revive bob" function and so we get exactly the same behaviour as before.

We just need to make "use defibrillator" call the same function now, so go to the defibrillator's use/give tab, and in the "use (on its own)" section choose "Run a script". Add a "call function" script, so that it also calls the "revive bob" function.

![](../images/Functionrevive2.png "Functionrevive2.png")

Launch the game now and verify you get the same response whether you type "use defibrillator on bob" or just "use defibrillator".

Note that if you pick up the defibrillator and go to the kitchen, "use defibrillator" will still work. It would be pretty remarkable for a defibrillator to work at such a long range, so consider adding an "if" command to the "revive bob" procedure. You can select "player is in room" from the list of conditions to check whether the player is in the lounge before carrying out the defibrillation. If they're not in the lounge, print a suitably sarcastic message.

Giving objects
--------------

Giving an object to a character works in exactly the same way as using objects on a character. Look at the "Give" sections - notice that you get the same options as for "Use". You can add objects to it in the same way.

Ask and Tell
------------

Ask and Tell work in the same way, so we'll only cover "ask" here.

Click on Bob and go to the "Ask/tell" tab. As with "Use/Give" this will have to be turned on, but it is done globally, which means you only need to do it once for your whole game, and that it is done from the _Features_ tab of the "game" at the top of the list on the left.

On Bob's "Ask/Tell" tab you can add subjects to the list, and give a script for each subject. You can also give a script to run when the player asks Bob about something he doesn't know about.

Let's make Bob respond to a question about the massive heart attack he's just amazingly recovered from. Click the "Add" ![](../images/Add.png "fig:Add.png") button and enter some topic keywords, for example "heart attack cardiac arrest". When the player asks Bob about anything, this list of keywords is checked for matches in the player's command. So the player could type "ask bob about heart" or "ask bob about cardiac arrest", and that will match this topic.

A Script Editor will appear. It would make sense that the player can only ask questions of Bob when he's been brought back to life, so the first thing to do is add an "if" command and check that Bob's "alive" flag is set. If it is, he can say something like "Well, one moment I was sitting there, feeling pretty happy with myself after eating my afternoon snack - a cheeseburger, pizza and ice cream pie, smothered in bacon, which I'd washed down with a bucket of coffee and six cans of Red Bull - when all of a sudden, I was in terrible pain, and then everything was peaceful. Then you came along."

![](../images/Asktell.png "Asktell.png")

[Next: Using containers](using_containers.html)


text:
<?php

require_once('domain/kortingscodes.php');
require_once('domain/db.php');

class KortingscodesTest extends PHPUnit_Framework_TestCase {

	private $codes;

	public function setUp() {
		if(file_exists('db.sqlite3')) {
			unlink('db.sqlite3');
		}
		$this->codes = new Kortingscodes();
	}

	public function tearDown() {
		$this->codes = null;
		Db::close();
	}

	public function testIsGeldig_UnknownCode_false() {
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => 'jos@jos.be'
		]);

		$this->assertFalse($this->codes->isGeldig('AAA', 'doesnot@matter.be'));
	}

	public function testIsGeldig_CodeAndEmailDoNotMatch_false() {
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => 'jos@jos.be'
		]);

		$this->assertFalse($this->codes->isGeldig('ABXY', 'wrong@notcorrect.com'));
	}

	public function testIsGeldig_MultipleCodesMultipleEmails_Matches_true() {
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => 'jos@jos.be'
		]);
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => 'jef@jef.be'
		]);

		$this->assertTrue($this->codes->isGeldig('ABXY', 'jef@jef.be'));
	}

	public function testIsGeldig_Matches_true() {
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => 'jos@jos.be'
		]);

		$this->assertTrue($this->codes->isGeldig('ABXY', 'jos@jos.be'));
	}

	public function testIsGeldig_CodeToBeUsedOnceWithoutEmail_true() {
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => ''
		]);

		$this->assertTrue($this->codes->isGeldig('ABXY', 'doesnot@matter.be'));
	}

	public function testClaimCodeDeletesAndReturnsPercentage() {
		$this->codes->save([
			'code' => 'ABXY',
			'percentage' => 10,
			'email' => 'jos@jos.be'
		]);

		$korting = $this->codes->claim('ABXY');
		$this->assertEquals(0, count($this->codes->findAll()));
		$this->assertEquals(10, $korting);
	}
}

?>


text:
This is a sample project to demostrate how to build a golang project with [Gogradle](https://github.com/blindpirate/gogradle) and customized go build command line arguments.

No need to install `Go` or set `GOPATH` at all. Just install [JRE 8+](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) and run

```
./gradlew goBuild
```
on POSIX or

```
gradlew goBuild
```
on Windows and see what happened in the project root!