text:
package lineProtocol

import (
	"errors"
	"fmt"
	"io"
	"net"
	"runtime"
	"strings"

	"github.com/nyxtom/broadcast/server"
)

type LineProtocol struct {
	ctx *server.BroadcastContext
}

func NewLineProtocol() *LineProtocol {
	return new(LineProtocol)
}

func (p *LineProtocol) Initialize(ctx *server.BroadcastContext) error {
	p.ctx = ctx
	return nil
}

func (p *LineProtocol) Name() string {
	return "line"
}

func (p *LineProtocol) HandleConnection(conn *net.TCPConn) (server.ProtocolClient, error) {
	return NewLineProtocolClientSize(conn, 128)
}

func (p *LineProtocol) RunClient(client server.ProtocolClient) {
	c, ok := client.(*LineProtocolClient)
	if !ok {
		client.WriteError(errInvalidProtocol)
		client.Close()
		return
	}

	defer func() {
		if e := recover(); e != nil {
			buf := make([]byte, 4096)
			n := runtime.Stack(buf, false)
			buf = buf[0:n]
			p.ctx.Events <- server.BroadcastEvent{"fatal", "client run panic", errors.New(fmt.Sprintf("%v", e)), buf}
		}

		c.Close()
		return
	}()

	reqErr := client.RequestErrorChan()
	for {
		data, err := c.readBulk()

		if err != nil {
			if err != io.EOF {
				p.ctx.Events <- server.BroadcastEvent{"error", "read error", err, nil}
			}
			return
		}

		err = p.handleData(data, c, reqErr)
		if err != nil {
			if err == errQuit {
				return
			} else {
				p.ctx.Events <- server.BroadcastEvent{"error", "accept error", err, nil}
				c.WriteError(err)
				c.Flush()
			}
		}
	}
}

func (p *LineProtocol) handleData(data [][]byte, client *LineProtocolClient, reqErr chan error) error {
	cmd := strings.ToUpper(string(data[0]))
	switch {
	case cmd == "QUIT":
		return errQuit
	default:
		handler, ok := p.ctx.Commands[cmd]
		if !ok {
			return errCmdNotFound
		}

		var err error
		go func() {
			reqErr <- handler(data[1:], client)
		}()
		err = <-reqErr
		return err
	}
}


text:
package defw.http

import org.scalatest._
import java.net.{URI => JavaNetURI}

class URITest extends FlatSpec {

  "URI.apply" should "create uri object from http://hc.apache.org/?a=b#c" in {
    val uri = URI("http://hc.apache.org/?a=b#c")
    assert(uri.isInstanceOf[JavaNetURI] === true)
  }

}

redpajama_set_name: RedPajamaGithub


text:
using BotEngine.Common;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Sanderling.Parse
{
	public class DroneLabel
	{
		public string Name;

		public string Status;
	}

	static public class Drone
	{
		public const string DroneEntryLabelRegexPattern = "([^\\(]+)\\(([^\\)]+)";

		static public Regex DroneEntryLabelRegex = DroneEntryLabelRegexPattern.AsRegexCompiledIgnoreCase();

		static public DroneLabel AsDroneLabel(this string droneLabel)
		{
			var Name = droneLabel?.Trim();
			string Status = null;

			var Match = DroneEntryLabelRegex.Match(droneLabel ?? "");

			if (Match.Success)
			{
				Name = Match.Groups[1].Value?.Trim();
				Status = Match.Groups[2].Value?.RemoveXmlTag()?.Trim();
			}

			return new DroneLabel()
			{
				Name = Name,
				Status = Status,
			};
		}
	}
}


text:
package com.sap.cloud.lm.sl.cf.process.util;

import org.cloudfoundry.client.lib.CloudControllerClient;
import org.cloudfoundry.client.lib.domain.CloudApplication;

import com.sap.cloud.lm.sl.cf.process.util.ElementUpdater.UpdateBehavior;

public abstract class ApplicationAttributeUpdater {

    protected CloudApplication existingApp;
    protected StepLogger stepLogger;
    protected UpdateBehavior updateBehavior;

    public ApplicationAttributeUpdater(CloudApplication existingApp, StepLogger stepLogger) {
        this(existingApp, UpdateBehavior.REPLACE, stepLogger);
    }

    public ApplicationAttributeUpdater(CloudApplication existingApp, UpdateBehavior updateBehavior, StepLogger stepLogger) {
        this.existingApp = existingApp;
        this.stepLogger = stepLogger;
        this.updateBehavior = updateBehavior;
    }

    public UpdateState updateApplication(CloudControllerClient client, CloudApplication app) {
        return shouldUpdateAttribute(app) ? updateApplicationAttribute(client, app) : UpdateState.UNCHANGED;
    }

    protected abstract boolean shouldUpdateAttribute(CloudApplication app);

    protected abstract UpdateState updateApplicationAttribute(CloudControllerClient client, CloudApplication app);

    public enum UpdateState {
        UPDATED, UNCHANGED
    }

}


