text:
// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package modules

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"github.com/bep/debounce"
	"github.com/gohugoio/hugo/common/loggers"

	"github.com/spf13/cast"

	"github.com/gohugoio/hugo/common/maps"

	"github.com/gohugoio/hugo/common/hugo"
	"github.com/gohugoio/hugo/parser/metadecoders"

	"github.com/gohugoio/hugo/hugofs/files"

	"github.com/rogpeppe/go-internal/module"

	"errors"

	"github.com/gohugoio/hugo/config"
	"github.com/spf13/afero"
)

var ErrNotExist = errors.New("module does not exist")

const vendorModulesFilename = "modules.txt"

// IsNotExist returns whether an error means that a module could not be found.
func IsNotExist(err error) bool {
	return errors.Is(err, os.ErrNotExist)
}

// CreateProjectModule creates modules from the given config.
// This is used in tests only.
func CreateProjectModule(cfg config.Provider) (Module, error) {
	workingDir := cfg.GetString("workingDir")
	var modConfig Config

	mod := createProjectModule(nil, workingDir, modConfig)
	if err := ApplyProjectConfigDefaults(cfg, mod); err != nil {
		return nil, err
	}

	return mod, nil
}

func (h *Client) Collect() (ModulesConfig, error) {
	mc, coll := h.collect(true)
	if coll.err != nil {
		return mc, coll.err
	}

	if err := (&mc).setActiveMods(h.logger); err != nil {
		return mc, err
	}

	if h.ccfg.HookBeforeFinalize != nil {
		if err := h.ccfg.HookBeforeFinalize(&mc); err != nil {
			return mc, err
		}
	}

	if err := (&mc).finalize(h.logger); err != nil {
		return mc, err
	}

	return mc, nil
}

func (h *Client) collect(tidy bool) (ModulesConfig, *collector) {
	c := &collector{
		Client: h,
	}

	c.collect()
	if c.err != nil {
		return ModulesConfig{}, c
	}

	// https://github.com/gohugoio/hugo/issues/6115
	/*if !c.skipTidy && tidy {
		if err := h.tidy(c.modules, true); err != nil {
			c.err = err
			return ModulesConfig{}, c
		}
	}*/

	return ModulesConfig{
		AllModules:        c.modules,
		GoModulesFilename: c.GoModulesFilename,
	}, c
}

type ModulesConfig struct {
	// All modules, including any disabled.
	AllModules Modules

	// All active modules.
	ActiveModules Modules

	// Set if this is a Go modules enabled project.
	GoModulesFilename string
}

func (m *ModulesConfig) setActiveMods(logger loggers.Logger) error {
	var activeMods Modules
	for _, mod := range m.AllModules {
		if !mod.Config().HugoVersion.IsValid() {
			logger.Warnf(`Module %q is not compatible with this Hugo version; run "hugo mod graph" for more information.`, mod.Path())
		}
		if !mod.Disabled() {
			activeMods = append(activeMods, mod)
		}
	}

	m.ActiveModules = activeMods

	return nil
}

func (m *ModulesConfig) finalize(logger loggers.Logger) error {
	for _, mod := range m.AllModules {
		m := mod.(*moduleAdapter)
		m.mounts = filterUnwantedMounts(m.mounts)
	}
	return nil
}

func filterUnwantedMounts(mounts []Mount) []Mount {
	// Remove duplicates
	seen := make(map[string]bool)
	tmp := mounts[:0]
	for _, m := range mounts {
		if !seen[m.key()] {
			tmp = append(tmp, m)
		}
		seen[m.key()] = true
	}
	return tmp
}

type collected struct {
	// Pick the first and prevent circular loops.
	seen map[string]bool

	// Maps module path to a _vendor dir. These values are fetched from
	// _vendor/modules.txt, and the first (top-most) will win.
	vendored map[string]vendoredModule

	// Set if a Go modules enabled project.
	gomods goModules

	// Ordered list of collected modules, including Go Modules and theme
	// components stored below /themes.
	modules Modules
}

// Collects and creates a module tree.
type collector struct {
	*Client

	// Store away any non-fatal error and return at the end.
	err error

	// Set to disable any Tidy operation in the end.
	skipTidy bool

	*collected
}

func (c *collector) initModules() error {
	c.collected = &collected{
		seen:     make(map[string]bool),
		vendored: make(map[string]vendoredModule),
		gomods:   goModules{},
	}

	// If both these are true, we don't even need Go installed to build.
	if c.ccfg.IgnoreVendor == nil && c.isVendored(c.ccfg.WorkingDir) {
		return nil
	}

	// We may fail later if we don't find the mods.
	return c.loadModules()
}

func (c *collector) isSeen(path string) bool {
	key := pathKey(path)
	if c.seen[key] {
		return true
	}
	c.seen[key] = true
	return false
}

func (c *collector) getVendoredDir(path string) (vendoredModule, bool) {
	v, found := c.vendored[path]
	return v, found
}

func (c *collector) add(owner *moduleAdapter, moduleImport Import, disabled bool) (*moduleAdapter, error) {
	var (
		mod       *goModule
		moduleDir string
		version   string
		vendored  bool
	)

	modulePath := moduleImport.Path
	var realOwner Module = owner

	if !c.ccfg.shouldIgnoreVendor(modulePath) {
		if err := c.collectModulesTXT(owner); err != nil {
			return nil, err
		}

		// Try _vendor first.
		var vm vendoredModule
		vm, vendored = c.getVendoredDir(modulePath)
		if vendored {
			moduleDir = vm.Dir
			realOwner = vm.Owner
			version = vm.Version

			if owner.projectMod {
				// We want to keep the go.mod intact with the versions and all.
				c.skipTidy = true
			}

		}
	}

	if moduleDir == "" {
		var versionQuery string
		mod = c.gomods.GetByPath(modulePath)
		if mod != nil {
			moduleDir = mod.Dir
			versionQuery = mod.Version
		}

		if moduleDir == "" {
			if c.GoModulesFilename != "" && isProbablyModule(modulePath) {
				// Try to "go get" it and reload the module configuration.
				if versionQuery == "" {
					// See https://golang.org/ref/mod#version-queries
					// This will select the latest release-version (not beta etc.).
					versionQuery = "upgrade"
				}
				if err := c.Get(fmt.Sprintf("%s@%s", modulePath, versionQuery)); err != nil {
					return nil, err
				}
				if err := c.loadModules(); err != nil {
					return nil, err
				}

				mod = c.gomods.GetByPath(modulePath)
				if mod != nil {
					moduleDir = mod.Dir
				}
			}

			// Fall back to project/themes/<mymodule>
			if moduleDir == "" {
				var err error
				moduleDir, err = c.createThemeDirname(modulePath, owner.projectMod || moduleImport.pathProjectReplaced)
				if err != nil {
					c.err = err
					return nil, nil
				}
				if found, _ := afero.Exists(c.fs, moduleDir); !found {
					c.err = c.wrapModuleNotFound(fmt.Errorf(`module %q not found; either add it as a Hugo Module or store it in %q.`, modulePath, c.ccfg.ThemesDir))
					return nil, nil
				}
			}
		}
	}

	if found, _ := afero.Exists(c.fs, moduleDir); !found {
		c.err = c.wrapModuleNotFound(fmt.Errorf("%q not found", moduleDir))
		return nil, nil
	}

	if !strings.HasSuffix(moduleDir, fileSeparator) {
		moduleDir += fileSeparator
	}

	ma := &moduleAdapter{
		dir:      moduleDir,
		vendor:   vendored,
		disabled: disabled,
		gomod:    mod,
		version:  version,
		// This may be the owner of the _vendor dir
		owner: realOwner,
	}

	if mod == nil {
		ma.path = modulePath
	}

	if !moduleImport.IgnoreConfig {
		if err := c.applyThemeConfig(ma); err != nil {
			return nil, err
		}
	}

	if err := c.applyMounts(moduleImport, ma); err != nil {
		return nil, err
	}

	c.modules = append(c.modules, ma)
	return ma, nil
}

func (c *collector) addAndRecurse(owner *moduleAdapter, disabled bool) error {
	moduleConfig := owner.Config()
	if owner.projectMod {
		if err := c.applyMounts(Import{}, owner); err != nil {
			return err
		}
	}

	for _, moduleImport := range moduleConfig.Imports {
		disabled := disabled || moduleImport.Disable

		if !c.isSeen(moduleImport.Path) {
			tc, err := c.add(owner, moduleImport, disabled)
			if err != nil {
				return err
			}
			if tc == nil || moduleImport.IgnoreImports {
				continue
			}
			if err := c.addAndRecurse(tc, disabled); err != nil {
				return err
			}
		}
	}
	return nil
}

func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error {
	if moduleImport.NoMounts {
		mod.mounts = nil
		return nil
	}

	mounts := moduleImport.Mounts

	modConfig := mod.Config()

	if len(mounts) == 0 {
		// Mounts not defined by the import.
		mounts = modConfig.Mounts
	}

	if !mod.projectMod && len(mounts) == 0 {
		// Create default mount points for every component folder that
		// exists in the module.
		for _, componentFolder := range files.ComponentFolders {
			sourceDir := filepath.Join(mod.Dir(), componentFolder)
			_, err := c.fs.Stat(sourceDir)
			if err == nil {
				mounts = append(mounts, Mount{
					Source: componentFolder,
					Target: componentFolder,
				})
			}
		}
	}

	var err error
	mounts, err = c.normalizeMounts(mod, mounts)
	if err != nil {
		return err
	}

	mounts, err = c.mountCommonJSConfig(mod, mounts)
	if err != nil {
		return err
	}

	mod.mounts = mounts
	return nil
}

func (c *collector) applyThemeConfig(tc *moduleAdapter) error {
	var (
		configFilename string
		themeCfg       map[string]any
		hasConfigFile  bool
		err            error
	)

	// Viper supports more, but this is the sub-set supported by Hugo.
	for _, configFormats := range config.ValidConfigFileExtensions {
		configFilename = filepath.Join(tc.Dir(), "config."+configFormats)
		hasConfigFile, _ = afero.Exists(c.fs, configFilename)
		if hasConfigFile {
			break
		}
	}

	// The old theme information file.
	themeTOML := filepath.Join(tc.Dir(), "theme.toml")

	hasThemeTOML, _ := afero.Exists(c.fs, themeTOML)
	if hasThemeTOML {
		data, err := afero.ReadFile(c.fs, themeTOML)
		if err != nil {
			return err
		}
		themeCfg, err = metadecoders.Default.UnmarshalToMap(data, metadecoders.TOML)
		if err != nil {
			c.logger.Warnf("Failed to read module config for %q in %q: %s", tc.Path(), themeTOML, err)
		} else {
			maps.PrepareParams(themeCfg)
		}
	}

	if hasConfigFile {
		if configFilename != "" {
			var err error
			tc.cfg, err = config.FromFile(c.fs, configFilename)
			if err != nil {
				return err
			}
		}

		tc.configFilenames = append(tc.configFilenames, configFilename)

	}

	// Also check for a config dir, which we overlay on top of the file configuration.
	configDir := filepath.Join(tc.Dir(), "config")
	dcfg, dirnames, err := config.LoadConfigFromDir(c.fs, configDir, c.ccfg.Environment)
	if err != nil {
		return err
	}

	if len(dirnames) > 0 {
		tc.configFilenames = append(tc.configFilenames, dirnames...)

		if hasConfigFile {
			// Set will overwrite existing keys.
			tc.cfg.Set("", dcfg.Get(""))
		} else {
			tc.cfg = dcfg
		}
	}

	config, err := decodeConfig(tc.cfg, c.moduleConfig.replacementsMap)
	if err != nil {
		return err
	}

	const oldVersionKey = "min_version"

	if hasThemeTOML {

		// Merge old with new
		if minVersion, found := themeCfg[oldVersionKey]; found {
			if config.HugoVersion.Min == "" {
				config.HugoVersion.Min = hugo.VersionString(cast.ToString(minVersion))
			}
		}

		if config.Params == nil {
			config.Params = make(map[string]any)
		}

		for k, v := range themeCfg {
			if k == oldVersionKey {
				continue
			}
			config.Params[k] = v
		}

	}

	tc.config = config

	return nil
}

