text:
package events

import (
	"errors"
	"sync"

	"code.cloudfoundry.org/bbs/models"
	"code.cloudfoundry.org/lager"
)

const MAX_PENDING_SUBSCRIBER_EVENTS = 1024

var ErrReadFromClosedSource = errors.New("read from closed source")
var ErrSendToClosedSource = errors.New("send to closed source")
var ErrSourceAlreadyClosed = errors.New("source already closed")
var ErrSlowConsumer = errors.New("slow consumer")

var ErrSubscribedToClosedHub = errors.New("subscribed to closed hub")
var ErrHubAlreadyClosed = errors.New("hub already closed")

//go:generate counterfeiter -o eventfakes/fake_hub.go . Hub
type Hub interface {
	Subscribe() (EventSource, error)
	Emit(models.Event)
	Close() error

	RegisterCallback(func(count int))
	UnregisterCallback()
}

type hub struct {
	subscribers map[*hubSource]struct{}
	closed      bool
	lock        sync.Mutex
	logger      lager.Logger

	cb func(count int)
}

func NewHub(logger lager.Logger) Hub {
	return &hub{
		subscribers: make(map[*hubSource]struct{}),
		logger:      logger,
	}
}

func (hub *hub) RegisterCallback(cb func(int)) {
	hub.lock.Lock()
	hub.cb = cb
	size := len(hub.subscribers)
	hub.lock.Unlock()
	if cb != nil {
		cb(size)
	}
}

func (hub *hub) UnregisterCallback() {
	hub.lock.Lock()
	hub.cb = nil
	hub.lock.Unlock()
}

func (hub *hub) Subscribe() (EventSource, error) {
	hub.lock.Lock()

	if hub.closed {
		hub.lock.Unlock()

		return nil, ErrSubscribedToClosedHub
	}

	sub := newSource(MAX_PENDING_SUBSCRIBER_EVENTS, hub.subscriberClosed)
	hub.subscribers[sub] = struct{}{}
	cb := hub.cb
	size := len(hub.subscribers)
	hub.lock.Unlock()

	if cb != nil {
		cb(size)
	}
	return sub, nil
}

func (hub *hub) Emit(event models.Event) {
	hub.lock.Lock()
	size := len(hub.subscribers)

	for sub, _ := range hub.subscribers {
		err := sub.send(event)
		if err != nil {
			hub.logger.Error("got-error-sending-event", err)
			delete(hub.subscribers, sub)
		}
	}

	var cb func(int)
	if len(hub.subscribers) != size {
		cb = hub.cb
		size = len(hub.subscribers)
	}
	hub.lock.Unlock()

	if cb != nil {
		cb(size)
	}
}

func (hub *hub) Close() error {
	hub.lock.Lock()
	defer hub.lock.Unlock()

	if hub.closed {
		return ErrHubAlreadyClosed
	}

	hub.closeSubscribers()
	hub.closed = true
	if hub.cb != nil {
		hub.cb(0)
	}
	return nil
}

func (hub *hub) closeSubscribers() {
	for sub, _ := range hub.subscribers {
		_ = sub.Close()
	}
	hub.subscribers = nil
}

func (hub *hub) subscriberClosed(source *hubSource) {
	hub.lock.Lock()
	delete(hub.subscribers, source)
	cb := hub.cb
	count := len(hub.subscribers)
	hub.lock.Unlock()

	if cb != nil {
		cb(count)
	}
}

type hubSource struct {
	events        chan models.Event
	closeCallback func(*hubSource)
	closed        bool
	lock          sync.Mutex
}

func newSource(maxPendingEvents int, closeCallback func(*hubSource)) *hubSource {
	return &hubSource{
		events:        make(chan models.Event, maxPendingEvents),
		closeCallback: closeCallback,
	}
}

func (source *hubSource) Next() (models.Event, error) {
	event, ok := <-source.events
	if !ok {
		return nil, ErrReadFromClosedSource
	}
	return event, nil
}

func (source *hubSource) Close() error {
	source.lock.Lock()
	defer source.lock.Unlock()

	if source.closed {
		return ErrSourceAlreadyClosed
	}
	close(source.events)
	source.closed = true
	go source.closeCallback(source)
	return nil
}

func (source *hubSource) send(event models.Event) error {
	source.lock.Lock()

	if source.closed {
		source.lock.Unlock()
		return ErrSendToClosedSource
	}

	select {
	case source.events <- event:
		source.lock.Unlock()
		return nil

	default:
		source.lock.Unlock()
		err := source.Close()
		if err != nil {
			return err
		}

		return ErrSlowConsumer
	}
}

redpajama_set_name: RedPajamaGithub


text:
const fmiRequest = require('../lib/fmiRequest');

const queryId = 'fmi::forecast::hirlam::surface::point::simple';
exports.queryId = queryId;
exports.params = ['place', 'latlon'];

exports.run = function runQuery(place) {
  return fmiRequest.get({ queryId, params: { place } })
    .then(results => Promise.resolve(results))
    .catch(err => console.log(err));
};

/**
 * Fetches forecasts by LatLng, eg. 61.23,23.31
 */
exports.runLatLon = function runQuery(latlon) {
  return fmiRequest.get({ queryId, params: { latlon } })
    .then(results => Promise.resolve(results))
    .catch(err => console.log(err));
};


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var Compiler = require("./Compiler");
var MultiCompiler = require("./MultiCompiler");
var NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
var WebpackOptionsApply = require("./WebpackOptionsApply");
var WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter");

function webpack(options, callback) {
	var compiler;
	if(Array.isArray(options)) {
		compiler = new MultiCompiler(options.map(function(options) {
			return webpack(options);
		}));
	} else if(typeof options === "object") {
		new WebpackOptionsDefaulter().process(options);

		compiler = new Compiler();
		compiler.options = options;
		compiler.options = new WebpackOptionsApply().process(options, compiler);
		new NodeEnvironmentPlugin().apply(compiler);
		compiler.applyPlugins("environment");
		compiler.applyPlugins("after-environment");
	} else {
		throw new Error("Invalid argument: options");
	}
	if(callback) {
		if(typeof callback !== "function") throw new Error("Invalid argument: callback");
		if(options.watch === true || (Array.isArray(options) &&
				options.some(function(o) {
					return o.watch;
				}))) {
			var watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {};
			// TODO remove this in next major version
			var watchDelay = (!Array.isArray(options) ? options : options[0]).watchDelay;
			if(watchDelay) {
				console.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
				watchOptions.aggregateTimeout = watchDelay;
			}
			return compiler.watch(watchOptions, callback);
		}
		compiler.run(callback);
	}
	return compiler;
}
exports = module.exports = webpack;

webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
webpack.WebpackOptionsApply = WebpackOptionsApply;
webpack.Compiler = Compiler;
webpack.MultiCompiler = MultiCompiler;
webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin;

function exportPlugins(exports, path, plugins) {
	plugins.forEach(function(name) {
		Object.defineProperty(exports, name, {
			configurable: false,
			enumerable: true,
			get: function() {
				return require(path + "/" + name);
			}
		});
	});
}

exportPlugins(exports, ".", [
	"DefinePlugin",
	"NormalModuleReplacementPlugin",
	"ContextReplacementPlugin",
	"IgnorePlugin",
	"WatchIgnorePlugin",
	"BannerPlugin",
	"PrefetchPlugin",
	"AutomaticPrefetchPlugin",
	"ProvidePlugin",
	"HotModuleReplacementPlugin",
	"ResolverPlugin",
	"SourceMapDevToolPlugin",
	"EvalSourceMapDevToolPlugin",
	"EvalDevToolModulePlugin",
	"CachePlugin",
	"ExtendedAPIPlugin",
	"ExternalsPlugin",
	"JsonpTemplatePlugin",
	"LibraryTemplatePlugin",
	"LoaderTargetPlugin",
	"MemoryOutputFileSystem",
	"ProgressPlugin",
	"SetVarMainTemplatePlugin",
	"UmdMainTemplatePlugin",
	"NoErrorsPlugin",
	"NewWatchingPlugin",
	"OldWatchingPlugin",
	"EnvironmentPlugin",
	"DllPlugin",
	"DllReferencePlugin",
	"NamedModulesPlugin"
]);
exportPlugins(exports.optimize = {}, "./optimize", [
	"AggressiveMergingPlugin",
	"CommonsChunkPlugin",
	"DedupePlugin",
	"LimitChunkCountPlugin",
	"MinChunkSizePlugin",
	"OccurenceOrderPlugin",
	"OccurrenceOrderPlugin",
	"UglifyJsPlugin"
]);
exportPlugins(exports.dependencies = {}, "./dependencies", [
	"LabeledModulesPlugin"
]);


text:
package silky

import java.util.UUID.randomUUID
import scala.util.DynamicVariable

object MessageFlowId {
  private val messageFlowIds = new DynamicVariable[Option[MessageFlowId]](init = None)

  def set(messageFlowId: Option[MessageFlowId]): Option[MessageFlowId] = {
    messageFlowIds value_= messageFlowId
    messageFlowId
  }

  def get: Option[MessageFlowId] = messageFlowIds.value

  def makeOneUp: Option[MessageFlowId] = set(Some(MessageFlowId(randomUUID.toString)))

  def clear(): Unit = set(messageFlowId = None)
}

case class MessageFlowId(value: String) {
  override def toString: String = value
}


text:
'use strict';

var chai = require('chai');

var verquire = require('../../utils/verquire');

var Excel = verquire('excel');

var expect = chai.expect;

// this file to contain integration tests created from github issues
var TEST_XLSX_FILE_NAME = './spec/out/wb.test.xlsx';

describe('github issues', function() {
  describe('issue 219 - 1904 dates not supported', function() {
    it('Reading 1904.xlsx', function() {
      var wb = new Excel.Workbook();
      return wb.xlsx.readFile('./spec/integration/data/1904.xlsx')
        .then(function() {
          expect(wb.properties.date1904).to.equal(true);

          var ws = wb.getWorksheet('Sheet1');
          expect(ws.getCell('B4').value.toISOString()).to.equal('1904-01-01T00:00:00.000Z');
        });
    });
    it('Writing and Reading', function() {
      var wb = new Excel.Workbook();
      wb.properties.date1904 = true;
      var ws = wb.addWorksheet('Sheet1');
      ws.getCell('B4').value = new Date('1904-01-01T00:00:00.000Z');
      return wb.xlsx.writeFile(TEST_XLSX_FILE_NAME)
        .then(function() {
          var wb2 = new Excel.Workbook();
          return wb2.xlsx.readFile(TEST_XLSX_FILE_NAME);
        })
        .then(function(wb2) {
          expect(wb2.properties.date1904).to.equal(true);

          var ws2 = wb2.getWorksheet('Sheet1');
          expect(ws2.getCell('B4').value.toISOString()).to.equal('1904-01-01T00:00:00.000Z');
        });
    });
  });
});


text:
using namespace std;

// ========== Local Headers ========================================================================

// read next line of csv from stream, parsed into cells, note whether cells quoted or not; blank
// line terminates reading; return true if more to read, false if done reading
bool nextCsvLine(std::istream& is,
                 std::vector<std::string>& line,
                 std::vector<bool>& lineQuoted);

// ========== Functions ============================================================================

// read csv data from stream; return cells, column names, and whether cells are quoted
void readCsv(std::istream& is,
             bool readHeader,
             std::vector< std::vector<std::string> >& cells,
             std::vector< std::vector<bool> >& quoted,
             std::vector<std::string>& colNames)
{
    cells.clear();
    quoted.clear();
    colNames.clear();

    vector<string> line;
    vector<bool> lineQuoted;

    if (readHeader) {
        nextCsvLine(is, colNames, lineQuoted);
    }

    while (nextCsvLine(is, line, lineQuoted)) {
        cells.push_back(line);
        quoted.push_back(lineQuoted);
    }
}

// -------------------------------------------------------------------------------------------------