text:
var AllTags="";
$(function() {

    $(".sfLocale").localize({
        moduleKey: AspxTagsManagement
    });

    var aspxCommonObj = {
        StoreID: AspxCommerce.utils.GetStoreID(),
        PortalID: AspxCommerce.utils.GetPortalID(),
        UserName: AspxCommerce.utils.GetUserName(),
        CultureName: AspxCommerce.utils.GetCultureName()
    };
    var arrTagItems = new Array();
    var arrTagItemsToBind = new Array();
    AllTags = {
        config: {
            isPostBack: false,
            async: false,
            cache: false,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: '{}',
            dataType: "json",
            baseURL: aspxservicePath + "AspxCoreHandler.ashx/",
            url: "",
            method: ""
        },
        LoadItemTagRssImage: function() {
            var pageurl = aspxRedirectPath + rssFeedUrl + pageExtension;
            $('#allTagsRssImage').parent('a').show();
            $('#allTagsRssImage').parent('a').removeAttr('href').prop('href', pageurl + '?type=rss&action=newtags');
            $('#allTagsRssImage').removeAttr('src').prop('src', aspxTemplateFolderPath + '/images/rss-icon.png');
            $('#allTagsRssImage').removeAttr('title').prop('title', getLocale(AspxTagsManagement,'New Tag Rss Feed'));
            $('#allTagsRssImage').removeAttr('alt').prop('alt', getLocale(AspxTagsManagement,'New Tag Rss Feed'));
        },
        init: function() {
            AllTags.HideAll();
            $("#divShowTagDetails").show();
            AllTags.LoadAllTagsStaticImage();
            AllTags.BindTagDetails(null, null);
                       if (newItemTagRss.toLowerCase() == 'true') {
                AllTags.LoadItemTagRssImage();
            }
            $("#btnSaveTag").click(function() {
                var validTag = $("#form1").validate({
                    messages: {
                        Tag: {
                            required: '*',
                            maxlength: "*"
                        }
                    }
                });
                if (validTag.form()) {
                    AllTags.UpdateTags();
                } else return false;
            });
            $("#tblTagsItems").on("change", ".classStatusList", function() {
                var itemId = $(this).attr("itemid");
                var itemTagId = $(this).attr("tags");
                AllTags.UpdateTags(itemId, itemTagId, $(this).val());
            });
            $("#btnSearchTags").click(function() {
                AllTags.SearchTags();
            });
            $("#btnBack").click(function() {
                AllTags.HideAll();
                $("#divTagedItemsDetails").find('tblTagsItems>tbody').html('');
                $("#divShowTagDetails").show();
            });
            $("#btnCancel").click(function() {
                AllTags.HideAll();
                $("#divShowTagDetails").show();
            });
            $("#ddlTagItemDisplay").change(function() {
                var items_per_page = $(this).val();
                $("#Pagination").pagination(arrTagItems.length, {
                    callback: pageselectCallback,
                    items_per_page: items_per_page,
                                                          prev_text: "Prev",
                    next_text: "Next",
                    prev_show_always: false,
                    next_show_always: false
                });
            });
            $('#btnDeleteSelected').click(function() {
                var itemTags_Ids = '';
                               itemTags_Ids = SageData.Get("gdvTags").Arr.join(',');
                if (itemTags_Ids.length>0) {
                    var properties = {
                        onComplete: function(e) {
                            AllTags.ConfirmDeleteMultipleItemTags(itemTags_Ids, e);
                        }
                    };
                    csscody.confirm("
"+getLocale(AspxTagsManagement,'Delete Confirmation')+'

'+getLocale(AspxTagsManagement,'Are you sure you want to the selected tag(s)?')+"
", properties);
                } else {
                    csscody.alert('
'+getLocale(AspxTagsManagement,'Information Alert')+'

'+getLocale(AspxTagsManagement,'Please select at least one tag before delete.')+'
');
                }
            });
            $('#txtSearchTag,#ddlStatus').keyup(function(event) {
                if (event.keyCode == 13) {
                    AllTags.SearchTags();
                }
            });
        },

        ajaxCall: function(config) {
            $.ajax({
                type: AllTags.config.type, beforeSend: function (request) {
                    request.setRequestHeader('ASPX-TOKEN', _aspx_token);
                    request.setRequestHeader("UMID", umi);
                    request.setRequestHeader("UName", AspxCommerce.utils.GetUserName());
                    request.setRequestHeader("PID", AspxCommerce.utils.GetPortalID());
                    request.setRequestHeader("PType", "v");
                    request.setRequestHeader('Escape', '0');
                },
                contentType: AllTags.config.contentType,
                cache: AllTags.config.cache,
                async: AllTags.config.async,
                data: AllTags.config.data,
                dataType: AllTags.config.dataType,
                url: AllTags.config.url,
                success: AllTags.ajaxSuccess,
                error: AllTags.ajaxFailure
            });
        },
        LoadAllTagsStaticImage: function() {
            $('#ajaxAllTagsImage').prop('src', '' + aspxTemplateFolderPath + '/images/ajax-loader.gif');
        },

        UpdateTags: function(itemId, itemTagId, newStatusID) {
            this.config.url = this.config.baseURL + "UpdateTag";
            this.config.data = JSON2.stringify({ itemTagIDs: itemTagId, itemId: itemId, statusID: newStatusID, aspxCommonObj: aspxCommonObj });
            this.config.ajaxCallMode = 1;
            this.ajaxCall(this.config);
        },

        HideAll: function() {
            $("#divEditTag").hide();
            $("#divShowTagDetails").hide();
            $("#divTagedItemsDetails").hide();
        },

        clearTagForm: function() {

            $('#txtTag').removeClass('error');
            $('#txtTag').parents('td').find('label').remove();
        },

        GetStatusOfTag: function() {
            this.config.url = this.config.baseURL + "GetStatus";
            this.config.data = JSON2.stringify({ aspxCommonObj: aspxCommonObj });
            this.config.ajaxCallMode = 2;
            this.ajaxCall(this.config)
        },

        BindTagDetails: function(tags, tagStatus) {
            this.config.method = "GetTagDetailsList";
            var offset_ = 1;
            var current_ = 1;
            var perpage = ($("#gdvTags_pagesize").length > 0) ? $("#gdvTags_pagesize :selected").text() : 10;

            $("#gdvTags").sagegrid({
                url: this.config.baseURL,
                functionMethod: this.config.method,
                colModel: [
                    { display: getLocale(AspxTagsManagement,'ItemTagIDs'), name: 'itemtag_ids', cssclass: 'cssClassHeadCheckBox', coltype: 'checkbox', align: 'center', elemClass: 'TagChkbox', elemDefault: false, controlclass: 'tagHeaderChkbox' },
                    { display: getLocale(AspxTagsManagement,'Tag'), name: 'tag', cssclass: '', controlclass: '', coltype: 'label', align: 'left' },
                    { display: getLocale(AspxTagsManagement,'User Counts'), name: 'user_count', cssclass: 'cssClassHeadNumber', controlclass: '', coltype: 'label', align: 'left', showpopup: false },
                    { display: getLocale(AspxTagsManagement,'Item Counts'), name: 'item_count', cssclass: 'cssClassHeadNumber', controlclass: '', coltype: 'label', align: 'left', showpopup: false },
                    { display: getLocale(AspxTagsManagement,'Status'), name: 'status', cssclass: '', controlclass: '', coltype: 'label', align: 'left', hide: true },
                    { display: getLocale(AspxTagsManagement,'StatusID'), name: 'status_id', cssclass: 'cssClassHeadNumber', controlclass: '', coltype: 'label', align: 'left', hide: true },
                    { display: getLocale(AspxTagsManagement,'UserIDs'), name: 'user_ids', cssclass: '', controlclass: '', coltype: 'label', align: 'left', hide: true },
                    { display: getLocale(AspxTagsManagement,'ItemIDs'), name: 'item_ids', cssclass: '', controlclass: '', coltype: 'label', align: 'left', hide: true },
                    { display: getLocale(AspxTagsManagement,'Tag Count'), name: 'tag_count', cssclass: 'cssClassHeadNumber', controlclass: '', coltype: 'label', align: 'left', hide: true },
                    { display: getLocale(AspxTagsManagement,'Actions'), name: 'action', cssclass: 'cssClassAction', coltype: 'label', align: 'center' }
                ],
                buttons: [
                    { display: getLocale(AspxTagsManagement,'View'), name: 'view_items', enable: true, _event: 'click', trigger: '3', callMethod: 'AllTags.ShowTaggedItems', arguments: '1,2,3,4,5,6,7,8,9' },
                                   { display: getLocale(AspxTagsManagement,'Delete'), name: 'delete', enable: true, _event: 'click', trigger: '2', callMethod: 'AllTags.DeleteTags', arguments: '0' }
                ],
                rp: perpage,
                nomsg: getLocale(AspxTagsManagement,"No Records Found!"),
                param: { tag: tags, tagStatus: tagStatus, aspxCommonObj: aspxCommonObj },
                current: current_,
                pnew: offset_,
                sortcol: { 0: { sorter: false }, 9: { sorter: false } }
            });
        },

        EditTags: function(tblID, argus) {
            switch (tblID) {
            case "gdvTags":
                $("#" + lblEditTagDetails).html("Edit Tag: '" + argus[4] + "'");
                AllTags.HideAll();
                AllTags.clearTagForm();
                $("#divEditTag").show();
                $("#hdnItemTagID").val(argus[3]);
                $("#hdnTag").val(argus[4]);
                $("#hdnStatusID").val(argus[5]);
                $("#txtTag").val(argus[4]);
                $("#selectStatus").val(argus[5]);
                break;
            default:
                break;
            }
        },

        DeleteTags: function(tblID, argus) {
            switch (tblID) {
            case "gdvTags":
                var properties = {
                    onComplete: function(e) {
                        AllTags.ConfirmDeleteTag(argus[3], e);
                    }
                }
                csscody.confirm("
"+getLocale(AspxTagsManagement,'Delete Confirmation')+'

'+getLocale(AspxTagsManagement,'Are you sure you want to delete this tag?')+"
", properties);
                break;
            default:
                break;
            }
        },

        ConfirmDeleteTag: function(itemTagIDs, event) {
            if (event) {
                this.config.url = this.config.baseURL + "DeleteTag";
                this.config.data = JSON2.stringify({ itemTagIDs: itemTagIDs, aspxCommonObj: aspxCommonObj });
                this.config.ajaxCallMode = 3;
                this.ajaxCall(this.config)
            }
            return false;
        },

        ConfirmDeleteMultipleItemTags: function(Ids, event) {
            AllTags.DeleteItemTagInfo(Ids, event);
        },

        DeleteItemTagInfo: function(_TagID_Ids, event) {
            if (event) {
                this.config.url = this.config.baseURL + "DeleteMultipleTag";
                this.config.data = JSON2.stringify({ itemTagIDs: _TagID_Ids, aspxCommonObj: aspxCommonObj });
                this.config.ajaxCallMode = 4;
                this.ajaxCall(this.config)
            }
            return false;
        },

        ShowTaggedItems: function(tblID, argus) {
            switch (tblID) {
            case "gdvTags":
                $("#" + lblTagViewHeading).html(getLocale(AspxTagsManagement,"View Tag:") + argus[3]);
                AllTags.BindTagedItemsDetails(argus[9], argus[3]);
                break;
            default:
                break;
            }
        },
        BindTagedItemsDetails: function(IDs, tagNm) {
            this.config.url = this.config.baseURL + "GetItemsByMultipleItemID";
            this.config.data = JSON2.stringify({ itemIDs: IDs, tagName: tagNm, aspxCommonObj: aspxCommonObj });
            this.config.ajaxCallMode = 5;
            this.ajaxCall(this.config);
        },
        SearchTags: function() {
            var tags = $.trim($("#txtSearchTag").val());
            var tagStatus = '';
            if (tags.length < 1) {
                tags = null;
            }
            if ($("#ddlStatus").val() != 0) {
                tagStatus = $.trim($("#ddlStatus").val());
            } else {
                tagStatus = null;
            }
            AllTags.BindTagDetails(tags, tagStatus);
        },
        ajaxSuccess: function(data) {
            switch (AllTags.config.ajaxCallMode) {
            case 0:
                break;
            case 1:
                csscody.info('
'+getLocale(AspxTagsManagement,'Successful Message')+'

'+getLocale(AspxTagsManagement,'Status has been updated successfully.')+'
');
                break;
            case 2:
                $.each(data.d, function(index, item) {
                                                          $(".classStatusList").append("<option value=" + item.StatusID + ">" + item.Status + "</option>");
                });
                break;
            case 3:
                AllTags.BindTagDetails(null, null);
                csscody.info('
'+getLocale(AspxTagsManagement,'Successful Message')+'

'+getLocale(AspxTagsManagement,'Tag has been deleted successfully.')+'
');
                break;
            case 4:
                AllTags.BindTagDetails(null, null);
                csscody.info('
'+getLocale(AspxTagsManagement,'Successful Message')+'

'+getLocale(AspxTagsManagement,'Selected tag(s) has been deleted successfully.')+'
');
                break;
            case 5:
                var tableElements = "";
                AllTags.HideAll();
                $("#divTagedItemsDetails").show();
                $.each(data.d, function(index, item) {
                    $(".classStatusList").html('');
                    tableElements += '
';
                    tableElements += '	';
                    tableElements += '' + item.Name + '	';
                    tableElements += '' + item.SKU + '	';
                    tableElements += '' + item.Price + '	';
                    if (item.StatusID == 1) {
                        tableElements += '<select id="status' + item.ItemTagIDs + '" class="classStatusList" itemid=' + item.ItemID + ' tags=' + item.ItemTagIDs + '><option value=1>' + getLocale(AspxTagsManagement, 'Disabled') + '</option><option value=2>' + getLocale(AspxTagsManagement,' Pending')+'</option><option value=3>' + getLocale(AspxTagsManagement,'Approved')+'</option></select>	';
                    } else if (item.StatusID == 2) {
                        tableElements += '<select id="status' + item.ItemTagIDs + '" class="classStatusList" itemid=' + item.ItemID + ' tags=' + item.ItemTagIDs + '><option value=2>' + getLocale(AspxTagsManagement, 'Pending')+'</option><option value=1>' + getLocale(AspxTagsManagement,'Disabled')+'</option><option value=3>' + getLocale(AspxTagsManagement,'Approved')+'</option></select>	';
                    } else if (item.StatusID == 3) {
                        tableElements += '<select id="status' + item.ItemTagIDs + '" class="classStatusList" itemid=' + item.ItemID + ' tags=' + item.ItemTagIDs + '><option value=3>' + getLocale(AspxTagsManagement, 'Approved')+'</option><option value=1>' + getLocale(AspxTagsManagement, 'Disabled')+'</option><option value=2>' + getLocale(AspxTagsManagement,'Pending')+'</option></select>	';
                    }
                    tableElements += '
';
                    $("#table>tbody>tr .classStatusList").find("option[text=" + item.Status + "]").prop("selected", "selected");

                });
                $("#divTagedItemsDetails").find('table>tbody').html(tableElements);
                $("#divTagedItemsDetails").find("table>tbody tr:even").addClass("sfEven");
                $("#divTagedItemsDetails").find("table>tbody tr:odd").addClass("sfOdd");
                $('.cssClassFormatCurrency').formatCurrency({ colorize: true, region: '' + region + '' });
                break;
            }
        }
    };
    AllTags.init();
});


text:
using namespace iulib;
using namespace colib;
using namespace ocropus;

int main(int argc,char **argv) {
  try {
    bytearray image;
    intarray output;

    read_image_binary(image,argv[1]);

    init_ocropus_components();

    autodel<ISegmentPage> segmenter;
    make_component(segmenter, "SegmentPageByVORONOI");

    segmenter->segment(output, image);

    write_image_binary(argv[2],image);
  } catch(const char *message) {
    fprintf(stderr,"error: %s\n",message);
    exit(1);
  }
}


text:
// AUTO-GENERATED: do not modify this file directly.
// If you need to make changes, modify generate-fp.ts (if necessary), then open a terminal in types/lodash/scripts, and do:
// npm run fp

import _ = require("../index");

interface Partition {
    /**
    * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for,
    * while the second of which contains elements predicate returns falsey for.
    * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
    *
    * If a property name is provided for predicate the created _.property style callback
    * returns the property value of the given element.
    *
    * If a value is also provided for thisArg the created _.matchesProperty style callback
    * returns true for elements that have a matching property value, else false.
    *
    * If an object is provided for predicate the created _.matches style callback returns
    * true for elements that have the properties of the given object, else false.
    *
    * @param collection The collection to iterate over.
    * @param callback The function called per iteration.
    * @param thisArg The this binding of predicate.
    * @return Returns the array of grouped elements.
    **/
    (): Partition;
    /**
    * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for,
    * while the second of which contains elements predicate returns falsey for.
    * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
    *
    * If a property name is provided for predicate the created _.property style callback
    * returns the property value of the given element.
    *
    * If a value is also provided for thisArg the created _.matchesProperty style callback
    * returns true for elements that have a matching property value, else false.
    *
    * If an object is provided for predicate the created _.matches style callback returns
    * true for elements that have the properties of the given object, else false.
    *
    * @param collection The collection to iterate over.
    * @param callback The function called per iteration.
    * @param thisArg The this binding of predicate.
    * @return Returns the array of grouped elements.
    **/
    <T>(callback: _.ValueIteratee<T>): Partition1x1<T>;
    /**
    * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for,
    * while the second of which contains elements predicate returns falsey for.
    * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
    *
    * If a property name is provided for predicate the created _.property style callback
    * returns the property value of the given element.
    *
    * If a value is also provided for thisArg the created _.matchesProperty style callback
    * returns true for elements that have a matching property value, else false.
    *
    * If an object is provided for predicate the created _.matches style callback returns
    * true for elements that have the properties of the given object, else false.
    *
    * @param collection The collection to iterate over.
    * @param callback The function called per iteration.
    * @param thisArg The this binding of predicate.
    * @return Returns the array of grouped elements.
    **/
    <T>(callback: _.ValueIteratee<T>, collection: _.List<T> | null | undefined): [T[], T[]];
    /**
    * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for,
    * while the second of which contains elements predicate returns falsey for.
    * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
    *
    * If a property name is provided for predicate the created _.property style callback
    * returns the property value of the given element.
    *
    * If a value is also provided for thisArg the created _.matchesProperty style callback
    * returns true for elements that have a matching property value, else false.
    *
    * If an object is provided for predicate the created _.matches style callback returns
    * true for elements that have the properties of the given object, else false.
    *
    * @param collection The collection to iterate over.
    * @param callback The function called per iteration.
    * @param thisArg The this binding of predicate.
    * @return Returns the array of grouped elements.
    **/
    <T extends object>(callback: _.ValueIteratee<T[keyof T]>, collection: T | null | undefined): [Array<T[keyof T]>, Array<T[keyof T]>];
}
interface Partition1x1<T> {
    /**
    * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for,
    * while the second of which contains elements predicate returns falsey for.
    * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
    *
    * If a property name is provided for predicate the created _.property style callback
    * returns the property value of the given element.
    *
    * If a value is also provided for thisArg the created _.matchesProperty style callback
    * returns true for elements that have a matching property value, else false.
    *
    * If an object is provided for predicate the created _.matches style callback returns
    * true for elements that have the properties of the given object, else false.
    *
    * @param collection The collection to iterate over.
    * @param callback The function called per iteration.
    * @param thisArg The this binding of predicate.
    * @return Returns the array of grouped elements.
    **/
    (): Partition1x1<T>;
    /**
    * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for,
    * while the second of which contains elements predicate returns falsey for.
    * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
    *
    * If a property name is provided for predicate the created _.property style callback
    * returns the property value of the given element.
    *
    * If a value is also provided for thisArg the created _.matchesProperty style callback
    * returns true for elements that have a matching property value, else false.
    *
    * If an object is provided for predicate the created _.matches style callback returns
    * true for elements that have the properties of the given object, else false.
    *
    * @param collection The collection to iterate over.
    * @param callback The function called per iteration.
    * @param thisArg The this binding of predicate.
    * @return Returns the array of grouped elements.
    **/
    (collection: _.List<T> | object | null | undefined): [T[], T[]];
}

declare const partition: Partition;
export = partition;


text:
<?php

namespace APIDocGen\Model;

final class Documentation extends BaseModel
{
	protected $table = 'documentation';

	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Create table
	 */
	public function createTable()
	{
		$this->getConnection()->getSchemaBuilder()->create($this->getTable(), function($table) {
			$table->increments('id');
			$table->string('name', 100);
			$table->string('version', 5);
			$table->string('description', 255);
			$table->string('title', 100);
			$table->string('url', 100);
			$table->string('header', 100)->nullable();
			$table->text('header_content')->nullable();
			$table->string('footer', 100)->nullable();
			$table->text('footer_content')->nullable();
			$table->timestamps();
			$table->unique(['name', 'version']);
		});
	}
}


text:
@implementation UIStoryboard (ViewController)

+ (nonnull __kindof UIViewController *)instantiateInitialViewControllerWithStoryboard:(nonnull NSString *)storyboardName {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    UIViewController *vc = [storyboard instantiateInitialViewController];
    return vc;
}

+ (nonnull __kindof UIViewController *)instantiateViewControllerWithStoryboard:(nonnull NSString *)storyboardName vcIdentifier:(nonnull NSString *)vcIdentifier {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:vcIdentifier];
    return vc;
}

@end


text:
'use strict';
var Game = require('../models/game');
var User = require('../models/user');

var Engine = require('uci'),
    engineConfig = require('../config/engine'),
    constants = require('../constants/constants');

function getLANMove(move) {
    var lanMove = '';
    lanMove += move.from + move.to;
    if(move.promotion) {
        lanMove += move.promotion;
    }

    return lanMove;
};

function convertPGNToLAN(movesArray) {
    var movesToReturn = [];
    var movesCount = movesArray.length;

    for(var i = 0; i < movesCount; i++) {
        movesToReturn.push( getLANMove(movesArray[i]) );
    }

    return movesToReturn;
};

function emitGameProgress(socketioGameNamespace, gameId) {
    Game.findById(gameId, function(err, game) {
        if( !err ) {
            // TODO: Sending the whole game on each move is not very performant but we don't have to bother
            // with it at the moment since the game analysis is a million times more expensive
            socketioGameNamespace.to(gameId).emit('progress', game);
        }
    });
}

function startAnalizing(game, gameModel, chess, socketioGameNamespace, engine) {
    // Get the user's preferences
    User.findById(game.uploadedByUserId, function(err, user) {
        if(err) {
            console.log('Could not find user ' + game.uploadedByUserId);
            return;
        }

        // convert the pgn notation to long algebraic notation
        var moves = convertPGNToLAN(chess.history({verbose: true}));
        if(!moves.length) {
            console.log('Game contains no moves');
            return;
        }

        var movesCount = moves.length;
        if( chess.in_checkmate() || chess.in_stalemate() || chess.in_threefold_repetition() || chess.insufficient_material() ) {
            movesCount -= 1;
        }

        var updateCriteria = {_id: game._id};

        var promiseChain = engine.runProcess()
                            .then(function() {
                                return gameModel.update(
                                        updateCriteria,
                                        { $set: { 'analysis.status': constants.StatusTypes.Analyzing }}
                                    ).exec(function(err, res) {
                                            if(err) {
                                                socketioGameNamespace.to(game._id).emit('error', { message: 'Error setting status' });
                                                socketioGameNamespace.leave(game._id);
                                            } else {
                                                emitGameProgress(socketioGameNamespace, game._id);
                                            }
                                        });
                            }).then(function () {
                                // Started
                                return engine.uciCommand();
                            }).then(function (idAndOptions) {
                                // Engine name
                                return engine.isReadyCommand();
                            }).then(function () {
                                // Ready
                                return engine.uciNewGameCommand();
                            });
        // loop over the moves and build the promise chain
        var currentMove = '';
        for(var i = 0; i < movesCount; ++i) {
            currentMove += ' ' + moves[i];
            let currentPosition = currentMove;
            let currentScore = {};
            let currentMoveIndex = i;
            promiseChain = promiseChain.then(function () {
                            // Position set
                            return engine.positionCommand('startpos', currentPosition.trim());
                        }).then(function () {
                            // Starting analysis
                            return engine.goInfiniteCommand(function infoHandler(info) {
                                let matches = info.match(constants.Analyze.ScoreRegex);
                                if(matches && matches[1] && matches[2] ) {
                                    if(matches[1] === 'mate' ) {
                                        currentScore.mate = matches[2];
                                        currentScore.cp = constants.NotAvailable;
                                    } else if(matches[1] === 'cp' ) {
                                        currentScore.mate = constants.NotAvailable;

                                        // The cp score is given from the engine's perspective.
                                        // If it is white's turn we should negate the score.
                                        let whiteToMove = ( currentMoveIndex%2 == 0 );
                                        if( whiteToMove ) {
                                            currentScore.cp = -parseInt(matches[2]);
                                        } else {
                                            currentScore.cp = matches[2];
                                        }
                                    } else {
                                        // case for lowerbound and upperbound
                                        currentScore.mate = constants.NotAvailable;
                                        currentScore.cp = constants.NotAvailable;
                                    }
                                }
                            });
                        }).delay(user.preferences.uci.msPerMove)
                        .then(function () {
                            // Stopping analysis
                            return engine.stopCommand();
                        }).then(function (bestmove) {
                            let currentProgress = Math.round( (currentMoveIndex+1) / movesCount * 100 );
                            return gameModel.update(
                                        updateCriteria,
                                        {
                                            $push: {
                                                'analysis.moves': {
                                                    bestMove: bestmove.from + ' ' + bestmove.to,
                                                    'score.cp': currentScore.cp,
                                                    'score.mate': currentScore.mate
                                                }
                                            },
                                            $set: { 'analysis.progress': currentProgress }
                                        }
                                    ).exec(function(err, res) {
                                            if(err) {
                                                socketioGameNamespace.to(game._id).emit('error', { message: 'Error analyzing game' });
                                                socketioGameNamespace.leave(game._id);
                                            } else {
                                                emitGameProgress(socketioGameNamespace, game._id);
                                            }
                                        });
                        });
        }

        promiseChain.then(function () {
                    // Stopping engine
                    return engine.quitCommand();
                }).then(function () {
                    return gameModel.update(
                                updateCriteria,
                                { $set: { 'analysis.status': constants.StatusTypes.Complete }}
                        ).exec(function(err, res) {
                                    if(err) {
                                        socketioGameNamespace.to(game._id).emit('error', { message: 'Error setting status' });
                                    } else {
                                        emitGameProgress(socketioGameNamespace, game._id);
                                    }
                                });
                }).fail(function (error) {
                    console.error('Error:', error);
                    // Stopping engine
                    return engine.quitCommand();
                }).done();
    });
};

module.exports = {
    analyze: function(game, gameModel, chessJS, socketioGameNamespace, engine) {
        engine = engine || new Engine(engineConfig.enginePath);

        startAnalizing(game, gameModel, chessJS, socketioGameNamespace, engine);
    }
};


text:
#include "jsspi.h"
#include "jsi2c.h"
#include "jswrap_spi_i2c.h"
#include "jsdevices.h"
#include "jsinteractive.h"
#include "jswrap_arraybuffer.h"

/*JSON{
  "type" : "class",
  "class" : "SPI"
}
This class allows use of the built-in SPI ports. Currently it is SPI master only.
 */

/*JSON{
  "type" : "object",
  "name" : "SPI1",
  "instanceof" : "SPI",
  "#if" : "SPI_COUNT>=1"
}
The first SPI port
 */
/*JSON{
  "type" : "object",
  "name" : "SPI2",
  "instanceof" : "SPI",
  "#if" : "SPI_COUNT>=2"
}
The second SPI port
 */
/*JSON{
  "type" : "object",
  "name" : "SPI3",
  "instanceof" : "SPI",
  "#if" : "SPI_COUNT>=3"
}
The third SPI port
 */

/*JSON{
  "type" : "constructor",
  "class" : "SPI",
  "name" : "SPI",
  "generate" : "jswrap_spi_constructor"
}
Create a software SPI port. This has limited functionality (no baud rate), but it can work on any pins.

Use `SPI.setup` to configure this port.
 */
JsVar *jswrap_spi_constructor() {
  return jsvNewObject();
}

/*JSON{
  "type" : "staticmethod",
  "class" : "SPI",
  "name" : "find",
  "generate_full" : "jshGetDeviceObjectFor(JSH_SPI1, JSH_SPIMAX, pin)",
  "params" : [
    ["pin","pin","A pin to search with"]
  ],
  "return" : ["JsVar","An object of type `SPI`, or `undefined` if one couldn't be found."]
}
Try and find an SPI hardware device that will work on this pin (eg. `SPI1`)

May return undefined if no device can be found.
*/

/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "setup",
  "generate" : "jswrap_spi_setup",
  "params" : [
    ["options","JsVar",["An optional structure containing extra information on initialising the SPI port","Please note that baud rate is set to the nearest that can be managed - which may be -+ 50%","```{sck:pin, miso:pin, mosi:pin, baud:integer=100000, mode:integer=0, order:'msb'/'lsb'='msb' }```","If sck,miso and mosi are left out, they will automatically be chosen. However if one or more is specified then the unspecified pins will not be set up.","You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `SPI` marker.","The SPI ```mode``` is between 0 and 3 - see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase","On STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually grouped on the chip - and you can't mix pins from two groups). Espruino will not warn you about this."]]
  ]
}
Set up this SPI port as an SPI Master.
 */
void jswrap_spi_setup(
    JsVar *parent, //!< The variable that is the class instance of this function.
    JsVar *options //!< The options controlling SPI.
  ) {
  //
  // Design: The options variable is a JS Object which contains a series of settings.  These
  // settings are parsed by `jsspiPopulateSPIInfo` to populate a C structure of type
  // `JshSPIInfo`.
  //
  // The options are also hung off the class instance variable in a property symbolically called
  // DEVICE_OPTIONS_NAME ("_options").
  //
  IOEventFlags device = jsiGetDeviceFromClass(parent);
  JshSPIInfo inf;

  // Debug
  // jsiConsolePrintf("jswrap_spi_setup called parent=%v, options=%v\n", parent, options);

  if (!jsspiPopulateSPIInfo(&inf, options)) return;

  if (DEVICE_IS_SPI(device)) {
    jshSPISetup(device, &inf);
#ifdef LINUX
    if (jsvIsObject(options)) {
      jsvObjectSetChildAndUnLock(parent, "path", jsvObjectGetChild(options, "path", 0));
    }
#endif
  } else if (device == EV_NONE) {
    // software mode - at least configure pins properly
    if (inf.pinSCK != PIN_UNDEFINED)
      jshPinSetState(inf.pinSCK,  JSHPINSTATE_GPIO_OUT);
    if (inf.pinMISO != PIN_UNDEFINED)
      jshPinSetState(inf.pinMISO,  JSHPINSTATE_GPIO_IN);
    if (inf.pinMOSI != PIN_UNDEFINED)
      jshPinSetState(inf.pinMOSI,  JSHPINSTATE_GPIO_OUT);
  } else return;
  // Set up options, so we can initialise it on startup
  if (options)
    jsvUnLock(jsvSetNamedChild(parent, options, DEVICE_OPTIONS_NAME));
  else
    jsvObjectRemoveChild(parent, DEVICE_OPTIONS_NAME);
}

/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "send",
  "generate" : "jswrap_spi_send",
  "params" : [
    ["data","JsVar","The data to send - either an Integer, Array, String, or Object of the form `{data: ..., count:#}`"],
    ["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised."]
  ],
  "return" : ["JsVar","The data that was returned"]
}
Send data down SPI, and return the result. Sending an integer will return an integer, a String will return a String, and anything else will return a Uint8Array.

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.

For maximum speeds, please pass either Strings or Typed Arrays as arguments. Note that you can even pass arrays of arrays, like `[1,[2,3,4],5]`

 */
typedef struct {
  spi_sender spiSend;          //!< A function to be called to send SPI data.
  spi_sender_data spiSendData; //!< Control information on the nature of the SPI interface.
  int rxAmt;                   //!<
  int txAmt;                   //!<
  JsvArrayBufferIterator it;   //!< A buffer to hold the response data from MISO
} jswrap_spi_send_data;

/**
 * Send a single byte to the SPI device, used as callback.
 */
void jswrap_spi_send_cb(
    int c,                     //!< The byte to send through SPI.
    jswrap_spi_send_data *data //!< Control information on how to send to SPI.
  ) {
  // Invoke the SPI send function to transmit the single byte.
  int result = data->spiSend(c, &data->spiSendData);
  if (c>=0) data->txAmt++;
  if (result>=0) {
    jsvArrayBufferIteratorSetByteValue(&data->it, (char)result);
    jsvArrayBufferIteratorNext(&data->it);
    data->rxAmt++;
  }
}

/**
 * Send data through SPI.
 * The data can be in a variety of formats including:
 * * `numeric` - A single byte is transmitted.
 * * `string` - Each character in the string is transmitted.
 * * `iterable` - An iterable object is transmitted.
 * \return the Received bytes (MISO).  This is byte array.
 */
JsVar *jswrap_spi_send(
    JsVar *parent,  //!< A description of the SPI device to send data through.
    JsVar *srcdata, //!< The data to send through SPI.
    Pin    nss_pin  //!< The pin to toggle low then high (CS)
  ) {
  // Debug
  // jsiConsolePrintf("jswrap_spi_send called: parent=%j, srcdata=%j, nss_pin=%p\n", parent, srcdata, nss_pin);
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  jswrap_spi_send_data data;
  if (!jsspiGetSendFunction(parent, &data.spiSend, &data.spiSendData))
    return 0;

  JsVar *dst = 0;

  // we're sending and receiving
  if (DEVICE_IS_SPI(device)) jshSPISetReceive(device, true);

  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);

  // Now that we are setup, we can send the data.

  // Handle the data being a single byte value
  if (jsvIsNumeric(srcdata)) {
    int d = jsvGetInteger(srcdata);
    if (d<0) d = 0; // protect against -1 as we use this in the jshardware SPI implementation
    int r = data.spiSend(d, &data.spiSendData);
    if (r<0) r = data.spiSend(-1, &data.spiSendData);
    dst = jsvNewFromInteger(r); // retrieve the byte (no send!)
  }
  // Handle the data being a string
  else if (jsvIsString(srcdata)) {
    dst = jsvNewFromEmptyString();
    JsvStringIterator it;
    jsvStringIteratorNew(&it, srcdata, 0);
    int incount = 0, outcount = 0;
    while (jsvStringIteratorHasChar(&it) && !jspIsInterrupted()) {
      unsigned char in = (unsigned char)jsvStringIteratorGetChar(&it);
      incount++;
      int out = data.spiSend(in, &data.spiSendData);
      if (out>=0) {
        outcount++;
        char outc = (char)out;
        jsvAppendStringBuf(dst, (char*)&outc, 1);
      }
      jsvStringIteratorNext(&it);
    }
    jsvStringIteratorFree(&it);
    // finally add the remaining bytes  (no send!)
    while (outcount < incount && !jspIsInterrupted()) {
      outcount++;
      unsigned char out = (unsigned char)data.spiSend(-1, &data.spiSendData);
      jsvAppendStringBuf(dst, (char*)&out, 1);
    }
  } else {
    // Handle the data being an iterable.
    int nBytes = jsvIterateCallbackCount(srcdata);
    dst = jsvNewTypedArray(ARRAYBUFFERVIEW_UINT8, nBytes);
    if (dst) {
      data.rxAmt = data.txAmt = 0;
      jsvArrayBufferIteratorNew(&data.it, dst, 0);
      // Write data
      jsvIterateCallback(srcdata, (void (*)(int,  void *))jswrap_spi_send_cb, &data);
      // Wait until SPI send is finished, and flush data
      while (data.rxAmt < data.txAmt && !jspIsInterrupted())
        jswrap_spi_send_cb(-1, &data);
      jsvArrayBufferIteratorFree(&data.it);
    }
  }

  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
  return dst;
}

/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "write",
  "generate" : "jswrap_spi_write",
  "params" : [
    ["data","JsVarArray",["One or more items to write. May be ints, strings, arrays, or objects of the form `{data: ..., count:#}`.","If the last argument is a pin, it is taken to be the NSS pin"]]
  ]
}
Write a character or array of characters to SPI - without reading the result back.

For maximum speeds, please pass either Strings or Typed Arrays as arguments.
 */
void jswrap_spi_write(
    JsVar *parent, //!<
    JsVar *args    //!<
  ) {
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  spi_sender spiSend;
  spi_sender_data spiSendData;
  if (!jsspiGetSendFunction(parent, &spiSend, &spiSendData))
    return;

  Pin nss_pin = PIN_UNDEFINED;
  // If the last value is a pin, use it as the NSS pin
  JsVarInt len = jsvGetArrayLength(args);
  if (len > 0) {
    JsVar *last = jsvGetArrayItem(args, len-1); // look at the last value
    if (jsvIsPin(last)) {
      nss_pin = jshGetPinFromVar(last);
      jsvUnLock(jsvArrayPop(args));
    }
    jsvUnLock(last);
  }

  // we're only sending (no receive)
  if (DEVICE_IS_SPI(device)) jshSPISetReceive(device, false);

  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);
  // Write data
  jsvIterateCallback(args, (void (*)(int,  void *))spiSend, &spiSendData);
  // Wait until SPI send is finished, and flush data
  if (DEVICE_IS_SPI(device))
    jshSPIWait(device);
  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
}