func (c *collector) collect() {
	defer c.logger.PrintTimerIfDelayed(time.Now(), "hugo: collected modules")
	d := debounce.New(2 * time.Second)
	d(func() {
		c.logger.Println("hugo: downloading modules …")
	})
	defer d(func() {})

	if err := c.initModules(); err != nil {
		c.err = err
		return
	}

	projectMod := createProjectModule(c.gomods.GetMain(), c.ccfg.WorkingDir, c.moduleConfig)

	if err := c.addAndRecurse(projectMod, false); err != nil {
		c.err = err
		return
	}

	// Add the project mod on top.
	c.modules = append(Modules{projectMod}, c.modules...)
}

func (c *collector) isVendored(dir string) bool {
	_, err := c.fs.Stat(filepath.Join(dir, vendord, vendorModulesFilename))
	return err == nil
}

func (c *collector) collectModulesTXT(owner Module) error {
	vendorDir := filepath.Join(owner.Dir(), vendord)
	filename := filepath.Join(vendorDir, vendorModulesFilename)

	f, err := c.fs.Open(filename)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}

		return err
	}

	defer f.Close()

	scanner := bufio.NewScanner(f)

	for scanner.Scan() {
		// # github.com/alecthomas/chroma v0.6.3
		line := scanner.Text()
		line = strings.Trim(line, "# ")
		line = strings.TrimSpace(line)
		parts := strings.Fields(line)
		if len(parts) != 2 {
			return fmt.Errorf("invalid modules list: %q", filename)
		}
		path := parts[0]

		shouldAdd := c.Client.moduleConfig.VendorClosest

		if !shouldAdd {
			if _, found := c.vendored[path]; !found {
				shouldAdd = true
			}
		}

		if shouldAdd {
			c.vendored[path] = vendoredModule{
				Owner:   owner,
				Dir:     filepath.Join(vendorDir, path),
				Version: parts[1],
			}
		}

	}
	return nil
}

func (c *collector) loadModules() error {
	modules, err := c.listGoMods()
	if err != nil {
		return err
	}
	c.gomods = modules
	return nil
}

// Matches postcss.config.js etc.
var commonJSConfigs = regexp.MustCompile(`(babel|postcss|tailwind)\.config\.js`)

func (c *collector) mountCommonJSConfig(owner *moduleAdapter, mounts []Mount) ([]Mount, error) {
	for _, m := range mounts {
		if strings.HasPrefix(m.Target, files.JsConfigFolderMountPrefix) {
			// This follows the convention of the other component types (assets, content, etc.),
			// if one or more is specified by the user, we skip the defaults.
			// These mounts were added to Hugo in 0.75.
			return mounts, nil
		}
	}

	// Mount the common JS config files.
	fis, err := afero.ReadDir(c.fs, owner.Dir())
	if err != nil {
		return mounts, err
	}

	for _, fi := range fis {
		n := fi.Name()

		should := n == files.FilenamePackageHugoJSON || n == files.FilenamePackageJSON
		should = should || commonJSConfigs.MatchString(n)

		if should {
			mounts = append(mounts, Mount{
				Source: n,
				Target: filepath.Join(files.ComponentFolderAssets, files.FolderJSConfig, n),
			})
		}

	}

	return mounts, nil
}

func (c *collector) normalizeMounts(owner *moduleAdapter, mounts []Mount) ([]Mount, error) {
	var out []Mount
	dir := owner.Dir()

	for _, mnt := range mounts {
		errMsg := fmt.Sprintf("invalid module config for %q", owner.Path())

		if mnt.Source == "" || mnt.Target == "" {
			return nil, errors.New(errMsg + ": both source and target must be set")
		}

		mnt.Source = filepath.Clean(mnt.Source)
		mnt.Target = filepath.Clean(mnt.Target)
		var sourceDir string

		if owner.projectMod && filepath.IsAbs(mnt.Source) {
			// Abs paths in the main project is allowed.
			sourceDir = mnt.Source
		} else {
			sourceDir = filepath.Join(dir, mnt.Source)
		}

		// Verify that Source exists
		_, err := c.fs.Stat(sourceDir)
		if err != nil {
			continue
		}

		// Verify that target points to one of the predefined component dirs
		targetBase := mnt.Target
		idxPathSep := strings.Index(mnt.Target, string(os.PathSeparator))
		if idxPathSep != -1 {
			targetBase = mnt.Target[0:idxPathSep]
		}
		if !files.IsComponentFolder(targetBase) {
			return nil, fmt.Errorf("%s: mount target must be one of: %v", errMsg, files.ComponentFolders)
		}

		out = append(out, mnt)
	}

	return out, nil
}

func (c *collector) wrapModuleNotFound(err error) error {
	err = fmt.Errorf(err.Error()+": %w", ErrNotExist)
	if c.GoModulesFilename == "" {
		return err
	}

	baseMsg := "we found a go.mod file in your project, but"

	switch c.goBinaryStatus {
	case goBinaryStatusNotFound:
		return fmt.Errorf(baseMsg+" you need to install Go to use it. See https://golang.org/dl/ : %q", err)
	case goBinaryStatusTooOld:
		return fmt.Errorf(baseMsg+" you need to a newer version of Go to use it. See https://golang.org/dl/ : %w", err)
	}

	return err
}

type vendoredModule struct {
	Owner   Module
	Dir     string
	Version string
}

func createProjectModule(gomod *goModule, workingDir string, conf Config) *moduleAdapter {
	// Create a pseudo module for the main project.
	var path string
	if gomod == nil {
		path = "project"
	}

	return &moduleAdapter{
		path:       path,
		dir:        workingDir,
		gomod:      gomod,
		projectMod: true,
		config:     conf,
	}
}

// In the first iteration of Hugo Modules, we do not support multiple
// major versions running at the same time, so we pick the first (upper most).
// We will investigate namespaces in future versions.
// TODO(bep) add a warning when the above happens.
func pathKey(p string) string {
	prefix, _, _ := module.SplitPathVersion(p)

	return strings.ToLower(prefix)
}


text:
<?php

namespace app\modules\news;

/**
 * news module definition class
 */
class Module extends \yii\base\Module
{
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'app\modules\news\controllers';

    /**
     * @inheritdoc
     */
    public $defaultRoute = 'news/list';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.dannil.urldatabind.model.bind.result;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class ActionTest {

    private class DummyAction implements Action {

        @Override
        public Object trigger() {
            return Math.PI;
        }

    }

    @Test
    public void trigger() {
        DummyAction dummy = new DummyAction();

        assertEquals(Math.PI, dummy.trigger());
    }

}


text:
var mysqlLib = require('../mysqlLib');

exports.display_ryg  = function(req, res){

  res.render('urls/custom/ryg_build_alert',{page_title:"Alert - CommandCenter"});
};

/*
 * GET urls listing.
 */

exports.list = function(req, res){

  mysqlLib.getConnection(function(err,connection){

        var sql = 'SELECT u.url_id, u.url_string, u.description,ut.url_type_cd, ' +
                  'date_format(u.created, \'%m/%d/%Y\') created, u.created_by,  if (u.updated,date_format(u.updated, \'%m/%d/%Y\'),null) updated,' +
                  'u.updated_by FROM urls u ' +
                  'inner join url_types ut on ut.url_type_id = u.url_type_id order by greatest(u.created, u.updated) desc ';

        connection.query(sql,function(err,rows)
        {

            if(err)
                console.log("Error Selecting : %s ",err );

            res.render('urls/urls',{page_title:"URLs - CommandCenter",data:rows});

         });

    });

};

exports.addform = function(req, res){

  mysqlLib.getConnection(function(err,connection){

        var sql = 'SELECT url_type_id, url_type_cd FROM url_types';

        connection.query(sql,function(err,rows)
        {

            if(err)
                console.log("Error Selecting : %s ",err );

            res.render('urls/add_url',{page_title:"Add Url - CommandCenter",data:rows});

         });

    });

};

exports.editform = function(req, res){

    var id = req.params.id;

    mysqlLib.getConnection(function(err,connection){
        var sql = 'SELECT url_id, url_string, length(url_string) url_string_length, description, ' +
                  ' length(description) description_length, active ' +
                  ' FROM urls where url_id = ?'
        connection.query(sql,[id],function(err,rows)
        {

            if(err)
                console.log("Error Selecting : %s ",err );

            res.render('urls/edit_url',{page_title:"Edit urls - CommandCenter",data:rows});

         });

    });
};

/*Save the URL*/
exports.save = function(req,res){

    var input = JSON.parse(JSON.stringify(req.body));

    mysqlLib.getConnection(function (err, connection) {

        var data = {

            url_string    : input.url_string,
            description   : input.description,
            url_type_id   : input.url_type_id,
            created_by    : input.created_by,
            active        : 1

        };
        var sql = 'INSERT INTO urls set ?';
        connection.query(sql,[data], function(err, rows)
        {

          if (err)
              console.log("Error inserting : %s ",err );

          res.redirect('/urls');

        });

    });
};

exports.save_edit = function(req,res){

    var input = JSON.parse(JSON.stringify(req.body));
    var id = req.params.id;

    mysqlLib.getConnection(function (err, connection) {

        var data = {
            url_string    : input.url_string,
            description   : input.description,
            updated_by    : input.updated_by,
            active        : input.active,

        };
        var sql = 'UPDATE urls set ?, updated=CURRENT_TIMESTAMP() WHERE url_id = ? ';
        connection.query(sql,[data,id], function(err, rows)
        {

          if (err)
              console.log("Error Updating : %s ",err );

          res.redirect('/urls');

        });

    });
};

exports.delete = function(req,res){

     var id = req.params.id;
     mysqlLib.getConnection(function (err, connection) {
        var sql = 'DELETE FROM urls WHERE url_id = ?';
        connection.query(sql,[id], function(err, rows)
        {

             if(err)
                 console.log("Error deleting : %s ",err );

             res.redirect('/urls');

        });

     });
};


text:
package org.scalatest

import org.scalactic.Equality
import org.scalactic.StringNormalizations._
import SharedHelpers._
import FailureMessages.decorateToStringValue
import Matchers._
import exceptions.TestFailedException

class OptionShouldContainOneOfSpec extends Spec {

  val invertedStringEquality =
    new Equality[String] {
      def areEqual(a: String, b: Any): Boolean = a != b
    }

  val upperCaseEquality =
    new Equality[String] {
      def areEqual(a: String, b: Any): Boolean = a.toUpperCase == b
    }

  object `an Option` {

    val fumSome: Option[String] = Some("fum")
    val toSome: Option[String] = Some("to")