// write csv data to stream
void writeCsv(std::ostream& os,
              bool writeHeader,
              const std::vector< std::vector<std::string> >& cells,
              const std::vector< std::vector<bool> >& quoted,
              const std::vector<std::string>& colNames)
{
    size_t numRows = cells.size();
    size_t numCols = cells[0].size();

    if (writeHeader) {
        for (size_t col = 0; col < colNames.size(); col++) {
            if (col > 0) {
                os << ",";
            }

            // quote column names in header
            os << '"';

            for (size_t k = 0; k < colNames[col].length(); k++) {
                if (colNames[col][k] == '"') {
                    // quotes within cell are output as double quote ""
                    os << '"' << '"';

                } else {
                    os << colNames[col][k];
                }
            }

            os << '"';
        }

        os << endl;
    }

    for (size_t row = 0; row < numRows; row++) {
        for (size_t col = 0; col < numCols; col++) {
            if (col > 0) {
                os << ",";
            }

            bool needQuotes = quoted[row][col];

            for (size_t k = 0; k < cells[row][col].length() && !needQuotes; k++) {
                char c = cells[row][col][k];
                if ( ((c >= '0') && (c <= '9')) || c == '.') {
                    // no quote needed

                } else {
                    // quote anything that isn't a number or period
                    needQuotes = true;
                }
            }

            if (needQuotes) os << '"';

            for (size_t k = 0; k < cells[row][col].length(); k++) {
                if (cells[row][col][k] == '"') {
                    // quotes within cell are output as double quote ""
                    os << '"' << '"';

                } else {
                    os << cells[row][col][k];
                }
            }

            if (needQuotes) os << '"';
        }

        os << endl;
    }
}

// -------------------------------------------------------------------------------------------------

// write data and header row to csv file
void writeCsvPath(const std::string& path,
                  const std::vector< std::vector<std::string> >& cells,
                  const std::vector< std::vector<bool> >& quoted,
                  const std::vector<std::string>& colNames)
{
    ofstream ofs(path.c_str());

    RUNTIME_ERROR_IF(!ofs.good(), badPathErrorMessage(path));

    bool writeHeader = true;

    writeCsv(ofs, writeHeader, cells, quoted, colNames);

    ofs.close();

}

// write data to csv file
void writeCsvPath(const std::string& path,
                  const std::vector< std::vector<std::string> >& cells,
                  const std::vector< std::vector<bool> >& quoted)
{
    fstream ofs(path.c_str());

    RUNTIME_ERROR_IF(!ofs.good(), badPathErrorMessage(path));

    bool writeHeader = false;
    std::vector<std::string> colNames;  // ignored

    writeCsv(ofs, writeHeader, cells, quoted, colNames);

    ofs.close();

}

// -------------------------------------------------------------------------------------------------

// read csv file with header row; return cells, column names, and whether cells are quoted
void readCsvPath(const std::string& path,
                 std::vector< std::vector<std::string> >& cells,
                 std::vector< std::vector<bool> >& quoted,
                 std::vector<std::string>& colNames)
{
    ifstream ifs(path.c_str());

    RUNTIME_ERROR_IF(!ifs.good(), badPathErrorMessage(path));

    bool readHeader = true;

    readCsv(ifs, readHeader, cells, quoted, colNames) ;

    ifs.close();
}

// read csv file without header row; return cells, and whether cells are quoted
void readCsvPath(const std::string& path,
                 std::vector< std::vector<std::string> >& cells,
                 std::vector< std::vector<bool> >& quoted)
{
    ifstream ifs(path.c_str());

    RUNTIME_ERROR_IF(!ifs.good(), badPathErrorMessage(path));

    bool readHeader = false;
    std::vector<std::string> colNames;  // ignored

    readCsv(ifs, readHeader, cells, quoted, colNames) ;

    ifs.close();
}

// -------------------------------------------------------------------------------------------------

// read csv string with header row; return cells, column names, and whether cells are quoted
void readCsvString(const std::string& csvString,
                   std::vector< std::vector<std::string> >& cells,
                   std::vector< std::vector<bool> >& quoted,
                   std::vector<std::string>& colNames)
{
    istringstream iss(csvString);

    bool readHeader = true;

    readCsv(iss, readHeader, cells, quoted, colNames) ;
}

// read csv file without header row; return cells, and whether cells are quoted
void readCsvString(const std::string& csvString,
                   std::vector< std::vector<std::string> >& cells,
                   std::vector< std::vector<bool> >& quoted)
{
    istringstream iss(csvString);

    bool readHeader = false;
    std::vector<std::string> colNames;  // ignored

    readCsv(iss, readHeader, cells, quoted, colNames) ;
}

// -------------------------------------------------------------------------------------------------

// for debugging or logging; print cells and column names to CERR
void printCells(const std::vector< std::vector<std::string> >& cells,
                const std::vector< std::vector<bool> >& quoted,
                const std::vector<std::string>& colNames)
{
    size_t numRows = cells.size();

    if (colNames.size() > 0) {
        for (size_t col = 0; col < colNames.size(); col++) {
            if (col > 0) CERR << '\t';

            CERR << colNames[col];
        }

        CERR << endl;

        for (size_t col = 0; col < colNames.size(); col++) {
            if (col > 0) CERR << '\t';

            CERR << "-";
        }

        CERR << endl;
    }

    for (size_t row = 0; row < numRows; row++) {
        for (size_t col = 0; col < cells[row].size(); col++) {
            if (col > 0) CERR << '\t';

            if (quoted[row][col]) CERR << '"';

            CERR << cells[row][col];

            if (quoted[row][col]) CERR << '"';
        }

        CERR << endl;
    }
}

// for debugging or logging; print cells to CERR
void printCells(const std::vector< std::vector<std::string> >& cells,
                const std::vector< std::vector<bool> >& quoted)
{
    vector<string> colNames;

    printCells(cells, quoted, colNames);
}

// -------------------------------------------------------------------------------------------------

// check number of cells in each row; if lengths are all the same, return true, else false
bool uniformRowLengths(const std::vector< std::vector<std::string> >& cells)
{
    bool result = true;

    size_t numCols = 0;

    for (size_t row = 0; row < cells.size() && result; row++) {
        if (row == 0) {
            numCols = cells[row].size();

        } else if (numCols != cells[row].size()) {
            result = false;
        }
    }

    return result;
}

// check number of cells in each row; if lengths are all the same as number of column names, return
// true, else false
bool uniformRowLengths(const std::vector< std::vector<std::string> >& cells,
                       const std::vector<std::string>& colNames)
{
    bool result = true;

    size_t numCols = colNames.size();

    for (size_t row = 0; row < cells.size() && result; row++) {
        if (numCols != cells[row].size()) {
            result = false;
        }
    }

    return result;
}

// ========== Local Functions ======================================================================

// read next line of csv from stream, parsed into cells, note whether cells quoted or not; blank
// line terminates reading; return true if more to read, false if done reading
bool nextCsvLine(std::istream& is,
                 std::vector<std::string>& line,
                 std::vector<bool>& lineQuoted)
{
    line.clear();
    lineQuoted.clear();

    string str;
    getline(is, str);

    size_t strLength = str.length();

    // in case line ends with CRLF, exclude CR appearing at end of line
    if (strLength > 0 && str[strLength - 1] == '\r') {
        strLength--;
    }

    bool success = strLength > 0;

    size_t startIndex = 0;  // beginning of current cell

    // loop for each cell in line
    while (success && startIndex < strLength) {
        // skip leading spaces and tabs
        while (str[startIndex] == ' ' || str[startIndex] == '\t') {
            startIndex++;
        }

        // continue if anything left in line
        if (startIndex < strLength) {
            bool quotedCell = false;
            if (str[startIndex] == '"') {
                quotedCell = true;
                startIndex++;
            }

            size_t endIndex = startIndex;   // advance endCell until past end of current cell
            bool done = false;  // true when done with current cell

            if (quotedCell) {
                string cell;

                while (!done) {
                    if (endIndex == strLength) {
                        // no closed quote before end of line
                        cell.append(str.substr(startIndex, endIndex - startIndex));
                        done = true;

                    } else if (str[endIndex] == '"') {
                        // found quote; handle special cases
                        if (endIndex + 1 == strLength) {
                            // end of line follows closing quote
                            cell.append(str.substr(startIndex, endIndex - startIndex));
                            done = true;

                        } else if (str[endIndex + 1] == '"') {
                            // pair of quotes: converts to a single quote
                            endIndex++;
                            cell.append(str.substr(startIndex, endIndex - startIndex));
                            endIndex++;
                            startIndex = endIndex;

                        } else if (str[endIndex + 1] == ',') {
                            // comma follows closing quote
                            cell.append(str.substr(startIndex, endIndex - startIndex));
                            endIndex++;
                            done = true;

                        } else {
                            // closing quote; cell continues
                            cell.append(str.substr(startIndex, endIndex - startIndex));
                            endIndex++;
                            startIndex = endIndex;
                        }

                    } else {
                        // not an embedded quote; keep adding characters
                        endIndex++;
                    }
                }

                line.push_back(cell);
                lineQuoted.push_back(true);

            } else {
                while (!done) {
                    if (endIndex == strLength) {
                        // cell terminates at end of line
                        done = true;

                    } else if (str[endIndex] == ',') {
                        // cell terminates at comma
                        done = true;

                    } else {
                        endIndex++;
                    }

                }

                string cell = str.substr(startIndex, endIndex - startIndex);
                line.push_back(cell);
                lineQuoted.push_back(false);
            }

            // skip over comma; continue with next cell
            startIndex = endIndex + 1;
        }
    }

    return success;
}

// ========== Tests ================================================================================

// component tests
void ctest_csv(int& totalPassed, int& totalFailed, bool verbose)
{
    int passed = 0;
    int failed = 0;

    // ~~~~~~~~~~~~~~~~~~~~~~
    // readCsv

    // ~~~~~~~~~~~~~~~~~~~~~~
    // writeCsv

    // ~~~~~~~~~~~~~~~~~~~~~~
    // readCsvPath
    // readCsvPath

    // ~~~~~~~~~~~~~~~~~~~~~~
    // readCsvString
    // readCsvString

    // ~~~~~~~~~~~~~~~~~~~~~~
    // printCells
    // printCells

    // ~~~~~~~~~~~~~~~~~~~~~~
    // writeCsvPath
    // writeCsvPath

    // ~~~~~~~~~~~~~~~~~~~~~~
    // uniformRowLengths
    // uniformRowLengths

    vector< vector<string> > cells;
    vector< vector<bool> > quoted;
    vector<string> colNames;

    readCsvString("C1, \"C\"\"2\", C3\n 1, \"A\", 3\n 4, 5, 6", cells, quoted, colNames);

    if (uniformRowLengths(cells, colNames)) passed++; else failed++;;

    cells.push_back(vector<string>(1, "X"));

    if (!uniformRowLengths(cells, colNames)) passed++; else failed++;;

    readCsvString("1, B, 3\n 4, \"C\"\"\", 6", cells, quoted);

    if (uniformRowLengths(cells)) passed++; else failed++;;

    cells.push_back(vector<string>(1, "X"));

    if (!uniformRowLengths(cells)) passed++; else failed++;;

    // ~~~~~~~~~~~~~~~~~~~~~~
    // nextCsvLine

    vector<string> line;
    vector<bool> lineQuoted;

    istringstream iss1(" \t1,2,\"A\",\"BC\"\"D\",\"E\"");
    nextCsvLine(iss1, line, lineQuoted);
    if (line[0] == "1" && !lineQuoted[0] &&
        line[1] == "2" && !lineQuoted[1] &&
        line[2] == "A" && lineQuoted[2] &&
        line[3] == "BC\"D" && lineQuoted[3] &&
        line[4] == "E" && lineQuoted[4]) {
        passed++;
    } else {
        failed++;
    }

    istringstream iss2("\"F");
    nextCsvLine(iss2, line, lineQuoted);
    if (line[0] == "F" && lineQuoted[0]) {
        passed++;
    } else {
        failed++;
    }

    istringstream iss3("3");
    nextCsvLine(iss3, line, lineQuoted);
    if (line[0] == "3" && !lineQuoted[0]) {
        passed++;
    } else {
        failed++;
    }

    istringstream iss4("\"G\"H");
    nextCsvLine(iss4, line, lineQuoted);
    if (line[0] == "GH" && lineQuoted[0]) {
        passed++;
    } else {
        failed++;
    }

    // ~~~~~~~~~~~~~~~~~~~~~~

    if (verbose) {
        CERR << "csv.cpp" << "\t\t" << passed << " passed, " << failed << " failed" << endl;
    }

    totalPassed += passed;
    totalFailed += failed;
}