/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "send4bit",
  "generate" : "jswrap_spi_send4bit",
  "params" : [
    ["data","JsVar","The data to send - either an integer, array, or string"],
    ["bit0","int32","The 4 bits to send for a 0 (MSB first)"],
    ["bit1","int32","The 4 bits to send for a 1 (MSB first)"],
    ["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised."]
  ]
}
Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
 */
void jswrap_spi_send4bit(JsVar *parent, JsVar *srcdata, int bit0, int bit1, Pin nss_pin) {
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);
  if (!DEVICE_IS_SPI(device)) {
    jsExceptionHere(JSET_ERROR, "SPI.send4bit only works on hardware SPI");
    return;
  }

  jshSPISet16(device, true); // 16 bit output

  if (bit0==0 && bit1==0) {
    bit0 = 0x01;
    bit1 = 0x03;
  }
  bit0 = bit0 & 0x0F;
  bit1 = bit1 & 0x0F;

  if (!jshIsDeviceInitialised(device)) {
    JshSPIInfo inf;
    jshSPIInitInfo(&inf);
    jshSPISetup(device, &inf);
  }

  // we're just sending (no receive)
  jshSPISetReceive(device, false);
  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);

  // send data
  if (jsvIsNumeric(srcdata)) {
    jsspiSend4bit(device, (unsigned char)jsvGetInteger(srcdata), bit0, bit1);
  } else if (jsvIsIterable(srcdata)) {
    jshInterruptOff();
    JsvIterator it;
    jsvIteratorNew(&it, srcdata);
    while (jsvIteratorHasElement(&it)) {
      unsigned char in = (unsigned char)jsvIteratorGetIntegerValue(&it);
      jsspiSend4bit(device, in, bit0, bit1);
      jsvIteratorNext(&it);
    }
    jsvIteratorFree(&it);
    jshInterruptOn();
  } else {
    jsExceptionHere(JSET_ERROR, "Variable type %t not suited to transmit operation", srcdata);
  }

  jshSPIWait(device); // wait until SPI send finished and clear the RX buffer

  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
  jshSPISet16(device, false); // back to 8 bit
}