    object `when used with contain oneOf (...) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        fumSome should contain oneOf ("fee", "fie", "foe", "fum")
        val e1 = intercept[TestFailedException] {
          fumSome should contain oneOf ("happy", "birthday", "to", "you")
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message.get should be (Resources.didNotContainOneOfElements(decorateToStringValue(fumSome), "\"happy\", \"birthday\", \"to\", \"you\""))
      }
      def `should use the implicit Equality in scope` {
        implicit val ise = upperCaseEquality
        fumSome should contain oneOf ("FEE", "FIE", "FOE", "FUM")
        intercept[TestFailedException] {
          fumSome should contain oneOf ("fee", "fie", "foe", "fum")
        }
      }
      def `should use an explicitly provided Equality` {
        (fumSome should contain oneOf ("FEE", "FIE", "FOE", "FUM")) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (fumSome should contain oneOf ("fee", "fie", "foe", "fum")) (decided by upperCaseEquality)
        }
        intercept[TestFailedException] {
          fumSome should contain oneOf (" FEE ", " FIE ", " FOE ", " FUM ")
        }
        (fumSome should contain oneOf (" FEE ", " FIE ", " FOE ", " FUM ")) (after being lowerCased and trimmed)
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          fumSome should contain oneOf ("fee", "fie", "foe", "fie", "fum")
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }

    object `when used with (contain oneOf (...)) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {

        fumSome should (contain oneOf ("fee", "fie", "foe", "fum"))
        val e1 = intercept[TestFailedException] {
          fumSome should (contain oneOf ("happy", "birthday", "to", "you"))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message.get should be (Resources.didNotContainOneOfElements(decorateToStringValue(fumSome), "\"happy\", \"birthday\", \"to\", \"you\""))
      }
      def `should use the implicit Equality in scope` {
        implicit val ise = upperCaseEquality
        fumSome should (contain oneOf ("FEE", "FIE", "FOE", "FUM"))
        intercept[TestFailedException] {
          fumSome should (contain oneOf ("fee", "fie", "foe", "fum"))
        }
      }
      def `should use an explicitly provided Equality` {
        (fumSome should (contain oneOf ("FEE", "FIE", "FOE", "FUM"))) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (fumSome should (contain oneOf ("fee", "fie", "foe", "fum"))) (decided by upperCaseEquality)
        }
        intercept[TestFailedException] {
          fumSome should (contain oneOf (" FEE ", " FIE ", " FOE ", " FUM "))
        }
        (fumSome should (contain oneOf (" FEE ", " FIE ", " FOE ", " FUM "))) (after being lowerCased and trimmed)
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          fumSome should (contain oneOf ("fee", "fie", "foe", "fie", "fum"))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }

/*
 I purposely don't want to support this syntax:

        fumSome should contain (oneOf ("fee", "fie", "foe", "fum"))
        fumSome should (contain (oneOf ("fee", "fie", "foe", "fum")))

 Reason is that I don't want people putting parentheses between contain and oneOf, etc. This will not compile.
*/
    object `when used with not contain oneOf (...) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        toSome should not contain oneOf ("fee", "fie", "foe", "fum")
        val e1 = intercept[TestFailedException] {
          toSome should not contain oneOf ("happy", "birthday", "to", "you")
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message.get should be (Resources.containedOneOfElements(decorateToStringValue(toSome), "\"happy\", \"birthday\", \"to\", \"you\""))
      }
      def `should use the implicit Equality in scope` {
        implicit val ise = upperCaseEquality
        toSome should not contain oneOf ("happy", "birthday", "to", "you")
        intercept[TestFailedException] {
          toSome should not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU")
        }
      }
      def `should use an explicitly provided Equality` {
        (toSome should not contain oneOf ("happy", "birthday", "to", "you")) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (toSome should not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU")) (decided by upperCaseEquality)
        }
        toSome should not contain oneOf (" HAPPY ", " BIRTHDAY ", " TO ", " YOU ")
        intercept[TestFailedException] {
          (toSome should not contain oneOf (" HAPPY ", " BIRTHDAY ", " TO ", " YOU ")) (after being lowerCased and trimmed)
        }
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          toSome should not contain oneOf ("fee", "fie", "foe", "fie", "fum")
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }

/*
Interesting, of these three, the top one does happen to compile and run:

        toSome should not contain (oneOf ("fee", "fie", "foe", "fum"))
        // toSome should not (contain (oneOf ("fee", "fie", "foe", "fum")))
        // toSome should (not (contain (oneOf ("fee", "fie", "foe", "fum"))))

The bottom two don't, but still I don't want to support that in general.
*/
    object `when used with (not contain oneOf (...)) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        toSome should (not contain oneOf ("fee", "fie", "foe", "fum"))
        val e1 = intercept[TestFailedException] {
          toSome should (not contain oneOf ("happy", "birthday", "to", "you"))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message.get should be (Resources.containedOneOfElements(decorateToStringValue(toSome), "\"happy\", \"birthday\", \"to\", \"you\""))
      }
      def `should use the implicit Equality in scope` {
        implicit val ise = upperCaseEquality
        toSome should (not contain oneOf ("happy", "birthday", "to", "you"))
        intercept[TestFailedException] {
          toSome should (not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU"))
        }
      }
      def `should use an explicitly provided Equality` {
        (toSome should (not contain oneOf ("happy", "birthday", "to", "you"))) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (toSome should (not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU"))) (decided by upperCaseEquality)
        }
        toSome should (not contain oneOf (" HAPPY ", " BIRTHDAY ", " TO ", " YOU "))
        intercept[TestFailedException] {
          (toSome should (not contain oneOf (" HAPPY ", " BIRTHDAY ", " TO ", " YOU "))) (after being lowerCased and trimmed)
        }
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          toSome should (not contain oneOf ("fee", "fie", "foe", "fie", "fum"))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }
  }

  object `a collection of Options` {

    val some1s: Vector[Option[Int]] = Vector(Some(1), Some(1), Some(1))
    val somes: Vector[Option[Int]] = Vector(Some(1), Some(1), Some(2))
    val nones: Vector[Option[Int]] = Vector(None, None, None)
    val somesNone: Vector[Option[Int]] = Vector(Some(1), Some(1), None)
    val hiSomes: Vector[Option[String]] = Vector(Some("hi"), Some("hi"), Some("hi"))
    val toSomes: Vector[Option[String]] = Vector(Some("to"), Some("to"), Some("to"))

    object `when used with contain oneOf (...) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        all (some1s) should contain oneOf (1, 3, 4)
        atLeast (2, somes) should contain oneOf (1, 3, 4)
        atMost (2, somes) should contain oneOf (2, 3, 4)
        no (somes) should contain oneOf (3, 4, 5)
        no (nones) should contain oneOf (1, 3, 4)
        no (somesNone) should contain oneOf (3, 4, 5)

        val e1 = intercept[TestFailedException] {
          all (somes) should contain oneOf (1, 3, 4)
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 2, " + FailureMessages.didNotContainOneOfElements(somes(2), UnquotedString("1, 3, 4")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(Some(1), Some(1), Some(2))"))

        val e2 = intercept[TestFailedException] {
          all (nones) should contain oneOf ("ho", "hey", "howdy")
        }
        e2.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e2.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e2.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 0, " + FailureMessages.didNotContainOneOfElements(nones(0), UnquotedString("\"ho\", \"hey\", \"howdy\"")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(None, None, None)"))

        val e4 = intercept[TestFailedException] {
          all (somesNone) should contain oneOf (1, 3, 4)
        }
        e4.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e4.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e4.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 2, " + FailureMessages.didNotContainOneOfElements(somesNone(2), UnquotedString("1, 3, 4")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(Some(1), Some(1), None)"))
      }

      def `should use the implicit Equality in scope` {
        all (hiSomes) should contain oneOf ("hi", "he")
        intercept[TestFailedException] {
          all (hiSomes) should contain oneOf ("ho", "he")
        }
        implicit val ise = upperCaseEquality
        all (hiSomes) should contain oneOf ("HI", "HE")
        intercept[TestFailedException] {
          all (hiSomes) should contain oneOf ("hi", "he")
        }
      }
      def `should use an explicitly provided Equality` {
        (all (hiSomes) should contain oneOf ("HI", "HE")) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (all (hiSomes) should contain oneOf ("hi", "he")) (decided by upperCaseEquality)
        }
        implicit val ise = upperCaseEquality
        (all (hiSomes) should contain oneOf ("hi", "he")) (decided by defaultEquality[String])
        intercept[TestFailedException] {
          (all (hiSomes) should contain oneOf ("HI", "HE")) (decided by defaultEquality[String])
        }
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          all (some1s) should contain oneOf (1, 2, 2, 3)
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }

    object `when used with (contain oneOf (...)) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        all (some1s) should (contain oneOf (1, 3, 4))
        atLeast (2, somes) should (contain oneOf (1, 3, 4))
        atMost (2, somes) should (contain oneOf (2, 3, 4))
        no (somes) should (contain oneOf (3, 4, 5))
        no (nones) should (contain oneOf (1, 3, 4))
        no (somesNone) should (contain oneOf (3, 4, 5))

        val e1 = intercept[TestFailedException] {
          all (somes) should (contain oneOf (1, 3, 4))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 2, " + FailureMessages.didNotContainOneOfElements(somes(2), UnquotedString("1, 3, 4")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(Some(1), Some(1), Some(2))"))

        val e2 = intercept[TestFailedException] {
          all (nones) should (contain oneOf ("ho", "hey", "howdy"))
        }
        e2.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e2.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e2.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 0, " + FailureMessages.didNotContainOneOfElements(nones(0), UnquotedString("\"ho\", \"hey\", \"howdy\"")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(None, None, None)"))

        val e4 = intercept[TestFailedException] {
          all (somesNone) should (contain oneOf (1, 3, 4))
        }
        e4.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e4.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e4.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 2, " + FailureMessages.didNotContainOneOfElements(somesNone(2), UnquotedString("1, 3, 4")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(Some(1), Some(1), None)"))
      }

      def `should use the implicit Equality in scope` {
        all (hiSomes) should (contain oneOf ("hi", "he"))
        intercept[TestFailedException] {
          all (hiSomes) should (contain oneOf ("HI", "HE"))
        }
        implicit val ise = upperCaseEquality
        all (hiSomes) should (contain oneOf ("HI", "HE"))
        intercept[TestFailedException] {
          all (hiSomes) should (contain oneOf ("hi", "he"))
        }
      }
      def `should use an explicitly provided Equality` {
        (all (hiSomes) should (contain oneOf ("HI", "HE"))) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (all (hiSomes) should (contain oneOf ("hi", "he"))) (decided by upperCaseEquality)
        }
        implicit val ise = upperCaseEquality
        (all (hiSomes) should (contain oneOf ("hi", "he"))) (decided by defaultEquality[String])
        intercept[TestFailedException] {
          (all (hiSomes) should (contain oneOf ("HI", "HE"))) (decided by defaultEquality[String])
        }
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          all (some1s) should (contain oneOf (1, 2, 2, 3))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }

/*
 I purposely don't want to support this syntax:

scala> all (some1s) should contain (oneOf (1, 3, 4))
<console>:15: error: org.scalatest.words.NewContainWord does not take parameters
              all (some1s) should contain (oneOf (1, 3, 4))
                                             ^

scala> all (some1s) should (contain (oneOf (1, 3, 4)))
<console>:15: error: org.scalatest.words.NewContainWord does not take parameters
              all (some1s) should (contain (oneOf (1, 3, 4)))
                                              ^

 Reason is that I don't want people putting parentheses between contain and oneOf, etc. This will not compile.
*/
    object `when used with not contain oneOf (...) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        all (toSomes) should not contain oneOf ("fee", "fie", "foe", "fum")
        val e1 = intercept[TestFailedException] {
          all (toSomes) should not contain oneOf ("happy", "birthday", "to", "you")
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 0, " + FailureMessages.containedOneOfElements(toSomes(0), UnquotedString("\"happy\", \"birthday\", \"to\", \"you\"")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(Some(\"to\"), Some(\"to\"), Some(\"to\"))"))
      }
      def `should use the implicit Equality in scope` {
        implicit val ise = upperCaseEquality
        all (toSomes) should not contain oneOf ("happy", "birthday", "to", "you")
        intercept[TestFailedException] {
          all (toSomes) should not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU")
        }
      }
      def `should use an explicitly provided Equality` {
        (all (toSomes) should not contain oneOf ("happy", "birthday", "to", "you")) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (all (toSomes) should not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU")) (decided by upperCaseEquality)
        }
        all (toSomes) should not contain oneOf (" happy ", " birthday ", " to ", " you ")
        intercept[TestFailedException] {
          (all (toSomes) should not contain oneOf (" happy ", " birthday ", " to ", " you ")) (after being lowerCased and trimmed)
        }
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          all (toSomes) should not contain oneOf ("fee", "fie", "foe", "fie", "fum")
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }

/*
Interesting, of these three, the last one does happen to compile and run:

scala> all (toSomes) should (not (contain (oneOf ("fee", "fie", "foe", "fum"))))
<console>:15: error: org.scalatest.words.NewContainWord does not take parameters
              all (toSomes) should (not (contain (oneOf ("fee", "fie", "foe", "fum"))))
                                                    ^

scala> all (toSomes) should not (contain (oneOf ("fee", "fie", "foe", "fum")))
<console>:15: error: org.scalatest.words.NewContainWord does not take parameters
              all (toSomes) should not (contain (oneOf ("fee", "fie", "foe", "fum")))
                                                   ^

scala> all (toSomes) should not contain (oneOf ("fee", "fie", "foe", "fum"))

The top two don't, but still I don't want to support that in general.
*/
    object `when used with (not contain oneOf (...)) syntax` {

      def `should do nothing if valid, else throw a TFE with an appropriate error message` {
        all (toSomes) should (not contain oneOf ("fee", "fie", "foe", "fum"))
        val e1 = intercept[TestFailedException] {
          all (toSomes) should (not contain oneOf ("happy", "birthday", "to", "you"))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some("'all' inspection failed, because: \n" +
                                   "  at index 0, " + FailureMessages.containedOneOfElements(toSomes(0), UnquotedString("\"happy\", \"birthday\", \"to\", \"you\"")) + " (OptionShouldContainOneOfSpec.scala:" + (thisLineNumber - 5) + ") \n" +
                                   "in Vector(Some(\"to\"), Some(\"to\"), Some(\"to\"))"))
      }
      def `should use the implicit Equality in scope` {
        implicit val ise = upperCaseEquality
        all (toSomes) should (not contain oneOf ("happy", "birthday", "to", "you"))
        intercept[TestFailedException] {
          all (toSomes) should (not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU"))
        }
      }
      def `should use an explicitly provided Equality` {
        (all (toSomes) should (not contain oneOf ("happy", "birthday", "to", "you"))) (decided by upperCaseEquality)
        intercept[TestFailedException] {
          (all (toSomes) should (not contain oneOf ("HAPPY", "BIRTHDAY", "TO", "YOU"))) (decided by upperCaseEquality)
        }
        all (toSomes) should (not contain oneOf (" happy ", " birthday ", " to ", " you "))
        intercept[TestFailedException] {
          (all (toSomes) should (not contain oneOf (" HAPPY ", " BIRTHDAY ", " TO ", " YOU "))) (after being lowerCased and trimmed)
        }
      }
      def `should throw NotAllowedException with correct stack depth and message when RHS contain duplicated value` {
        val e1 = intercept[exceptions.NotAllowedException] {
          all (toSomes) should (not contain oneOf ("fee", "fie", "foe", "fie", "fum"))
        }
        e1.failedCodeFileName.get should be ("OptionShouldContainOneOfSpec.scala")
        e1.failedCodeLineNumber.get should be (thisLineNumber - 3)
        e1.message should be (Some(Resources.oneOfDuplicate))
      }
    }
  }
}


text:
require "test_helper"

class Invenio::PullRequestTest < MiniTest::Unit::TestCase
  def setup
    @user = "simeonwillbanks"
    @number = 1
    @files = ["discoveries/20131221/simeonwillbanks_a-good-discovery.md"]
    @bad_files = @files + ["20131221/a-bad-discovery.md"]
    @options = {
      :user => @user,
      :number => @number
    }
    @client = MiniTest::Mock.new
    @klass = Invenio::PullRequest
  end

  def test_can_accept_with_good_files
    @client.expect :pull_request_files, @files, [@number]

    pull_request = @klass.new @options, @client
    assert pull_request.acceptable?
    assert @client.verify
  end

  def test_cant_accept_with_bad_files
    @client.expect :pull_request_files, @bad_files, [@number]

    pull_request = @klass.new @options, @client
    refute pull_request.acceptable?
    assert @client.verify
  end

  def test_merge_when_acceptable
    @client.expect :pull_request_files, @files, [@number]
    @client.expect :merge_pull_request, nil, [@number]

    pull_request = @klass.new @options, @client
    pull_request.review
    assert @client.verify
  end

  def test_comment_when_not_acceptable
    @client.expect :pull_request_files, @bad_files, [@number]
    @client.expect :pull_request_bot_commented?, false, [@number]
    @client.expect :add_pull_request_comment, nil, [@number, String]

    pull_request = @klass.new @options, @client
    pull_request.review
    assert @client.verify
  end

  def test_dont_comment_when_not_acceptable_but_already_commented
    @client.expect :pull_request_files, @bad_files, [@number]
    @client.expect :pull_request_bot_commented?, true, [@number]
    # should not receive
    @client.expect :add_pull_request_comment, nil

    pull_request = @klass.new @options, @client
    pull_request.review
    # assert should not receive
    assert_raises MockExpectationError, "expected add_pull_request_comment" do
      @client.verify
    end
  end
end


text:
test:
	./vendor/bin/phpunit


text:
@interface PodsDummy_AKCalendar : NSObject
@end
@implementation PodsDummy_AKCalendar
@end


text:
'use strict';

class UserError extends Error {}
exports.UserError = UserError;

/**
 * Get unique error field name
 */
var getUniqueErrorMessage = function(err) {
    var output;

    try {
        var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
        output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exist';

    } catch(ex) {
        output = 'Unique field already exist';
    }

    return output;
};

/**
 * Get the error message from error object
 */
exports.getErrorMessage = function(err) {
    var message = '';

    if (err instanceof UserError) {
        message = err.message;
    } else if (err.code) {
        switch (err.code) {
            case 11000:
            case 11001:
                message = getUniqueErrorMessage(err);
                break;
            default:
                message = 'Something went wrong';
        }
    } else if (err.errors) {
        for (var errName in err.errors) {
            if (err.errors[errName].message) message = err.errors[errName].message;
        }
    } else if (err.message) {
        message = err.message;
    }

    if (message) {
        console.error(message);
    }
    else {
        console.error(err);
    }

    return message;
};


text:
import argparse
import os
import subprocess
import sys

from compose import config
from compose.config import environment

import compose_deploy
from compose_deploy import remote

def _search_up(filename, stop_at_git=True):
    prefix = ''
    while True:
        path = os.path.join(prefix, filename)

        if os.path.isfile(path):
            return path
        elif prefix == '/' or (os.path.isdir(os.path.join(prefix, '.git')) and
                               stop_at_git):
            # insisting that .git is a dir means we will traverse out of git
            # submodules, a behaviour I desire
            raise IOError('{} not found here or any directory above here'
                          .format(filename))
        prefix = os.path.realpath(os.path.join(prefix, '..'))

def get_config(basedir, files):
    """ Returns the config object for the selected docker-compose.yml

    This is an instance of `compose.config.config.Config`.
    """
    config_details = config.find(
        basedir, files,
        environment.Environment.from_env_file(basedir))

    return config.load(config_details)

def parse_services_arg(config, arg_services):
    all_services = [service['name'] for service in config.services]

    def get_service_dicts(service_names):
        services_dict_out = {}

        for service_dict in config.services:
            name = service_dict['name']
            if name in service_names:
                services_dict_out[name] = service_dict

        return services_dict_out

    if not arg_services:
        return get_service_dicts(all_services)

    services_out = []
    added = []
    negated = []

    for service in arg_services:
        if service.startswith(':'):
            negated.append(service)
            service = service[1:]
        else:
            added.append(service)

        if service not in all_services:
            raise ValueError('Service "{}" not defined'.format(service))

    if not added:
        services_out.extend(all_services)

    services_out.extend(added)
    for service in negated:
        services_out.remove(service[1:])

    # Keep `services_out` for ordering
    return get_service_dicts(services_out)

def _call(what, *args, **kwargs):
    # If they can modify the docker-compose file then they can already gain
    # root access without particular difficulty. "shell=True" is fine here.
    return subprocess.check_output(what, *args, shell=True, **kwargs)

def _call_output(what, *args, **kwargs):
    return subprocess.call(what, *args, shell=True, stdout=sys.stdout,
                           stderr=subprocess.STDOUT, **kwargs)

def _get_version():
    return _call('git describe --tags HEAD')

def build(config, services):
    """ Builds images and tags them appropriately.

    Where "appropriately" means with the output of:

        git describe --tags HEAD

    and 'latest' as well (so the "latest" image for each will always be the
    most recently built)
    """
    filtered_services = {name: service for name, service in services.iteritems() if 'build' in service}

    _call_output('docker-compose build {}'.format(' '.join(filtered_services.iterkeys())))

    version = _get_version()

    for service_name, service_dict in filtered_services.iteritems():
        # Tag with proper version, they're already tagged latest from build
        image = service_dict['image']
        _call('docker tag {image}:latest {image}:{version}'.format(
                image=image,
                version=version
            )
        )

def push(config, services):
    """ Upload the defined services to their respective repositories.

    So's we can then tell the remote docker host to then pull and run them.
    """
    version = _get_version()
    for service_name, service_dict in services.iteritems():
        image = service_dict['image']
        things = {'image': image, 'version': version}
        _call_output('docker push {image}:latest'.format(**things))
        _call_output('docker push {image}:{version}'.format(**things))

def buildpush_main(command, args):
    _base = os.path.abspath(_search_up(args.file[0]))

    basedir = os.path.dirname(_base)

    config = get_config(basedir, args.file)

    actual_services = parse_services_arg(config, args.services)

    # Dispatch to appropriate function
    {'build': build, 'push': push}[command](config, actual_services)

def remote_main(args):
    remote.remote(args.server, args.command)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--version', '-V', action='version',
        version='%(prog)s {}'.format(compose_deploy.__version__))

    buildpush_parent = argparse.ArgumentParser(add_help=False)
    buildpush_parent.add_argument(
        '--file', '-f', nargs='+',
        default=['docker-compose.yml'],
        help='Same as the -f argument to docker-compose.')
    buildpush_parent.add_argument(
        'services', nargs='*',
        help='Which services to work on, all if empty')

    subparsers = parser.add_subparsers(dest='action')

    build_parser = subparsers.add_parser('build', parents=[buildpush_parent],  # noqa
                                         help='Build and tag the images')

    remote_parser = subparsers.add_parser(
        'remote',
        help='Run a shell with a connection to a remote docker server')
    remote_parser.add_argument(
        'server',
        help='The remote docker server to connect to; '
             'Uses openssh underneath so setup ~/.ssh/config appropriately, '
             'needs passwordless login '
             '(e.g. via ssh-agent or passwordless key)')
    remote_parser.add_argument(
        '--command', '-c', default=None,
        help='Command to run in the opened shell (and then immediately exit)')

    push_parser = subparsers.add_parser(  # noqa
        'push', parents=[buildpush_parent],
        help='Push the images to their repositories')

    args = parser.parse_args()

    if args.action in ['build', 'push']:
        buildpush_main(args.action, args)
    elif args.action in ['remote']:
        remote_main(args)

if __name__ == '__main__':
    main()


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <base href="/">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

      <link rel="stylesheet" href="bower_components/pure/pure.css" />

    <link rel="stylesheet" href="app/app.css">

      <link rel="stylesheet" href="app/main/purewoof.css">


text:
package bridge

import (
	"errors"
	"net"
	"strings"
	"sync"

	"github.com/docker/libnetwork/driverapi"
	"github.com/docker/libnetwork/ipallocator"
	"github.com/docker/libnetwork/netlabel"
	"github.com/docker/libnetwork/netutils"
	"github.com/docker/libnetwork/options"
	"github.com/docker/libnetwork/portmapper"
	"github.com/docker/libnetwork/sandbox"
	"github.com/docker/libnetwork/types"
	"github.com/vishvananda/netlink"
)

const (
	networkType             = "bridge"
	vethPrefix              = "veth"
	vethLen                 = 7
	containerVethPrefix     = "eth"
	maxAllocatePortAttempts = 10
	ifaceID                 = 1
)

var (
	ipAllocator *ipallocator.IPAllocator
	portMapper  *portmapper.PortMapper
)

// Configuration info for the "bridge" driver.
type Configuration struct {
	EnableIPForwarding bool
}

// NetworkConfiguration for network specific configuration
type NetworkConfiguration struct {
	BridgeName            string
	AddressIPv4           *net.IPNet
	FixedCIDR             *net.IPNet
	FixedCIDRv6           *net.IPNet
	EnableIPv6            bool
	EnableIPTables        bool
	EnableIPMasquerade    bool
	EnableICC             bool
	Mtu                   int
	DefaultGatewayIPv4    net.IP
	DefaultGatewayIPv6    net.IP
	DefaultBindingIP      net.IP
	AllowNonDefaultBridge bool
	EnableUserlandProxy   bool
}

// EndpointConfiguration represents the user specified configuration for the sandbox endpoint
type EndpointConfiguration struct {
	MacAddress   net.HardwareAddr
	PortBindings []types.PortBinding
	ExposedPorts []types.TransportPort
}

// ContainerConfiguration represents the user specified configuration for a container
type ContainerConfiguration struct {
	ParentEndpoints []string
	ChildEndpoints  []string
}

type bridgeEndpoint struct {
	id              types.UUID
	intf            *sandbox.Interface
	macAddress      net.HardwareAddr
	config          *EndpointConfiguration // User specified parameters
	containerConfig *ContainerConfiguration
	portMapping     []types.PortBinding // Operation port bindings
}

type bridgeNetwork struct {
	id        types.UUID
	bridge    *bridgeInterface // The bridge's L3 interface
	config    *NetworkConfiguration
	endpoints map[types.UUID]*bridgeEndpoint // key: endpoint id
	sync.Mutex
}

type driver struct {
	config  *Configuration
	network *bridgeNetwork
	sync.Mutex
}

func init() {
	ipAllocator = ipallocator.New()
	portMapper = portmapper.New()
}

// New constructs a new bridge driver
func newDriver() driverapi.Driver {
	return &driver{}
}

// Init registers a new instance of bridge driver
func Init(dc driverapi.DriverCallback) error {
	return dc.RegisterDriver(networkType, newDriver())
}

// Validate performs a static validation on the network configuration parameters.
// Whatever can be assessed a priori before attempting any programming.
func (c *NetworkConfiguration) Validate() error {
	if c.Mtu < 0 {
		return ErrInvalidMtu(c.Mtu)
	}

	// If bridge v4 subnet is specified
	if c.AddressIPv4 != nil {
		// If Container restricted subnet is specified, it must be a subset of bridge subnet
		if c.FixedCIDR != nil {
			// Check Network address
			if !c.AddressIPv4.Contains(c.FixedCIDR.IP) {
				return &ErrInvalidContainerSubnet{}
			}
			// Check it is effectively a subset
			brNetLen, _ := c.AddressIPv4.Mask.Size()
			cnNetLen, _ := c.FixedCIDR.Mask.Size()
			if brNetLen > cnNetLen {
				return &ErrInvalidContainerSubnet{}
			}
		}
		// If default gw is specified, it must be part of bridge subnet
		if c.DefaultGatewayIPv4 != nil {
			if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
				return &ErrInvalidGateway{}
			}
		}
	}

	// If default v6 gw is specified, FixedCIDRv6 must be specified and gw must belong to FixedCIDRv6 subnet
	if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
		if c.FixedCIDRv6 == nil || !c.FixedCIDRv6.Contains(c.DefaultGatewayIPv6) {
			return &ErrInvalidGateway{}
		}
	}

	return nil
}

func (n *bridgeNetwork) getEndpoint(eid types.UUID) (*bridgeEndpoint, error) {
	n.Lock()
	defer n.Unlock()

	if eid == "" {
		return nil, InvalidEndpointIDError(eid)
	}

	if ep, ok := n.endpoints[eid]; ok {
		return ep, nil
	}

	return nil, nil
}

func (d *driver) Config(option map[string]interface{}) error {
	var config *Configuration

	d.Lock()
	defer d.Unlock()

	if d.config != nil {
		return &ErrConfigExists{}
	}

	genericData, ok := option[netlabel.GenericData]
	if ok && genericData != nil {
		switch opt := genericData.(type) {
		case options.Generic:
			opaqueConfig, err := options.GenerateFromModel(opt, &Configuration{})
			if err != nil {
				return err
			}
			config = opaqueConfig.(*Configuration)
		case *Configuration:
			config = opt
		default:
			return &ErrInvalidDriverConfig{}
		}

		d.config = config
	} else {
		config = &Configuration{}
	}

	if config.EnableIPForwarding {
		return setupIPForwarding(config)
	}

	return nil
}

func (d *driver) getNetwork(id types.UUID) (*bridgeNetwork, error) {
	// Just a dummy function to return the only network managed by Bridge driver.
	// But this API makes the caller code unchanged when we move to support multiple networks.
	d.Lock()
	defer d.Unlock()
	return d.network, nil
}

func parseNetworkOptions(option options.Generic) (*NetworkConfiguration, error) {
	var config *NetworkConfiguration

	genericData, ok := option[netlabel.GenericData]
	if ok && genericData != nil {
		switch opt := genericData.(type) {
		case options.Generic:
			opaqueConfig, err := options.GenerateFromModel(opt, &NetworkConfiguration{})
			if err != nil {
				return nil, err
			}
			config = opaqueConfig.(*NetworkConfiguration)
		case *NetworkConfiguration:
			config = opt
		default:
			return nil, &ErrInvalidNetworkConfig{}
		}

		if err := config.Validate(); err != nil {
			return nil, err
		}
	} else {
		config = &NetworkConfiguration{}
	}

	if _, ok := option[netlabel.EnableIPv6]; ok {
		config.EnableIPv6 = option[netlabel.EnableIPv6].(bool)
	}

	return config, nil
}

// Create a new network using bridge plugin
func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {
	var err error

	// Driver must be configured
	d.Lock()

	// Sanity checks
	if d.network != nil {
		d.Unlock()
		return &ErrNetworkExists{}
	}

	// Create and set network handler in driver
	d.network = &bridgeNetwork{id: id, endpoints: make(map[types.UUID]*bridgeEndpoint)}
	network := d.network
	d.Unlock()

	// On failure make sure to reset driver network handler to nil
	defer func() {
		if err != nil {
			d.Lock()
			d.network = nil
			d.Unlock()
		}
	}()

	config, err := parseNetworkOptions(option)
	if err != nil {
		return err
	}
	network.config = config

	// Create or retrieve the bridge L3 interface
	bridgeIface := newInterface(config)
	network.bridge = bridgeIface

	// Prepare the bridge setup configuration
	bridgeSetup := newBridgeSetup(config, bridgeIface)

	// If the bridge interface doesn't exist, we need to start the setup steps
	// by creating a new device and assigning it an IPv4 address.
	bridgeAlreadyExists := bridgeIface.exists()
	if !bridgeAlreadyExists {
		bridgeSetup.queueStep(setupDevice)
	}

	// Even if a bridge exists try to setup IPv4.
	bridgeSetup.queueStep(setupBridgeIPv4)

	// Conditionally queue setup steps depending on configuration values.
	for _, step := range []struct {
		Condition bool
		Fn        setupStep
	}{
		// Enable IPv6 on the bridge if required. We do this even for a
		// previously  existing bridge, as it may be here from a previous
		// installation where IPv6 wasn't supported yet and needs to be
		// assigned an IPv6 link-local address.
		{config.EnableIPv6, setupBridgeIPv6},

		// We ensure that the bridge has the expectedIPv4 and IPv6 addresses in
		// the case of a previously existing device.
		{bridgeAlreadyExists, setupVerifyAndReconcile},

		// Setup the bridge to allocate containers IPv4 addresses in the
		// specified subnet.
		{config.FixedCIDR != nil, setupFixedCIDRv4},

		// Setup the bridge to allocate containers global IPv6 addresses in the
		// specified subnet.
		{config.FixedCIDRv6 != nil, setupFixedCIDRv6},

		// Setup Loopback Adresses Routing
		{!config.EnableUserlandProxy, setupLoopbackAdressesRouting},

		// Setup IPTables.
		{config.EnableIPTables, setupIPTables},

		// Setup DefaultGatewayIPv4
		{config.DefaultGatewayIPv4 != nil, setupGatewayIPv4},

		// Setup DefaultGatewayIPv6
		{config.DefaultGatewayIPv6 != nil, setupGatewayIPv6},
	} {
		if step.Condition {
			bridgeSetup.queueStep(step.Fn)
		}
	}

	// Block bridge IP from being allocated.
	bridgeSetup.queueStep(allocateBridgeIP)
	// Apply the prepared list of steps, and abort at the first error.
	bridgeSetup.queueStep(setupDeviceUp)
	if err = bridgeSetup.apply(); err != nil {
		return err
	}

	return nil
}

func (d *driver) DeleteNetwork(nid types.UUID) error {
	var err error

	// Get network handler and remove it from driver
	d.Lock()
	n := d.network
	d.network = nil
	d.Unlock()

	// On failure set network handler back in driver, but
	// only if is not already taken over by some other thread
	defer func() {
		if err != nil {
			d.Lock()
			if d.network == nil {
				d.network = n
			}
			d.Unlock()
		}
	}()

	// Sanity check
	if n == nil {
		err = driverapi.ErrNoNetwork(nid)
		return err
	}

	// Cannot remove network if endpoints are still present
	if len(n.endpoints) != 0 {
		err = ActiveEndpointsError(n.id)
		return err
	}

	// Programming
	err = netlink.LinkDel(n.bridge.Link)

	return err
}

func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
	var (
		ipv6Addr *net.IPNet
		err      error
	)

	if epInfo == nil {
		return errors.New("invalid endpoint info passed")
	}

	if len(epInfo.Interfaces()) != 0 {
		return errors.New("non empty interface list passed to bridge(local) driver")
	}

	// Get the network handler and make sure it exists
	d.Lock()
	n := d.network
	config := n.config
	d.Unlock()
	if n == nil {
		return driverapi.ErrNoNetwork(nid)
	}

	// Sanity check
	n.Lock()
	if n.id != nid {
		n.Unlock()
		return InvalidNetworkIDError(nid)
	}
	n.Unlock()

	// Check if endpoint id is good and retrieve correspondent endpoint
	ep, err := n.getEndpoint(eid)
	if err != nil {
		return err
	}

	// Endpoint with that id exists either on desired or other sandbox
	if ep != nil {
		return driverapi.ErrEndpointExists(eid)
	}

	// Try to convert the options to endpoint configuration
	epConfig, err := parseEndpointOptions(epOptions)
	if err != nil {
		return err
	}

	// Create and add the endpoint
	n.Lock()
	endpoint := &bridgeEndpoint{id: eid, config: epConfig}
	n.endpoints[eid] = endpoint
	n.Unlock()

	// On failure make sure to remove the endpoint
	defer func() {
		if err != nil {
			n.Lock()
			delete(n.endpoints, eid)
			n.Unlock()
		}
	}()

	// Generate a name for what will be the host side pipe interface
	name1, err := generateIfaceName()
	if err != nil {
		return err
	}

	// Generate a name for what will be the sandbox side pipe interface
	name2, err := generateIfaceName()
	if err != nil {
		return err
	}

	// Generate and add the interface pipe host <-> sandbox
	veth := &netlink.Veth{
		LinkAttrs: netlink.LinkAttrs{Name: name1, TxQLen: 0},
		PeerName:  name2}
	if err = netlink.LinkAdd(veth); err != nil {
		return err
	}

	// Get the host side pipe interface handler
	host, err := netlink.LinkByName(name1)
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			netlink.LinkDel(host)
		}
	}()

	// Get the sandbox side pipe interface handler
	sbox, err := netlink.LinkByName(name2)
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			netlink.LinkDel(sbox)
		}
	}()

	// Set the sbox's MAC. If specified, use the one configured by user, otherwise use a random one
	mac := electMacAddress(epConfig)
	err = netlink.LinkSetHardwareAddr(sbox, mac)
	if err != nil {
		return err
	}
	endpoint.macAddress = mac

	// Add bridge inherited attributes to pipe interfaces
	if config.Mtu != 0 {
		err = netlink.LinkSetMTU(host, config.Mtu)
		if err != nil {
			return err
		}
		err = netlink.LinkSetMTU(sbox, config.Mtu)
		if err != nil {
			return err
		}
	}

	// Attach host side pipe interface into the bridge
	if err = netlink.LinkSetMaster(host,
		&netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: config.BridgeName}}); err != nil {
		return err
	}

	// v4 address for the sandbox side pipe interface
	ip4, err := ipAllocator.RequestIP(n.bridge.bridgeIPv4, nil)
	if err != nil {
		return err
	}
	ipv4Addr := &net.IPNet{IP: ip4, Mask: n.bridge.bridgeIPv4.Mask}

	// v6 address for the sandbox side pipe interface
	ipv6Addr = &net.IPNet{}
	if config.EnableIPv6 {
		var ip6 net.IP

		network := n.bridge.bridgeIPv6
		if config.FixedCIDRv6 != nil {
			network = config.FixedCIDRv6
		}

		ones, _ := network.Mask.Size()
		if ones <= 80 {
			ip6 = make(net.IP, len(network.IP))
			copy(ip6, network.IP)
			for i, h := range mac {
				ip6[i+10] = h
			}
		}

		ip6, err := ipAllocator.RequestIP(network, ip6)
		if err != nil {
			return err
		}

		ipv6Addr = &net.IPNet{IP: ip6, Mask: network.Mask}
	}

	// Create the sandbox side pipe interface
	intf := &sandbox.Interface{}
	intf.SrcName = name2
	intf.DstName = containerVethPrefix
	intf.Address = ipv4Addr

	if config.EnableIPv6 {
		intf.AddressIPv6 = ipv6Addr
	}

	// Store the interface in endpoint, this is needed for cleanup on DeleteEndpoint()
	endpoint.intf = intf

	err = epInfo.AddInterface(ifaceID, endpoint.macAddress, *ipv4Addr, *ipv6Addr)
	if err != nil {
		return err
	}

	// Program any required port mapping and store them in the endpoint
	endpoint.portMapping, err = allocatePorts(epConfig, intf, config.DefaultBindingIP, config.EnableUserlandProxy)
	if err != nil {
		return err
	}

	return nil
}

func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
	var err error

	// Get the network handler and make sure it exists
	d.Lock()
	n := d.network
	config := n.config
	d.Unlock()
	if n == nil {
		return driverapi.ErrNoNetwork(nid)
	}

	// Sanity Check
	n.Lock()
	if n.id != nid {
		n.Unlock()
		return InvalidNetworkIDError(nid)
	}
	n.Unlock()

	// Check endpoint id and if an endpoint is actually there
	ep, err := n.getEndpoint(eid)
	if err != nil {
		return err
	}
	if ep == nil {
		return EndpointNotFoundError(eid)
	}

	// Remove it
	n.Lock()
	delete(n.endpoints, eid)
	n.Unlock()

	// On failure make sure to set back ep in n.endpoints, but only
	// if it hasn't been taken over already by some other thread.
	defer func() {
		if err != nil {
			n.Lock()
			if _, ok := n.endpoints[eid]; !ok {
				n.endpoints[eid] = ep
			}
			n.Unlock()
		}
	}()

	// Remove port mappings. Do not stop endpoint delete on unmap failure
	releasePorts(ep)

	// Release the v4 address allocated to this endpoint's sandbox interface
	err = ipAllocator.ReleaseIP(n.bridge.bridgeIPv4, ep.intf.Address.IP)
	if err != nil {
		return err
	}

	// Release the v6 address allocated to this endpoint's sandbox interface
	if config.EnableIPv6 {
		err := ipAllocator.ReleaseIP(n.bridge.bridgeIPv6, ep.intf.AddressIPv6.IP)
		if err != nil {
			return err
		}
	}

	// Try removal of link. Discard error: link pair might have
	// already been deleted by sandbox delete.
	link, err := netlink.LinkByName(ep.intf.SrcName)
	if err == nil {
		netlink.LinkDel(link)
	}

	return nil
}

func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
	// Get the network handler and make sure it exists
	d.Lock()
	n := d.network
	d.Unlock()
	if n == nil {
		return nil, driverapi.ErrNoNetwork(nid)
	}

	// Sanity check
	n.Lock()
	if n.id != nid {
		n.Unlock()
		return nil, InvalidNetworkIDError(nid)
	}
	n.Unlock()

	// Check if endpoint id is good and retrieve correspondent endpoint
	ep, err := n.getEndpoint(eid)
	if err != nil {
		return nil, err
	}
	if ep == nil {
		return nil, driverapi.ErrNoEndpoint(eid)
	}

	m := make(map[string]interface{})

	if ep.portMapping != nil {
		// Return a copy of the operational data
		pmc := make([]types.PortBinding, 0, len(ep.portMapping))
		for _, pm := range ep.portMapping {
			pmc = append(pmc, pm.GetCopy())
		}
		m[netlabel.PortMap] = pmc
	}

	if len(ep.macAddress) != 0 {
		m[netlabel.MacAddress] = ep.macAddress
	}

	return m, nil
}

// Join method is invoked when a Sandbox is attached to an endpoint.
func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
	network, err := d.getNetwork(nid)
	if err != nil {
		return err
	}

	endpoint, err := network.getEndpoint(eid)
	if err != nil {
		return err
	}

	if endpoint == nil {
		return EndpointNotFoundError(eid)
	}

	for _, iNames := range jinfo.InterfaceNames() {
		// Make sure to set names on the correct interface ID.
		if iNames.ID() == ifaceID {
			err = iNames.SetNames(endpoint.intf.SrcName, endpoint.intf.DstName)
			if err != nil {
				return err
			}
		}
	}

	err = jinfo.SetGateway(network.bridge.gatewayIPv4)
	if err != nil {
		return err
	}

	err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6)
	if err != nil {
		return err
	}

	if !network.config.EnableICC {
		return d.link(network, endpoint, options, true)
	}

	return nil
}

// Leave method is invoked when a Sandbox detaches from an endpoint.
func (d *driver) Leave(nid, eid types.UUID) error {
	network, err := d.getNetwork(nid)
	if err != nil {
		return err
	}

	endpoint, err := network.getEndpoint(eid)
	if err != nil {
		return err
	}

	if endpoint == nil {
		return EndpointNotFoundError(eid)
	}

	if !network.config.EnableICC {
		return d.link(network, endpoint, nil, false)
	}

	return nil
}

func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, options map[string]interface{}, enable bool) error {
	var (
		cc  *ContainerConfiguration
		err error
	)

	if enable {
		cc, err = parseContainerOptions(options)
		if err != nil {
			return err
		}
	} else {
		cc = endpoint.containerConfig
	}

	if cc == nil {
		return nil
	}

	if endpoint.config != nil && endpoint.config.ExposedPorts != nil {
		for _, p := range cc.ParentEndpoints {
			var parentEndpoint *bridgeEndpoint
			parentEndpoint, err = network.getEndpoint(types.UUID(p))
			if err != nil {
				return err
			}
			if parentEndpoint == nil {
				err = InvalidEndpointIDError(p)
				return err
			}

			l := newLink(parentEndpoint.intf.Address.IP.String(),
				endpoint.intf.Address.IP.String(),
				endpoint.config.ExposedPorts, network.config.BridgeName)
			if enable {
				err = l.Enable()
				if err != nil {
					return err
				}
				defer func() {
					if err != nil {
						l.Disable()
					}
				}()
			} else {
				l.Disable()
			}
		}
	}

	for _, c := range cc.ChildEndpoints {
		var childEndpoint *bridgeEndpoint
		childEndpoint, err = network.getEndpoint(types.UUID(c))
		if err != nil {
			return err
		}
		if childEndpoint == nil {
			err = InvalidEndpointIDError(c)
			return err
		}
		if childEndpoint.config == nil || childEndpoint.config.ExposedPorts == nil {
			continue
		}

		l := newLink(endpoint.intf.Address.IP.String(),
			childEndpoint.intf.Address.IP.String(),
			childEndpoint.config.ExposedPorts, network.config.BridgeName)
		if enable {
			err = l.Enable()
			if err != nil {
				return err
			}
			defer func() {
				if err != nil {
					l.Disable()
				}
			}()
		} else {
			l.Disable()
		}
	}

	if enable {
		endpoint.containerConfig = cc
	}

	return nil
}

func (d *driver) Type() string {
	return networkType
}

func parseEndpointOptions(epOptions map[string]interface{}) (*EndpointConfiguration, error) {
	if epOptions == nil {
		return nil, nil
	}

	ec := &EndpointConfiguration{}

	if opt, ok := epOptions[netlabel.MacAddress]; ok {
		if mac, ok := opt.(net.HardwareAddr); ok {
			ec.MacAddress = mac
		} else {
			return nil, &ErrInvalidEndpointConfig{}
		}
	}

	if opt, ok := epOptions[netlabel.PortMap]; ok {
		if bs, ok := opt.([]types.PortBinding); ok {
			ec.PortBindings = bs
		} else {
			return nil, &ErrInvalidEndpointConfig{}
		}
	}

	if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
		if ports, ok := opt.([]types.TransportPort); ok {
			ec.ExposedPorts = ports
		} else {
			return nil, &ErrInvalidEndpointConfig{}
		}
	}

	return ec, nil
}

func parseContainerOptions(cOptions map[string]interface{}) (*ContainerConfiguration, error) {
	if cOptions == nil {
		return nil, nil
	}
	genericData := cOptions[netlabel.GenericData]
	if genericData == nil {
		return nil, nil
	}
	switch opt := genericData.(type) {
	case options.Generic:
		opaqueConfig, err := options.GenerateFromModel(opt, &ContainerConfiguration{})
		if err != nil {
			return nil, err
		}
		return opaqueConfig.(*ContainerConfiguration), nil
	case *ContainerConfiguration:
		return opt, nil
	default:
		return nil, nil
	}
}

func electMacAddress(epConfig *EndpointConfiguration) net.HardwareAddr {
	if epConfig != nil && epConfig.MacAddress != nil {
		return epConfig.MacAddress
	}
	return netutils.GenerateRandomMAC()
}

// Generates a name to be used for a virtual ethernet
// interface. The name is constructed by 'veth' appended
// by a randomly generated hex value. (example: veth0f60e2c)
func generateIfaceName() (string, error) {
	for i := 0; i < 3; i++ {
		name, err := netutils.GenerateRandomName(vethPrefix, vethLen)
		if err != nil {
			continue
		}
		if _, err := net.InterfaceByName(name); err != nil {
			if strings.Contains(err.Error(), "no such") {
				return name, nil
			}
			return "", err
		}
	}
	return "", &ErrIfaceName{}
}


text:
#class: HarmonyAsync
**Extends**: `Async`
**Members**

* [class: HarmonyAsync](#HarmonyAsync)
  * [new HarmonyAsync()](#new_HarmonyAsync)

##new HarmonyAsync()
HarmonyAsync

**Extends**: `Async`
**Author**: Sergey Kamardin <s.kamardin@tcsbank.ru>


text:
@interface TDPathExpression ()
@property (nonatomic, retain) NSString *head;
@property (nonatomic, retain) NSArray *tail;
@end

@implementation TDPathExpression

+ (instancetype)pathExpressionWithSteps:(NSArray *)steps {
    return [[[self alloc] initWithSteps:steps] autorelease];
}

- (instancetype)initWithSteps:(NSArray *)steps {
    self = [super init];
    if (self) {
        NSUInteger c = [steps count];
        TDAssert(c);
        TDAssert(NSNotFound != c);
//        self.head = [[steps firstObject] stringValue];
        self.head = [steps firstObject];
        TDAssert([_head length]);
        if (c > 1) {
            self.tail = [steps subarrayWithRange:NSMakeRange(1, c-1)];
            TDAssert([_tail count]);
        }
    }
    return self;
}

- (void)dealloc {
    self.head = nil;
    self.tail = nil;
    [super dealloc];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@ %p `%@.%@`>", [self class], self, self.head, [self.tail componentsJoinedByString:@"."]];
}

- (TDExpression *)simplify {
    return self;
}

- (TDValue *)evaluateInContext:(TDTemplateContext *)ctx {
    TDAssert([_head length]);
    id obj = [ctx resolveVariable:_head];

    TDValue *result = nil;

    if (obj) {
        if (_tail) {
            // TODO
//            NSMutableArray *strs = [NSMutableArray arrayWithCapacity:[_tail count]];
//            for (PKToken *tok in _tail) {
//                [strs addObject:tok.stringValue];
//            }
//            obj = [obj valueForKeyPath:[strs componentsJoinedByString:@"."]];
            NSString *path = [_tail componentsJoinedByString:@"."];
            obj = [obj valueForKeyPath:path];
        }

        result = TDValueFromObject(obj);
    }

    return result;
}

- (TDDataType)dataType {
    return TDDataTypeAny;
}

@end


text:
package com.facebook.buck.dalvik.firstorder;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

class FirstOrderMethodVisitor extends MethodVisitor {

  private final FirstOrderVisitorContext mContext;
  private final FirstOrderTypeInfo.Builder mBuilder;

  public FirstOrderMethodVisitor(FirstOrderVisitorContext context) {
    super(Opcodes.ASM4);
    mContext = context;
    mBuilder = context.builder;
  }

  @Override
  public AnnotationVisitor visitAnnotationDefault() {
    return mContext.annotationVisitor;
  }

  @Override
  public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
    //Unused by dexopt: mBuilder.addDependencyDesc(desc);
    return mContext.annotationVisitor;
  }

  @Override
  public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) {
    //Unused by dexopt: mBuilder.addDependencyDesc(desc);
    return mContext.annotationVisitor;
  }

  @Override
  public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
    visitFrameEntries(nLocal, local);
    visitFrameEntries(nStack, stack);
  }

  @Override
  public void visitTypeInsn(int opcode, String type) {
    mBuilder.addDependencyInternalName(type);
  }

  @Override
  public void visitFieldInsn(int opcode, String owner, String name, String desc) {
    mBuilder.addDependencyInternalName(owner);
    mBuilder.addDependencyDesc(desc);
  }

  @Override
  public void visitMethodInsn(int opcode, String owner, String name, String desc) {
    mBuilder.addDependencyInternalName(owner);
    mBuilder.addDependencyDesc(desc);
  }

  @Override
  public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object...bsmArgs) {
    mBuilder.addDependencyDesc(desc);
    mBuilder.addValue(bsm);
    for (Object bsmArg : bsmArgs) {
      mBuilder.addValue(bsmArg);
    }
  }

  @Override
  public void visitLdcInsn(Object cst) {
    mBuilder.addValue(cst);
  }

  @Override
  public void visitMultiANewArrayInsn(String desc, int dims) {
    mBuilder.addDependencyDesc(desc);
  }

  @Override
  public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
    mBuilder.addDependencyInternalName(type);
  }

  @Override
  public void visitLocalVariable(
      String name,
      String desc,
      String signature,
      Label start,
      Label end,
      int index) {
    mBuilder.addDependencyDesc(desc);
  }

  private void visitFrameEntries(int n, Object[] entries) {
    for (int i = 0; i < n; i++) {
      if (entries[i] instanceof String) {
        mBuilder.addDependencyInternalName((String) entries[i]);
      }
    }
  }
}


text:
import {BaseComponent} from "../ReactGlobals";
import V from "../../Packages/V/V";
import BackgroundTimer from "react-native-background-timer";
import {Global, IDProvider, Log} from "../Globals";
import {LL} from "../../LucidLink";
import {Assert} from "../../Packages/VDF/VDF";

export class TimerContext {
	timers = [] as Timer[];
	Reset() {
		for (let timer of this.timers)
			timer.Stop();
		this.timers = [];
	}
}

// methods
// ==========

export function TryCall(func, /*optional:*/ args_) { if (func instanceof Function) func.apply(this, V.CloneArray(arguments).splice(0, 1)); }
export function TryCall_OnX(obj, func, /*optional:*/ args_) { if (func instanceof Function) func.apply(obj, V.CloneArray(arguments).splice(0, 1)); }
g.Extend({TryCall, TryCall_OnX});

//window.requestAnimationFrame = function() {};

//export function WaitXThenRun(waitTime, func): number { return setTimeout(func, waitTime); }
export function WaitXThenRun(waitTime, func): number { return BackgroundTimer.setTimeout(func, waitTime); }
export function WaitXThenRun_BuiltIn(waitTime, func): number { return setTimeout(func, waitTime); }
export function Sleep(ms) {
	var startTime = new Date().getTime();
	while (new Date().getTime() - startTime < ms)
	{}
}

var DoNothingXTimesThenDoY_counters = {};
export function DoNothingXTimesThenDoY(doNothingCount: number, func: Function, key = "default") {
	if (DoNothingXTimesThenDoY_counters[key] == null)
		DoNothingXTimesThenDoY_counters[key] = 0;

	if (DoNothingXTimesThenDoY_counters[key] >= doNothingCount)
		func();
	DoNothingXTimesThenDoY_counters[key]++;
}

// interval is in seconds (can be decimal)
export class Timer {
	constructor(intervalInS: number, func: ()=>void, maxCallCount = -1, asBackground = false) {
	    this.intervalInS = intervalInS;
	    this.func = func;
	    this.maxCallCount = maxCallCount;
		this.asBackground = asBackground;
	}

	intervalInS: number;
	func: ()=>void;
	maxCallCount: number;
	asBackground: boolean;

	SetContext(timerContext: TimerContext | BaseComponent<any, any>) {
		Assert(timerContext, "TimerContext cannot be null.");
		timerContext.timers.push(this);
		return this;
	}

	timerID = -1;
	get IsRunning() { return this.timerID != -1; }

	callCount = 0;
	Start() {
		let wrapperFunc = ()=> {
			this.func();
			this.callCount++;
			if (this.maxCallCount != -1 && this.callCount >= this.maxCallCount)
				this.Stop();
		};
		this.timerID = this.asBackground
			? BackgroundTimer.setInterval(wrapperFunc, this.intervalInS * 1000)
			: setInterval(wrapperFunc, this.intervalInS * 1000);
		return this;
	}
	Stop() {
		if (this.asBackground)
			BackgroundTimer.clearInterval(this.timerID);
		else
			clearInterval(this.timerID);
		this.timerID = -1;
	}
}
export class TimerMS extends Timer {
    constructor(interval_decimal, func, maxCallCount = -1) {
        super(interval_decimal / 1000, func, maxCallCount);
    }
}

export class Sequence {
	static idProvider = new IDProvider();
	constructor(asBackground = true) {
		this.id = Sequence.idProvider.GetID();
		this.asBackground = asBackground;
	}
	id: number;
	asBackground: boolean;

	timerContext: TimerContext;
	SetContext(timerContext: TimerContext) {
		Assert(timerContext, "Timer-context cannot be null.");
		Assert(!this.Active, "Can't set timer-context after starting.");
		this.timerContext = timerContext;
		return this;
	}

	segments = [] as SequenceStep[];
	AddSegment(delayInS: number, func: Function, infoStr?: string) {
		this.segments.push(new SequenceStep(delayInS, func, infoStr));
	}

	nextSegment = null as SequenceStep;
	get Active() { return this.nextSegment != null; }

	Start() {
		Assert(this.segments.length, "Cannot start a sequence with no segments.");
		Log(`Starting sequence ${this.id}`);
		this.nextSegment = this.segments[0];
		this.nextSegment.StartDelay(this, this.asBackground);
	}
	OnCompleteSegment(segment: SequenceStep) {
		Assert(this.Active, "OnCompleteSegment() was called when the sequence was not active.");
		this.nextSegment = this.segments[this.segments.indexOf(segment) + 1];
		Log(`Completed segment ${segment.id} of sequence ${this.id}. Next segment: ${this.nextSegment ? this.nextSegment.id : -1}`);
		if (this.nextSegment) {
			this.nextSegment.StartDelay(this, this.asBackground);
		}
	}
	Stop() {
		Log(`Stopping sequence ${this.id}`);
		if (this.nextSegment)
			this.nextSegment.Stop();
		this.nextSegment = null;
	}
}
class SequenceStep {
	static idProvider = new IDProvider();
	constructor(delayInS: number, func: Function, infoStr?: string) {
		this.id = SequenceStep.idProvider.GetID();
		this.delayInS = delayInS;
		this.func = func;
		this.infoStr = infoStr;
	}
	id: number;
	delayInS = 0;
	func = null as Function;
	infoStr: string;

	timer: Timer;
	StartDelay(sequence: Sequence, asBackground: boolean) {
		Log(`Starting segment ${this.id}${this.infoStr||""}`);
		this.timer = new Timer(this.delayInS, ()=> {
			Log(`Running-and-ending segment ${this.id}`);
			this.func();
			sequence.OnCompleteSegment(this);
		}, 1, asBackground).Start();
		if (sequence.timerContext)
			this.timer.SetContext(sequence.timerContext);
	}
	Stop() {
		Log(`Stopping segment ${this.id} (timer call-count: ${this.timer ? this.timer.callCount : -1})`);
		if (this.timer)
			this.timer.Stop();
	}
}

var funcLastScheduledRunTimes = {};
/** If time-since-last-run is above minInterval, run func right away.
 * Else, schedule next-run to occur as soon as the minInterval is passed. */
export function BufferAction(minInterval: number, func: Function);
/** If time-since-last-run is above minInterval, run func right away.
 * Else, schedule next-run to occur as soon as the minInterval is passed. */
export function BufferAction(key: string, minInterval: number, func: Function);
export function BufferAction(...args) {
	if (args.length == 2) var [minInterval, func] = args, key = null;
	else if (args.length == 3) var [key, minInterval, func] = args;

    var lastScheduledRunTime = funcLastScheduledRunTimes[key] || 0;
    var now = new Date().getTime();
    var timeSinceLast = now - lastScheduledRunTime;
    if (timeSinceLast >= minInterval) { // if we've waited enough since last run, run right now
        func();
        funcLastScheduledRunTimes[key] = now;
    } else {
		let waitingForNextRunAlready = lastScheduledRunTime > now;
		if (!waitingForNextRunAlready) { // else, if we're not already waiting for next-run, schedule next-run
			var nextRunTime = lastScheduledRunTime + minInterval;
			var timeTillNextRun = nextRunTime - now;
			WaitXThenRun(timeTillNextRun, func);
			funcLastScheduledRunTimes[key] = nextRunTime;
		}
	}
}


text:
package vpp1904

import (
	"fmt"
	"net"

	govppapi "git.fd.io/govpp.git/api"
	"github.com/ligato/cn-infra/logging"

	ba_ip "github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp1904/ip"
	ba_punt "github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp1904/punt"
	"github.com/ligato/vpp-agent/plugins/vpp/ifplugin/ifaceidx"
	"github.com/ligato/vpp-agent/plugins/vpp/puntplugin/vppcalls"
)

func init() {
	var msgs []govppapi.Message
	msgs = append(msgs, ba_ip.AllMessages()...)
	msgs = append(msgs, ba_punt.AllMessages()...)

	vppcalls.Versions["vpp1904"] = vppcalls.HandlerVersion{
		Msgs: msgs,
		New: func(channel govppapi.Channel, index ifaceidx.IfaceMetadataIndex, logger logging.Logger) vppcalls.PuntVppAPI {
			return NewPuntVppHandler(channel, index, logger)
		},
	}
}

// PuntVppHandler is accessor for punt-related vppcalls methods.
type PuntVppHandler struct {
	callsChannel govppapi.Channel
	ifIndexes    ifaceidx.IfaceMetadataIndex
	log          logging.Logger
}

// NewPuntVppHandler creates new instance of punt vppcalls handler
func NewPuntVppHandler(
	callsChan govppapi.Channel, ifIndexes ifaceidx.IfaceMetadataIndex, log logging.Logger,
) *PuntVppHandler {
	return &PuntVppHandler{
		callsChannel: callsChan,
		ifIndexes:    ifIndexes,
		log:          log,
	}
}

func ipToAddress(ipstr string) (addr ba_ip.Address, err error) {
	netIP := net.ParseIP(ipstr)
	if netIP == nil {
		return ba_ip.Address{}, fmt.Errorf("invalid IP: %q", ipstr)
	}
	if ip4 := netIP.To4(); ip4 == nil {
		addr.Af = ba_ip.ADDRESS_IP6
		var ip6addr ba_ip.IP6Address
		copy(ip6addr[:], netIP.To16())
		addr.Un.SetIP6(ip6addr)
	} else {
		addr.Af = ba_ip.ADDRESS_IP4
		var ip4addr ba_ip.IP4Address
		copy(ip4addr[:], ip4)
		addr.Un.SetIP4(ip4addr)
	}
	return
}


text:
import React from 'react';
import Drawer from '..';
import { fireEvent, render } from '../../../tests/utils';

describe('Drawer', () => {
  const getDrawer = props => (
    <Drawer visible getContainer={false} {...props}>
      Here is content of Drawer
    </Drawer>
  );

  it('render correctly', () => {
    const { container, asFragment, rerender } = render(getDrawer());
    expect(container.querySelector('.ant-drawer-body')).toBeTruthy();

    rerender(getDrawer({ visible: false }));

    expect(container.querySelector('.ant-drawer-body').textContent).toEqual(
      'Here is content of Drawer',
    );

    expect(asFragment().firstChild).toMatchSnapshot();
  });

  it('mask trigger onClose', () => {
    const onClose = jest.fn();
    const { container } = render(getDrawer({ onClose }));

    fireEvent.click(container.querySelector('.ant-drawer-mask'));
    expect(onClose).toHaveBeenCalled();
  });

  it('close button trigger onClose', () => {
    const onClose = jest.fn();
    const { container } = render(getDrawer({ onClose }));

    fireEvent.click(container.querySelector('.ant-drawer-close'));
    expect(onClose).toHaveBeenCalled();
  });

  it('maskClosable no trigger onClose', () => {
    const onClose = jest.fn();
    const { container } = render(getDrawer({ onClose, maskClosable: false }));

    fireEvent.click(container.querySelector('.ant-drawer-mask'));
    expect(onClose).not.toHaveBeenCalled();
  });

  it('dom should be removed after close when destroyOnClose is true', () => {
    const { container, rerender } = render(getDrawer({ destroyOnClose: true }));

    rerender(getDrawer({ destroyOnClose: true, visible: false }));
    const ev = new TransitionEvent('transitionend', { bubbles: true });
    ev.propertyName = 'transform';
    fireEvent(document.querySelector('.ant-drawer-content-wrapper'), ev);

    expect(container.querySelector('.ant-drawer-wrapper-body')).toBeFalsy();
  });

  it('dom should be existed after close when destroyOnClose is false', () => {
    const { container, rerender } = render(getDrawer());
    expect(container.querySelector('.ant-drawer-wrapper-body')).toBeTruthy();

    rerender(getDrawer({ visible: false }));
    const ev = new TransitionEvent('transitionend', { bubbles: true });
    ev.propertyName = 'transform';
    fireEvent(document.querySelector('.ant-drawer-content-wrapper'), ev);

    expect(container.querySelector('.ant-drawer-wrapper-body')).toBeTruthy();
  });
  it('dom should be existed after close twice when getContainer is false', () => {
    const { container, rerender } = render(getDrawer({ visible: true, getContainer: false }));
    rerender(getDrawer({ visible: false, getContainer: false }));
    const ev = new TransitionEvent('transitionend', { bubbles: true });
    ev.propertyName = 'transform';
    fireEvent(document.querySelector('.ant-drawer-content-wrapper'), ev);

    rerender(getDrawer({ visible: true, getContainer: false }));
    const ev2 = new TransitionEvent('transitionend', { bubbles: true });
    ev2.propertyName = 'transform';
    fireEvent(document.querySelector('.ant-drawer-content-wrapper'), ev2);

    rerender(getDrawer({ visible: false, getContainer: false }));
    const ev3 = new TransitionEvent('transitionend', { bubbles: true });
    ev3.propertyName = 'transform';
    fireEvent(document.querySelector('.ant-drawer-content-wrapper'), ev3);

    expect(container.querySelector('.ant-drawer-wrapper-body')).toBeTruthy();
  });
  it('test afterVisibleChange', async () => {
    const afterVisibleChange = jest.fn();
    const { rerender } = render(getDrawer({ afterVisibleChange, visible: true }));
    rerender(getDrawer({ afterVisibleChange, visible: false }));
    const ev = new TransitionEvent('transitionend', { bubbles: true });
    ev.propertyName = 'transform';
    fireEvent(document.querySelector('.ant-drawer-content-wrapper'), ev);
    expect(afterVisibleChange).toBeCalledTimes(1);
  });
  it('should support children ref', () => {
    const fn = jest.fn();

    const refCallback = ref => {
      expect(typeof ref).toBe('object');
      fn();
    };

    const RefDemo = () => {
      const ref = React.useRef();
      const [visible, setVisible] = React.useState(false);

      React.useEffect(() => {
        if (visible) {
          refCallback(ref.current);
        }
      }, [visible]);

      return (
        <>
           setVisible(true)}>open
          <Drawer visible={visible}>

          </Drawer>
        </>
      );
    };
    const { container } = render(<RefDemo />);
    fireEvent.click(container.querySelector('a'));
    expect(fn).toBeCalled();
  });
});


text:
function setup(varargin)
% setUpPath.m
% by John Swoboda
% swoboj@bu.edu
% This function will set up the path for the ISR toolbox and make the path
% selection perminent if the user so desires.
% Example use
% setUpPath()
% setUpPath(setup_type,save_type)
% setUpPath(setup_type,save_location)
% Inputs
% setup_type - (Optional) This determines whether the user wants to
% perminetly add the changes to the pathdef.m file.  The choices are 'temp'
% or 'permanent'.  The default is temp.
% save_type - (Optional) This is for developers, it will make a test
% directory to house test code.
% save_location - (Optional) This determines the location of the pathdef.m
% file is the user chooses to save the file.
%% Deal with inputs
if nargin ==0
    setup_type = 'temp';
    save_type = 'normal';
    save_location = [];
elseif nargin ==1
    setup_type = varargin{1};
    save_type = 'normal';
    save_location = [];
elseif nargin ==2
    setup_type = varargin{1};
    save_type = varargin{2};
    save_location = [];

elseif nargin==3
    setup_type = varargin{1};
    save_type = varargin{2};
    save_location = varargin{3};
end
%% Make a test folder
if strcmp(save_type,'develop')
    if ~exist('Test','dir')
        mkdir('Test');
        disp('Made directory Test/ for testing');
    end
end

%% Do path set up
% get the current path of this file
tmp = mfilename('fullpath');
[code_path,~,~] = fileparts(tmp);

all_folders = genpath(code_path);

all_paths_cell = regexp(all_folders,pathsep,'split');
% check for hidden folders and get rid of them because they won't be on the
% path and they clutter everything
path_log = true(size(all_paths_cell));
first_entry = true;
for k = 1:length(all_paths_cell)

    if isempty(strfind(all_paths_cell{k},[filesep,'.']))
        if first_entry
            big_path_string = all_paths_cell{k};
            first_entry = false;
        else
            big_path_string = [big_path_string,pathsep,all_paths_cell{k}];
        end
    else
        path_log(k) = false;
    end
    % Keep the test directory out of the path
    if ~isempty(strfind(all_paths_cell{k},[filesep,'Test']))
        path_log(k) = false;
    end
    if ~isempty(strfind(all_paths_cell{k},[filesep,'logo']))
        path_log(k) = false;
    end
    % Some times this adds empty strings to the path
    if isempty(all_paths_cell{k})
        path_log(k) = false;
    end
end

all_paths_cell = all_paths_cell(path_log);
addpath(all_paths_cell{:},'-end');
disp('Folders added to the path:')
disp(all_paths_cell')
%% Make path perminent or not
if strcmpi(setup_type,'permanent')
    resp = input('Are you sure you want to perminetly modify your path, y/n: ', 's');
    if strcmpi(resp, 'y')&&exist(save_location,'dir')
        status = savepath(fullfile(save_location,'pathdef.m'));
        if ~status
            disp(['New pathdef.m file saved to directory: ',save_location]);
        else
            disp('pathdef.m was not saved, this path will only be temporary, check folder permissions');
        end
    elseif strcmpi(resp,'y')&& isempty(save_location)
        status = savepath;
        if ~status
            disp('New pathdef.m file saved to directory to root directory');
        else
            disp('pathdef.m was not saved, this path will only be temporary, check folder permissions');
        end
    elseif strcmpi(resp, 'y')&&~exist(save_location,'dir')
        disp('Folder does not exist, run this function again with a folder that exists');
    end
end