// code coverage
void cover_csv(bool verbose)
{
    // ~~~~~~~~~~~~~~~~~~~~~~
    // readCsv
    // readCsvPath
    // readCsvPath
    // printCells
    // printCells

    stringToFile("C1, C2, C3\n 1, \"2\", 3\n 4, 5, 6", "foo.csv");

    vector< vector<string> > cells;
    vector< vector<bool> > quoted;
    vector<string> colNames;

    readCsvPath("foo.csv", cells, quoted, colNames);
    if (verbose) {
        printCells(cells, quoted, colNames);
    }

    stringToFile("1, \"2\", 3\n 4, 5, 6", "foo.csv");

    readCsvPath("foo.csv", cells, quoted);
    if (verbose) {
        printCells(cells, quoted);
    }

    remove("foo.csv");

    // ~~~~~~~~~~~~~~~~~~~~~~
    // readCsvString
    // readCsvString

    readCsvString("C1, C2, C3\n 1, \"2\", 3\n 4, 5, 6", cells, quoted, colNames);
    readCsvString("1, \"2\", 3\n 4, 5, 6", cells, quoted);

    // ~~~~~~~~~~~~~~~~~~~~~~
    // writeCsv
    // writeCsvPath
    // writeCsvPath
    // uniformRowLengths
    // uniformRowLengths

    readCsvString("C1, \"C\"\"2\", C3\n 1, \"A\", 3\n 4, 5, 6", cells, quoted, colNames);
    writeCsvPath("foo.csv", cells, quoted, colNames);
    uniformRowLengths(cells, colNames);

    cells.push_back(vector<string>(1, "X"));
    uniformRowLengths(cells, colNames);

    readCsvString("1, B, 3\n 4, \"C\"\"\", 6", cells, quoted);
    writeCsvPath("foo.csv", cells, quoted);
    uniformRowLengths(cells);

    cells.push_back(vector<string>(1, "X"));
    uniformRowLengths(cells);

    remove("foo.csv");

    // ~~~~~~~~~~~~~~~~~~~~~~
    // nextCsvLine

    vector<string> line;
    vector<bool> lineQuoted;

    istringstream iss1(" \t1,2,\"A\",\"BC\"\"D\",\"E\"");
    nextCsvLine(iss1, line, lineQuoted);
    if (verbose) {
        for (size_t k = 0; k < line.size(); k++) {
            CERR << k << "]\t" << (lineQuoted.at(k) ? "T" : "F") << "\t" << line.at(k) << endl;
        }
    }

    istringstream iss2("\"F");
    nextCsvLine(iss2, line, lineQuoted);
    if (verbose) {
        for (size_t k = 0; k < line.size(); k++) {
            CERR << k << "]\t" << (lineQuoted.at(k) ? "T" : "F") << "\t" << line.at(k) << endl;
        }
    }

    istringstream iss3("3");
    nextCsvLine(iss3, line, lineQuoted);
    if (verbose) {
        for (size_t k = 0; k < line.size(); k++) {
            CERR << k << "]\t" << (lineQuoted.at(k) ? "T" : "F") << "\t" << line.at(k) << endl;
        }
    }

    istringstream iss4("\"G\"H");
    nextCsvLine(iss4, line, lineQuoted);
    if (verbose) {
        for (size_t k = 0; k < line.size(); k++) {
            CERR << k << "]\t" << (lineQuoted.at(k) ? "T" : "F") << "\t" << line.at(k) << endl;
        }
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Econ. Taxon. Bot. 7(1): 32 (1985)

#### Original name
Cercospora cassiatorae R.C. Rajak

### Remarks
null


text:
from .model import Model
from .parameterized import Parameterized
from .param import Param
from .core.observable_array import ObsAr
from paramz import transformations as constraints
from . import caching, optimization
from . import examples

def _unpickle(file_or_path, pickle, strcl, p3kw):
    if isinstance(file_or_path, strcl):
        with open(file_or_path, 'rb') as f:
            m = pickle.load(f, **p3kw)
    else:
        m = pickle.load(file_or_path, **p3kw)
    return m

def load(file_or_path):
    """
    Load a previously pickled model, using `m.pickle('path/to/file.pickle)'`

    :param file_name: path/to/file.pickle
    """
    from pickle import UnpicklingError
    try:
        import cPickle as pickle
        strcl = basestring
        p3kw = {}
        return _unpickle(file_or_path, pickle, strcl, p3kw)
    except ImportError: #python3
        import pickle
        strcl = str
        p3kw = dict(encoding='latin1')
        return _unpickle(file_or_path, pickle, strcl, p3kw)
    except UnpicklingError: # pragma: no coverage
        import pickle
        return _unpickle(file_or_path, pickle, strcl, p3kw)


text:
For the Box exercise check out the chapter [Using Box to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html).

For the Arc exercise check out the chapter [Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html) of the Rust Book.

For the Iterator exercise check out the chapters [Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) of the Rust Book and the [Iterator documentation](https://doc.rust-lang.org/stable/std/iter/).
Do not adjust your monitors-- iterators1.rs is indeed missing. Iterators is a challenging topic, so we're leaving space for a simpler exercise!


text:
package io.vertigo.orchestra.plugins.services.execution.db;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

import io.vertigo.app.Home;
import io.vertigo.commons.daemon.DaemonManager;
import io.vertigo.core.component.di.injector.DIInjector;
import io.vertigo.dynamo.domain.model.DtList;
import io.vertigo.dynamo.transaction.VTransactionManager;
import io.vertigo.dynamo.transaction.VTransactionWritable;
import io.vertigo.lang.Activeable;
import io.vertigo.lang.Assertion;
import io.vertigo.orchestra.dao.definition.OActivityDAO;
import io.vertigo.orchestra.dao.execution.ExecutionPAO;
import io.vertigo.orchestra.dao.execution.OActivityExecutionDAO;
import io.vertigo.orchestra.dao.execution.OActivityLogDAO;
import io.vertigo.orchestra.dao.execution.OActivityWorkspaceDAO;
import io.vertigo.orchestra.dao.execution.OProcessExecutionDAO;
import io.vertigo.orchestra.definitions.ProcessDefinition;
import io.vertigo.orchestra.definitions.ProcessType;
import io.vertigo.orchestra.domain.definition.OActivity;
import io.vertigo.orchestra.domain.execution.OActivityExecution;
import io.vertigo.orchestra.domain.execution.OActivityLog;
import io.vertigo.orchestra.domain.execution.OActivityWorkspace;
import io.vertigo.orchestra.domain.execution.OProcessExecution;
import io.vertigo.orchestra.impl.node.NodeManager;
import io.vertigo.orchestra.impl.services.execution.AbstractActivityEngine;
import io.vertigo.orchestra.impl.services.execution.ActivityLogger;
import io.vertigo.orchestra.impl.services.execution.ProcessExecutorPlugin;
import io.vertigo.orchestra.plugins.services.MapCodec;
import io.vertigo.orchestra.services.execution.ActivityEngine;
import io.vertigo.orchestra.services.execution.ActivityExecutionWorkspace;
import io.vertigo.orchestra.services.execution.ExecutionState;
import io.vertigo.util.ClassUtil;

/**
 * Executeur des processus orchestra sous la forme d'une séquence linéaire d'activités.
 *
 * @author mlaroche.
 * @version $Id$
 */
public final class DbProcessExecutorPlugin implements ProcessExecutorPlugin, Activeable {

	private static final Logger LOGGER = Logger.getLogger(DbProcessExecutorPlugin.class);

	@Inject
	private DaemonManager daemonManager;
	@Inject
	private OProcessExecutionDAO processExecutionDAO;
	@Inject
	private OActivityExecutionDAO activityExecutionDAO;
	@Inject
	private OActivityWorkspaceDAO activityWorkspaceDAO;
	@Inject
	private ExecutionPAO executionPAO;
	@Inject
	private OActivityLogDAO activityLogDAO;
	@Inject
	private OActivityDAO activityDAO;

	private final int workersCount;
	private final Long nodId;
	private final ExecutorService workers;
	private final int executionPeriodSeconds;

	private final NodeManager nodeManager;
	private final VTransactionManager transactionManager;

	private final MapCodec mapCodec = new MapCodec();

	/**
	 * Constructeur.
	 * @param nodeManager le gestionnaire de noeud
	 * @param transactionManager le gestionnaire de transaction
	 * @param nodeName le nom du noeud en cours
	 * @param workersCount le nombre de worker du noeud
	 * @param executionPeriodSeconds le timer du long-polling
	 */
	@Inject
	public DbProcessExecutorPlugin(
			final NodeManager nodeManager,
			final VTransactionManager transactionManager,
			@Named("nodeName") final String nodeName,
			@Named("workersCount") final int workersCount,
			@Named("executionPeriodSeconds") final int executionPeriodSeconds) {
		Assertion.checkNotNull(nodeManager);
		Assertion.checkNotNull(transactionManager);
		Assertion.checkNotNull(nodeName);
		// ---
		Assertion.checkState(workersCount >= 1, "We need at least 1 worker");
		// ---
		this.nodeManager = nodeManager;
		this.transactionManager = transactionManager;
		// We register the node
		nodId = nodeManager.registerNode(nodeName);
		// ---
		Assertion.checkNotNull(nodId);
		// ---
		this.workersCount = workersCount;
		this.executionPeriodSeconds = executionPeriodSeconds;
		workers = Executors.newFixedThreadPool(workersCount);
	}

	/** {@inheritDoc} */
	@Override
	public void start() {
		handleDeadNodeProcesses();
		daemonManager.registerDaemon("O_DB_PROCESS_EXECUTOR_DAEMON", () -> () -> {
			try {
				executeToDo();
				nodeManager.updateHeartbeat(nodId);
				handleDeadNodeProcesses();
			} catch (final Exception e) {
				// We log the error and we continue the timer
				LOGGER.error("Exception launching activities to executes", e);
			}

		}, executionPeriodSeconds);

	}

	/** {@inheritDoc} */
	@Override
	public void stop() {
		workers.shutdownNow();
	}

	/** {@inheritDoc} */
	@Override
	public ProcessType getHandledProcessType() {
		return ProcessType.SUPERVISED;
	}

	//--------------------------------------------------------------------------------------------------
	//--- Package
	//--------------------------------------------------------------------------------------------------

	/** {@inheritDoc} */
	@Override
	public void execute(final ProcessDefinition processDefinition, final Optional<String> initialParams) {
		Assertion.checkNotNull(processDefinition);
		// ---
		// We need to be as short as possible for the commit
		if (transactionManager.hasCurrentTransaction()) {
			doExecute(processDefinition, initialParams);
		} else {
			try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
				doExecute(processDefinition, initialParams);
				transaction.commit();
			}
		}
	}

	private void doExecute(final ProcessDefinition processDefinition, final Optional<String> initialParams) {
		final OProcessExecution processExecution = initProcessExecution(processDefinition);
		initFirstActivityExecution(processExecution, initialParams);

	}

	/** {@inheritDoc} */
	@Override
	public void endPendingActivityExecution(final Long activityExecutionId, final String token, final ExecutionState executionState, final Optional<String> errorMessageOpt) {
		Assertion.checkNotNull(activityExecutionId);
		Assertion.checkNotNull(token);
		// ---
		OActivityExecution activityExecution;
		ActivityExecutionWorkspace workspace;
		try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
			activityExecution = activityExecutionDAO.getActivityExecutionByToken(activityExecutionId, token);
			Assertion.checkNotNull(activityExecution, "Activity token and id are not compatible");
			workspace = getWorkspaceForActivityExecution(activityExecution.getAceId(), false);
			transaction.commit();
		}
		// ---
		Assertion.checkState(ExecutionState.PENDING.name().equals(activityExecution.getEstCd()), "Only pending executions can be ended remotly");
		Assertion.checkState(workspace != null, "Workspace for activityExecution not found");

		// We execute the postTreatment of the pending activity when it's released
		// ---
		final ActivityEngine activityEngine = DIInjector.newInstance(
				ClassUtil.classForName(activityExecution.getEngine(), ActivityEngine.class), Home.getApp().getComponentSpace());

		try {
			switch (executionState) {
				case DONE:
					workspace = activityEngine.successfulPostTreatment(workspace);
					break;
				case ERROR:
					workspace = activityEngine.errorPostTreatment(workspace, new RuntimeException(errorMessageOpt.orElse("ThirdPartyException")));
					break;
				case PENDING:
				case RUNNING:
				case SUBMITTED:
				case WAITING:
				default:
					throw new UnsupportedOperationException();
			}

		} catch (final Exception e) {
			LOGGER.info("Unknow error ending a pending activity", e);
			endActivityExecution(activityExecution, ExecutionState.ERROR);

		} finally {
			handleOtherServices(activityEngine, activityExecution, workspace);
		}

		// we continue with the standard workflow for ending executions
		endActivityExecution(activityExecution, executionState);

	}

	/** {@inheritDoc} */
	@Override
	public void setActivityExecutionPending(final Long activityExecutionId, final ActivityExecutionWorkspace workspace) {
		// We need to be as short as possible for the commit
		if (transactionManager.hasCurrentTransaction()) {
			try (final VTransactionWritable transaction = transactionManager.createAutonomousTransaction()) {
				doSetActivityExecutionPending(activityExecutionId, workspace);
				transaction.commit();
			}
		} else {
			try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
				doSetActivityExecutionPending(activityExecutionId, workspace);
				transaction.commit();
			}
		}

	}

	private void doSetActivityExecutionPending(final Long activityExecutionId, final ActivityExecutionWorkspace workspace) {
		Assertion.checkNotNull(activityExecutionId);
		// ---
		final OActivityExecution activityExecution = activityExecutionDAO.get(activityExecutionId);
		endActivityExecution(activityExecution, ExecutionState.PENDING);
		saveActivityExecutionWorkspace(activityExecutionId, workspace, false);
	}
	//--------------------------------------------------------------------------------------------------
	//--- Private
	//--------------------------------------------------------------------------------------------------

	private void executeToDo() {
		final DtList<OActivityExecution> activitiesToLaunch;
		try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
			activitiesToLaunch = getActivitiesToLaunch();
			transaction.commit();
		}
		for (final OActivityExecution activityExecution : activitiesToLaunch) { //We submit only the process we can handle, no queue
			ActivityExecutionWorkspace workspace;
			try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
				workspace = getWorkspaceForActivityExecution(activityExecution.getAceId(), true);
				doChangeExecutionState(activityExecution, ExecutionState.SUBMITTED);
				// We set the beginning time of the activity
				activityExecution.setBeginTime(new Date());
				transaction.commit();
			}
			workers.submit(() -> doRunActivity(activityExecution, workspace));
		}

	}

	private void doRunActivity(final OActivityExecution activityExecution, final ActivityExecutionWorkspace workspace) {
		clearAllThreadLocals();
		ActivityExecutionWorkspace result;
		try {
			result = execute(activityExecution, workspace);
			putResult(activityExecution, result, null);
		} catch (final Exception e) {
			LOGGER.info("Error executing activity", e);
			putResult(activityExecution, null, e.getCause());
		}
	}

	private static void clearAllThreadLocals() {
		try {
			final Field threadLocals = Thread.class.getDeclaredField("threadLocals");
			threadLocals.setAccessible(true);
			threadLocals.set(Thread.currentThread(), null);
		} catch (final Exception e) {
			throw new AssertionError(e);
		}
	}

	private ActivityExecutionWorkspace execute(final OActivityExecution activityExecution, final ActivityExecutionWorkspace workspace) {
		ActivityExecutionWorkspace resultWorkspace = workspace;

		try {
			changeExecutionState(activityExecution, ExecutionState.RUNNING);
			// ---
			final ActivityEngine activityEngine = DIInjector.newInstance(
					ClassUtil.classForName(activityExecution.getEngine(), ActivityEngine.class), Home.getApp().getComponentSpace());

			try {

				// If the engine extends the abstractEngine we can provide the services associated (LOGGING,...) so we log the workspace
				if (activityEngine instanceof AbstractActivityEngine) {
					final String workspaceInLog = new StringBuilder("Workspace in :").append(mapCodec.encode(workspace.asMap())).toString();
					((AbstractActivityEngine) activityEngine).getLogger().info(workspaceInLog);
				}
				// We try the execution and we keep the result
				resultWorkspace = activityEngine.execute(workspace);
				Assertion.checkNotNull(resultWorkspace);
				Assertion.checkNotNull(resultWorkspace.getValue("status"), "Le status est obligatoire dans le résultat");
				// if pending we delegated the treatment to a third party so we are not sure that we are successful
				if (!resultWorkspace.isPending()) {
					// we call the posttreament
					resultWorkspace = activityEngine.successfulPostTreatment(resultWorkspace);
				}

			} catch (final Exception e) {
				// In case of failure we keep the current workspace
				resultWorkspace.setFailure();
				LOGGER.error("Erreur de l'activité : " + activityExecution.getEngine(), e);
				// we call the posttreament
				resultWorkspace = activityEngine.errorPostTreatment(resultWorkspace, e);

			} finally {
				handleOtherServices(activityEngine, activityExecution, resultWorkspace);
			}

		} catch (final Exception e) {
			// Informative log
			resultWorkspace.setFailure();
			LOGGER.error("Erreur de l'activité : " + activityExecution.getEngine(), e);
		}

		return resultWorkspace;
	}

	private void putResult(final OActivityExecution activityExecution, final ActivityExecutionWorkspace workspaceOut, final Throwable error) {
		Assertion.checkNotNull(workspaceOut);
		Assertion.checkNotNull(workspaceOut.getValue("status"), "Le status est obligatoire dans le résultat");
		// ---
		// 2. We manage the execution workflow
		if (error != null) {
			// We log the error and we continue the timer
			LOGGER.info("Error in activity " + activityExecution.getActId() + " execution", error);
			endActivityExecution(activityExecution, ExecutionState.ERROR);
		} else {
			if (workspaceOut.isSuccess()) {
				endActivityExecution(activityExecution, ExecutionState.DONE);
			} else if (workspaceOut.isFinished()) {
				// If finished we tag the whole process as DONE and dont launch next activities
				finishProcessExecution(activityExecution);
			} else if (workspaceOut.isPending()) {
				// We do nothing because we already delegated the change of status in the AbstractActivityEngine
			} else {
				endActivityExecution(activityExecution, ExecutionState.ERROR);
			}
		}

	}

	private void changeExecutionState(final OActivityExecution activityExecution, final ExecutionState executionState) {
		if (transactionManager.hasCurrentTransaction()) {
			doChangeExecutionState(activityExecution, executionState);
		} else {
			try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
				doChangeExecutionState(activityExecution, executionState);
				transaction.commit();
			}
		}
	}

	private OProcessExecution initProcessExecution(final ProcessDefinition processDefinition) {
		Assertion.checkNotNull(processDefinition);
		// ---
		final OProcessExecution newProcessExecution = new OProcessExecution();
		newProcessExecution.setProId(processDefinition.getId());
		newProcessExecution.setBeginTime(new Date());
		changeProcessExecutionState(newProcessExecution, ExecutionState.RUNNING);
		processExecutionDAO.save(newProcessExecution);

		return newProcessExecution;
	}

	private DtList<OActivityExecution> getActivitiesToLaunch() {
		final int maxNumber = getUnusedWorkersCount();
		// ---
		executionPAO.reserveActivitiesToLaunch(nodId, maxNumber);
		return activityExecutionDAO.getActivitiesToLaunch(nodId);
	}

	private void initFirstActivityExecution(final OProcessExecution processExecution, final Optional<String> initialParams) {
		Assertion.checkNotNull(processExecution.getProId());
		Assertion.checkNotNull(processExecution.getPreId());
		// ---
		final OActivity firstActivity = activityDAO.getFirstActivityByProcess(processExecution.getProId());
		final OActivityExecution firstActivityExecution = initActivityExecutionWithActivity(firstActivity, processExecution.getPreId());
		activityExecutionDAO.save(firstActivityExecution);

		final ActivityExecutionWorkspace initialWorkspace = new ActivityExecutionWorkspace(mapCodec.decode(processExecution
				.getProcess()
				.getInitialParams()));
		if (initialParams.isPresent()) {
			// If Plannification specifies initialParams we take them in addition
			initialWorkspace.addExternalParams(mapCodec.decode(initialParams.get()));
		}
		// We set in the workspace essentials params
		initialWorkspace.setProcessName(processExecution.getProcess().getName());
		initialWorkspace.setProcessExecutionId(processExecution.getPreId());
		initialWorkspace.setActivityExecutionId(firstActivityExecution.getAceId());
		initialWorkspace.setToken(firstActivityExecution.getToken());
		// ---
		saveActivityExecutionWorkspace(firstActivityExecution.getAceId(), initialWorkspace, true);

	}

	private static OActivityExecution initActivityExecutionWithActivity(final OActivity activity, final Long preId) {
		Assertion.checkNotNull(preId);
		// ---
		final OActivityExecution activityExecution = new OActivityExecution();

		activityExecution.setPreId(preId);
		activityExecution.setActId(activity.getActId());
		activityExecution.setCreationTime(new Date());
		activityExecution.setEngine(activity.getEngine());
		changeActivityExecutionState(activityExecution, ExecutionState.WAITING);
		activityExecution.setToken(ActivityTokenGenerator.getToken());

		return activityExecution;

	}

	private void reserveActivityExecution(final OActivityExecution activityExecution) {
		activityExecution.setEstCd(ExecutionState.SUBMITTED.name());
		activityExecution.setNodId(nodId);
	}

	private void endActivityExecutionAndInitNext(final OActivityExecution activityExecution) {
		try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
			endActivity(activityExecution);

			final Optional<OActivity> nextActivity = activityDAO.getNextActivityByActId(activityExecution.getActId());
			if (nextActivity.isPresent()) {
				final OActivityExecution nextActivityExecution;
				final ActivityExecutionWorkspace nextWorkspace;
				nextActivityExecution = initActivityExecutionWithActivity(nextActivity.get(), activityExecution.getPreId());
				// We keep the previous worker (Not the same but the slot) for the next Activity Execution
				reserveActivityExecution(nextActivityExecution);
				activityExecutionDAO.save(nextActivityExecution);

				// We keep the old workspace for the nextTask
				final ActivityExecutionWorkspace previousWorkspace = getWorkspaceForActivityExecution(activityExecution.getAceId(), false);
				// We remove the status and update the activityExecutionId and token
				previousWorkspace.resetStatus();
				previousWorkspace.resetAttachment();
				previousWorkspace.setActivityExecutionId(nextActivityExecution.getAceId());
				previousWorkspace.setToken(nextActivityExecution.getToken());
				// ---
				saveActivityExecutionWorkspace(nextActivityExecution.getAceId(), previousWorkspace, true);
				nextActivityExecution.setBeginTime(new Date());
				nextWorkspace = previousWorkspace;
				//we close the transaction now
				transaction.addAfterCompletion(
						succeeded -> {
							if (succeeded) {
								doRunActivity(nextActivityExecution, nextWorkspace);
							}
						});

			} else {
				endProcessExecution(activityExecution.getPreId(), ExecutionState.DONE);
			}
			transaction.commit();
		}
	}

	private void endActivityExecution(final OActivityExecution activityExecution, final ExecutionState executionState) {
		Assertion.checkNotNull(activityExecution);
		Assertion.checkNotNull(executionState);
		// ---

		switch (executionState) {
			case DONE:
				endActivityExecutionAndInitNext(activityExecution);
				break;
			case ERROR:
				changeExecutionState(activityExecution, ExecutionState.ERROR);
				break;
			case PENDING:
				changeExecutionState(activityExecution, ExecutionState.PENDING);
				break;
			case RUNNING:
			case SUBMITTED:
			case WAITING:
			default:
				throw new IllegalArgumentException("Unknwon case for ending activity execution :  " + executionState.name());
		}

	}

	private ActivityExecutionWorkspace getWorkspaceForActivityExecution(final Long aceId, final Boolean in) {
		Assertion.checkNotNull(aceId);
		Assertion.checkNotNull(in);
		// ---
		final OActivityWorkspace activityWorkspace = activityWorkspaceDAO.getActivityWorkspace(aceId, in).get();
		return new ActivityExecutionWorkspace(mapCodec.decode(activityWorkspace.getWorkspace()));
	}

	private void saveActivityExecutionWorkspace(final Long aceId, final ActivityExecutionWorkspace workspace, final Boolean in) {
		Assertion.checkNotNull(aceId);
		Assertion.checkNotNull(in);
		Assertion.checkNotNull(workspace);
		// ---
		// we need at most one workspace in and one workspace out
		final OActivityWorkspace activityWorkspace = activityWorkspaceDAO.getActivityWorkspace(aceId, in).orElse(new OActivityWorkspace());
		activityWorkspace.setAceId(aceId);
		activityWorkspace.setIsIn(in);
		activityWorkspace.setWorkspace(mapCodec.encode(workspace.asMap()));

		activityWorkspaceDAO.save(activityWorkspace);

	}

	private void doChangeExecutionState(final OActivityExecution activityExecution, final ExecutionState executionState) {
		Assertion.checkNotNull(activityExecution);
		// ---
		changeActivityExecutionState(activityExecution, executionState);
		activityExecutionDAO.save(activityExecution);

		// If it's an error the entire process is in Error
		if (ExecutionState.ERROR.equals(executionState)) {
			endProcessExecution(activityExecution.getPreId(), ExecutionState.ERROR);
		}

	}

	private void finishProcessExecution(final OActivityExecution activityExecution) {
		if (transactionManager.hasCurrentTransaction()) {
			doFinishProcessExecution(activityExecution);
		} else {
			try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
				doFinishProcessExecution(activityExecution);
				transaction.commit();
			}
		}
	}

	private void doFinishProcessExecution(final OActivityExecution activityExecution) {
		Assertion.checkNotNull(activityExecution);
		// ---
		endActivity(activityExecution);
		endProcessExecution(activityExecution.getPreId(), ExecutionState.DONE);
	}

	private void endActivity(final OActivityExecution activityExecution) {
		activityExecution.setEndTime(new Date());
		changeActivityExecutionState(activityExecution, ExecutionState.DONE);
		activityExecutionDAO.save(activityExecution);

	}

	private void handleOtherServices(final ActivityEngine activityEngine, final OActivityExecution activityExecution, final ActivityExecutionWorkspace resultWorkspace) {
		try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
			// We save the workspace which is the minimal state
			saveActivityExecutionWorkspace(activityExecution.getAceId(), resultWorkspace, false);
			if (activityEngine instanceof AbstractActivityEngine) {
				// If the engine extends the abstractEngine we can provide the services associated (LOGGING,...)
				saveActivityLogs(activityExecution.getAceId(), ((AbstractActivityEngine) activityEngine).getLogger(), resultWorkspace);
			}
			transaction.commit();
		}
	}

	private void endProcessExecution(final Long preId, final ExecutionState executionState) {
		final OProcessExecution processExecution = processExecutionDAO.get(preId);
		processExecution.setEndTime(new Date());
		changeProcessExecutionState(processExecution, executionState);
		processExecutionDAO.save(processExecution);

	}

	private void saveActivityLogs(final Long aceId, final ActivityLogger activityLogger, final ActivityExecutionWorkspace resultWorkspace) {
		Assertion.checkNotNull(aceId);
		Assertion.checkNotNull(activityLogger);
		// ---
		// we need at most on log per activityExecution
		final OActivityLog activityLog = activityLogDAO.getActivityLogByAceId(aceId).orElse(new OActivityLog());
		activityLog.setAceId(aceId);
		final String log = new StringBuilder(activityLog.getLog() == null ? "" : activityLog.getLog()).append(activityLogger.getLogAsString())//
				.append("ResultWorkspace : ").append(mapCodec.encode(resultWorkspace.asMap())).append("\n")//
				.toString();
		activityLog.setLog(log);
		if (resultWorkspace.getAttachment() != null) {
			activityLog.setAttachment(resultWorkspace.getAttachment());
		}
		activityLogDAO.save(activityLog);
	}

	private int getUnusedWorkersCount() {
		Assertion.checkNotNull(workers);
		// ---
		if (workers instanceof ThreadPoolExecutor) {
			final ThreadPoolExecutor workersPool = (ThreadPoolExecutor) workers;
			return workersCount - workersPool.getActiveCount();
		}
		return workersCount;
	}

	private void handleDeadNodeProcesses() {
		try (final VTransactionWritable transaction = transactionManager.createCurrentTransaction()) {
			final Long now = System.currentTimeMillis();
			// We wait two heartbeat to be sure that the node is dead
			final Date maxDate = new Date(now - 2 * executionPeriodSeconds * 1000);
			executionPAO.handleProcessesOfDeadNodes(maxDate);
			transaction.commit();
		}
	}

	private static void changeActivityExecutionState(final OActivityExecution activityExecution, final ExecutionState executionState) {
		// we need to check if the transistion is valid
		activityExecution.setEstCd(executionState.name());
	}

	private static void changeProcessExecutionState(final OProcessExecution processExecution, final ExecutionState executionState) {
		// we need to check if the transistion is valid
		processExecution.setEstCd(executionState.name());
	}

}