/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "send8bit",
  "ifndef" : "SAVE_ON_FLASH",
  "generate" : "jswrap_spi_send8bit",
  "params" : [
    ["data","JsVar","The data to send - either an integer, array, or string"],
    ["bit0","int32","The 8 bits to send for a 0 (MSB first)"],
    ["bit1","int32","The 8 bits to send for a 1 (MSB first)"],
    ["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised"]
  ]
}
Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
 */
void jswrap_spi_send8bit(JsVar *parent, JsVar *srcdata, int bit0, int bit1, Pin nss_pin) {
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);
  if (!DEVICE_IS_SPI(device)) {
    jsExceptionHere(JSET_ERROR, "SPI.send8bit only works on hardware SPI");
    return;
  }
  jshSPISet16(device, true); // 16 bit output

  if (bit0==0 && bit1==0) {
    bit0 = 0x03;
    bit1 = 0x0F;
  }
  bit0 = bit0 & 0xFF;
  bit1 = bit1 & 0xFF;

  if (!jshIsDeviceInitialised(device)) {
    JshSPIInfo inf;
    jshSPIInitInfo(&inf);
    jshSPISetup(device, &inf);
  }

  // we're just sending (no receive)
  jshSPISetReceive(device, false);
  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);

  // send data
  if (jsvIsNumeric(srcdata)) {
    jsspiSend8bit(device, (unsigned char)jsvGetInteger(srcdata), bit0, bit1);
  } else if (jsvIsIterable(srcdata)) {
    jshInterruptOff();
    JsvIterator it;
    jsvIteratorNew(&it, srcdata);
    while (jsvIteratorHasElement(&it)) {
      unsigned char in = (unsigned char)jsvIteratorGetIntegerValue(&it);
      jsspiSend8bit(device, in, bit0, bit1);
      jsvIteratorNext(&it);
    }
    jsvIteratorFree(&it);
    jshInterruptOn();
  } else {
    jsExceptionHere(JSET_ERROR, "Variable type %t not suited to transmit operation", srcdata);
  }

  jshSPIWait(device); // wait until SPI send finished and clear the RX buffer

  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
  jshSPISet16(device, false); // back to 8 bit
}