text:
'use strict';
/*
	http://source-docs.blesta.com/class-PackageGroups.html
	Package Group management

Model
*/

module.exports = function(blesta){
	const _ = require('lodash');

	return {
		get: function(package_id, callback){
			return blesta.request('get', 'packages/get', {
				package_id: package_id,
			}, callback);
		},
		getByPricingId: function(package_pricing_id, callback){
			return blesta.request('get', 'packages/getByPricingId', {
				package_pricing_id: package_pricing_id,
			}, callback);
		},
		getAll: function(company_id, data, callback){
			if(data && !callback){
				callback = data;
				data = {};
			}
			return blesta.request('get', 'packages/getAll', _.defaults({
				company_id: company_id,
			}, _.pick(data, ['order', 'status', 'type'])), callback);
		},
		getList: function(company_id, data, callback){
			if(data && !callback){
				callback = data;
				data = {};
			}
			return blesta.request('get', 'packages/getList', _.defaults({
				company_id: company_id,
			}, _.pick(data, ['page', 'order_by', 'status'])), callback);
		},
		search: function(query, data, callback){
			if(data && !callback){
				callback = data;
				data = {};
			}
			return blesta.request('get', 'packages/search', _.defaults({
				query: query,
			}, _.pick(data, ['page'])), callback);
		},
		getSearchCount: function(query, callback){
			return blesta.request('get', 'packages/getSearchCount', {
				query: query,
			}, callback);
		},
		getAllPackagesByGroup: function(package_group_id, data, callback){
			if(data && !callback){
				callback = data;
				data = {};
			}
			return blesta.request('get', 'packages/getAllPackagesByGroup', _.defaults({
				package_group_id: package_group_id,
			}, _.pick(data, ['status'])), callback);
		},
		convertPricing: function(pricing, data, callback){
			if(data && !callback){
				callback = data;
				data = {};
			}
			return blesta.request('post', 'packages/convertPricing', _.defaults({
				pricing: pricing,
			}, _.pick(data, ['currency', 'allow_conversion'])), callback);
		},
	};
};