/*JSON{
  "type" : "class",
  "class" : "I2C"
}
This class allows use of the built-in I2C ports. Currently it allows I2C Master mode only.

All addresses are in 7 bit format. If you have an 8 bit address then you need to shift it one bit to the right.
 */
/*JSON{
  "type" : "constructor",
  "class" : "I2C",
  "name" : "I2C",
  "generate" : "jswrap_i2c_constructor"
}
Create a software I2C port. This has limited functionality (no baud rate), but it can work on any pins.

Use `SPI.setup` to configure this port.
 */
JsVar *jswrap_i2c_constructor() {
  return jsvNewObject();
}

/*JSON{
  "type" : "staticmethod",
  "class" : "I2C",
  "name" : "find",
  "generate_full" : "jshGetDeviceObjectFor(JSH_I2C1, JSH_I2CMAX, pin)",
  "params" : [
    ["pin","pin","A pin to search with"]
  ],
  "return" : ["JsVar","An object of type `I2C`, or `undefined` if one couldn't be found."]
}
Try and find an I2C hardware device that will work on this pin (eg. `I2C1`)

May return undefined if no device can be found.
*/

/*JSON{
  "type" : "object",
  "name" : "I2C1",
  "instanceof" : "I2C",
  "#if" : "I2C_COUNT>=1"
}
The first I2C port
 */
/*JSON{
  "type" : "object",
  "name" : "I2C2",
  "instanceof" : "I2C",
  "#if" : "I2C_COUNT>=2"
}
The second I2C port
 */
/*JSON{
  "type" : "object",
  "name" : "I2C3",
  "instanceof" : "I2C",
  "#if" : "I2C_COUNT>=3"
}
The third I2C port
 */

/*JSON{
  "type" : "method",
  "class" : "I2C",
  "name" : "setup",
  "generate" : "jswrap_i2c_setup",
  "params" : [
    ["options","JsVar",["An optional structure containing extra information on initialising the I2C port","```{scl:pin, sda:pin, bitrate:100000}```","You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `I2C` marker. Note that 400000kHz is the maximum bitrate for most parts."]]
  ]
}
Set up this I2C port

If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral)
 */
void jswrap_i2c_setup(JsVar *parent, JsVar *options) {
  IOEventFlags device = jsiGetDeviceFromClass(parent);
  JshI2CInfo inf;
  if (jsi2cPopulateI2CInfo(&inf, options)) {
    if (DEVICE_IS_I2C(device)) {
      jshI2CSetup(device, &inf);
    } else if (device == EV_NONE) {
#ifndef SAVE_ON_FLASH
      // software mode - at least configure pins properly
      if (inf.pinSCL != PIN_UNDEFINED) {
        jshPinSetValue(inf.pinSCL, 1);
        jshPinSetState(inf.pinSCL,  JSHPINSTATE_GPIO_OUT_OPENDRAIN_PULLUP);
      }
      if (inf.pinSDA != PIN_UNDEFINED) {
        jshPinSetValue(inf.pinSDA, 1);
        jshPinSetState(inf.pinSDA,  JSHPINSTATE_GPIO_OUT_OPENDRAIN_PULLUP);
      }
#endif
    }
    // Set up options, so we can initialise it on startup
    if (options)
      jsvUnLock(jsvSetNamedChild(parent, options, DEVICE_OPTIONS_NAME));
    else
      jsvObjectRemoveChild(parent, DEVICE_OPTIONS_NAME);
  }
}

static NO_INLINE int i2c_get_address(JsVar *address, bool *sendStop) {
  *sendStop = true;
  if (jsvIsObject(address)) {
    JsVar *stopVar = jsvObjectGetChild(address, "stop", 0);
    if (stopVar) *sendStop = jsvGetBoolAndUnLock(stopVar);
    return jsvGetIntegerAndUnLock(jsvObjectGetChild(address, "address", 0));
  } else
    return jsvGetInteger(address);
}

/*JSON{
  "type" : "method",
  "class" : "I2C",
  "name" : "writeTo",
  "generate" : "jswrap_i2c_writeTo",
  "params" : [
    ["address","JsVar","The 7 bit address of the device to transmit to, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal."],
    ["data","JsVarArray","One or more items to write. May be ints, strings, arrays, or objects of the form `{data: ..., count:#}`."]
  ]
}
Transmit to the slave device with the given address. This is like Arduino's beginTransmission, write, and endTransmission rolled up into one.
 */

void jswrap_i2c_writeTo(JsVar *parent, JsVar *addressVar, JsVar *args) {
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  bool sendStop = true;
  int address = i2c_get_address(addressVar, &sendStop);

  JSV_GET_AS_CHAR_ARRAY( dataPtr, dataLen, args);

  if (dataPtr && dataLen) {
    if (DEVICE_IS_I2C(device)) {
      jshI2CWrite(device, (unsigned char)address, (int)dataLen, (unsigned char*)dataPtr, sendStop);
    } else if (device == EV_NONE) {
#ifndef SAVE_ON_FLASH
      // software
      JshI2CInfo inf;
      JsVar *options = jsvObjectGetChild(parent, DEVICE_OPTIONS_NAME, 0);
      if (jsi2cPopulateI2CInfo(&inf, options)) {
        inf.started = jsvGetBoolAndUnLock(jsvObjectGetChild(parent, "started", 0));
        jsi2cWrite(&inf, (unsigned char)address, (int)dataLen, (unsigned char*)dataPtr, sendStop);
      }
      jsvUnLock2(jsvObjectSetChild(parent, "started", jsvNewFromBool(inf.started)), options);
#endif
    }
  }
}

/*JSON{
  "type" : "method",
  "class" : "I2C",
  "name" : "readFrom",
  "generate" : "jswrap_i2c_readFrom",
  "params" : [
    ["address","JsVar","The 7 bit address of the device to request bytes from, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal."],
    ["quantity","int32","The number of bytes to request"]
  ],
  "return" : ["JsVar","The data that was returned - as a Uint8Array"],
  "return_object" : "Uint8Array"
}
Request bytes from the given slave device, and return them as a Uint8Array (packed array of bytes). This is like using Arduino Wire's requestFrom, available and read functions.  Sends a STOP
 */
JsVar *jswrap_i2c_readFrom(JsVar *parent, JsVar *addressVar, int nBytes) {
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  bool sendStop = true;
  int address = i2c_get_address(addressVar, &sendStop);

  if (nBytes<=0)
    return 0;
  if ((unsigned int)nBytes+256 > jsuGetFreeStack()) {
    jsExceptionHere(JSET_ERROR, "Not enough free stack to receive this amount of data");
    return 0;
  }
  unsigned char *buf = (unsigned char *)alloca((size_t)nBytes);

  if (DEVICE_IS_I2C(device)) {
    jshI2CRead(device, (unsigned char)address, nBytes, buf, sendStop);
  } else if (device == EV_NONE) {
#ifndef SAVE_ON_FLASH
    // software
    JshI2CInfo inf;
    JsVar *options = jsvObjectGetChild(parent, DEVICE_OPTIONS_NAME, 0);
    if (jsi2cPopulateI2CInfo(&inf, options)) {
      inf.started = jsvGetBoolAndUnLock(jsvObjectGetChild(parent, "started", 0));
      jsi2cRead(&inf, (unsigned char)address, nBytes, buf, sendStop);
    }
    jsvUnLock2(jsvObjectSetChild(parent, "started", jsvNewFromBool(inf.started)), options);
#endif
  } else return 0;

  JsVar *array = jsvNewTypedArray(ARRAYBUFFERVIEW_UINT8, nBytes);
  if (array) {
    JsvArrayBufferIterator it;
    jsvArrayBufferIteratorNew(&it, array, 0);
    unsigned int i;
    for (i=0;i<(unsigned)nBytes;i++) {
      jsvArrayBufferIteratorSetByteValue(&it, (char)buf[i]);
      jsvArrayBufferIteratorNext(&it);
    }
    jsvArrayBufferIteratorFree(&it);
  }
  return array;
}


text:
+++
# Add a title in the format . . .
title = ""

# Date is added automatically -- don't edit this part!
date = {{ .Date }}

# A 1-2 sentence summary of the quirk
summary = ""

# Tags -- instructions below!
tags = ["Flare",
        "CSS",
        "v2017r2",
        "Win10",
        "online", "print",
        "XML editor"]

######################################################################
# Delete existing tags and attach at least 1 tag from each category: #
######################################################################

# MadCap Product: Flare, Analyzer, Capture, Lingo, Mimic, Central
# File type: Conditions, CSS, Glossary, Image, JS, Masterpage, Page Layout, Relationship Table, Skins, Snippet, Target, TOC, Topic, Variables, CSH
# Flare version: v10-, v11, v12, v2017r2, v2017r2
# Operating system: Win7, Win8, Win10
# Output type: online, print
# UI element/module: XML editor, text editor, content explorer, project organizer, stylesheet editor, source control

# Default draft value is true; change to false when ready to publish.
draft = true
+++

<!-- overview of quirk -->
## Overview

If . . . then . . .

<!-- the workaround for your quirk-->
## Workaround


text:
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_RCP.hpp>

// FRENSIE Includes
#include "MonteCarlo_UnitTestHarnessExtensions.hpp"
#include "MonteCarlo_KleinNishinaPhotonScatteringDistribution.hpp"
#include "Utility_RandomNumberGenerator.hpp"

//---------------------------------------------------------------------------//
// Testing Variables
//---------------------------------------------------------------------------//

Teuchos::RCP<MonteCarlo::PhotonScatteringDistribution>
  distribution( new MonteCarlo::KleinNishinaPhotonScatteringDistribution() );

//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that distribution can be evaluated
TEUCHOS_UNIT_TEST( KleinNishinaPhotonScatteringDistribution, evaluate )
{
  double dist_value = distribution->evaluate(
			 Utility::PhysicalConstants::electron_rest_mass_energy,
			 1.0 );

  TEST_FLOATING_EQUALITY( dist_value, 4.9893440508834e-1, 1e-12 );

  dist_value = distribution->evaluate(
			 Utility::PhysicalConstants::electron_rest_mass_energy,
			 -1.0 );

  TEST_FLOATING_EQUALITY( dist_value, 9.2395260201544e-2, 1e-12 );

  dist_value = distribution->evaluate( 1.0, 1.0 );

  TEST_FLOATING_EQUALITY( dist_value, 4.989344050883251e-1, 1e-15 );

  dist_value = distribution->evaluate( 1.0, 0.0 );

  TEST_FLOATING_EQUALITY( dist_value, 6.54837903834309e-2, 1e-15 );

  dist_value = distribution->evaluate( 1.0, -1.0 );

  TEST_FLOATING_EQUALITY( dist_value, 5.287012135320711e-2, 1e-15 );
}

//---------------------------------------------------------------------------//
// Check that the distribution PDF can be evaluated
TEUCHOS_UNIT_TEST( KleinNishinaPhotonScatteringDistribution, evaluatePDF )
{
  double pdf_value = distribution->evaluatePDF(
			 Utility::PhysicalConstants::electron_rest_mass_energy,
			 1.0 );

  TEST_FLOATING_EQUALITY( pdf_value, 1.7412387289976, 1e-12 );

  pdf_value = distribution->evaluatePDF(
			 Utility::PhysicalConstants::electron_rest_mass_energy,
			 -1.0 );

  TEST_FLOATING_EQUALITY( pdf_value, 0.32245161648103, 1e-12 );

  pdf_value = distribution->evaluatePDF( 1.0, 1.0 );

  TEST_FLOATING_EQUALITY( pdf_value, 2.3622907264473127, 1e-15 );

  pdf_value = distribution->evaluatePDF( 1.0, 0.0 );

  TEST_FLOATING_EQUALITY( pdf_value, 0.3100442646924977, 1e-15 );

  pdf_value = distribution->evaluatePDF( 1.0, -1.0 );

  TEST_FLOATING_EQUALITY( pdf_value, 0.2503226799056189, 1e-15 );
}

//---------------------------------------------------------------------------//
// Check that the integrated cross section can be evaluated
TEUCHOS_UNIT_TEST( KleinNishinaPhotonScatteringDistribution,
		   evaluateIntegratedCrossSection )
{
  double cross_section = distribution->evaluateIntegratedCrossSection(
			 Utility::PhysicalConstants::electron_rest_mass_energy,
			 1e-6 );

  TEST_FLOATING_EQUALITY( cross_section, 2.8653991941448027e-1, 1e-15 );

  cross_section = distribution->evaluateIntegratedCrossSection( 1.0, 1e-6 );

  TEST_FLOATING_EQUALITY( cross_section, 2.1120787526380407e-1, 1e-15 );

  cross_section = distribution->evaluateIntegratedCrossSection( 20.0, 1e-6 );

  TEST_FLOATING_EQUALITY( cross_section, 3.02498575770817e-2, 1e-15 );
}

//---------------------------------------------------------------------------//
// Check that the outgoing energy and direction can be sampled
TEUCHOS_UNIT_TEST( KleinNishinaPhotonScatteringDistribution, sample )
{
  double outgoing_energy, scattering_angle_cosine;

  // Left branch of Kahn's method
  std::vector<double> fake_stream( 6 );
  fake_stream[0] = 0.27;
  fake_stream[1] = 0.25;
  fake_stream[2] = 0.90; // reject
  fake_stream[3] = 0.10;
  fake_stream[4] = 0.50;
  fake_stream[5] = 0.999;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  distribution->sample( Utility::PhysicalConstants::electron_rest_mass_energy,
			outgoing_energy,
			scattering_angle_cosine );

  TEST_FLOATING_EQUALITY(
		       outgoing_energy,
		       Utility::PhysicalConstants::electron_rest_mass_energy/2,
		       1e-15 );
  UTILITY_TEST_FLOATING_EQUALITY( scattering_angle_cosine, 0.0, 1e-15 );

  // Right branch of Kahn's method
  fake_stream[0] = 0.273;
  fake_stream[1] = 0.5;
  fake_stream[2] = 0.459; // reject
  fake_stream[3] = 0.80;
  fake_stream[4] = 0.25;
  fake_stream[5] = 0.25;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  distribution->sample( Utility::PhysicalConstants::electron_rest_mass_energy,
			outgoing_energy,
			scattering_angle_cosine );

  TEST_FLOATING_EQUALITY(
		       outgoing_energy,
		       Utility::PhysicalConstants::electron_rest_mass_energy/2,
		       1e-15 );
  UTILITY_TEST_FLOATING_EQUALITY( scattering_angle_cosine, 0.0, 1e-15 );

  // Koblinger's Method
  fake_stream.resize( 8 );
  fake_stream[0] = 0.120;
  fake_stream[1] = 0.2;
  fake_stream[2] = 0.698;
  fake_stream[3] = 0.4;
  fake_stream[4] = 0.818;
  fake_stream[5] = 0.6;
  fake_stream[6] = 0.90;
  fake_stream[7] = 0.8;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  // Sample 1st term
  distribution->sample( 3.1,
			outgoing_energy,
			scattering_angle_cosine );

  TEST_FLOATING_EQUALITY( outgoing_energy, 0.9046816718380433, 1e-12 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine, 0.6, 1e-15 );

  // Sample the 2nd term
  distribution->sample( 3.1,
			outgoing_energy,
			scattering_angle_cosine );

  TEST_FLOATING_EQUALITY( outgoing_energy, 1.1066615373683126, 1e-15 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine,
			  0.7030902148167004,
			  1e-15 );

  // Sample the 3rd term
  distribution->sample( 3.1,
			outgoing_energy,
			scattering_angle_cosine );

  TEST_FLOATING_EQUALITY( outgoing_energy, 1.9544179334621479, 1e-12 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine,
			  0.9033799968311882,
			  1e-15 );

  // Sample the 4th term
  distribution->sample( 3.1,
			outgoing_energy,
			scattering_angle_cosine );

  TEST_FLOATING_EQUALITY( outgoing_energy, 1.4023457957281122, 1e-15 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine,
			  0.8004496947064347,
			  1e-15 );

  Utility::RandomNumberGenerator::unsetFakeStream();
}

//---------------------------------------------------------------------------//
// Check that the outgoing energy and direction can be sampled and the trials
// can be recorded
TEUCHOS_UNIT_TEST( KleinNishinaPhotonScatteringDistribution,
		   sampleAndRecordTrials )
{
  double outgoing_energy, scattering_angle_cosine;
  unsigned trials = 0;

  // Left branch of Kahn's method
  std::vector<double> fake_stream( 6 );
  fake_stream[0] = 0.27;
  fake_stream[1] = 0.25;
  fake_stream[2] = 0.90; // reject
  fake_stream[3] = 0.10;
  fake_stream[4] = 0.50;
  fake_stream[5] = 0.999;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  distribution->sampleAndRecordTrials(
			 Utility::PhysicalConstants::electron_rest_mass_energy,
			 outgoing_energy,
			 scattering_angle_cosine,
			 trials );

  TEST_FLOATING_EQUALITY(
		       outgoing_energy,
		       Utility::PhysicalConstants::electron_rest_mass_energy/2,
		       1e-15 );
  UTILITY_TEST_FLOATING_EQUALITY( scattering_angle_cosine, 0.0, 1e-15 );
  TEST_EQUALITY_CONST( 1.0/trials, 0.5 );

  // Right branch of Kahn's method
  fake_stream[0] = 0.273;
  fake_stream[1] = 0.5;
  fake_stream[2] = 0.459; // reject
  fake_stream[3] = 0.80;
  fake_stream[4] = 0.25;
  fake_stream[5] = 0.25;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  distribution->sampleAndRecordTrials(
			Utility::PhysicalConstants::electron_rest_mass_energy,
			outgoing_energy,
			scattering_angle_cosine,
			trials );

  TEST_FLOATING_EQUALITY(
		       outgoing_energy,
		       Utility::PhysicalConstants::electron_rest_mass_energy/2,
		       1e-15 );
  UTILITY_TEST_FLOATING_EQUALITY( scattering_angle_cosine, 0.0, 1e-15 );
  TEST_EQUALITY_CONST( 2.0/trials, 0.5 );

  // Koblinger's Method
  fake_stream.resize( 8 );
  fake_stream[0] = 0.120;
  fake_stream[1] = 0.2;
  fake_stream[2] = 0.698;
  fake_stream[3] = 0.4;
  fake_stream[4] = 0.818;
  fake_stream[5] = 0.6;
  fake_stream[6] = 0.90;
  fake_stream[7] = 0.8;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  trials = 0;

  // Sample 1st term
  distribution->sampleAndRecordTrials( 3.1,
				       outgoing_energy,
				       scattering_angle_cosine,
				       trials );

  TEST_FLOATING_EQUALITY( outgoing_energy, 0.9046816718380433, 1e-12 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine, 0.6, 1e-15 );
  TEST_EQUALITY_CONST( 1.0/trials, 1.0 );

  // Sample the 2nd term
  distribution->sampleAndRecordTrials( 3.1,
				       outgoing_energy,
				       scattering_angle_cosine,
				       trials );

  TEST_FLOATING_EQUALITY( outgoing_energy, 1.1066615373683126, 1e-15 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine,
			  0.7030902148167004,
			  1e-15 );
  TEST_EQUALITY_CONST( 2.0/trials, 1.0 );

  // Sample the 3rd term
  distribution->sampleAndRecordTrials( 3.1,
				       outgoing_energy,
				       scattering_angle_cosine,
				       trials );

  TEST_FLOATING_EQUALITY( outgoing_energy, 1.9544179334621479, 1e-12 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine,
			  0.9033799968311882,
			  1e-15 );
  TEST_EQUALITY_CONST( 3.0/trials, 1.0 );

  // Sample the 4th term
  distribution->sampleAndRecordTrials( 3.1,
				       outgoing_energy,
				       scattering_angle_cosine,
				       trials );

  TEST_FLOATING_EQUALITY( outgoing_energy, 1.4023457957281122, 1e-15 );
  TEST_FLOATING_EQUALITY( scattering_angle_cosine,
			  0.8004496947064347,
			  1e-15 );
  TEST_EQUALITY_CONST( 4.0/trials, 1.0 );

  Utility::RandomNumberGenerator::unsetFakeStream();
}

//---------------------------------------------------------------------------//
// Check that a photon can be randomly scattered
TEUCHOS_UNIT_TEST( KleinNishinaPhotonScatteringDistribution, scatterPhoton )
{
  MonteCarlo::PhotonState photon( 0 );
  photon.setEnergy( Utility::PhysicalConstants::electron_rest_mass_energy );
  photon.setDirection( 0.0, 0.0, 1.0 );

  MonteCarlo::ParticleBank bank;

  MonteCarlo::SubshellType shell_of_interaction;

  // Left branch of Kahn's method
  std::vector<double> fake_stream( 7 );
  fake_stream[0] = 0.27;
  fake_stream[1] = 0.25;
  fake_stream[2] = 0.90; // reject
  fake_stream[3] = 0.10;
  fake_stream[4] = 0.50;
  fake_stream[5] = 0.999;
  fake_stream[6] = 0.0;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  distribution->scatterPhoton( photon, bank, shell_of_interaction );

  TEST_FLOATING_EQUALITY(
		       photon.getEnergy(),
		       Utility::PhysicalConstants::electron_rest_mass_energy/2,
		       1e-15 );
  UTILITY_TEST_FLOATING_EQUALITY( photon.getZDirection(), 0.0, 1e-15 );
  TEST_EQUALITY_CONST( bank.size(), 0 );
  TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::UNKNOWN_SUBSHELL );

  // Right branch of Kahn's method
  fake_stream[0] = 0.273;
  fake_stream[1] = 0.5;
  fake_stream[2] = 0.459; // reject
  fake_stream[3] = 0.80;
  fake_stream[4] = 0.25;
  fake_stream[5] = 0.25;
  fake_stream[6] = 0.0; // azimuthal angle

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  photon.setEnergy( Utility::PhysicalConstants::electron_rest_mass_energy );
  photon.setDirection( 0.0, 0.0, 1.0 );

  distribution->scatterPhoton( photon, bank, shell_of_interaction );

  TEST_FLOATING_EQUALITY(
		       photon.getEnergy(),
		       Utility::PhysicalConstants::electron_rest_mass_energy/2,
		       1e-15 );
  UTILITY_TEST_FLOATING_EQUALITY( photon.getZDirection(), 0.0, 1e-15 );
  TEST_EQUALITY_CONST( bank.size(), 0 );
  TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::UNKNOWN_SUBSHELL );

  // Koblinger's Method
  fake_stream.resize( 12 );
  fake_stream[0] = 0.120;
  fake_stream[1] = 0.2;
  fake_stream[2] = 0.0;
  fake_stream[3] = 0.698;
  fake_stream[4] = 0.4;
  fake_stream[5] = 0.0;
  fake_stream[6] = 0.818;
  fake_stream[7] = 0.6;
  fake_stream[8] = 0.0;
  fake_stream[9] = 0.90;
  fake_stream[10] = 0.8;
  fake_stream[11] = 0.0;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  photon.setEnergy( 3.1 );
  photon.setDirection( 0.0, 0.0, 1.0 );

  // Sample 1st term
  distribution->scatterPhoton( photon, bank, shell_of_interaction );

  TEST_FLOATING_EQUALITY( photon.getEnergy(), 0.9046816718380433, 1e-12 );
  TEST_FLOATING_EQUALITY( photon.getZDirection(), 0.6, 1e-15 );
  TEST_EQUALITY_CONST( bank.size(), 0 );
  TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::UNKNOWN_SUBSHELL );

  photon.setEnergy( 3.1 );
  photon.setDirection( 0.0, 0.0, 1.0 );

  // Sample the 2nd term
  distribution->scatterPhoton( photon, bank, shell_of_interaction );

  TEST_FLOATING_EQUALITY( photon.getEnergy(), 1.1066615373683126, 1e-15 );
  TEST_FLOATING_EQUALITY( photon.getZDirection(),
			  0.7030902148167004,
			  1e-15 );
  TEST_EQUALITY_CONST( bank.size(), 0 );
  TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::UNKNOWN_SUBSHELL );

  photon.setEnergy( 3.1 );
  photon.setDirection( 0.0, 0.0, 1.0 );

  // Sample the 3rd term
  distribution->scatterPhoton( photon, bank, shell_of_interaction );

  TEST_FLOATING_EQUALITY( photon.getEnergy(), 1.9544179334621479, 1e-12 );
  TEST_FLOATING_EQUALITY( photon.getZDirection(),
			  0.9033799968311882,
			  1e-15 );
  TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::UNKNOWN_SUBSHELL );

  photon.setEnergy( 3.1 );
  photon.setDirection( 0.0, 0.0, 1.0 );

  // Sample the 4th term
  distribution->scatterPhoton( photon, bank, shell_of_interaction );

  TEST_FLOATING_EQUALITY( photon.getEnergy(), 1.4023457957281122, 1e-15 );
  TEST_FLOATING_EQUALITY( photon.getZDirection(),
			  0.8004496947064347,
			  1e-15 );
  TEST_EQUALITY_CONST( bank.size(), 0 );
  TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::UNKNOWN_SUBSHELL );

  Utility::RandomNumberGenerator::unsetFakeStream();
}