text:
module Mojikun
  class SaveNode
  end
end


text:
Known issues & workarounds
==========================

## `dotnet restore` times out on Win7 x64
If you have Virtual Box and you try to use the CLI on a Win7 x64 machine, `dotnet restore` will be really slow and will eventually time out without doing much restoring.

**Issues tracking this:**

* [#1732](https://github.com/dotnet/cli/issues/1732)

**Affects:** `dotnet restore`

**Workaround:** disable the VirtualBox network interface and do the restore.

## Resolving the Standard library packages
The StdLib package is on a MyGet feed. In order to restore it, a MyGet feed needs to be added
to the NuGet feeds, either locally per application or in a central location.

**Issues tracking this:**

* [#535](https://github.com/dotnet/cli/issues/535)

**Affects:** `dotnet restore`

**Workaround:** update to the latest bits and run `dotnet new` in an empty directory. This will
now drop a `nuget.config` file that you can use in other applications.

If you cannot update, you can use the following `nuget.config`:

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key="dotnet-core" value="https://dotnet.myget.org/F/dotnet-core/api/v3/index.json" />
    <add key="api.nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>
```

## Uninstalling/reinstalling the PKG on OS X
OS X doesn't really have an uninstall capacity for PKGs like Windows has for
MSIs. There is, however, a way to remove the bits as well as the "recipe" for
dotnet. More information can be found on [this SuperUser question](http://superuser.com/questions/36567/how-do-i-uninstall-any-apple-pkg-package-file).

# What is this document about?
This document outlines the known issues and workarounds for the current state of
the CLI tools. Issues will also have a workaround and affects sections if necessary. You can use this page to
get information and get unblocked.

# What is a "known issue"?
A "known issue" is a major issue that block users in doing their everyday tasks and that affect all or
most of the commands in the CLI tools. If you want to report or see minor issues, you can use the [issues list](https://github.com/dotnet/cli/issues).


text:
/*
 * This is an implementation of the SauceLabs Driver Provider.
 * It is responsible for setting up the account object, tearing
 * it down, and setting up the driver correctly.
 */

import {WebDriver} from 'selenium-webdriver';
import * as util from 'util';

import {Config} from '../config';
import {Logger} from '../logger';

import {DriverProvider} from './driverProvider';

const SauceLabs = require('saucelabs');
const SAUCE_REGIONS: {[key: string]: string} = {
  'us': '',  // default endpoint
  'eu': 'eu-central-1.'
};

let logger = new Logger('sauce');
export class Sauce extends DriverProvider {
  sauceServer_: any;

  constructor(config: Config) {
    super(config);
  }

  /**
   * Hook to update the sauce job.
   * @public
   * @param {Object} update
   * @return {Promise} A promise that will resolve when the update is complete.
   */
  updateJob(update: any): Promise<any> {
    let mappedDrivers = this.drivers_.map(async (driver: WebDriver) => {
      const session = await driver.getSession();
      logger.info('SauceLabs results available at http://saucelabs.com/jobs/' + session.getId());
      this.sauceServer_.updateJob(session.getId(), update, (err: Error) => {
        if (err) {
          throw new Error('Error updating Sauce pass/fail status: ' + util.inspect(err));
        }
      });
    });
    return Promise.all(mappedDrivers);
  }

  /**
   * Configure and launch (if applicable) the object's environment.
   * @public
   * @return {Promise} A promise which will resolve when the environment is
   *     ready to test.
   */
  protected async setupDriverEnv(): Promise<any> {
    this.sauceServer_ = new SauceLabs({
      hostname: this.getSauceEndpoint(this.config_.sauceRegion),
      username: this.config_.sauceUser,
      password: this.config_.sauceKey,
      agent: this.config_.sauceAgent,
      proxy: this.config_.sauceProxy
    });
    this.config_.capabilities['username'] = this.config_.sauceUser;
    this.config_.capabilities['accessKey'] = this.config_.sauceKey;
    this.config_.capabilities['build'] = this.config_.sauceBuild;
    let protocol = this.config_.sauceSeleniumUseHttp ? 'http://' : 'https://';
    let auth = protocol + this.config_.sauceUser + ':' + this.config_.sauceKey + '@';
    this.config_.seleniumAddress = auth +
        (this.config_.sauceSeleniumAddress ?
             this.config_.sauceSeleniumAddress :
             `ondemand.${this.getSauceEndpoint(this.config_.sauceRegion)}:443/wd/hub`);

    // Append filename to capabilities.name so that it's easier to identify
    // tests.
    if (this.config_.capabilities.name && this.config_.capabilities.shardTestFiles) {
      this.config_.capabilities.name +=
          (':' + this.config_.specs.toString().replace(/^.*[\\\/]/, ''));
    }

    logger.info(
        'Using SauceLabs selenium server at ' +
        this.config_.seleniumAddress.replace(/\/\/.+@/, '//'));
  }

  /**
   * Get the Sauce Labs endpoint
   * @private
   * @param {string} region
   * @return {string} The endpoint that needs to be used
   */
  private getSauceEndpoint(region: string): string {
    const dc = region ?
        typeof SAUCE_REGIONS[region] !== 'undefined' ? SAUCE_REGIONS[region] : (region + '.') :
        '';
    return `${dc}saucelabs.com`;
  }
}


text:
-- This test is designed for testing MariaDB's key_cache_segments for MyISAM,
-- and should work with other storage engines as well.
--
-- For details about key_cache_segments please refer to:
-- http://kb.askmonty.org/v/segmented-key-cache
--
function prepare()
   local query
   local i

   set_vars()

   db_connect()

   print("Creating table 'sbtest'...")

   if (db_driver == "mysql") then
      query = [[
        CREATE TABLE sbtest (
          id INTEGER UNSIGNED NOT NULL ]] .. ((oltp_auto_inc and "AUTO_INCREMENT") or "") .. [[,
          k INTEGER UNSIGNED DEFAULT '0' NOT NULL,
          c CHAR(120) DEFAULT '' NOT NULL,
          pad CHAR(60) DEFAULT '' NOT NULL,
          PRIMARY KEY (id)
        ) /*! ENGINE = ]] .. mysql_table_engine .. " MAX_ROWS = " .. myisam_max_rows .. " */"

   elseif (db_driver == "oracle") then
      query = [[
        CREATE TABLE sbtest (
          id INTEGER NOT NULL,
          k INTEGER,
          c CHAR(120) DEFAULT '' NOT NULL,
          pad CHAR(60 DEFAULT '' NOT NULL,
          PRIMARY KEY (id)
       ) ]]

   elseif (db_driver == "pgsql") then
      query = [[
        CREATE TABLE sbtest (
          id ]] .. (sb.oltp_auto_inc and "SERIAL") or "" .. [[,
          k INTEGER DEFAULT '0' NOT NULL,
          c CHAR(120) DEFAULT '' NOT NULL,
          pad CHAR(60) DEFAULT '' NOT NULL,
          PRIMARY KEY (id)
        ) ]]

   elseif (db_driver == "drizzle") then
      query = [[
        CREATE TABLE sbtest (
          id INTEGER NOT NULL ]] .. ((oltp_auto_inc and "AUTO_INCREMENT") or "") .. [[,
          k INTEGER DEFAULT '0' NOT NULL,
          c CHAR(120) DEFAULT '' NOT NULL,
          pad CHAR(60) DEFAULT '' NOT NULL,
          PRIMARY KEY (id)
        ) ]]

   else
      print("Unknown database driver: " .. db_driver)
      return 1
   end

   db_query(query)

   if (db_driver == "oracle") then
      db_query("CREATE SEQUENCE sbtest_seq")
      db_query([[CREATE TRIGGER sbtest_trig BEFORE INSERT ON sbtest
                 FOR EACH ROW BEGIN SELECT sbtest_seq.nextval INTO :new.id FROM DUAL; END;]])
   end

   db_query("CREATE INDEX k on sbtest(k)")

   print("Inserting " .. oltp_table_size .. " records into 'sbtest'")

   if (oltp_auto_inc) then
      db_bulk_insert_init("INSERT INTO sbtest(k, c, pad) VALUES")
   else
      db_bulk_insert_init("INSERT INTO sbtest(id, k, c, pad) VALUES")
   end

   for i = 1,oltp_table_size do
      if (oltp_auto_inc) then
          db_bulk_insert_next("("..i..", ' ', 'qqqqqqqqqqwwwwwwwwwweeeeeeeeeerrrrrrrrrrtttttttttt')")
      else
          db_bulk_insert_next("("..i..", "..i..", ' ', 'qqqqqqqqqqwwwwwwwwwweeeeeeeeeerrrrrrrrrrtttttttttt')")
      end
   end

   db_bulk_insert_done()

   return 0
end

function cleanup()
   print("Dropping table 'sbtest'...")
   db_query("DROP TABLE sbtest")
end

function thread_init(thread_id)
   set_vars()

   points = ""
   for i = 1,random_points do
      points = points .. "?, "
   end

   -- Get rid of last comma and space.
   points = string.sub(points, 1, string.len(points) - 2)

   stmt = db_prepare([[
        SELECT id, k, c, pad
          FROM sbtest
          WHERE k IN (]] .. points .. [[)
        ]])

   params = {}
   for j = 1,random_points do
      params[j] = 1
   end

   db_bind_param(stmt, params)
end

function event(thread_id)
   local rs

   -- To prevent overlapping of our range queries we need to partition the whole table
   -- into num_threads segments and then make each thread work with its own segment.
   for i = 1,random_points do
      params[i] = sb_rand(oltp_table_size / num_threads * thread_id, oltp_table_size / num_threads * (thread_id + 1))
   end

   rs = db_execute(stmt)
   db_store_results(rs)
   db_free_results(rs)
end

function set_vars()
   oltp_table_size = oltp_table_size or 10000
   random_points = random_points or 10

   if (oltp_auto_inc == 'off') then
      oltp_auto_inc = false
   else
      oltp_auto_inc = true
   end
end


text:
"""
Run this file two ways under coverage and see that the times are the same:

    $ coverage run lab/bug397.py slow
    Runtime per example: 130.96 +/- 3.70 us
    $ coverage run lab/bug397.py fast
    Runtime per example: 131.34 +/- 4.48 us

Written by David MacIver as part of
https://bitbucket.org/ned/coveragepy/issues/397/stopping-and-resuming-coverage-with

"""
from __future__ import print_function

import sys
import random
import time
import math

if sys.argv[1] == "slow":
    sys.settrace(sys.gettrace())

random.seed(1)

def hash_str(s):
    h = 0
    for c in s:
        h = (h * 31 + ord(c)) & (2 ** 64 - 1)
    return h

data = [
    hex(random.getrandbits(1024)) for _ in range(500)
]

N_SAMPLES = 100

def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs)

def sd(xs):
    return math.sqrt(mean(x ** 2 for x in xs) - mean(xs) ** 2)

if __name__ == '__main__':
    timing = []
    for _ in range(N_SAMPLES):
        start = time.time()
        for d in data:
            hash_str(d)
        timing.append(1000000 * (time.time() - start) / len(data))
    print("Runtime per example:", "%.2f +/- %.2f us" % (mean(timing), sd(timing)))


text:
/// <reference path='./Scripts/DlhSoft.ProjectData.GanttChart.HTML.Controls.d.ts'/>
import GanttChartView = DlhSoft.Controls.GanttChartView;
import GanttChartItem = GanttChartView.Item;
import ScheduleChartView = DlhSoft.Controls.ScheduleChartView;
import ScheduleChartItem = ScheduleChartView.Item;

// Query string syntax: ?theme
// Supported themes: Default, Generic-bright, Generic-blue, DlhSoft-gray, Purple-green, Steel-blue, Dark-black, Cyan-green, Blue-navy, Orange-brown, Teal-green, Purple-beige, Gray-blue, Aero.
var queryString = window.location.search;
var theme = queryString ? queryString.substr(1) : null;
declare var initializeGanttChartTheme;

// Retrieve and store the control element for reference purposes.
var scheduleChartViewElement = <HTMLElement>document.querySelector('#scheduleChartView');

var date = new Date(), year = date.getFullYear(), month = date.getMonth();
var scheduleChartItems = <ScheduleChartItem[]>[
    { content: 'Resource 1', start: new Date(), ganttChartItems: [{ content: 'Task A (Resource 1)', start: new Date(year, month, 2, 8, 0, 0), finish: new Date(year, month, 8, 16, 0, 0), completedFinish: new Date(year, month, 5, 16, 0, 0) }] },
    {
        content: 'Resource 2', start: new Date(), ganttChartItems: [
            { content: 'Task A (Resource 2)', start: new Date(year, month, 2, 8, 0, 0), finish: new Date(year, month, 8, 16, 0, 0), completedFinish: new Date(year, month, 5, 16, 0, 0), assignmentsContent: '50%' },
            { content: 'Task B (Resource 2)', start: new Date(year, month, 11, 8, 0, 0), finish: new Date(year, month, 12, 16, 0, 0), completedFinish: new Date(year, month, 12, 16, 0, 0) },
            { content: 'Task C (Resource 2)', start: new Date(year, month, 14, 8, 0, 0), finish: new Date(year, month, 14, 16, 0, 0) }]
    },
    { content: 'Resource 3', start: new Date(), ganttChartItems: [{ content: 'Task D (Resource 3)', start: new Date(year, month, 12, 12, 0, 0), finish: new Date(year, month, 14, 16, 0, 0) }] }];
for (var i = 4; i <= 16; i++)
    scheduleChartItems.push({
        content: 'Resource ' + i, start: new Date(), ganttChartItems: [
            { content: 'Task X (Resource ' + i + ')', start: new Date(year, month, 2, 8, 0, 0), finish: new Date(year, month, 5, 16, 0, 0) },
            { content: 'Task Y (Resource ' + i + ')', start: new Date(year, month, 7, 8, 0, 0), finish: new Date(year, month, 8, 16, 0, 0) }]
    });

var settings = <ScheduleChartView.Settings>{
    currentTime: new Date(year, month, 2, 12, 0, 0)
};

// Optionally, initialize custom themes (themes.js).
initializeGanttChartTheme(settings, theme);

// Define special days.
var specialDayIntervals = [
    { start: new Date(year, month, 4), finish: new Date(year, month, 6) },
    { start: new Date(year, month, 8), finish: new Date(year, month, 9) },
    { start: new Date(year, month, 11), finish: new Date(year, month, 17) }
];
// Highlight special days using a scale item without headers.
var scales = settings.scales ? settings.scales : GanttChartView.getDefaultScales(settings);
scales.push(<GanttChartView.Scale>{
    scaleType: 'Custom', isHeaderVisible: false,
    intervals: specialDayIntervals,
    isHighlightingVisible: true, highlightingStyle: 'fill: green; opacity: 0.25'
});
settings.scales = scales;

// Initialize the component.
var scheduleChartView = DlhSoft.Controls.ScheduleChartView.initialize(scheduleChartViewElement, scheduleChartItems, settings);


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Material Design</title>
	<link rel="stylesheet" href="../../resources/lesszy.css">

Ripple

Ripple delegate paper

Ripple bound false

Ripple delegate paper, bound false

Ripple diameterLimit true

Ripple delegate paper, diameterLimit true

Ripple diameterLimit 20

Ripple delegate paper, diameterLimit 20

Ripple centered true

Ripple delegate paper, centered true

Ripple color #E91E63

Ripple delegate paper, color #E91E63


text:
function initDefaultMCE() {
    tinyMCE.init({
        mode : "none",
        theme : "advanced",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        plugins: 'media, paste, advimage, advlink, template',
        theme_advanced_buttons1 : "bold,italic,strikethrough,separator,bullist,numlist,undo,redo,link,unlink, blockquote, |, justifyleft, justifycenter, justifyright, justifyfull, image ,media,  |, code",
        theme_advanced_buttons2 : "formatselect,filemanager,pastetext,pasteword,selectall, template",
        theme_advanced_buttons3 : "",
        relative_urls : false,
        content_css:    '/css/main.css',
        paste_auto_cleanup_on_paste : true,
        external_link_list_url : "/admin-arbo-site.html",
        template_external_list_url : "/js/tinytemplate.js",
        theme_advanced_resizing : true
    });
}

$.editable.addInputType('mce', {
    element : function(settings, original) {
        var textarea = $('<textarea id="'+$(original).attr("id")+'_mce"/>');
        if (settings.rows) {
            textarea.attr('rows', settings.rows);
        } else {
            textarea.height(settings.height);
        }

        if (settings.cols) {
            textarea.attr('cols', settings.cols);
        } else {
            textarea.width(settings.width);
        }

        $(this).append(textarea);

        return(textarea);
    },

    plugin : function(settings, original) {
        if (window.initMCE) {
            initMCE();
        } else {
            initDefaultMCE();
        }

        tinyMCE.execCommand("mceAddControl", true, $(original).attr("id")+'_mce');
    },

    submit : function(settings, original) {
        tinyMCE.triggerSave();
        tinyMCE.execCommand("mceRemoveControl", true, $(original).attr("id")+'_mce');
    },

    reset : function(settings, original) {
        tinyMCE.execCommand("mceRemoveControl", true, $(original).attr("id")+'_mce');
        original.reset();
    }
});


text:
#include <errno.h>
#include <assert.h>
#include "../linker_set.h"
#include "../internal.h"

static struct rpct_member *union_read_member(const char *decl,
    rpc_object_t obj, struct rpct_type *type)
{
	struct rpct_member *member;
	const char *typedecl = NULL;
	const char *description = NULL;
	rpc_object_t constraints = NULL;

	rpc_object_unpack(obj, "{s,s,v}",
	    "type", &typedecl,
	    "description", &description,
	    "constraints", &constraints);

	if (typedecl == NULL) {
		rpc_set_last_errorf(EINVAL, "%s: type key not provided or invalid", decl);
		return (NULL);
	}

	member = g_malloc0(sizeof(*member));
	member->name = g_strdup(decl);
	member->description = description != NULL ? g_strdup(description) : NULL;
	member->origin = type;
	member->type = rpct_instantiate_type(typedecl, NULL, type, type->file);
	member->constraints = g_hash_table_new_full(g_str_hash, g_str_equal,
	    g_free, (GDestroyNotify)rpc_release_impl);

	if (constraints != NULL) {
		rpc_dictionary_apply(constraints, ^(const char *key, rpc_object_t value) {
			g_hash_table_insert(member->constraints, g_strdup(key),
			    value);
			return ((bool)true);
		});
	}

	return (member);
}

static bool
union_validate(struct rpct_typei *typei, rpc_object_t obj,
    struct rpct_error_context *errctx)
{
	__block struct rpct_typei *mtypei;
	__block rpc_object_t interior = NULL;
	bool ret;

	ret = rpct_members_apply(typei->type, ^(struct rpct_member *member) {
		struct rpct_error_context newctx = {
			.path = errctx->path,
			.errors = g_ptr_array_new()
		};

		mtypei = rpct_typei_get_member_type(typei, member);
		interior = rpc_copy(obj);
		rpct_set_typei(mtypei, interior);

		if (rpct_validate_instance(mtypei, interior, &newctx)) {
			g_ptr_array_free(newctx.errors, true);
			return ((bool)false);
		}

		g_ptr_array_free(newctx.errors, true);
		return ((bool)true);
	});

	if (!ret) {
		rpct_add_error(errctx, NULL,
		    "None of the union branches matches the object");
		return (false);
	}

	ret = rpct_run_validators(mtypei, interior, errctx);
	rpc_release(interior);
	return (ret);
}

static rpc_object_t
union_serialize(rpc_object_t obj)
{

	assert(obj != NULL);
	assert(obj->ro_typei != NULL);

	return (rpc_object_pack("{s,v}",
	    RPCT_TYPE_FIELD, obj->ro_typei->canonical_form,
	    RPCT_VALUE_FIELD, rpc_copy(obj)));
}

static rpc_object_t
union_deserialize(rpc_object_t obj)
{

	return (rpc_copy(rpc_dictionary_get_value(obj, RPCT_VALUE_FIELD)));
}

static struct rpct_class_handler union_class_handler = {
	.id = RPC_TYPING_UNION,
	.name = "union",
	.member_fn = union_read_member,
	.validate_fn = union_validate,
	.serialize_fn = union_serialize,
	.deserialize_fn = union_deserialize
};

DECLARE_TYPE_CLASS(union_class_handler);


text:
"""Unit tests for tf_inspect."""

# pylint: disable=unused-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import inspect

from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_decorator
from tensorflow.python.util import tf_inspect

def test_decorator(decorator_name, decorator_doc=None):

  def make_tf_decorator(target):
    return tf_decorator.TFDecorator(decorator_name, target, decorator_doc)

  return make_tf_decorator

def test_undecorated_function():
  pass

@test_decorator('decorator 1')
@test_decorator('decorator 2')
@test_decorator('decorator 3')
def test_decorated_function(x):
  """Test Decorated Function Docstring."""
  return x * 2

@test_decorator('decorator')
def test_decorated_function_with_defaults(a, b=2, c='Hello'):
  """Test Decorated Function With Defaults Docstring."""
  return [a, b, c]

@test_decorator('decorator')
class TestDecoratedClass(object):
  """Test Decorated Class."""

  def __init__(self):
    pass

  def two(self):
    return 2

class TfInspectTest(test.TestCase):

  def testCurrentFrame(self):
    self.assertEqual(inspect.currentframe(), tf_inspect.currentframe())

  def testGetArgSpecOnDecoratorsThatDontProvideArgspec(self):
    argspec = tf_inspect.getargspec(test_decorated_function_with_defaults)
    self.assertEqual(['a', 'b', 'c'], argspec.args)
    self.assertEqual((2, 'Hello'), argspec.defaults)

  def testGetArgSpecOnDecoratorThatChangesArgspec(self):
    argspec = tf_inspect.ArgSpec(
        args=['a', 'b', 'c'],
        varargs=None,
        keywords=None,
        defaults=(1, 'hello'))

    decorator = tf_decorator.TFDecorator('', test_undecorated_function, '',
                                         argspec)
    self.assertEqual(argspec, tf_inspect.getargspec(decorator))

  def testGetArgSpecIgnoresDecoratorsThatDontProvideArgspec(self):
    argspec = tf_inspect.ArgSpec(
        args=['a', 'b', 'c'],
        varargs=None,
        keywords=None,
        defaults=(1, 'hello'))

    inner_decorator = tf_decorator.TFDecorator('', test_undecorated_function,
                                               '', argspec)
    outer_decorator = tf_decorator.TFDecorator('', inner_decorator)
    self.assertEqual(argspec, tf_inspect.getargspec(outer_decorator))

  def testGetArgSpecReturnsOutermostDecoratorThatChangesArgspec(self):
    outer_argspec = tf_inspect.ArgSpec(
        args=['a'], varargs=None, keywords=None, defaults=None)
    inner_argspec = tf_inspect.ArgSpec(
        args=['b'], varargs=None, keywords=None, defaults=None)

    inner_decorator = tf_decorator.TFDecorator('', test_undecorated_function,
                                               '', inner_argspec)
    outer_decorator = tf_decorator.TFDecorator('', inner_decorator, '',
                                               outer_argspec)
    self.assertEqual(outer_argspec, tf_inspect.getargspec(outer_decorator))

  def testGetDoc(self):
    self.assertEqual('Test Decorated Function With Defaults Docstring.',
                     tf_inspect.getdoc(test_decorated_function_with_defaults))

  def testGetFile(self):
    self.assertTrue('tf_inspect_test.py' in tf_inspect.getfile(
        test_decorated_function_with_defaults))
    self.assertTrue('tf_decorator.py' in tf_inspect.getfile(
        test_decorator('decorator')(tf_decorator.unwrap)))

  def testGetMembers(self):
    self.assertEqual(
        inspect.getmembers(TestDecoratedClass),
        tf_inspect.getmembers(TestDecoratedClass))

  def testGetModule(self):
    self.assertEqual(
        inspect.getmodule(TestDecoratedClass),
        tf_inspect.getmodule(TestDecoratedClass))
    self.assertEqual(
        inspect.getmodule(test_decorated_function),
        tf_inspect.getmodule(test_decorated_function))
    self.assertEqual(
        inspect.getmodule(test_undecorated_function),
        tf_inspect.getmodule(test_undecorated_function))

  def testGetSource(self):
    expected = '''@test_decorator('decorator')
def test_decorated_function_with_defaults(a, b=2, c='Hello'):
  """Test Decorated Function With Defaults Docstring."""
  return [a, b, c]
'''
    self.assertEqual(
        expected, tf_inspect.getsource(test_decorated_function_with_defaults))

  def testIsClass(self):
    self.assertTrue(tf_inspect.isclass(TestDecoratedClass))
    self.assertFalse(tf_inspect.isclass(test_decorated_function))

  def testIsFunction(self):
    self.assertTrue(tf_inspect.isfunction(test_decorated_function))
    self.assertFalse(tf_inspect.isfunction(TestDecoratedClass))

  def testIsMethod(self):
    self.assertTrue(tf_inspect.ismethod(TestDecoratedClass().two))
    self.assertFalse(tf_inspect.ismethod(test_decorated_function))

  def testIsModule(self):
    self.assertTrue(
        tf_inspect.ismodule(inspect.getmodule(inspect.currentframe())))
    self.assertFalse(tf_inspect.ismodule(test_decorated_function))

  def testIsRoutine(self):
    self.assertTrue(tf_inspect.isroutine(len))
    self.assertFalse(tf_inspect.isroutine(TestDecoratedClass))

  def testStack(self):
    expected_stack = inspect.stack()
    actual_stack = tf_inspect.stack()
    self.assertEqual(len(expected_stack), len(actual_stack))
    self.assertEqual(expected_stack[0][0], actual_stack[0][0])  # Frame object
    self.assertEqual(expected_stack[0][1], actual_stack[0][1])  # Filename
    self.assertEqual(expected_stack[0][2],
                     actual_stack[0][2] - 1)  # Line number
    self.assertEqual(expected_stack[0][3], actual_stack[0][3])  # Function name
    self.assertEqual(expected_stack[1:], actual_stack[1:])

class TfInspectGetCallArgsTest(test.TestCase):

  def testReturnsEmptyWhenUnboundFuncHasNoParameters(self):

    def empty():
      pass

    self.assertEqual({}, tf_inspect.getcallargs(empty))

  def testUnboundFuncWithOneParamPositional(self):

    def func(a):
      return a

    self.assertEqual({'a': 5}, tf_inspect.getcallargs(func, 5))

  def testUnboundFuncWithTwoParamsPositional(self):

    def func(a, b):
      return (a, b)

    self.assertEqual({'a': 10, 'b': 20}, tf_inspect.getcallargs(func, 10, 20))

  def testUnboundFuncWithOneParamKeyword(self):

    def func(a):
      return a

    self.assertEqual({'a': 5}, tf_inspect.getcallargs(func, a=5))

  def testUnboundFuncWithTwoParamsKeyword(self):

    def func(a, b):
      return (a, b)

    self.assertEqual({'a': 6, 'b': 7}, tf_inspect.getcallargs(func, a=6, b=7))

  def testUnboundFuncWithOneParamDefault(self):

    def func(a=13):
      return a

    self.assertEqual({'a': 13}, tf_inspect.getcallargs(func))

  def testUnboundFuncWithOneParamDefaultOnePositional(self):

    def func(a=0):
      return a

    self.assertEqual({'a': 1}, tf_inspect.getcallargs(func, 1))

  def testUnboundFuncWithTwoParamsDefaultOnePositional(self):

    def func(a=1, b=2):
      return (a, b)

    self.assertEqual({'a': 5, 'b': 2}, tf_inspect.getcallargs(func, 5))

  def testUnboundFuncWithTwoParamsDefaultTwoPositional(self):

    def func(a=1, b=2):
      return (a, b)

    self.assertEqual({'a': 3, 'b': 4}, tf_inspect.getcallargs(func, 3, 4))

  def testUnboundFuncWithOneParamDefaultOneKeyword(self):

    def func(a=1):
      return a

    self.assertEqual({'a': 3}, tf_inspect.getcallargs(func, a=3))

  def testUnboundFuncWithTwoParamsDefaultOneKeywordFirst(self):

    def func(a=1, b=2):
      return (a, b)

    self.assertEqual({'a': 3, 'b': 2}, tf_inspect.getcallargs(func, a=3))

  def testUnboundFuncWithTwoParamsDefaultOneKeywordSecond(self):

    def func(a=1, b=2):
      return (a, b)

    self.assertEqual({'a': 1, 'b': 4}, tf_inspect.getcallargs(func, b=4))

  def testUnboundFuncWithTwoParamsDefaultTwoKeywords(self):

    def func(a=1, b=2):
      return (a, b)

    self.assertEqual({'a': 3, 'b': 4}, tf_inspect.getcallargs(func, a=3, b=4))

  def testBoundFuncWithOneParam(self):

    class Test(object):

      def bound(self):
        pass

    t = Test()
    self.assertEqual({'self': t}, tf_inspect.getcallargs(t.bound))

  def testBoundFuncWithManyParamsAndDefaults(self):

    class Test(object):

      def bound(self, a, b=2, c='Hello'):
        return (a, b, c)

    t = Test()
    self.assertEqual({
        'self': t,
        'a': 3,
        'b': 2,
        'c': 'Goodbye'
    }, tf_inspect.getcallargs(t.bound, 3, c='Goodbye'))

  def testClassMethod(self):

    class Test(object):

      @classmethod
      def test(cls, a, b=3, c='hello'):
        return (a, b, c)

    self.assertEqual({
        'cls': Test,
        'a': 5,
        'b': 3,
        'c': 'goodbye'
    }, tf_inspect.getcallargs(Test.test, 5, c='goodbye'))

  def testUsesOutermostDecoratorsArgSpec(self):

    def func():
      pass

    def wrapper(*args, **kwargs):
      return func(*args, **kwargs)

    decorated = tf_decorator.make_decorator(
        func,
        wrapper,
        decorator_argspec=tf_inspect.ArgSpec(
            args=['a', 'b', 'c'],
            varargs=None,
            keywords=None,
            defaults=(3, 'hello')))

    self.assertEqual({
        'a': 4,
        'b': 3,
        'c': 'goodbye'
    }, tf_inspect.getcallargs(decorated, 4, c='goodbye'))

if __name__ == '__main__':
  test.main()


text:
<html>
	<head>
		<script type="text/javascript" src="fckeditor.js"></script>
	</head>

	<textarea name="content"></textarea>

	<script type="text/javascript">
		var oFCKeditor = new FCKeditor( 'content' ) ;
		oFCKeditor.BasePath	= "./" ;
		oFCKeditor.Height = "300";
		oFCKeditor.Width = "600";
		oFCKeditor.ToolbarSet = "itcastForum";
		oFCKeditor.ReplaceTextarea() ;
	</script>

</html>


text:
"""Fit a polynomial chaos expansion using linear regression."""
import numpy
import numpoly

def fit_regression(
    polynomials,
    abscissas,
    evals,
    model=None,
    retall=0,
):
    """
    Fit a polynomial chaos expansion using linear regression.

    Args:
        polynomials (numpoly.ndpoly):
            Polynomial expansion with ``polynomials.shape == (M,)`` and
            `polynomials.dim=D`.
        abscissas (numpy.ndarray):
            Collocation nodes with ``abscissas.shape == (D, K)``.
        evals (numpy.ndarray):
            Model evaluations with ``len(evals) == K``.
        model (Optional[sklearn.base.BaseEstimator]):
            By default regression is done using the classical least-square
            method. However, if provided, and `sklearn` regression model can be
            used instead.
        retall (int):
            What the function should return.
            0: only return fitted polynomials, with shape `evals.shape[1:]`.
            1: polynomials, and Fourier coefficients,
            2: polynomials, coefficients and polynomial evaluations.

    Returns:
        (chaospy.ndpoly, numpy.ndarray, numpy.ndarray):
            Returned value as determined by `retval`.

    Examples:
        >>> x, y = chaospy.variable(2)
        >>> polynomials = chaospy.polynomial([1, x, y])
        >>> abscissas = [[-1, -1, 1, 1],  [-1, 1, -1, 1]]
        >>> evals = [0, 1, 1, 2]
        >>> chaospy.fit_regression(polynomials, abscissas, evals).round(14)
        polynomial(0.5*q1+0.5*q0+1.0)
        >>> model = sklearn.linear_model.LinearRegression(fit_intercept=False)
        >>> chaospy.fit_regression(
        ...     polynomials, abscissas, evals, model=model).round(14)
        polynomial(0.5*q1+0.5*q0+1.0)

    """
    abscissas = numpy.atleast_2d(abscissas)
    assert abscissas.ndim == 2, "too many dimensions"

    polynomials = numpoly.aspolynomial(polynomials)

    evals = numpy.asarray(evals)
    assert abscissas.shape[-1] == len(evals)

    poly_evals = polynomials(*abscissas).T
    shape = evals.shape[1:]
    if shape:
        evals = evals.reshape(len(evals), -1)

    if model is None:
        uhat, _, _, _ = numpy.linalg.lstsq(poly_evals, evals, rcond=None)

    else:
        try:
            from sklearn.base import BaseEstimator
        except ImportError:  # pragma: no cover
            raise ValueError(
                "arg model != None requires that scikit-learn is installed"
            )
        assert isinstance(model, BaseEstimator), (
            "model not recognized; " "Optional[sklearn.base.BaseEstimator] expected"
        )
        if hasattr(model, "fit_intercept"):
            assert not model.fit_intercept, (
                "requires %s(fit_intercept=False)" % model.__class__.__name__
            )
        uhat = numpy.transpose(model.fit(poly_evals, evals).coef_)

    approx_model = numpoly.sum((polynomials * uhat.T), -1).reshape(shape)
    choices = {
        0: approx_model,
        1: (approx_model, uhat),
        2: (approx_model, uhat, poly_evals),
    }
    return choices[retall]


text:
#pragma once

#include "interfaces.hpp"

#include <string>

namespace pid_control
{

/**
 * Abstract base class for all sensors.
 */
class Sensor
{
  public:
    /**
     * Given a sensor's type, return the default timeout value.
     * A timeout of 0 means there isn't a timeout for this sensor.
     * By default a fan sensor isn't checked for a timeout, whereas
     * any of sensor is meant to be sampled once per second.  By default.
     *
     * @param[in] type - the sensor type (e.g. fan)
     * @return the default timeout for that type (in seconds).
     */
    static int64_t getDefaultTimeout(const std::string& type)
    {
        return (type == "fan") ? 0 : 2;
    }

    Sensor(const std::string& name, int64_t timeout) :
        _name(name), _timeout(timeout)
    {}

    virtual ~Sensor()
    {}

    virtual ReadReturn read(void) = 0;
    virtual void write(double value) = 0;

    virtual void write(double value, bool force, int64_t* written)
    {
        (void)force;
        (void)written;
        return write(value);
    }

    virtual bool getFailed(void)
    {
        return false;
    };

    std::string getName(void) const
    {
        return _name;
    }

    /* Returns the configurable timeout period
     * for this sensor in seconds (undecorated).
     */
    int64_t getTimeout(void) const
    {
        return _timeout;
    }

  private:
    std::string _name;
    int64_t _timeout;
};

} // namespace pid_control


text:
package com.ajah.spring.mvc.editor;

import java.beans.PropertyEditorSupport;

import com.ajah.util.Identifiable;
import com.ajah.util.IdentifiableEnum;
import com.ajah.util.StringUtils;

/**
 * Generic class that will map an enum based on its {@link Identifiable#getId()}
 * method.
 *
 * @author Eric F. Savage, code@efsavage.com.
 *
 * @param <E>
 */
public class IdentifiableEnumPropertyEditor<E extends IdentifiableEnum<?>> extends PropertyEditorSupport {

	private final E[] values;
	private final boolean matchId;
	private final boolean matchEnumName;
	private final boolean matchName;
	private final boolean matchCode;
	private final boolean caseSensitive;

	/**
	 * Pass the result of Enum.getValues() because I can't seem to find a way to
	 * derive this from the type parameter.
	 *
	 * Matches on ID only, case-sensitive. See
	 * {@link #IdentifiableEnumPropertyEditor(IdentifiableEnum[], boolean, boolean, boolean, boolean, boolean)}
	 * for other options.
	 *
	 * @param values
	 *            The values of the enum.
	 */
	public IdentifiableEnumPropertyEditor(final E[] values) {
		this(values, true, false, false, false, true);
	}

	/**
	 * Pass the result of Enum.getValues() because I can't seem to find a way to
	 * derive this from the type parameter.
	 *
	 * This is the most flexible option, with all matching enabled.
	 *
	 * @param values
	 *            The values of the enum.
	 * @param caseSensitive
	 *            Should matching be case sensitive?
	 */
	public IdentifiableEnumPropertyEditor(final E[] values, final boolean caseSensitive) {
		this(values, true, true, true, true, caseSensitive);
	}

	/**
	 * Pass the result of Enum.getValues() because I can't seem to find a way to
	 * derive this from the type parameter.
	 *
	 * @param values
	 *            The values of the enum.
	 * @param matchId
	 *            Match on the enum's ID?
	 * @param matchEnumName
	 *            Match on the enum's name() value?
	 * @param matchName
	 *            Match on the enum's getName() value?
	 * @param matchCode
	 *            Match on the enum's code ID?
	 * @param caseSensitive
	 *            Should matching be case sensitive?
	 */
	public IdentifiableEnumPropertyEditor(final E[] values, final boolean matchId, final boolean matchEnumName, final boolean matchName, final boolean matchCode, final boolean caseSensitive) {
		this.values = values;
		this.matchId = matchId;
		this.matchEnumName = matchEnumName;
		this.matchName = matchName;
		this.matchCode = matchCode;
		this.caseSensitive = caseSensitive;
	}

	/**
	 * Matches strings, is aware of the caseSensitive property.
	 *
	 * @param first
	 *            The first string to match.
	 * @param second
	 *            The second string to match.
	 * @return The results of {@link String#equals(Object)} or
	 *         {@link String#equalsIgnoreCase(String)} as appropriate.
	 */
	private boolean equals(final String first, final String second) {
		if (this.caseSensitive) {
			return first.equals(second);
		}
		return first.equalsIgnoreCase(second);
	}

	/**
	 * Gets the property value as a string suitable for presentation to a human
	 * to edit.
	 *
	 * @return The property value as a string suitable for presentation to a
	 *         human to edit.
	 *

	 *         Returns null if the value can't be expressed as a string.
	 *

	 *         If a non-null value is returned, then the PropertyEditor should
	 *         be prepared to parse that string back in setAsText().
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String getAsText() {
		return (getValue() != null) ? ((E) getValue()).getId().toString() : null;
	}

	/**
	 * Sets the property value by parsing a given String. May raise
	 * java.lang.IllegalArgumentException if either the String is badly
	 * formatted or if this kind of property can't be expressed as text.
	 *
	 * @param text
	 *            The string to be parsed.
	 */
	@Override
	public void setAsText(final String text) throws java.lang.IllegalArgumentException {
		if (StringUtils.isBlank(text)) {
			setValue(null);
			return;
		}
		for (final E candidate : this.values) {
			if (this.matchId && equals(candidate.getId().toString(), text)) {
				setValue(candidate);
				return;
			}
			if (this.matchEnumName && equals(candidate.name(), text)) {
				setValue(candidate);
				return;
			}
			if (this.matchName && equals(candidate.getName(), text)) {
				setValue(candidate);
				return;
			}
			if (this.matchCode && equals(candidate.getCode(), text)) {
				setValue(candidate);
				return;
			}
		}
		throw new java.lang.IllegalArgumentException(text);
	}

}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sg.atom.core.lang;

/**
 *
 * @author CuongNguyen
 */
public class AUID{

}