//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char** argv )
{
  // Initialize the random number generator
  Utility::RandomNumberGenerator::createStreams();

  Teuchos::GlobalMPISession mpiSession( &argc, &argv );
  return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv );
}

//---------------------------------------------------------------------------//
// end tstKleinNishinaPhotonScatteringDistribution.cpp
//---------------------------------------------------------------------------//


text:
let crypto;
try {
    crypto = require('crypto');
} catch (err) {
    console.error('crypto support is disabled !');
}

const readline = require('readline');
const yaml = require('node-yaml');
const fs = require('fs');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
const hash = crypto.createHash('sha256');

function updateParam(hashStr) {
    const rootPathParam = 'config/param.yml';
    const relativePathParam = '../config/param.yml';
    if (!fs.existsSync(rootPathParam)) {
        console.error('param.yml do not exist !\n');
        return;
    }

    let yamlData = yaml.readSync(relativePathParam);
    console.log('Updating param.yml... \n');
    yamlData.passModalHash = hashStr;
    yaml.writeSync(relativePathParam, yamlData);
    console.log('Done ! \n');
}

rl.question('Set modal password : ', (answer) => {
    hash.write(answer);
    console.log('\n');
    updateParam(hash.digest('hex'));
    rl.close();
});


text:
// ensure we get the posix version of dirname by including this first
#include <libgen.h>

#include "configuration.h"
#include "util.h"
#include "get_executable.h"

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define MAX_SIZE 10

static const char COMMENT_BEGIN_CHAR = '#';
static const char SECTION_LINE_BEGIN_CHAR = '[';
static const char SECTION_LINE_END_CHAR = ']';

//clean up method for freeing section
void free_section(struct section *section) {
  int i = 0;
  for (i = 0; i < section->size; i++) {
    if (section->kv_pairs[i]->key != NULL) {
      free((void *) section->kv_pairs[i]->key);
    }
    if (section->kv_pairs[i]->value != NULL) {
      free((void *) section->kv_pairs[i]->value);
    }
    free(section->kv_pairs[i]);
  }
  if (section->kv_pairs) {
    free(section->kv_pairs);
    section->kv_pairs = NULL;
  }
  if (section->name) {
    free(section->name);
    section->name = NULL;
  }
  section->size = 0;
  free(section);
}

//clean up method for freeing configuration
void free_configuration(struct configuration *cfg) {
  int i = 0;
  for (i = 0; i < cfg->size; i++) {
    if (cfg->sections[i] != NULL) {
      free_section(cfg->sections[i]);
    }
  }
  if (cfg->sections) {
    free(cfg->sections);
  }
  cfg->size = 0;
}

/**
 * Is the file/directory only writable by root.
 * Returns 1 if true
 */
static int is_only_root_writable(const char *file) {
  struct stat file_stat;
  if (stat(file, &file_stat) != 0) {
    fprintf(ERRORFILE, "Can't stat file %s - %s\n", file, strerror(errno));
    return 0;
  }
  if (file_stat.st_uid != 0) {
    fprintf(ERRORFILE, "File %s must be owned by root, but is owned by %" PRId64 "\n",
            file, (int64_t) file_stat.st_uid);
    return 0;
  }
  if ((file_stat.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
    fprintf(ERRORFILE,
            "File %s must not be world or group writable, but is %03lo\n",
            file, (unsigned long) file_stat.st_mode & (~S_IFMT));
    return 0;
  }
  return 1;
}

/**
 * Return a string with the configuration file path name resolved via realpath(3)
 *
 * NOTE: relative path names are resolved relative to the second argument not getwd(3)
 */
char *resolve_config_path(const char *file_name, const char *root) {
  const char *real_fname = NULL;
  char buffer[EXECUTOR_PATH_MAX * 2 + 1];

  if (file_name[0] == '/') {
    real_fname = file_name;
  } else if (realpath(root, buffer) != NULL) {
    strncpy(strrchr(buffer, '/') + 1, file_name, EXECUTOR_PATH_MAX);
    real_fname = buffer;
  }

#ifdef HAVE_CANONICALIZE_FILE_NAME
  char * ret = (real_fname == NULL) ? NULL : canonicalize_file_name(real_fname);
#else
  char *ret = (real_fname == NULL) ? NULL : realpath(real_fname, NULL);
#endif
#ifdef DEBUG
  fprintf(stderr,"ret = %s\n", ret);
  fprintf(stderr, "resolve_config_path(file_name=%s,root=%s)=%s\n",
          file_name, root ? root : "null", ret ? ret : "null");
#endif
  return ret;
}

/**
 * Ensure that the configuration file and all of the containing directories
 * are only writable by root. Otherwise, an attacker can change the
 * configuration and potentially cause damage.
 * returns 0 if permissions are ok
 */
int check_configuration_permissions(const char *file_name) {
  if (!file_name) {
    return -1;
  }

  // copy the input so that we can modify it with dirname
  char *dir = strdup(file_name);
  if (!dir) {
    fprintf(stderr, "Failed to make a copy of filename in %s.\n", __func__);
    return -1;
  }

  char *buffer = dir;
  do {
    if (!is_only_root_writable(dir)) {
      free(buffer);
      return -1;
    }
    dir = dirname(dir);
  } while (strcmp(dir, "/") != 0);
  free(buffer);
  return 0;
}

/**
 * Read a line from the the config file and return it without the newline.
 * The caller must free the memory allocated.
 */
static char *read_config_line(FILE *conf_file) {
  char *line = NULL;
  size_t linesize = 100000;
  ssize_t size_read = 0;
  size_t eol = 0;

  line = (char *) malloc(linesize);
  if (line == NULL) {
    fprintf(ERRORFILE, "malloc failed while reading configuration file.\n");
    exit(OUT_OF_MEMORY);
  }
  size_read = getline(&line, &linesize, conf_file);

  //feof returns true only after we read past EOF.
  //so a file with no new line, at last can reach this place
  //if size_read returns negative check for eof condition
  if (size_read == -1) {
    free(line);
    line = NULL;
    if (!feof(conf_file)) {
      fprintf(ERRORFILE, "Line read returned -1 without eof\n");
      exit(INVALID_CONFIG_FILE);
    }
  } else {
    eol = strlen(line) - 1;
    if (line[eol] == '\n') {
      //trim the ending new line
      line[eol] = '\0';
    }
  }
  return line;
}

/**
 * Return if the given line is a comment line.
 *
 * @param line the line to check
 *
 * @return 1 if the line is a comment line, 0 otherwise
 */
static int is_comment_line(const char *line) {
  if (line != NULL) {
    return (line[0] == COMMENT_BEGIN_CHAR);
  }
  return 0;
}

/**
 * Return if the given line is a section start line.
 *
 * @param line the line to check
 *
 * @return 1 if the line is a section start line, 0 otherwise
 */
static int is_section_start_line(const char *line) {
  size_t len = 0;
  if (line != NULL) {
    len = strlen(line) - 1;
    return (line[0] == SECTION_LINE_BEGIN_CHAR
            && line[len] == SECTION_LINE_END_CHAR);
  }
  return 0;
}

/**
 * Return the name of the section from the given section start line. The
 * caller must free the memory used.
 *
 * @param line the line to extract the section name from
 *
 * @return string with the name of the section, NULL otherwise
 */
static char *get_section_name(const char *line) {
  char *name = NULL;
  size_t len;

  if (is_section_start_line(line)) {
    // length of the name is the line - 2(to account for '[' and ']')
    len = strlen(line) - 2;
    name = (char *) malloc(len + 1);
    if (name == NULL) {
      fprintf(ERRORFILE, "malloc failed while reading section name.\n");
      exit(OUT_OF_MEMORY);
    }
    strncpy(name, line + sizeof(char), len);
    name[len] = '\0';
  }
  return name;
}

/**
 * Read an entry for the section from the line. Function returns 0 if an entry
 * was found, non-zero otherwise. Return values less than 0 indicate an error
 * with the config file.
 *
 * @param line the line to read the entry from
 * @param section the struct to read the entry into
 *
 * @return 0 if an entry was found
 *         <0 for config file errors
 *         >0 for issues such as empty line
 *
 */
static int read_section_entry(const char *line, struct section *section) {
  char *equaltok;
  char *temp_equaltok;
  const char *splitter = "=";
  char *buffer;
  size_t len = 0;
  if (line == NULL || section == NULL) {
    fprintf(ERRORFILE, "NULL params passed to read_section_entry");
    return -1;
  }
  len = strlen(line);
  if (len == 0) {
    return 1;
  }
  if ((section->size) % MAX_SIZE == 0) {
    section->kv_pairs = (struct kv_pair **) realloc(
        section->kv_pairs,
        sizeof(struct kv_pair *) * (MAX_SIZE + section->size));
    if (section->kv_pairs == NULL) {
      fprintf(ERRORFILE,
              "Failed re-allocating memory for configuration items\n");
      exit(OUT_OF_MEMORY);
    }
  }

  buffer = strdup(line);
  if (!buffer) {
    fprintf(ERRORFILE, "Failed to allocating memory for line, %s\n", __func__);
    exit(OUT_OF_MEMORY);
  }

  //tokenize first to get key and list of values.
  //if no equals is found ignore this line, can be an empty line also
  equaltok = strtok_r(buffer, splitter, &temp_equaltok);
  if (equaltok == NULL) {
    fprintf(ERRORFILE, "Error with line '%s', no '=' found\n", buffer);
    exit(INVALID_CONFIG_FILE);
  }
  section->kv_pairs[section->size] = (struct kv_pair *) malloc(
      sizeof(struct kv_pair));
  if (section->kv_pairs[section->size] == NULL) {
    fprintf(ERRORFILE, "Failed allocating memory for single section item\n");
    exit(OUT_OF_MEMORY);
  }
  memset(section->kv_pairs[section->size], 0,
         sizeof(struct kv_pair));
  section->kv_pairs[section->size]->key = trim(equaltok);

  equaltok = strtok_r(NULL, splitter, &temp_equaltok);
  if (equaltok == NULL) {
    // this can happen because no value was set
    // e.g. banned.users=#this is a comment
    int has_values = 1;
    if (strstr(line, splitter) == NULL) {
      fprintf(ERRORFILE, "configuration tokenization failed, error with line %s\n", line);
      has_values = 0;
    }

    // It is not a valid line, free memory.
    free((void *) section->kv_pairs[section->size]->key);
    free((void *) section->kv_pairs[section->size]);
    section->kv_pairs[section->size] = NULL;
    free(buffer);

    // Return -1 when no values
    if (!has_values) {
      return -1;
    }

    // Return 2 for comments
    return 2;
  }

#ifdef DEBUG
  fprintf(LOGFILE, "read_config : Adding conf value : %s \n", equaltok);
#endif

  section->kv_pairs[section->size]->value = trim(equaltok);
  section->size++;
  free(buffer);
  return 0;
}

/**
 * Remove any trailing comment from the supplied line. Function modifies the
 * argument provided.
 *
 * @param line the line from which to remove the comment
 */
static void trim_comment(char *line) {
  char *begin_comment = NULL;
  if (line != NULL) {
    begin_comment = strchr(line, COMMENT_BEGIN_CHAR);
    if (begin_comment != NULL) {
      *begin_comment = '\0';
    }
  }
}

/**
 * Allocate a section struct and initialize it. The memory must be freed by
 * the caller. Function calls exit if any error occurs.
 *
 * @return pointer to the allocated section struct
 *
 */
static struct section *allocate_section() {
  struct section *section = (struct section *) malloc(sizeof(struct section));
  if (section == NULL) {
    fprintf(ERRORFILE, "malloc failed while allocating section.\n");
    exit(OUT_OF_MEMORY);
  }
  section->name = NULL;
  section->kv_pairs = NULL;
  section->size = 0;
  return section;
}

/**
 * Populate the given section struct with fields from the config file.
 *
 * @param conf_file the file to read from
 * @param section pointer to the section struct to populate
 *
 */
static void populate_section_fields(FILE *conf_file, struct section *section) {
  char *line;
  long int offset = 0;
  while (!feof(conf_file)) {
    offset = ftell(conf_file);
    line = read_config_line(conf_file);
    if (line != NULL) {
      if (!is_comment_line(line)) {
        trim_comment(line);
        if (!is_section_start_line(line)) {
          if (section->name != NULL) {
            if (read_section_entry(line, section) < 0) {
              fprintf(ERRORFILE, "Error parsing line %s", line);
              exit(INVALID_CONFIG_FILE);
            }
          } else {
            fprintf(ERRORFILE, "Line '%s' doesn't belong to a section\n",
                    line);
            exit(INVALID_CONFIG_FILE);
          }
        } else {
          if (section->name == NULL) {
            section->name = get_section_name(line);
            if (strlen(section->name) == 0) {
              fprintf(ERRORFILE, "Empty section name");
              exit(INVALID_CONFIG_FILE);
            }
          } else {
            // we've reached the next section
            fseek(conf_file, offset, SEEK_SET);
            free(line);
            return;
          }
        }
      }
      free(line);
    }
  }
}

/**
 * Read the section current section from the conf file. Section start is
 * marked by lines of the form '[section-name]' and continue till the next
 * section.
 */
static struct section *read_section(FILE *conf_file) {
  struct section *section = allocate_section();
  populate_section_fields(conf_file, section);
  if (section->name == NULL) {
    free_section(section);
    section = NULL;
  }
  return section;
}

/**
 * Merge two sections and free the second one after the merge, if desired.
 * @param section1 the first section
 * @param section2 the second section
 * @param free_second_section free the second section if set
 */
static void merge_sections(struct section *section1, struct section *section2, const int free_second_section) {
  int i = 0;
  section1->kv_pairs = (struct kv_pair **) realloc(
            section1->kv_pairs,
            sizeof(struct kv_pair *) * (section1->size + section2->size));
  if (section1->kv_pairs == NULL) {
    fprintf(ERRORFILE,
                "Failed re-allocating memory for configuration items\n");
    exit(OUT_OF_MEMORY);
  }
  for (i = 0; i < section2->size; ++i) {
    section1->kv_pairs[section1->size + i] = section2->kv_pairs[i];
  }
  section1->size += section2->size;
  if (free_second_section) {
    free(section2->name);
    free(section2->kv_pairs);
    memset(section2, 0, sizeof(*section2));
    free(section2);
  }
}

int read_config(const char *file_path, struct configuration *cfg) {
  FILE *conf_file;

  if (file_path == NULL) {
    fprintf(ERRORFILE, "Null configuration filename passed in\n");
    return INVALID_CONFIG_FILE;
  }

#ifdef DEBUG
  fprintf(LOGFILE, "read_config :Conf file name is : %s \n", file_path);
#endif

  cfg->size = 0;
  conf_file = fopen(file_path, "r");
  if (conf_file == NULL) {
    fprintf(ERRORFILE, "Invalid conf file provided, unable to open file"
        " : %s \n", file_path);
    return (INVALID_CONFIG_FILE);
  }

  cfg->sections = (struct section **) malloc(
        sizeof(struct section *) * MAX_SIZE);
  if (!cfg->sections) {
    fprintf(ERRORFILE,
            "Failed to allocate memory for configuration sections\n");
    exit(OUT_OF_MEMORY);
  }

  // populate any entries in the older format(no sections)
  cfg->sections[cfg->size] = allocate_section();
  cfg->sections[cfg->size]->name = strdup("");
  populate_section_fields(conf_file, cfg->sections[cfg->size]);
  if (cfg->sections[cfg->size]) {
    if (cfg->sections[cfg->size]->size) {
      cfg->size++;
    } else {
      free_section(cfg->sections[cfg->size]);
    }
  }

  // populate entries in the sections format
  while (!feof(conf_file)) {
    cfg->sections[cfg->size] = NULL;
    struct section *new_section = read_section(conf_file);
    if (new_section != NULL) {
      struct section *existing_section =
          get_configuration_section(new_section->name, cfg);
      if (existing_section != NULL) {
        merge_sections((struct section *) existing_section, new_section, 1);
      } else {
        cfg->sections[cfg->size] = new_section;
      }
    }

    // Check if we need to expand memory for sections.
    if (cfg->sections[cfg->size]) {
      if ((cfg->size + 1) % MAX_SIZE == 0) {
        cfg->sections = (struct section **) realloc(cfg->sections,
                           sizeof(struct sections *) * (MAX_SIZE + cfg->size));
        if (cfg->sections == NULL) {
          fprintf(ERRORFILE,
                  "Failed re-allocating memory for configuration items\n");
          exit(OUT_OF_MEMORY);
        }
      }
      cfg->size++;
    }
  }

  fclose(conf_file);

  if (cfg->size == 0) {
    free_configuration(cfg);
    fprintf(ERRORFILE, "Invalid configuration provided in %s\n", file_path);
    return INVALID_CONFIG_FILE;
  }
  return 0;
}

/*
 * function used to get a configuration value.
 * The function for the first time populates the configuration details into
 * array, next time onwards used the populated array.
 *
 */
char *get_section_value(const char *key, const struct section *section) {
  int count;
  if (key == NULL || section == NULL) {
    return NULL;
  }
  for (count = 0; count < section->size; count++) {
    if (strcmp(section->kv_pairs[count]->key, key) == 0) {
      return strdup(section->kv_pairs[count]->value);
    }
  }
  return NULL;
}

/**
 * Function to return an array of values for a key.
 * Value delimiter is assumed to be a ','.
 */
char **get_section_values(const char *key, const struct section *cfg) {
  return get_section_values_delimiter(key, cfg, ",");
}

/**
 * Function to return an array of values for a key, using the specified
 delimiter.
 */
char **get_section_values_delimiter(const char *key, const struct section *cfg,
                                    const char *delim) {
  if (key == NULL || cfg == NULL || delim == NULL) {
    return NULL;
  }
  char *value = get_section_value(key, cfg);
  char **split_values = split_delimiter(value, delim);

  if (value) {
    free(value);
  }

  return split_values;
}

char *get_configuration_value(const char *key, const char *section,
                              const struct configuration *cfg) {
  const struct section *section_ptr;
  if (key == NULL || section == NULL || cfg == NULL) {
    return NULL;
  }
  section_ptr = get_configuration_section(section, cfg);
  if (section_ptr != NULL) {
    return get_section_value(key, section_ptr);
  }
  return NULL;
}

char **get_configuration_values(const char *key, const char *section,
                                const struct configuration *cfg) {
  const struct section *section_ptr;
  if (key == NULL || section == NULL || cfg == NULL) {
    return NULL;
  }
  section_ptr = get_configuration_section(section, cfg);
  if (section_ptr != NULL) {
    return get_section_values(key, section_ptr);
  }
  return NULL;
}

char **get_configuration_values_delimiter(const char *key, const char *section,
                                          const struct configuration *cfg, const char *delim) {
  const struct section *section_ptr;
  if (key == NULL || section == NULL || cfg == NULL || delim == NULL) {
    return NULL;
  }
  section_ptr = get_configuration_section(section, cfg);
  if (section_ptr != NULL) {
    return get_section_values_delimiter(key, section_ptr, delim);
  }
  return NULL;
}

struct section *get_configuration_section(const char *section,
                                          const struct configuration *cfg) {
  int i = 0;
  if (cfg == NULL || section == NULL) {
    return NULL;
  }
  for (i = 0; i < cfg->size; ++i) {
    if (strcmp(cfg->sections[i]->name, section) == 0) {
      return cfg->sections[i];
    }
  }
  return NULL;
}

/**
 * If str is a string of the form key=val, find 'key'
 */
int get_kv_key(const char *input, char *out, size_t out_len) {

  if (input == NULL)
    return -EINVAL;

  const char *split = strchr(input, '=');

  if (split == NULL)
    return -EINVAL;

  unsigned long key_len = split - input;

  if (out_len < (key_len + 1) || out == NULL)
    return -ENAMETOOLONG;

  memcpy(out, input, key_len);
  out[key_len] = '\0';

  return 0;
}

/**
 * If str is a string of the form key=val, find 'val'
 */
int get_kv_value(const char *input, char *out, size_t out_len) {

  if (input == NULL)
    return -EINVAL;

  const char *split = strchr(input, '=');

  if (split == NULL)
    return -EINVAL;

  split++; // advance past '=' to the value
  unsigned long val_len = (input + strlen(input)) - split;

  if (out_len < (val_len + 1) || out == NULL)
    return -ENAMETOOLONG;

  memcpy(out, split, val_len);
  out[val_len] = '\0';

  return 0;
}

char *get_config_path(const char *argv0) {
  char *executable_file = get_executable((char *) argv0);
  if (!executable_file) {
    fprintf(ERRORFILE, "realpath of executable: %s\n",
            errno != 0 ? strerror(errno) : "unknown");
    return NULL;
  }

  const char *orig_conf_file = HADOOP_CONF_DIR "/" CONF_FILENAME;
  char *conf_file = resolve_config_path(orig_conf_file, executable_file);
  free(executable_file);
  if (conf_file == NULL) {
    fprintf(ERRORFILE, "Configuration file %s not found.\n", orig_conf_file);
  }
  return conf_file;
}