text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>AXISJ API</title>

    <link rel="shortcut icon" href="https://www.axisj.com/sys-datas/plugins/axisj/ui/axisj.ico" type="image/x-icon" />
    <link rel="icon" href="https://www.axisj.com/sys-datas/plugins/axisj/ui/axisj.ico" type="image/x-icon" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://www.axisj.com/sys-datas/layouts/axisj/images/ax-symbol.png" />
    <link rel="apple-touch-icon-precomposed" href="https://www.axisj.com/sys-datas/layouts/axisj/images/ax-symbol.png" />

    <meta name="description" content="풀 스택 오픈소스 자바스크립트 UI 프레임워크 AXISJ JSDOC API서비스 입니다." />

        <meta name="keywords" content="AXISJ, JSDOC, API" />
        <meta name="keyword" content="AXISJ, JSDOC, API" />

    <meta property="og:title" content="AXISJ JSDOC"/>
    <meta property="og:type" content="JSDOC API"/>
    <meta property="og:image" content="http://dev.axisj.com/ui/AXJ.png"/>
    <meta property="og:site_name" content="풀 스택 오픈소스 자바스크립트 UI 프레임워크 - AXISJ"/>
    <meta property="og:url" content="http://newdoc.axisj.com"/>

    <link type="text/css" rel="stylesheet" media="only screen and (color)"  href="styles/sunburst.css">
    <link type="text/css" rel="stylesheet" media="only print" href="styles/prettify-jsdoc.css">

    <link type="text/css" rel="stylesheet" href="styles/axisjdoc.css" />
    <link rel="stylesheet" type="text/css" href="http://cdno.axisj.com/axicon/axicon.min.css" />

 AXISJ API

        <input id="search" type="text" class="form-control input-sm" placeholder="Search Documentations">

                Array

                static

            Methods

clear

convertTree

first

getIndex

getMaxObject

getMinObject

getToSeq

hasObject

last

remove

search

searchObject

                AXConfig

                static

            Members

AXContextMenu

AXEditor

AXGrid

AXInput

AXModal

AXProgress

AXReq

AXSelect

AXTab

AXTree

AXUpload5

AXValidator

mobile

weekDays

                AXContextMenu

                static

            Methods

bind

bindSetConfig

close

open

                axf

                static

            Members

browser

docTD

Event

mousewheelevt

            Methods

alert

clientHeight

clientWidth

confirm

console

copyObject

dayLen

each

encParam

get_event_target

getCookie

getId

getUniqueId

getUrlInfo

isEmpty

overwriteObject

scrollHeight

scrollWidth

setCookie

timekey

                AXPopOver

                static

            Methods

bind

bindSetConfig

close

open

                Class

                static

            Methods

create

                Date

                static

            Methods

axGetDay

getTimeAgo

print

                Error

                static

            Methods

print

                Function

                static

            Methods

argumentNames

bind

delay

                jQueryExtends

                static

            Methods

addTabs

bindAXResizable

bindChecked

bindDate

bindDateTime

bindInputDisabled

bindMoney

bindNumber

bindPlaceHolder

bindSearch

bindSegment

bindSelect

bindSelectAddOptions

bindSelectBlur

bindSelectDisabled

bindSelectFocus

bindSelectGetAnchorObject

bindSelector

bindSelectorBlur

bindSelectRemoveOptions

bindSelectSetValue

bindSelectUpdate

bindSelectUpdateOptions

bindSlider

bindSwitch

bindTab

bindTooltip

bindTwinDate

bindTwinDateTime

bindTwinSlider

closeTab

endFocus

mask

offwheel

onwheel

serializeObject

setCaret

setConfigInput

setConfigSelect

setValueInput

setValueSelect

setValueTab

unbindAXResizable

unbindDate

unbindInput

unbindSelect

unbindTab

updateTabs

                Number

                static

            Methods

abs

byte

ceil

date

div

floor

left

money

number

phone

rangeFrom

right

round

setDigit

                Object

                static

            Methods

clone

extend

isArray

isElement

isFunction

isHash

isNumber

isObject

isString

isUndefined

keys

toJSON

toJSONfn

values

                String

                static

            Methods

array

crlf

date

dec

delHtml

delScript

ecrlf

enc

getAnchorData

getByte

getFileName

lcase

left

money

number

object

phone

queryToObject

queryToObjectDec

right

setDigit

times

toColor

trim

ucase

                AXCalendar

            Members

config

            Methods

dayPageSetDay

getTime

monthPageSetMonth

printDayPage

printMonthPage

printTimePage

printYearPage

setConfig

yearPageSetYear

                AXContextMenuClass

            Methods

bind

bindSetConfig

close

open

setConfig

                AXEditor

            Methods

getContent

insertIMG

removeIMG

setConfig

setContent

                AXGrid

            Methods

ajaxGetList

appendList

bigDataSync

bigDataSyncApply

cancelEditor

changeGridView

checkedColSeq

clearSort

click

clipBoardClear

colGroupListClick

colHeadCheckBoxClick

colHeadMouseOut

colHeadMouseOver

colHeadNodeClick

colHeadResizerEnd

colHeadResizerMouseDown

colHeadResizerMouseMove

colHeadResizerMouseUp

colHeadResizerMove

colHeadToolClick

contentScrollContentSync

contentScrollEnd

contentScrollResize

contentScrollScrollEnd

contentScrollScrollMove

contentScrollScrollReady

contentScrollScrollSync

contentScrollScrollWheel

contentScrollTipOver

contentScrollTipOverMove

contentScrollTipOverOut

contentScrollTouchEnd

contentScrollTouchMove

contentScrollTouchstart

dataSync

editCell

editCellClear

fetchList

focusEditorForm

focusMove

getAddingClass

getCheckedList

getCheckedListWithIndex

getCheckedParams

getColGroup

getColHeadTd

getColSeqToHead

getDataSetFormatterValue

getEditorBody

getEditorFormatterValue

getEditorFormValue

getExcelColHeadTd

getExcelFootDataSet

getExcelFormat

getExcelHeadDataSet

getExcelItem

getExcelItemMarker

getFootDataSet

getFormatterValue

getHeadDataSet

getHeadMousePosition

getIconItem

getItem

getItemMarker

getList

getMarkerDisplay

getMobileItem

getMousePositionToContentScroll

getSelectedItem

getSortParam

getTooltipValue

getTouchPositionToContentScroll

goPageMove

gridBodyClick

gridBodyClickAct

gridBodyDBLClick

gridBodyOut

gridBodyOver

listLoadingDisplay

mergeCells

onContextmenu

onKeydown

onPageChange

openMobileConfig

printFoot

printHead

printList

pushList

redrawDataSet

redrawGrid

reloadList

removeList

removeListIndex

reorderColgroup

restoreList

saveEditor

saveEditorRequest

scrollTop

selectClear

setBody

setColHead

setConfig

setData

setDataSet

setEditCellValue

setEditor

setEditorForm

setFocus

setHeight

setList

setMobileTool

setPaging

setStatus

sortList

unbindAXbind

updateItem

updateList

validateCheck

formatter

inlineEditor

                AXInputConverter

                AXJ

            Members

config

name

            Methods

changeConfig

clearRange

getEventTarget

getMousePositon

setConfig

stopEvent

windowResize

                AXMask

            Methods

open

                AXMobileMenu

            Methods

close

open

setConfig

setHighLight

setHighLightMenu

setHighLightOriginID

setTree

                AXMobileModal

            Methods

close

open

setConfig

                AXModal

            Methods

close

loaded

open

openDiv

openNew

remove

resize

setConfig

setWidth

                AXMultiSelect

            Members

selects

            Methods

collect

getSelects

setConfig

                AXNotification

            Methods

push

                AXPopOverClass

            Methods

bind

close

open

                AXProgress

            Methods

cancel

close

initialize

restart

start

update

                AXReq

                AXReqQue

            Members

busy

que

            Methods

abort

add

start

                AXResizable

            Methods

bind

setConfig

unbind

                AXScroll

            Methods

focusElement

moveTo

scrollTop

setConfig

unbind

updateScroll

                AXSearch

            Methods

getItemId

getParam

reset

setConfig

setItemValue

submit

                AXSelectConverter

            Methods

bindSelectAddOptions

bindSelectRemoveOptions

bindSelectUpdateOptions

                AXSlideViewer

                AXTabClass

            Methods

addTabs

bind

bindTabClick

bindTabMoreClick

bindTabMove

bindTabMove

closeTab

focusingItem

getOptions

initTab

resizeCheck

setValueTab

updateTabOption

                AXTopDownMenu

            Methods

setHighLightID

setHighLightOriginID

setTree

                AXTree

            Methods

appendTree

clearFocus

click

collapseAll

expandAll

expandToggleList

getCheckedList

getFormatterValue

getSelectedList

getSelectedListParent

moveTree

relationFixedSync

removeTree

setConfig

setFocus

setList

setTree

updateTree

                AXUpload5

            Methods

getSelectUploadedList

getUploadedList

setUploadedList

                AXUserSelect

            Methods

push

                AXValidator

            Methods

add

del

getErrorElement

getErrorMessage

validate

Source: AXModal.js

/* AXISJ Javascript UI Framework */
/* http://www.axisj.com, license : http://www.axisj.com/license */

/**
 * @class AXModal
 * @classdesc 모달창을 생성하고 제어 합니다. 모달창은 window, iframe, div 세 가지로 생성할 수 있습니다.
 * @extends AXJ
 * @version v1.40
 * @author tom@axisj.com
 * @logs
 "2013-02-13 오전 10:39:17 - axmods 에서 컨버트 : tom ",
 "2013-04-08 오전 12:15:17 - resize 메소스 추가 및 버그 픽스 : tom ",
 "2013-06-20 오후 5:21:24 - open 메소드 속성에 width 조건 추가 : tom ",
 "2013-07-09 오후 4:41:48 - animateDuration 속성 추가  : tom ",
 "2013-08-21 오후 4:46:51 - openNew 버그 픽스 : tom ",
 "2013-08-22 오전 10:56:20 - resize 버그 픽스 : tom ",
 "2013-08-24 - openNew 메소드 기능 확장 : tom ",
 "2013-10-14 오전 6:54:40 - resize 기능 보강 : tom ",
 "2013-11-15 오후 4:01:29 - tom : openDiv scroll 버그 패치",
 "2013-11-18 오후 5:16:02 - tom resize 버그 패치",
 "2014-05-21 - tom : AXModal mediaQuery 속성 추가"
 "2014-06-09 tom : mediaQuery bugfix"
 "2014-08-04 tom : fix resize error"
 "2014-09-17 tom : 'add Config' scrollLock"
 "2014-11-16 tom : openDiv 메소드에 verticalAlign 속성 확장"
 "2015-03-25 root : 각 open 메소드에 closeButton 속성 확장"
 "2015-04-22 root : axdom 독립 우회 코드 변경"
 "2015-05-08 tom : loaded 메소드 추가"

 */
var AXModal = Class.create(AXJ, {
    initialize: function (AXJ_super) {
        AXJ_super();
        this.config.maskCss = "AXMask";
        this.config.windowBoxCss = "AXModalBox";
        this.config.padding = "0";
        this.config.defaultTop = 10;
        this.config.animateDuration = 300;
        this.config.autoHide = false;
        this.config.windowID = "AXModal" + AXUtil.timekey();
        this.config.contentDivClass = (AXConfig.AXModal) ? AXConfig.AXModal.contentDivClass : "bodyHeightDiv";
        this.config.displayLoading = true;
        this.config.viewMode = "dx";
        this.config.opendModalID = "";
        this.config.scrollLock = false;
        this.config.closeButton = true;
    },
    /**
     * 모달의 기본 환경설정값을 셋팅합니다.
     * @method AXModal.setConfig
     * @param {Object} modalConfig
     * @example
     * ```js
     * var myModal = new AXModal();
     * var modalConfig = {
     *     animateDuration: {Number} [300],
     *     contentDivClass: {String} ["bodyHeightDiv"] - iframe 모달의 창이 오픈된 경우 iframe 의 높이를 정확히 제어하기 위해 컨텐츠 전체를 감싸는 대상에 지정한 className 값,
     *     defaultTop: {Number} [10] - 모달창 포지션 top,
     *     displayLoading: {Boolean} [true] - 모달이 오픈될 때 로딩 표시 여부,
     *     maskCss: "AXMask" - 배경 mask div의 css,
     *     opendModalID: {String} - 모달 ID,
     *     padding: {(String|Number)} ["0"] - 모달 padding 값,
     *     viewMode: {String} ["dx"],
     *     width: {(String|Number)} - 모달의 기본 너비,
     *     windowBoxCss: {String} ["AXModalBox"] - 모달을 감싸는 제일 바깥쪽 div의 css,
     *     windowID: {String} ["AXModal" + timekey] - 모달 식별 아이디,
     *     onclose: {Function} - 모달창이 닫힐 때 이벤트,
     *     closeButton: {Boolean} [true] - 모달창 닫기버튼의 노출 여부
     * };
     * myModal.setConfig(modalConfig);
     * ```
     */
    init: function () {
        var cfg = this.config;
        this.mask = axdom("<div class=\"" + cfg.maskCss + "\"></div>");
        if (cfg.mediaQuery) {
            var _viewMode = "", clientWidth = axf.clientWidth();
            axf.each(cfg.mediaQuery, function (k, v) {
                if (Object.isObject(v)) {

                    if(v.min != undefined && v.max != undefined){
                        if (v.min <= clientWidth && clientWidth <= v.max) {
                            _viewMode = (k == "dx") ? "dx" : "mx";
                            return false;
                        }
                    }else{
                        if (v.min <= clientWidth) {
                            _viewMode = (k == "dx") ? "dx" : "mx";
                            return false;
                        }
                    }
                }
            });
            if (_viewMode != "") {
                cfg.viewMode = _viewMode;
            }
        }

    },
    /**
     * @method AXModal.setWidth
     * @param {(String|Number)} - 모달의 기본 너비 pixel({Number}) or percent({String})
     * @description 모달의 기본 너비 속성을 변경하고 창이 열려있는 상태이면 동적으로 창의 크기도 변경합니다. (단, openDIV 로 모달이 오픈된 경우는 해당사항 없음)
     * @example
     * ```js
     * myModal.setWidth(800);
     * myModal.setWidth("80%");
     * ```
     */
    setWidth: function (width) {
        var cfg = this.config;
        if (width) {
            cfg.width = width;
            this.config.fixedWidth = true;
        } else {
            cfg.width = undefined;
            this.config.fixedWidth = false;
        }

        axdom("#" + cfg.windowID).css({ width: width });
        var maskWidth = axdom("#" + cfg.windowID).outerWidth();
        var maskLeft = (axdom(document.body).width() / 2) - (maskWidth / 2);
        if (maskLeft < 0) maskLeft = 0;
        axdom("#" + cfg.windowID).css({ left: maskLeft });
    },
    /**
     * @method AXModal.open
     * @param {Object} - configs
     * @description iframe 을 내장하는 모달 창을 오픈합니다.
     * @example
     * ```js
     * var configs = {
     *     url: {String} - 모달창의 URL,
     *     pars: {(Object|Array)} - 모달창 URL 에 전달 될 파라미터,
     *     method: {String} ["post"] -파라미터 전달방식,
     *     top: {Number} [scrollTop + 100] - 모달창 포지션 top,
     *     width: {(String|Number)} - 모달창 너비,
     *     closeByEscKey: {Boolean} [false] - 모달창 닫기를 esc 키로 닫을 지 여부,
     *     closeButton: {Boolean} [true] - 모달창 닫기버튼의 노출 여부
     * }
     * myModal.open(configs);
     * ```
     */
    open: function (http) {
        var cfg = this.config;

        if (this._windowOpend) return;

        mask.open();
        this.winID = "mdw" + AXUtil.timekey();
        this.frmID = "frm" + AXUtil.timekey();

        var maskWidth, maskLeft;
        if (this.config.width) {
            maskWidth = this.config.width;
            maskLeft = (axdom(document.body).width() / 2) - (this.config.width / 2);
            this.config.fixedWidth = true;
        } else {
            maskWidth = axdom(document.body).width() - 50;
            maskLeft = 10;
            this.config.fixedWidth = false;
        }

        if (http.width) {
            maskWidth = http.width;
            maskLeft = (axdom(document.body).width() / 2) - (http.width / 2);
            this.config.fixedWidth = true;
        }

        var maskTop = this.config.defaultTop;
        if (http.top != undefined) {
            maskTop = http.top;
        } else {
            maskTop = axdom(window).scrollTop() + 100;
        }
        if (maskLeft < 0) maskLeft = 0;

        var po = [];
        po.push("<div id='" + this.config.windowID + "' class='" + this.config.windowBoxCss + "' style='top:" + maskTop + "px;left:" + maskLeft + "px;width:" + maskWidth + "px;'>");
        po.push("	<div class='windowbox' id='" + this.winID + "_box' style='padding:" + this.config.padding + "px'>");
        if (cfg.displayLoading) {
            po.push("		<div id='" + this.config.windowID + "_loading' style='position:absolute;left:0px;top:0px;width:100%;padding:50px 0px 0px 0px;' align='center'>");
            po.push("		<div class=\"AXLoading\"></div>");
            po.push("		<br/><br><span class='blue'>페이지를 로딩 중입니다. 잠시만 기다려 주세요.</span></div>");
        }

        var closeButton = (http.closeButton == undefined) ? cfg.closeButton : http.closeButton;
        if (closeButton){
            po.push("		<a id='" + this.config.windowID + "_close' class='closeBtn'>닫기</a>");
        }

        po.push("		<form name='" + this.frmID + "' method='" + (http.method || "post") + "' target='" + this.winID + "' action='" + http.url + "'>");
        po.push("		<input type='hidden' name='winID' value='" + this.winID + "' />");

        if (isNaN(http.pars.length)) {
            axdom.each(http.pars, function (key, val) {
                po.push("		<input type='hidden' name='" + key + "' value='" + val + "' />");
            });
        } else {
            axdom.each(http.pars, function () {
                axdom.each(this, function (key, val) {
                    po.push("		<input type='hidden' name='" + key + "' value='" + val + "' />");
                });
            });
        }

        if(AXConfig.AXModal.pars){
            var appendPars = {};
            if(Object.isString(AXConfig.AXModal.pars)){
                appendPars = AXConfig.AXModal.pars.queryToObject();
            }
            axdom.each(appendPars, function (key, val) {
                po.push("<input type='hidden' name='" + key + "' value='" + val + "' />");
            });
        }

        po.push("		</form>");
        po.push("		<iframe src='' name='" + this.winID + "' id='" + this.winID + "' frameborder='0' class='windowboxFrame' style='width:100%;overflow:-y:hidden;' scrolling='no'></iframe>");
        po.push("	</div>");
        po.push("</div>");

        if (this.config.appendTargetID) {
            axdom("#" + this.config.appendTargetID).append(po.join(''));
        } else {
            axdom(document.body).append(po.join(''));
        }

        axdom("#" + cfg.windowID).data("width", maskWidth);
        axdom("#" + cfg.windowID).data("top", maskTop);

        if(cfg.viewMode == "mx"){
            axdom("#" + cfg.windowID).css({ left: 0, top:axdom(window).scrollTop(), width:"100%" });
        }

        var loadingID = this.config.windowID + "_loading";
        var _winID = this.winID;
        var _frmID = this.frmID;

        document[_frmID].submit();
        var keydown = this.keydown.bind(this);

        axdom("#" + this.winID).bind("load", function () {
            var myIframe = window[_winID];

            var bodyHeight = axdom(myIframe.document).innerHeight();
            if (axdom(myIframe.document.body).find("." + cfg.contentDivClass).get(0)) {
                bodyHeight = axdom(myIframe.document.body).find("." + cfg.contentDivClass).outerHeight();
            }
            axdom(this).css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
            axdom("#" + _winID + "_box").css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
            if (cfg.displayLoading) axdom("#" + loadingID).fadeOut("slow");
            axdom("#" + _winID).addClass("loaded");

            if (http.closeByEscKey) {
                axdom(myIframe.document.body).bind("keydown.AXModal", keydown);
            }
        });

        axdom("#" + this.config.windowID + "_close").bind("click", this.close.bind(this));

        if (http.closeByEscKey) {
            axdom(document.body).bind("keydown.AXModal", keydown);
        }

        this._windowOpend = true;

        axdom(window).unbind("resize.AXModal");
        axdom(window).bind("resize.AXModal", this.onDocResize.bind(this));

        if (cfg.scrollLock == true) {
            axdom(document.body).css({'overflow':'hidden'});
        }
    },
    /**
     * @deprecated AXModal.openI
     * @see AXModal.open
     */
    openI: function (http) {
        var cfg = this.config;

        if (this._windowOpend) return;

        mask.open();
        this.winID = "mdw" + AXUtil.timekey();
        this.frmID = "frm" + AXUtil.timekey();

        var maskWidth, maskLeft;
        if (this.config.width) {
            maskWidth = this.config.width;
            maskLeft = (axdom(document.body).width() / 2) - (this.config.width / 2);
            this.config.fixedWidth = true;
        } else {
            maskWidth = axdom(document.body).width() - 50;
            maskLeft = 10;
            this.config.fixedWidth = false;
        }

        if (http.width) {
            maskWidth = http.width;
            maskLeft = (axdom(document.body).width() / 2) - (http.width / 2);
            this.config.fixedWidth = true;
        }

        var maskTop = this.config.defaultTop;
        if (http.top != undefined) {
            maskTop = http.top;
        } else {
            maskTop = axdom(window).scrollTop() + 100;
        }

        if (maskLeft < 0) maskLeft = 0;

        var po = [];
        po.push("<div id='" + this.config.windowID + "' class='" + this.config.windowBoxCss + "' style='top:" + maskTop + "px;left:" + maskLeft + "px;width:" + maskWidth + "px;'>");
        po.push("	<div class='windowbox' id='" + this.winID + "_box' style='padding:" + this.config.padding + "px'>");
        po.push("		<div id='" + this.config.windowID + "_loading' style='position:absolute;left:0px;top:0px;width:" + maskWidth + "px;padding:50px 0px 0px 0px;' align='center'>");
        po.push("		<div class=\"AXLoading\"></div>");
        po.push("		<br/><br><span class='blue'>페이지를 로딩 중입니다. 잠시만 기다려 주세요.</span></div>");

        var closeButton = (http.closeButton == undefined) ? cfg.closeButton : http.closeButton;
        if (closeButton){
            po.push("		<a href='#modsExecption' id='" + this.config.windowID + "_close' class='closeBtn'>닫기</a>");
        }

        po.push("		<form name='" + this.frmID + "' method='post' target='" + this.winID + "' action='" + http.url + "'>");
        po.push("		<input type='hidden' name='winID' value='" + this.winID + "' />");

        if (isNaN(http.pars.length)) {
            axdom.each(http.pars, function (key, val) {
                po.push("		<input type='hidden' name='" + key + "' value='" + val + "' />");
            });
        } else {
            axdom.each(http.pars, function () {
                axdom.each(this, function (key, val) {
                    po.push("		<input type='hidden' name='" + key + "' value='" + val + "' />");
                });
            });
        }

        if(AXConfig.AXModal.pars){
            var appendPars = {};
            if(Object.isString(AXConfig.AXModal.pars)){
                appendPars = AXConfig.AXModal.pars.queryToObject();
            }
            axdom.each(appendPars, function (key, val) {
                po.push("<input type='hidden' name='" + key + "' value='" + val + "' />");
            });
        }

        po.push("		</form>");

        if (http.maxHeight) {
            po.push("		<iframe src='' name='" + this.winID + "' id='" + this.winID + "' frameborder='0' class='windowboxFrame' style='width:100%;overflow:-y:hidden;' scrolling='auto'></iframe>");
        } else {
            po.push("		<iframe src='' name='" + this.winID + "' id='" + this.winID + "' frameborder='0' class='windowboxFrame' style='width:100%;overflow:-y:hidden;' scrolling='no'></iframe>");
        }

        po.push("	</div>");
        po.push("</div>");

        if (this.config.appendTargetID) {
            axdom("#" + this.config.appendTargetID).append(po.join(''));
        } else {
            axdom(document.body).append(po.join(''));
        }

        var loadingID = this.config.windowID + "_loading";
        var _winID = this.winID;
        var _frmID = this.frmID;

        document[_frmID].submit();

        axdom("#" + this.winID).bind("load", function () {
            var myIframe = window[_winID];

            var bodyHeight = axdom(myIframe.document).innerHeight();
            if (axdom(myIframe.document.body).find("." + cfg.contentDivClass).get(0)) {
                bodyHeight = axdom(myIframe.document.body).find("." + cfg.contentDivClass).outerHeight();
            }
            if (http.maxHeight) {
                if (http.maxHeight < (bodyHeight.number() + maskTop.number() + 10)) {
                    bodyHeight = http.maxHeight - maskTop.number() - 10;
                }
            }

            axdom(this).css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
            axdom("#" + _winID + "_box").css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
            axdom("#" + loadingID).fadeOut("slow");
            axdom("#" + _winID).addClass("loaded");
        });
        axdom("#" + this.config.windowID + "_close").bind("click", this.close.bind(this));

        /*
         if (this.mask) {
         if (this.config.autoHide) this.mask.bind("click", this.close.bind(this));
         }
         */
        //window.scroll(0, 0);
        this._windowOpend = true;

        axdom(window).unbind("resize.AXModal");
        axdom(window).bind("resize.AXModal", this.onDocResize.bind(this));

        if (cfg.scrollLock == true) {
            axdom(document.body).css({'overflow':'hidden'});
        }
    },
    windowResizeApply: function(){
        this.onDocResize();
    },
    /**
     * @method AXModal.openDiv
     * @param {Object} - configs
     * @description div 모달 창을 오픈합니다.
     * @example
     * ```js
     * var configs = {
     *     modalID: {String} - 모달창의 식별자,
     *     targetID: {String} - 모달창 타켓 엘리먼트 아이디,
     *     top: {Number} [scrollTop + 100] - 모달창 포지션 top,
     *     width: {(String|Number)} - 모달창 너비,
     *     closeByEscKey: {Boolean} [false] - 모달창 닫기를 esc 키로 닫을 지 여부,
     *     verticalAlign: {Boolean} [false] - 모달창 가운데 표시 여부,
     *     closeButton: {Boolean} [true] - 모달창 닫기버튼의 노출 여부
     * }
     * myModal.openDiv(configs);
     * ```
     */
    openDiv: function (args) {
        var cfg = this.config;
        mask.open();

        var modalID = cfg.opendModalID = args.modalID;

        if (AXgetId(modalID)) {
            var modalTarget = $("#" + modalID);
            modalTarget.show();

            var maskTop = this.config.defaultTop;
            if (args.top != undefined) {
                maskTop = axdom(window).scrollTop() + args.top;
            } else {
                maskTop = axdom(window).scrollTop() + 50;
            }

            if(cfg.viewMode == "mx"){
                maskTop = axdom(window).scrollTop();
            }

            if( args.verticalAlign ){
                modalTarget.css({top: axf.clientHeight() / 2 - modalTarget.height()/2 + axdom(window).scrollTop() })
            }else{
                modalTarget.css({ "top": maskTop });
            }

            if (args.closeByEscKey) {
                var keydown = this.keydown.bind(this);
                var keydownBind = function () {
                    keydown(event, modalID);
                };
                axdom(document.body).bind("keydown.AXModal", keydownBind);
            }
            return;
        }

        var maskWidth, maskLeft;
        if (this.config.width) {
            maskWidth = this.config.width;
            maskLeft = (axdom(document.body).width() / 2) - (this.config.width / 2);
            this.config.fixedWidth = true;
        } else {
            maskWidth = axdom(document.body).width() - 50;
            maskLeft = 10;
            this.config.fixedWidth = false;
        }

        if (args.width) {
            maskWidth = args.width;
            maskLeft = (axdom(document.body).width() / 2) - (args.width / 2);
            this.config.fixedWidth = true;
        }

        var maskTop = this.config.defaultTop;
        if (args.top != undefined) {
            maskTop = axdom(window).scrollTop() + args.top;
        } else {
            maskTop = axdom(window).scrollTop() + 50;
        }

        if (maskLeft < 0) maskLeft = 0;

        var po = [];
        po.push("<div id='" + modalID + "' class='" + this.config.windowBoxCss + "' style='top:" + maskTop + "px;left:" + maskLeft + "px;width:" + maskWidth + "px;'>");
        po.push("	<div class='windowbox' style='padding:" + this.config.padding + "px'>");

        var closeButton = (args.closeButton == undefined) ? cfg.closeButton : args.closeButton;
        if (closeButton){
            po.push("		<a href='#modsExecption' id='" + modalID + "_close' class='closeBtn'>닫기</a>");
        }

        po.push("		<div id='" + modalID + "_content'></div>");
        po.push("	</div>");
        po.push("</div>");

        axdom(document.body).append(po.join(''));

        axdom("#" + modalID + "_content").append(axdom("#" + args.targetID));

        axdom("#" + cfg.opendModalID).data("width", maskWidth);
        axdom("#" + cfg.opendModalID).data("top", maskTop);

        if(cfg.viewMode == "mx"){
            axdom("#" + cfg.opendModalID).css({ left: 0, top:axdom(window).scrollTop(), width:"100%" });
        }

        var loadingID = modalID + "_loading";

        var closeBind = this.close.bind(this);
        var closeModal = function (event) {
            closeBind(event, modalID);
        };
        axdom("#" + modalID + "_close").bind("click", closeModal);

        if (args.closeByEscKey) {
            var keydown = this.keydown.bind(this);
            var keydownBind = function () {
                keydown(event, modalID);
            };
            axdom(document.body).bind("keydown.AXModal", keydownBind);
        }

        /*
         if (this.mask) {
         if (this.config.autoHide) this.mask.bind("click", close);
         }
         */

        axdom(window).unbind("resize.AXModal");
        axdom(window).bind("resize.AXModal", this.onDocResize.bind(this));

        if (cfg.scrollLock == true) {
            axdom(document.body).css({'overflow':'hidden'});
        }

        if( args.verticalAlign ){
            var modalTarget = $("#" + modalID);
            $("#" + modalID).css({top: axf.clientHeight() / 2 - modalTarget.height()/2 + axdom(window).scrollTop() })
        }
    },
    /**
     * @method AXModal.openNew
     * @param {Object} - configs
     * @description 새로운 창으로 모달 창을 오픈 합니다.
     * @example
     * ```js
     * var configs = {
     *     url: {String} - 새창 오픈 URL,
     *     pars: {(Object|Array)} - 새창 오픈 URL 전달 파라미터,
     *     name: {String} ["mdw" + timekey]- 새창이름,
     *     options: {String} - 새창 오픈 옵션 window.open 속성과 동일합니다.
     * }
     * myModal.openNew(configs);
     * ```
     */
    openNew: function (http) {
        this.winID = "mdw" + AXUtil.timekey();
        this.frmID = "frm" + AXUtil.timekey();

        if (this.openWindow) {
            //top.mask.close();
            this.openWindow.close();
        }

        this.openWindow = window.open("", (http.name || this.winID), http.options);
        this.openWindow.focus();

        if (http.title != undefined){
            this.openWindow.document.title = http.title;
        }

        if (AXgetId(this.config.windowID)) axdom("#" + this.config.windowID).remove();

        var po = [];
        po.push("<div id='" + this.config.windowID + "'>");
        po.push("		<form name='" + this.frmID + "' method='" + (http.method || "post") + "' target='" + (http.name || this.winID) + "' action='" + http.url + "'>");
        po.push("		<input type='hidden' name='winID' value='" + this.winID + "' />");

        if (isNaN(http.pars.length)) {
            axdom.each(http.pars, function (key, val) {
                po.push("		<input type='hidden' name='" + key + "' value='" + val + "' />");
            });
        } else {
            axdom.each(http.pars, function () {
                axdom.each(this, function (key, val) {
                    po.push("		<input type='hidden' name='" + key + "' value='" + val + "' />");
                });
            });
        }
        po.push("		</form>");
        po.push("</div>");
        axdom(document.body).append(po.join(''));
        document[this.frmID].submit();
        axdom("#" + this.config.windowID).remove();
    },
    keydown: function (event, modalID) {
        if (event.keyCode == AXUtil.Event.KEY_ESC) {
            this.close(event, modalID);
        }
    },
    /**
     * @method AXModal.close
     * @param {String} - modalID
     * @description 오픈된 모달 창을 닫습니다.
     * @example
     * ```js
     * myModal.close("modalDiv01");
     * parent.myModal.close(); // iframe 모달창을 오픈한 경우 열려진 iframe 안에서 호출 합니다.
     * ```
     */
    close: function (event, modalID) {
        var cfg = this.config;
        if (this.openWindow) {
            this.openWindow.close();
        }

        if (event) {
            if (event.type == undefined) {
                modalID = event;
            }
        }

        if (modalID) {
            axdom("#" + modalID).hide();
            this.config.opendModalID = "";
            mask.close();
        } else {
            if (window[this.winID]) {
                window[this.winID].location.href = "about:blank";
                var windowID = this.config.windowID;

                setTimeout(function () {
                    axdom("#" + windowID).remove();
                }, 1);

                mask.close();
                this._windowOpend = false;
            }
        }

        axdom(document.body).unbind("keydown.AXModal");

        if(this.config.onclose){
            this.config.onclose.call(
                {
                    winID: this.winID,
                    windowID: this.config.windowID,
                    modalID: modalID
                }
            );
        }

        if (cfg.scrollLock == true) {
            axdom(document.body).css({'overflow':'auto'});
        }
    },
    /**
     * @method AXModal.remove
     * @description 오픈된 모달 창을 제거합니다.
     * @example
     * ```js
     * myModal.remove();
     * parent.myModal.remove(); //iframe 모달창을 오픈한 경우 열려진 iframe 안에서 호출 합니다.
     * ```
     */
    remove: function (event) {
        var windowID = this.config.windowID;
        setTimeout(function () {
            axdom("#" + windowID).remove();
        }, 1);
        mask.close();
        axdom(document.body).css({'overflow':'auto'});
        this._windowOpend = false;
        /*
         try {
         this.mask.remove();
         } catch (e) { }
         */
    },
    /**
     * @method AXModal.resize
     * @description 열려진 iframe modal 의 높이를 iframe 창의 높이 만큼 리사이즈 합니다. contentDivClass 가 정의된 경우 contentDivClass 높이값으로 resize 합니다.
     * @example
     * ```js
     * myModal.resize();
     * parent.myModal.resize(); //iframe 모달창을 오픈한 경우 열려진 iframe 안에서 호출 합니다.
     * ```
     */
    resize: function (event) {
        var cfg = this.config;
        var _winID = this.winID;
        setTimeout(function () {

            try {
                var myIframe = window[_winID];
                var bodyHeight = axdom(myIframe.document).innerHeight();
                if (axdom(myIframe.document.body).find("." + cfg.contentDivClass).get(0)) {
                    bodyHeight = axdom(myIframe.document.body).find("." + cfg.contentDivClass).outerHeight();
                }
                axdom("#" + _winID).css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
                axdom("#" + _winID + "_box").css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
            }catch(e){

            }

            try {
                parent.fcObj.contentResetHeight();
            } catch (e) {
                //trace(e);
            }

            try {
                parent.fnObj.contentResetHeight(null, bodyHeight + 100);
            } catch (e) {
                //trace(e);
            }
        }, 50);
    },
    onDocResize: function () {
        var cfg = this.config;

        if (cfg.mediaQuery) {
            var _viewMode = "", clientWidth = axf.clientWidth();

            axf.each(cfg.mediaQuery, function (k, v) {
                if (Object.isObject(v)) {

                    if(v.min != undefined && v.max != undefined){
                        if (v.min <= clientWidth && clientWidth <= v.max) {
                            _viewMode = (k == "dx") ? "dx" : "mx";
                            return false;
                        }
                    }else{
                        if (v.min <= clientWidth) {
                            _viewMode = (k == "dx") ? "dx" : "mx";
                            return false;
                        }
                    }
                }
            });
            if (_viewMode != "") {
                cfg.viewMode = _viewMode;
            }
        }

        if(cfg.viewMode == "dx"){
            try {
                if (cfg.fixedWidth) {
                    var maskWidth, maskLeft;
                    if(cfg.opendModalID != ""){
                        maskWidth = axdom("#" + cfg.opendModalID).outerWidth();
                        if(maskWidth != axdom("#" + cfg.opendModalID).data("width")) {
                            axdom("#" + cfg.opendModalID).css({
                                top: axdom("#" + cfg.opendModalID).data("top"),
                                width: axdom("#" + cfg.opendModalID).data("width")
                            });
                        }
                        maskLeft = (axdom(document.body).width() / 2) - (maskWidth / 2);
                        if (maskLeft < 0) maskLeft = 0;
                        axdom("#" + cfg.opendModalID).css({ left: maskLeft });
                    }else{
                        maskWidth = axdom("#" + cfg.windowID).outerWidth();
                        if(maskWidth != axdom("#" + cfg.windowID).data("width")) {
                            axdom("#" + cfg.windowID).css({
                                top: axdom("#" + cfg.windowID).data("top"),
                                width: axdom("#" + cfg.windowID).data("width")
                            });
                        }
                        maskLeft = (axdom(document.body).width() / 2) - (maskWidth / 2);
                        if (maskLeft < 0) maskLeft = 0;
                        axdom("#" + cfg.windowID).css({ left: maskLeft });
                    }
                } else {
                    if(cfg.opendModalID != "") {
                        maskWidth = axdom(".container").width() - 50;
                        axdom("#" + cfg.opendModalID).css({ width: maskWidth });
                    }else{
                        maskWidth = axdom(".container").width() - 50;
                        axdom("#" + cfg.windowID).css({ width: maskWidth });
                    }
                }
            } catch (e) {

            }
        }else if(cfg.viewMode == "mx"){
            if(cfg.opendModalID != "") {
                axdom("#" + cfg.opendModalID).css({ left: 0, top: axdom(window).scrollTop(), width: "100%" });
            }else {
                axdom("#" + cfg.windowID).css({ left: 0, top: axdom(window).scrollTop(), width: "100%" });
            }
        }

    },
    /**
     * @method AXModal.loaded
     * @description 모달의 로딩중 상태를 강제로 로드 완료 처리 합니다.
     * @example
     * ```js
     * myModal.loaded();
     * parent.myModal.loaded(); //iframe 모달창을 오픈한 경우 열려진 iframe 안에서 호출 합니다.
     * ```
     */
    loaded: function () {
        var cfg = this.config, _winID = this.winID;
        var loadingID = this.config.windowID + "_loading";
        var myIframe = window[this.winID];

        var bodyHeight = axdom(myIframe.document).innerHeight();
        if (axdom(myIframe.document.body).find("." + cfg.contentDivClass).get(0)) {
            bodyHeight = axdom(myIframe.document.body).find("." + cfg.contentDivClass).outerHeight();
        }
        axdom(this).css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
        axdom("#" + _winID + "_box").css({ height: (bodyHeight) }, cfg.animateDuration, "cubicInOut");
        if (cfg.displayLoading) axdom("#" + loadingID).fadeOut("slow");
        axdom("#" + _winID).addClass("loaded");
    }
});

            Documentation generated by JSDoc 3.4.0 on Thu Apr 21 2016 13:33:04 GMT+0900 (KST)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LPToolKit.MIDI;

namespace LPToolKit.Platform
{
    /// <summary>
    /// Windows specific implementation of MIDI support.
    /// </summary>
    public class WindowsMidiDriver : MidiDriver
    {
        #region Constructors

        internal WindowsMidiDriver() : base()
        {
            _callback = new Win32API.MidiInProc(this.InputCallback);
        }

        ~WindowsMidiDriver()
        {
            Release();
        }

        #endregion

        #region MidiDriver Implementation

        /// <summary>
        /// Sends a MIDI message to the device.  Ignored if the
        /// device is not set or does not support output.
        /// </summary>
        internal override void SendMessage(MidiMessage msg)
        {
            if (_outputOpen && msg != null)
            {
                Win32API.midiOutShortMsg(_outputHandle, msg.CreateShortMessage());
            }
        }

        /// <summary>
        /// Returns all connected devices.
        /// </summary>
        protected override List<MidiDevice> GetDeviceList()
        {
            var ret = new List<MidiDevice>();

            // get the list of input and output devices from WinMM.dll
            var inputs = GetInputList();
            var outputs = GetOutputList();
            var allDevices = inputs.Union(outputs);

            // create a MidiDevice for each device, deciding the direction
            // by which list the IDs are in.
            foreach (var device in allDevices)
            {
                MidiDirection direction;
                if (inputs.Contains(device))
                {
                    direction = outputs.Contains(device) ? MidiDirection.IO : MidiDirection.Input;
                }
                else // if (outputs.Contains(device))
                {
                    direction = MidiDirection.Output;
                }
                ret.Add(new MidiDevice()
                {
                    Direction = direction,
                    ID = device,
                    Name = device
                });
            }

            return ret;
        }

        /// <summary>
        /// Called whenever the midi device is changed so the platform
        /// specific code and acquire the appropriate resources from
        /// the operating system.
        /// </summary>
        protected override void UpdateSelectedDevice()
        {
            Release();
            Acquire(SelectedDevice);
        }

        #endregion

        #region Private

        /// <summary>
        /// Reference to the callback method.
        /// </summary>
        private Win32API.MidiInProc _callback;

        /// <summary>
        /// WinMM handle to the input device.
        /// </summary>
        private Win32API.HMIDIIN _inputHandle;

        /// <summary>
        /// WinMM handle to the output device.
        /// </summary>
        private Win32API.HMIDIOUT _outputHandle;

        /// <summary>
        /// Set to true when output is open.
        /// </summary>
        private bool _outputOpen = false;

        /// <summary>
        /// Set to true when input is open.
        /// </summary>
        private bool _inputOpen = false;

        /// <summary>
        /// Mutex for changing midi settings.
        /// </summary>
        private readonly object _acquireLock = new object();

        /// <summary>
        /// The list of recent device IDs by name.
        /// </summary>
        private static Dictionary<string, uint> _deviceIdByName = new Dictionary<string, uint>();

        /// <summary>
        /// Returns all the names of input devices from WinMM.dll
        /// </summary>
        private List<string> GetInputList()
        {
            var ret = new List<string>();

            uint inputDeviceCount = Win32API.midiInGetNumDevs();
            for (uint deviceId = 0; deviceId < inputDeviceCount; deviceId++)
            {
                Win32API.MIDIINCAPS caps = new Win32API.MIDIINCAPS();
                Win32API.midiInGetDevCaps((UIntPtr)deviceId, out caps);
                ret.Add(caps.szPname);

                _deviceIdByName["IN_" + caps.szPname] = deviceId;
            }

            return ret;
        }

        /// <summary>
        /// Returns all the names of output devices from WinMM.dll
        /// </summary>
        private List<string> GetOutputList()
        {
            var ret = new List<string>();

            uint outputDeviceCount = Win32API.midiOutGetNumDevs();
            for (uint deviceId = 0; deviceId < outputDeviceCount; deviceId++)
            {
                Win32API.MIDIOUTCAPS caps = new Win32API.MIDIOUTCAPS();
                Win32API.midiOutGetDevCaps((UIntPtr)deviceId, out caps);
                ret.Add(caps.szPname);

                _deviceIdByName["OUT_" + caps.szPname] = deviceId;
            }

            return ret;
        }

        /// <summary>
        /// Gets all MIDI resources needed to use the selected device.
        /// </summary>
        private void Acquire(MidiDevice device)
        {
            lock (_acquireLock)
            {
                if (device != null)
                {
                    // setup the input device
                    if (device.CanRead)
                    {
                        // grab the device id by name
                        uint deviceId = 0;
                        if (_deviceIdByName.TryGetValue("IN_" + device.ID, out deviceId) == false)
                        {
                            throw new Exception("Could not find MIDI input device " + device.ID);
                        }

                        // start streaming the input
                        WinMM.CheckReturnCode(Win32API.midiInOpen(out _inputHandle, (UIntPtr)deviceId, _callback, (UIntPtr)0));
                        WinMM.CheckReturnCode(Win32API.midiInStart(_inputHandle));
                        _inputOpen = true;
                    }
                    else
                    {
                        _inputOpen = false;
                    }

                    // setup the output device
                    if (device.CanWrite)
                    {
                        // grab the device id by name
                        uint deviceId = 0;
                        if (_deviceIdByName.TryGetValue("OUT_" + device.ID, out deviceId) == false)
                        {
                            throw new Exception("Could not find MIDI output device " + device.ID);
                        }

                        // setup the device
                        WinMM.CheckReturnCode(Win32API.midiOutOpen(out _outputHandle, (UIntPtr)deviceId, null, (UIntPtr)0));
                        _outputOpen = true;
                    }
                    else
                    {
                        _outputOpen = false;
                    }
                }
            }
        }

        /// <summary>
        /// Releases all currently used MIDI resources.
        /// </summary>
        private void Release()
        {
            lock (_acquireLock)
            {
                if (_inputOpen)
                {
                    WinMM.CheckReturnCode(Win32API.midiInStop(_inputHandle));
                    WinMM.CheckReturnCode(Win32API.midiInClose(_inputHandle));
                    _inputOpen = false;
                }

                if (_outputOpen)
                {
                    WinMM.CheckReturnCode(Win32API.midiOutReset(_outputHandle));// TODO: not sure if we should
                    WinMM.CheckReturnCode(Win32API.midiOutClose(_outputHandle));
                    _outputOpen = false;
                }
            }
        }

        /// <summary>
        /// The input callback for midiOutOpen.
        /// </summary>
        private void InputCallback(Win32API.HMIDIIN hMidiIn, Win32API.MidiInMessage wMsg,
            UIntPtr dwInstance, UIntPtr dwParam1, UIntPtr dwParam2)
        {
            if (wMsg == Win32API.MidiInMessage.MIM_DATA)
            {
                var msg = MidiMessage.FromShortMessage((uint)dwParam1);
                if (msg != null)
                {
                    Receive(msg);
                }
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function() {
  $(".iteration_select").change(function() {
    location = "code_review?problem_id=1&left_iteration=" + $("#left_iteration_select").val() + "&right_iteration=" + $("#right_iteration_select").val();
  });

  $('textarea').elastic();
  $('textarea').trigger('update');

  $(".comment_toggle").click(function () {
    $(this).prev().css("display", "block");
    $(this).css("display", "none");
  });

  $(".diff_file_path_link").click(function () {
    var diffFileId = '#' + this.id + '.diff_file';

    var toggleText = '';
    var displayValue = '';

    if ($(diffFileId).css('display') == 'none')
    {
      toggleText = 'Hide Code';
      displayValue = 'block';
    }
    else
    {
      toggleText = 'Show Code';
      displayValue = 'none';
    }

    $(diffFileId).css('display', displayValue);
    $(this).text(toggleText);
  });
});


text:
<?php
//functions.php

function convertTime($time, $currentTimezone, $timezoneRequired) {
    $dayLightFlag = false;
    $dayLgtSecCurrent = $dayLgtSecReq = 0;
    $system_timezone = date_default_timezone_get();
    $local_timezone = $currentTimezone;
    date_default_timezone_set($local_timezone);
    $local = date("Y-m-d H:i:s");

    date_default_timezone_set("GMT");
    $gmt = date("Y-m-d H:i:s");

    $require_timezone = $timezoneRequired;
    date_default_timezone_set($require_timezone);
    $required = date("Y-m-d H:i:s ");

    date_default_timezone_set($system_timezone);
    $diff1 = (strtotime($gmt) - strtotime($local));
    $diff2 = (strtotime($required) - strtotime($gmt));

    $date = new DateTime($time);

    $date->modify("+$diff1 seconds");
    $date->modify("+$diff2 seconds");

    if ($dayLightFlag) {
        $final_diff = $dayLgtSecCurrent + $dayLgtSecReq;
        $date->modify("$final_diff seconds");
    }

    $timestamp = $date->format("D, F jS, Y * h:i A");
    $timestamp=str_replace("*"," at ",$timestamp);

    return $timestamp;
}

function formatPhoneNumber($phoneNumber) {
    global $contactsList;
    $setNumber=$phoneNumber;
    $phoneNumber = preg_replace('/[^0-9]/','',$phoneNumber);

    if(strlen($phoneNumber) > 10) {
        $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10);
        $areaCode = substr($phoneNumber, -10, 3);
        $nextThree = substr($phoneNumber, -7, 3);
        $lastFour = substr($phoneNumber, -4, 4);

        $phoneNumber = ' ('.$areaCode.') '.$nextThree.'-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 10) {
        $areaCode = substr($phoneNumber, 0, 3);
        $nextThree = substr($phoneNumber, 3, 3);
        $lastFour = substr($phoneNumber, 6, 4);

        $phoneNumber = '('.$areaCode.') '.$nextThree.'-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 7) {
        $nextThree = substr($phoneNumber, 0, 3);
        $lastFour = substr($phoneNumber, 3, 4);

        $phoneNumber = $nextThree.'-'.$lastFour;
    }

    if($contactsList[$setNumber]) $personName=$contactsList[$setNumber];
    else $personName="Unknown";
    $personName.=" — ".$phoneNumber."";

    return $personName;
}

function formatAnonymousPhoneNumber($phoneNumber) {
    global $contactsList;
    $setNumber=$phoneNumber;
    $phoneNumber = preg_replace('/[^0-9]/','',$phoneNumber);

    if(strlen($phoneNumber) > 10) {
        $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10);
        $areaCode = substr($phoneNumber, -10, 3);
        $nextThree = substr($phoneNumber, -7, 3);
        $lastFour = substr($phoneNumber, -4, 4);

        $phoneNumber = ' ('.$areaCode.') ***-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 10) {
        $areaCode = substr($phoneNumber, 0, 3);
        $nextThree = substr($phoneNumber, 3, 3);
        $lastFour = substr($phoneNumber, 6, 4);

        $phoneNumber = '('.$areaCode.') ***-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 7) {
        $nextThree = substr($phoneNumber, 0, 3);
        $lastFour = substr($phoneNumber, 3, 4);

        $phoneNumber = '***-'.$lastFour;
    }

    if($contactsList[$setNumber]) $personName=$contactsList[$setNumber];
    else $personName="Unknown";
    $personName.=" — ".$phoneNumber."";

    return $personName;
}

function shortenText($t,$l){ // text, length
    if(strlen($t)>$l){
        $t=substr($t,0,$l)."...";
    }
    return $t;
}

function flagReadConversation($phoneNumber){ // Flag message as read
    global $dbConnection, $dbTable;

    $qSelect = "SELECT * FROM ".$dbTable." WHERE phonenumber='$phoneNumber';";
    $r = mysqli_query($dbConnection, $qSelect);

    if($r->num_rows==0){
        $qInsert = "INSERT INTO ".$dbTable." (id,phonenumber,flagread,label,active) VALUES ('','$phoneNumber','r','No tag assigned','');";
        $r = mysqli_query($dbConnection, $qInsert);
    }
    else {
        $qUpdate = "UPDATE ".$dbTable." SET flagread='r' WHERE phonenumber='$phoneNumber';";
        $r = mysqli_query($dbConnection, $qUpdate);
    }

}

function markConversationUnread($phoneNumber) { // mark a conversation as unread
    global $dbConnection, $dbTable;
    $qUpdate = "UPDATE ".$dbTable." SET flagread='u' WHERE phonenumber='$phoneNumber';";
    //echo $qUpdate;
    $r = mysqli_query($dbConnection, $qUpdate);

}

function assignTagConversation($phoneNumber, $filter){ // assigns a tag to a conversation
    global $dbConnection, $dbTable;
    $qUpdate = "UPDATE ".$dbTable." SET label='$filter' WHERE phonenumber='$phoneNumber';";
    //echo $qUpdate;
    $r = mysqli_query($dbConnection, $qUpdate);
}

function setConversationFilters($phoneNumber){
    global $dbConnection, $dbTable, $conversationFilters;

    foreach($conversationFilters as $f){
        $qSelect = "SELECT * FROM ".$dbTable." WHERE phonenumber='$phoneNumber' AND label='$f';";
        $r = mysqli_query($dbConnection, $qSelect);
        if($r->num_rows>0) echo "<option selected value=\"?mode=filter&no=".urlencode($phoneNumber)."&f=".$f."\">#".$f."</option>";
        else echo "<option value=\"?mode=filter&no=".urlencode($phoneNumber)."&f=".$f."\">#".$f."</option>";
    }
}

function checkReadConversation($phoneNumber){ // check read / unread conversations
    global $dbConnection, $dbTable;
    $flagRead="unread";

    $qSelect = "SELECT * FROM ".$dbTable." WHERE phonenumber='$phoneNumber' AND flagread='r';";
    $r = mysqli_query($dbConnection, $qSelect);
    //echo "
".$qSelect."
COUNT ".$r->num_rows;

    if($r->num_rows>0){
        $flagRead="read";
    }
    else {
        $flagRead="unread";
    }
    return $flagRead;
}

function getConversationFilter($phoneNumber){ // check read / unread conversations
    global $dbConnection, $dbTable;

    $qSelect = "SELECT label FROM ".$dbTable." WHERE phonenumber='$phoneNumber';";
    $r = mysqli_query($dbConnection, $qSelect);
    if ($r) {
      $obj = $r->fetch_object();
    }
    return $obj->label;

}

function array_multi_unique($array, $key){ // array_unique for multidimensional arrays
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val){
        if(!in_array($val[$key],$key_array)){
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}

function formatImages($text) {
    $regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';
    return preg_replace_callback($regex, function ($matches) {
        $img=$matches[0];
        return '';
    }, $text);
}

/*
function debugThis($obj){
    echo "
";
    var_dump($obj);
    echo "
";
}
*/

?>


text:
/**
 * @author Alex Casalboni <alex@cloudacademy.com>
 */

function Field($el) {
    this.$el = $el;
    this.width = 1000;
    this.height = 500;
    this.drones = [];
}

Field.prototype.initDrones = function($elements) {
    var self = this;
    $elements.each(function(i) {
        var $el = $(this);
        setTimeout(function() {
            var drone = new Drone($el, self);
            self.drones.push(drone);
        }, Math.round(Math.random() * 500) * i)
    });
};

Field.prototype.onDroneMove = function(drone) {
    console.log("TODO: override me!");
};

Field.prototype.notifyDrone = function(droneID, message) {
    this.drones.forEach(function(drone) {
        if (droneID == drone.id) {
            drone.onMessage(message);
        }
    });
};

Field.prototype.notifyDrones = function(message) {
    this.drones.forEach(function(drone, i) {
        setTimeout(function() {
            drone.onMessage(message);
        }, 5 * i);
    });
};

Field.prototype.removeDrone = function(drone) {
    var index = this.drones.indexOf(drone);
    console.log("removing drone with index", index, drone);
    this.drones.splice(index, 1);
}

function Drone($el, field) {
    this.id = newUUID();
    this.active = true;
    this.$el = $el;
    this.width = 50;
    this.height = 50;
    this.setPower(Math.round(Math.random() * 5));
    this.field = field;
    this.timer = 3000;
    this.initSpeed();

    // alarm state on click
    this.$el.click(this.alarm.bind(this));
    this.$el.dblclick(this.destroy.bind(this));

}

Drone.prototype.initSpeed = function() {
    this.$el.removeClass('alarm');
    this.xSpeed = this._randomSpeed();
    this.ySpeed = this._randomSpeed();
    this.animate();
};

Drone.prototype.getX = function() {
    return parseInt(this.$el.css('left'));
};

Drone.prototype.getY = function() {
    return parseInt(this.$el.css('top'));
};

Drone.prototype._randomSpeed = function() {
    return Math.round(Math.random() * 150) - 100;  // -30 to +30
};

Drone.prototype._randomSpeedPositive = function() {
    return Math.round(Math.random() * 40) + 10;  // +10 to +50
};

Drone.prototype._randomSpeedNegative = function() {
    return Math.round(Math.random() * -40) - 10;  // -50 to -10
};

Drone.prototype.animate = function() {
    if (!this.active) {
        return;
    }
    this.$el.animate({
        top: "+=" + this.ySpeed,
        left: "+=" + this.xSpeed
    }, this.timer, "linear", this.checkPosition.bind(this));
};

Drone.prototype.checkPosition = function() {
    var top = parseInt(this.$el.css('top')) + this.height/2,
        left = parseInt(this.$el.css('left')) + this.width/2;

    if (top <= 0 && this.ySpeed <= 0) {
        this.ySpeed = this._randomSpeedPositive();
        // console.log("Too hight, new speed:", this.ySpeed);
    } else if (top >= this.field.height && this.ySpeed >= 0) {
        this.ySpeed = this._randomSpeedNegative();
        // console.log("Too low, new speed:", this.ySpeed);
    }

    if (left <= 0 && this.xSpeed <= 0) {
        this.xSpeed = this._randomSpeedPositive();
        // console.log("Too left, new speed:", this.xSpeed);
    } else if (left >= this.field.width  && this.xSpeed >= 0) {
        this.xSpeed = this._randomSpeedNegative();
        // console.log("Too right, new speed:", this.xSpeed);
    }

    this.field.onDroneMove(this);
    this.animate();

};

Drone.prototype.getTemperature = function() {
    return Math.floor(Math.random() * 20) + 10;  // btw +10 and +30 (°C)
};

Drone.prototype.alarm = function() {
    this.$el.stop(true, false).addClass('alarm');
    this.xSpeed = this.ySpeed = 0;
    setTimeout(this.initSpeed.bind(this), this.timer);
};

Drone.prototype.destroy = function() {
    this.$el.stop().remove();
    this.active = false;
    this.field.removeDrone(this);
};

Drone.prototype.setPower = function(value) {
    this.power = value;
    this.$el.attr('data-power', value);
}

Drone.prototype.onMessage = function(message) {
    console.log("Drone ", this.id, " received message ", message);
    switch (message.action) {
        case 'alarm':
            return this.alarm();
        case 'destroy':
            return this.destroy();
        case 'power':
            return this.setPower(message.value);
        default:
            return console.error("Unrecognised msg:", message)
    }
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenopeziza ebulicola Rehm

### Remarks
null


text:
package paxos

import (
	"log"
	"time"
)

func CreateNetwork(nodes ...int) *network {
	nt := network{recvQueue: make(map[int]chan message, 0)}

	for _, node := range nodes {
		nt.recvQueue[node] = make(chan message, 1024)
	}

	return &nt
}

type network struct {
	recvQueue map[int]chan message
}

func (n *network) getNodeNetwork(id int) nodeNetwork {
	return nodeNetwork{id: id, net: n}
}

func (n *network) sendTo(m message) {
	log.Println("Send msg from:", m.from, " send to", m.to, " val:", m.val, " typ:", m.typ)
	n.recvQueue[m.to] <- m
}

func (n *network) recevFrom(id int) *message {
	select {
	case retMsg := <-n.recvQueue[id]:
		log.Println("Recev msg from:", retMsg.from, " send to", retMsg.to, " val:", retMsg.val, " typ:", retMsg.typ)
		return &retMsg
	case <-time.After(time.Second):
		//log.Println("id:", id, " don't get message.. time out.")
		return nil
	}
}

type nodeNetwork struct {
	id  int
	net *network
}

func (n *nodeNetwork) send(m message) {
	n.net.sendTo(m)
}

func (n *nodeNetwork) recev() *message {
	return n.net.recevFrom(n.id)
}


text:
package cc.factorie.util

/** The scala REPL available through an object main.
    Runs each of the command-line args as a scala command, then drops into an interpreter prompt. */
@deprecated("Not used anywhere", "Before 10/06/15")
object Interpreter {
  def main(args:Array[String]): Unit = {
    val settings = new scala.tools.nsc.Settings
    settings.usejavacp.value = true
    val iloop = new scala.tools.nsc.interpreter.ILoop
    args.foreach(iloop.command(_))
    iloop.process(settings)
  }
}


text:
<?php
/* vim: set shiftwidth=4 expandtab softtabstop=4: */

namespace Alexpw\Multicurl;

final class CurlNode
{
	public $handle;
	public $data;
}


text:
package org.apache.usergrid.persistence.cassandra.util;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.utils.UUIDUtils;

import com.google.common.base.Preconditions;

/**
 * Keeps the TraceTag as a ThreadLocal
 *
 * @author zznate
 */
public class TraceTagManager {
    private static final Logger logger = LoggerFactory.getLogger( TraceTagManager.class );

    private static ThreadLocal<TraceTag> localTraceTag = new ThreadLocal<TraceTag>();

    private boolean traceEnabled;

    private boolean reportUnattached;

    private boolean explicitOnly;

    private int flushAtOpCount = 100;

    @Resource
    private TraceTagReporter traceTagReporter;

    /** Enable tracing. Off by default. */
    public void setTraceEnabled( boolean traceEnabled ) {
        this.traceEnabled = traceEnabled;
    }

    public boolean getTraceEnabled() {
        return traceEnabled;
    }

    /**
     * The maximum number of o TimedOpTag objects we can attach to a tracing instance. Excess of this will for a
     * blocking flush on the current thread to the configured reporter instance.
     * <p/>
     * The default is 100. If you have other ThreadLocal variables, you should probably lower this value.
     */
    public int getFlushAtOpCount() {
        return flushAtOpCount;
    }

    public void setFlushAtOpCount( int flushAtOpCount ) {
        this.flushAtOpCount = flushAtOpCount;
    }

    /** If set to true we log all TimedOpTag objects not attached to a Trace */
    public void setReportUnattached( boolean reportUnattached ) {
        this.reportUnattached = reportUnattached;
    }

    /**
     * Allow for/check against traces in piecemeal. Use this when {@link #setTraceEnabled(boolean)} is set to false and
     * you want callers to control whether or not to initiate a trace. An example would be initiating traces in a
     * ServletFilter by looking for a header or parameter as tracing all requests would be expensive.
     */
    public boolean getExplicitOnly() {
        return explicitOnly;
    }

    public void setExplicitOnly( boolean explicitOnly ) {
        this.explicitOnly = explicitOnly;
    }

    /** Get the tag from a ThreadLocal. Will return null if no tag is attached. */
    public TraceTag acquire() {
        return localTraceTag.get();
    }

    public TimedOpTag timerInstance() {
        return TimedOpTag.instance( acquire() );
    }

    /**
     * Add this TimedOpTag to the underlying trace if there is one. Optionally log it's contents if no trace is active.
     * If an active trace was found and {@link org.apache.usergrid.persistence.cassandra.util.TraceTag#getOpCount()} exceeded
     * {@link #getFlushAtOpCount()}, then the trace is dumped to the reporter and {@link
     * org.apache.usergrid.persistence.cassandra.util.TraceTag#removeOps()} is invoked. The TraceTag stay attached with the
     * same name and ID, but now with no pending ops.
     */
    public void addTimer( TimedOpTag timedOpTag ) {
        if ( isActive() ) {
            TraceTag tag = acquire();
            if ( tag.getOpCount() >= flushAtOpCount ) {
                traceTagReporter.report( tag );
                tag.removeOps();
            }
            tag.add( timedOpTag );

            // if TraceTag#metered, send to meter by tag name
        }
        else {
            if ( reportUnattached ) {
                traceTagReporter.reportUnattached( timedOpTag );
            }
        }
    }

    /** Returns true if there is a trace in progress */
    public boolean isActive() {
        return acquire() != null;
    }

    /**
     * Attache the tag to the current Thread. Will throw an IllegalStateException if there is already a trace in
     * progress.
     */
    public void attach( TraceTag traceTag ) {
        Preconditions.checkState( !isActive(), "Attempt to attach on already active trace" );
        localTraceTag.set( traceTag );
        if (logger.isTraceEnabled()) {
            logger.trace("Attached TraceTag {} to thread", traceTag);
        }
    }

    /** Detach the tag from the current thread. Throws an IllegalStateException if there is no trace in progress. */
    public TraceTag detach() {
        TraceTag traceTag = localTraceTag.get();
        Preconditions.checkState( isActive(), "Attempt to detach on no active trace" );
        localTraceTag.remove();
        if (logger.isTraceEnabled()) {
            logger.trace("Detached TraceTag {} from thread", traceTag);
        }
        return traceTag;
    }

    /** Create a TraceTag */
    public TraceTag create( String tagName ) {
        return TraceTag.getInstance( UUIDUtils.newTimeUUID(), tagName );
    }

    public TraceTag createMetered( String tagName ) {
        return TraceTag.getMeteredInstance( UUIDUtils.newTimeUUID(), tagName );
    }
}


text:
package http

import (
	"net/http"

	"golang.org/x/net/context"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
)

// Server wraps an endpoint and implements http.Handler.
type Server struct {
	// A background context must be provided.
	context.Context

	// The endpoint that will be invoked.
	endpoint.Endpoint

	// DecodeRequestFunc must be provided.
	DecodeRequestFunc

	// EncodeResponseFunc must be provided.
	EncodeResponseFunc

	// Before functions are executed on the HTTP request object before the
	// request is decoded.
	Before []RequestFunc

	// After functions are executed on the HTTP response writer after the
	// endpoint is invoked, but before anything is written to the client.
	After []ResponseFunc

	// ErrorEncoder is used to encode errors to the http.ResponseWriter
	// whenever they're encountered in the processing of a request. Clients
	// can use this to provide custom error formatting and response codes. If
	// ErrorEncoder is nil, the error will be written as plain text with
	// an appropriate, if generic, status code.
	ErrorEncoder func(w http.ResponseWriter, err error)

	// Logger is used to log errors.
	Logger log.Logger
}

// ServeHTTP implements http.Handler.
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.ErrorEncoder == nil {
		s.ErrorEncoder = defaultErrorEncoder
	}

	ctx, cancel := context.WithCancel(s.Context)
	defer cancel()

	for _, f := range s.Before {
		ctx = f(ctx, r)
	}

	request, err := s.DecodeRequestFunc(r)
	if err != nil {
		_ = s.Logger.Log("err", err)
		s.ErrorEncoder(w, badRequestError{err})
		return
	}

	response, err := s.Endpoint(ctx, request)
	if err != nil {
		_ = s.Logger.Log("err", err)
		s.ErrorEncoder(w, err)
		return
	}

	for _, f := range s.After {
		f(ctx, w)
	}

	if err := s.EncodeResponseFunc(w, response); err != nil {
		_ = s.Logger.Log("err", err)
		s.ErrorEncoder(w, err)
		return
	}
}

func defaultErrorEncoder(w http.ResponseWriter, err error) {
	switch err.(type) {
	case badRequestError:
		http.Error(w, err.Error(), http.StatusBadRequest)
	default:
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

type badRequestError struct{ error }


text:
export const FETCH_QUOTA = 'FETCH_QUOTA';
export const UPDATE_QUOTA = 'UPDATE_QUOTA';


text:
package io.airlift.drift.client.guice;

import javax.inject.Qualifier;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Objects;
import java.util.Optional;

import static java.lang.String.format;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.util.Objects.requireNonNull;

public final class DriftClientAnnotationFactory
{
    private DriftClientAnnotationFactory() {}

    public static Annotation getDriftClientAnnotation(Class<?> value, Class<? extends Annotation> qualifier)
    {
        return new DriftClientAnnotationImpl(value, qualifier);
    }

    public static Optional<Class<? extends Annotation>> extractDriftClientBindingAnnotation(Annotation driftClientAnnotation)
    {
        if (driftClientAnnotation instanceof DriftClientAnnotation) {
            DriftClientAnnotation annotation = (DriftClientAnnotation) driftClientAnnotation;
            Class<? extends Annotation> qualifier = annotation.qualifier();
            if (qualifier != DefaultClient.class) {
                return Optional.of(qualifier);
            }
        }
        return Optional.empty();
    }

    @Target({FIELD, PARAMETER, METHOD})
    @Retention(RUNTIME)
    @Qualifier
    @interface DriftClientAnnotation
    {
        Class<?> value();

        Class<? extends Annotation> qualifier();
    }

    @SuppressWarnings("ClassExplicitlyAnnotation")
    private static final class DriftClientAnnotationImpl
            implements DriftClientAnnotation
    {
        private final Class<?> value;
        private final Class<? extends Annotation> qualifier;

        private DriftClientAnnotationImpl(Class<?> value, Class<? extends Annotation> qualifier)
        {
            this.value = requireNonNull(value, "value is null");
            this.qualifier = requireNonNull(qualifier, "qualifier is null");
        }

        @Override
        public Class<?> value()
        {
            return value;
        }

        @Override
        public Class<? extends Annotation> qualifier()
        {
            return qualifier;
        }

        @Override
        public Class<? extends Annotation> annotationType()
        {
            return DriftClientAnnotation.class;
        }

        @Override
        public int hashCode()
        {
            // This is specified in java.lang.Annotation.
            return (127 * "value".hashCode()) ^ value.hashCode() +
                    (127 * "qualifier".hashCode()) ^ qualifier.hashCode();
        }

        @Override
        public boolean equals(Object o)
        {
            if (!(o instanceof DriftClientAnnotation)) {
                return false;
            }
            DriftClientAnnotation other = (DriftClientAnnotation) o;
            return Objects.equals(value, other.value()) && Objects.equals(qualifier, other.qualifier());
        }

        @Override
        public String toString()
        {
            return format("@%s(value=%s, qualifier=%s)", DriftClientAnnotation.class.getName(), value, qualifier);
        }
    }
}


text:
package com.redhat.ceylon.model.loader.impl.reflect.mirror;

import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.redhat.ceylon.model.loader.mirror.ClassMirror;
import com.redhat.ceylon.model.loader.mirror.TypeKind;
import com.redhat.ceylon.model.loader.mirror.TypeMirror;
import com.redhat.ceylon.model.loader.mirror.TypeParameterMirror;

public class ReflectionType implements TypeMirror {

    private Type type;
    private List<TypeMirror> typeArguments;
    private ReflectionType componentType;
    private ReflectionType upperBound;
    private ReflectionType lowerBound;
    private boolean lowerBoundSet;
    private boolean upperBoundSet;
    private ReflectionClass declaredClass;
    private boolean declaredClassSet;
    private boolean typeParameterSet;
    private ReflectionTypeParameter typeParameter;
    private ReflectionType qualifyingType;
    private boolean qualifyingTypeSet;

    public ReflectionType(Type type) {
        this.type = type;
    }

    @Override
    public String getQualifiedName() {
        if(type instanceof ParameterizedType){
            return ((Class<?>)((ParameterizedType)type).getRawType()).getName();
        }
        if(type instanceof TypeVariable)
            return ((TypeVariable<?>)type).getName();
        Class<?> klass = (Class<?>)type;
        return klass.getName();
    }

    @Override
    public List<TypeMirror> getTypeArguments() {
        if(typeArguments != null)
            return typeArguments;
        if(type instanceof ParameterizedType){
            Type[] javaTypeArguments = ((ParameterizedType)type).getActualTypeArguments();
            typeArguments = new ArrayList<TypeMirror>(javaTypeArguments.length);
            for(Type typeArgument : javaTypeArguments)
                typeArguments.add(new ReflectionType(typeArgument));
            return typeArguments;
        }else
            typeArguments = Collections.<TypeMirror>emptyList();
        return typeArguments;
    }

    private static final Map<Class<?>, TypeKind> primitives = new HashMap<Class<?>, TypeKind>();
    static{
        primitives.put(Boolean.TYPE, TypeKind.BOOLEAN);
        primitives.put(Byte.TYPE, TypeKind.BYTE);
        primitives.put(Character.TYPE, TypeKind.CHAR);
        primitives.put(Short.TYPE, TypeKind.SHORT);
        primitives.put(Integer.TYPE, TypeKind.INT);
        primitives.put(Long.TYPE, TypeKind.LONG);
        primitives.put(Float.TYPE, TypeKind.FLOAT);
        primitives.put(Double.TYPE, TypeKind.DOUBLE);
        primitives.put(Void.TYPE, TypeKind.VOID);
    }

    @Override
    public TypeKind getKind() {
        if(type instanceof ParameterizedType)
            return TypeKind.DECLARED;
        if(type instanceof GenericArrayType)
            return TypeKind.ARRAY;
        if(type instanceof TypeVariable)
            return TypeKind.TYPEVAR;
        if(type instanceof WildcardType)
            return TypeKind.WILDCARD;
        if(type instanceof Class){
            TypeKind kind = primitives.get(type);
            if(kind != null)
                return kind;
            return ((Class<?>)type).isArray() ? TypeKind.ARRAY : TypeKind.DECLARED;
        }
        throw new RuntimeException("Unknown type: "+type);
    }

    @Override
    public TypeMirror getComponentType() {
        if(componentType != null)
            return componentType;
        Type ct;
        if(type instanceof Class)
            ct = ((Class<?>)type).getComponentType();
        else
            ct = ((GenericArrayType)type).getGenericComponentType();
        componentType = new ReflectionType(ct);
        return componentType;
    }

    @Override
    public boolean isPrimitive() {
        return primitives.containsKey(type);
    }

    @Override
    public String toString() {
        return "[ReflectionType: "+type.toString()+"]";
    }

    @Override
    public TypeMirror getUpperBound() {
        if(upperBoundSet)
            return upperBound;
        if(type instanceof WildcardType){
            // so the JavaDoc for WildcardType says that the upper bound can still be set to Object
            // even if we have a lower bound set. In order to detect this, we check the lower bound.
            // if there is no lower bound we will get null so all works out
            if(getLowerBound() == null){
                Type[] ct = ((WildcardType)type).getUpperBounds();
                // I don't see how there can possibly be more than one bound here according to the spec and grammar, for a wildcard type
                if(ct.length != 1)
                    throw new RuntimeException("Not one upper bound in wildcard type: "+ct.length);
                upperBound = new ReflectionType(ct[0]);
            }else
                upperBound = null;
        }
        upperBoundSet = true;
        return upperBound;
    }

    @Override
    public TypeMirror getLowerBound() {
        if(lowerBoundSet)
            return lowerBound;
        Type[] ct = ((WildcardType)type).getLowerBounds();
        if(ct.length == 0)
            return null;
        // I don't see how there can possibly be more than one bound here according to the spec and grammar, for a wildcard type
        if(ct.length > 1)
            throw new RuntimeException("More than one lower bound in wildcard type: "+ct.length);
        lowerBound = new ReflectionType(ct[0]);
        lowerBoundSet = true;
        return lowerBound;
    }

    @Override
    public boolean isRaw() {
        if(type instanceof ParameterizedType){
            // we're raw if our type is a parameterised type that should have type params
            ParameterizedType ptype = ((ParameterizedType)type);
            Class<?> klass = (Class<?>) ptype.getRawType();
            return klass.getTypeParameters().length != ptype.getActualTypeArguments().length;
        }
        if(type instanceof GenericArrayType)
            return getComponentType().isRaw();
        if(type instanceof TypeVariable)
            return false;
        if(type instanceof WildcardType)
            return false;
        if(type instanceof Class){
            // we're raw if our type is a parameterised type that should have type params
            return ((Class<?>)type).getTypeParameters().length != 0;
        }
        throw new RuntimeException("Unknown type: "+type);
    }

    @Override
    public ClassMirror getDeclaredClass() {
        if(!declaredClassSet){
            if(type instanceof Class){
                declaredClass = new ReflectionClass((Class<?>) type);
            }else if(type instanceof ParameterizedType){
                declaredClass = new ReflectionClass((Class<?>) ((ParameterizedType) type).getRawType());
            }
            declaredClassSet = true;
        }
        return declaredClass;
    }

    @Override
    public TypeParameterMirror getTypeParameter() {
        if(getKind() != TypeKind.TYPEVAR)
            return null;
        if(!typeParameterSet){
            typeParameter = new ReflectionTypeParameter(type);
            typeParameterSet = true;
        }
        return typeParameter;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public TypeMirror getQualifyingType() {
        if(!qualifyingTypeSet){
            Type ownerType = null;
            if(type instanceof Class){
                ownerType  = ((Class) type).getEnclosingClass();
            }else if(type instanceof ParameterizedType){
                ownerType = ((ParameterizedType) type).getOwnerType();
            }
            if(ownerType != null){
                qualifyingType = new ReflectionType(ownerType);
            }
            qualifyingTypeSet = true;
        }
        return qualifyingType;
    }
}


text:
package app.services;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.joda.time.DateTime;
import org.sql2o.Connection;

import app.entity.Bid;
import app.entity.Offer;
import app.system.AbstractBaseService;

public class OfferService extends AbstractBaseService {

	public void batchDeleteAndInsert(String asin, List<Offer> offers){
		delete(asin);
		for (Offer offer : offers) {
			offer.last_crawled = new DateTime();
			insert(offer);
		}
	}

	public Integer insert(Offer offer) {
		String sql = "";
		sql += "INSERT INTO offer (asin, cond, is_fba, no, price, shipping_costs, last_crawled, created) ";
		sql += "VALUES (:asin, :cond, :is_fba, :no, :price, :shipping_costs, :last_crawled, :created)";

		try (Connection con = sql2o.open()) {
			return con.createQuery(sql).addParameter("asin", offer.asin).addParameter("cond", offer.cond)
					.addParameter("is_fba", offer.is_fba).addParameter("no", offer.no)
					.addParameter("price", offer.price).addParameter("shipping_costs", offer.shipping_costs)
					.addParameter("last_crawled", offer.last_crawled).addParameter("created", new DateTime())
					.executeUpdate().getKey(Integer.class);
		}
	}

	public void delete(String asin) {
		String sql = "delete from offer where asin = :asin";

		try (Connection con = sql2o.open()) {
			con.createQuery(sql).addParameter("asin", asin).executeUpdate();
		}
	}

	public Bid findOne(String asin) {
		String sql = "select * from bid where asin = :asin ";
		try (Connection con = sql2o.open()) {
			Bid bid = con.createQuery(sql).addParameter("asin", asin).executeAndFetchFirst(Bid.class);
			return bid;
		}
	}

	public Integer calcSalesPrice(String asin) {
		String sql = "";
		sql += "select 1 id, min(price) sales_price from offer where asin = :asin and cond = 'usedVeryGood' group by cond ";
		sql += "union ";
		sql += "select 2 id, max(price) sales_price from offer where asin = :asin and cond = 'usedGood' group by cond ";
		sql += "union  ";
		sql += "select 3 id, max(price) sales_price from offer where asin = :asin and cond = 'usedAcceptable' group by cond ";
		sql += "order by id ";

		try (Connection con = sql2o.open()) {
			Bid bid = con.createQuery(sql).addParameter("asin", asin).addParameter("asin", asin)
					.addParameter("asin", asin).executeAndFetchFirst(Bid.class);
			return bid == null ? null : bid.sales_price;
		}
	}

	public Integer calcSalesPrice(List<Offer> offers) {
		List<Offer> usedLikeNews = new ArrayList<>();
		List<Offer> usedVeryGoods = new ArrayList<>();
		List<Offer> usedGoods = new ArrayList<>();
		List<Offer> usedAcceptables = new ArrayList<>();

		for (Offer offer : offers) {
			switch (offer.cond) {
			case "usedLikeNew":
				usedLikeNews.add(offer);
				break;
			case "usedVeryGood":
				usedVeryGoods.add(offer);
				break;
			case "usedGood":
				usedGoods.add(offer);
				break;
			case "usedAcceptable":
				usedAcceptables.add(offer);
				break;
			}
		}

		Offer usedVeryGoodOffer = Collections.min(usedVeryGoods);
		Offer usedGoodOffer = Collections.max(usedGoods);
		Offer usedAcceptableOffer = Collections.max(usedAcceptables);

		if (usedVeryGoodOffer != null) {
			return usedVeryGoodOffer.price;
		} else if (usedGoodOffer != null) {
			return usedGoodOffer.price;
		} else if (usedAcceptableOffer != null) {
			return usedAcceptableOffer.price;
		}
		return null;
	}

	public String convertCondtionString(String text) {
		if ("新品".equals(text)) {
			return "new";
		} else if ("中古品 - ほぼ新品".equals(text)) {
			return "usedLikeNew";
		} else if ("中古品 - 非常に良い".equals(text)) {
			return "usedVeryGood";
		} else if ("中古品 - 良い".equals(text)) {
			return "usedGood";
		} else if ("中古品 - 可".equals(text)) {
			return "usedAcceptable";
		}
		return null;
	}
}


text:
package ru.skysoftlab.gpio;

import java.io.Serializable;

public interface IPin extends Serializable {

	public String getName();

	public PinType getPinType();

}


text:
package mobi.qubits.ex.library.domain;

import org.axonframework.commandhandling.CommandExecutionException;

/**
 *
 * @author yizhuan
 *
 */
public class BorrowingSameBookException extends CommandExecutionException {

	public BorrowingSameBookException() {
		super("You are borrowing the same book you've laready borrowed.", null);
	}

	public BorrowingSameBookException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

}


text:
<?
	$form_household_members   = $this->session->userdata('form_household_members');
	$primary_name = $form_household_members[0]['first_name'];
	if (trim($form_household_members[0]['middle_initial'])) {
		$primary_name .= ' '.$form_household_members[0]['middle_initial'];
	}
	$primary_name .= ' '.$form_household_members[0]['last_name'];
?>

<?=$this->lang->line('electronic_sig_title')?>

			*
			<?=$this->lang->line('electronic_sig_subtitle')?>

<?=$this->lang->line('electronic_sig_statement')?>

						<input type="checkbox" name="electronicSignature" data-error="<?=$this->lang->line('error_electronic_sig_agree')?>" required>
						<?=$this->lang->line('electronic_sig_accept')?>

					<input type="text"
						class="form-control input-lg"
						name="electronic_signature"
						id="electronic_signature"
						data-match="#electronic_signature_match"
						data-error="<?=$this->lang->line('error_electronic_sig_name')?>"
						required />

					<?=$primary_name?>
					<input type="hidden" id="electronic_signature_match" value="<?=$primary_name?>" />

Last 4 digits of Social Security Number <?=help_icon($this->lang->line('electronic_sig_ssn_help'))?>

					XXX-XX-
					<input type="text" class="form-control input-lg ssn" name="social_security_last_four" data-error="<?=$this->lang->line('error_electronic_sig_social')?>" />

						<input type="checkbox" name="ssn_not_available" value="1">
						<?=$this->lang->line('electronic_sig_not_available')?>


text:
using System.Runtime.InteropServices;

namespace CreatorIDE.EngineAPI
{
    public static class EditorCamera
    {
        [DllImport(Engine.DllName, EntryPoint = "EditorCamera_SetFocusEntity")]
        public static extern void SetFocusEntity(string uid);
    }
}


text:
package com.guoquan.action.classdemo;

/**
 * @ClassName: B
 * @Package: com.guoquan.action.classdemo
 * @Description:
 * @Datetime: 2020/8/6 16:06
 * @Author: wuyunfeng
 */
public class B {
}


text:
@implementation UIView (Recursion)
- (UIView*)findViewRecursively:(BOOL(^)(UIView* subview, BOOL* stop))recurse
{
    for( UIView* subview in self.subviews ) {
        BOOL stop = NO;
        if( recurse( subview, &stop ) ) {
            return [subview findViewRecursively:recurse];
        } else if( stop ) {
            return subview;
        }
    }

    return nil;
}

-(void)runBlockOnAllSubviews:(SubviewBlock)block
{
    block(self);
    for (UIView* view in [self subviews])
    {
        [view runBlockOnAllSubviews:block];
    }
}

-(void)runBlockOnAllSuperviews:(SuperviewBlock)block
{
    block(self);
    if (self.superview)
    {
        [self.superview runBlockOnAllSuperviews:block];
    }
}

-(void)enableAllControlsInViewHierarchy
{
    [self runBlockOnAllSubviews:^(UIView *view) {

        if ([view isKindOfClass:[UIControl class]])
        {
            [(UIControl *)view setEnabled:YES];
        }
        else if ([view isKindOfClass:[UITextView class]])
        {
            [(UITextView *)view setEditable:YES];
        }
    }];
}

-(void)disableAllControlsInViewHierarchy
{
    [self runBlockOnAllSubviews:^(UIView *view) {

        if ([view isKindOfClass:[UIControl class]])
        {
            [(UIControl *)view setEnabled:NO];
        }
        else if ([view isKindOfClass:[UITextView class]])
        {
            [(UITextView *)view setEditable:NO];
        }
    }];
}
@end


text:
namespace base {
class DictionaryValue;
class Value;
}

namespace chromeos {
namespace onc {

struct OncValueSignature;

// The ONC Validator searches for the following invalid cases:
// - a value is found that has the wrong type or is not expected according to
//   the ONC spec (always an error)
//
// - a field name is found that is not part of the signature
//   (controlled by flag |error_on_unknown_field|)
//
// - a kRecommended array contains a field name that is not part of the
//   enclosing object's signature or if that field is dictionary typed
//   (controlled by flag |error_on_wrong_recommended|)
//
// - |managed_onc| is false and a field with name kRecommended is found
//   (always ignored)
//
// - a required field is missing (controlled by flag |error_on_missing_field|)
//
// If one of these invalid cases occurs and, in case of a controlling flag, that
// flag is true, then it is an error. The function ValidateAndRepairObject sets
// |result| to INVALID and returns NULL.
//
// Otherwise, a DeepCopy of the validated object is created, which contains
// all but the invalid fields and values.
//
// If one of the invalid cases occurs and the controlling flag is false, then
// it is a warning. The function ValidateAndRepairObject sets |result| to
// VALID_WITH_WARNINGS and returns the repaired copy.
//
// If no error occurred, |result| is set to VALID and an exact DeepCopy is
// returned.
class CHROMEOS_EXPORT Validator : public Mapper {
 public:
  enum Result {
    VALID,
    VALID_WITH_WARNINGS,
    INVALID
  };

  // See the class comment.
  Validator(bool error_on_unknown_field,
            bool error_on_wrong_recommended,
            bool error_on_missing_field,
            bool managed_onc);

  virtual ~Validator();

  // Sets the ONC source to |source|. If not set, defaults to ONC_SOURCE_NONE.
  // If the source is set to ONC_SOURCE_DEVICE_POLICY, validation additionally
  // checks:
  // - only the network types Wifi and Ethernet are allowed
  // - client certificate patterns are disallowed
  void SetOncSource(::onc::ONCSource source) {
    onc_source_ = source;
  }

  // Validate the given |onc_object| according to |object_signature|. The
  // |object_signature| has to be a pointer to one of the signatures in
  // |onc_signature.h|. If an error is found, the function returns NULL and sets
  // |result| to INVALID. If possible (no error encountered) a DeepCopy is
  // created that contains all but the invalid fields and values and returns
  // this "repaired" object. That means, if not handled as an error, then the
  // following are dropped from the copy:
  // - unknown fields
  // - invalid field names in kRecommended arrays
  // - kRecommended fields in an unmanaged ONC
  // If any of these cases occurred, sets |result| to VALID_WITH_WARNINGS and
  // otherwise to VALID.
  // For details, see the class comment.
  scoped_ptr<base::DictionaryValue> ValidateAndRepairObject(
      const OncValueSignature* object_signature,
      const base::DictionaryValue& onc_object,
      Result* result);

 private:
  // Overridden from Mapper:
  // Compare |onc_value|s type with |onc_type| and validate/repair according to
  // |signature|. On error returns NULL.
  virtual scoped_ptr<base::Value> MapValue(
    const OncValueSignature& signature,
    const base::Value& onc_value,
    bool* error) OVERRIDE;

  // Dispatch to the right validation function according to
  // |signature|. Iterates over all fields and recursively validates/repairs
  // these. All valid fields are added to the result dictionary. Returns the
  // repaired dictionary. Only on error returns NULL.
  virtual scoped_ptr<base::DictionaryValue> MapObject(
      const OncValueSignature& signature,
      const base::DictionaryValue& onc_object,
      bool* error) OVERRIDE;

  // Pushes/pops the |field_name| to |path_|, otherwise like |Mapper::MapField|.
  virtual scoped_ptr<base::Value> MapField(
      const std::string& field_name,
      const OncValueSignature& object_signature,
      const base::Value& onc_value,
      bool* found_unknown_field,
      bool* error) OVERRIDE;

  // Ignores nested errors in NetworkConfigurations and Certificates, otherwise
  // like |Mapper::MapArray|.
  virtual scoped_ptr<base::ListValue> MapArray(
      const OncValueSignature& array_signature,
      const base::ListValue& onc_array,
      bool* nested_error) OVERRIDE;

  // Pushes/pops the index to |path_|, otherwise like |Mapper::MapEntry|.
  virtual scoped_ptr<base::Value> MapEntry(
      int index,
      const OncValueSignature& signature,
      const base::Value& onc_value,
      bool* error) OVERRIDE;

  // This is the default validation of objects/dictionaries. Validates
  // |onc_object| according to |object_signature|. |result| must point to a
  // dictionary into which the repaired fields are written.
  bool ValidateObjectDefault(
      const OncValueSignature& object_signature,
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  // Validates/repairs the kRecommended array in |result| according to
  // |object_signature| of the enclosing object.
  bool ValidateRecommendedField(
      const OncValueSignature& object_signature,
      base::DictionaryValue* result);

  bool ValidateToplevelConfiguration(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateNetworkConfiguration(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateEthernet(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateIPConfig(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateWiFi(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateVPN(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateIPsec(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateOpenVPN(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateCertificatePattern(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateProxySettings(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateProxyLocation(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateEAP(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool ValidateCertificate(
      const base::DictionaryValue& onc_object,
      base::DictionaryValue* result);

  bool FieldExistsAndHasNoValidValue(const base::DictionaryValue& object,
                                     const std::string &field_name,
                                     const char** valid_values);

  bool FieldExistsAndIsNotInRange(const base::DictionaryValue& object,
                                  const std::string &field_name,
                                  int lower_bound,
                                  int upper_bound);

  bool FieldExistsAndIsEmpty(const base::DictionaryValue& object,
                             const std::string& field_name);

  bool RequireField(const base::DictionaryValue& dict, const std::string& key);

  // Prohibit certificate patterns for device policy ONC so that an unmanaged
  // user won't have a certificate presented for them involuntarily.
  bool IsCertPatternInDevicePolicy(const std::string& cert_type);

  // Prohibit global network configuration in user ONC imports.
  bool IsGlobalNetworkConfigInUserImport(
      const base::DictionaryValue& onc_object);

  std::string MessageHeader();

  const bool error_on_unknown_field_;
  const bool error_on_wrong_recommended_;
  const bool error_on_missing_field_;
  const bool managed_onc_;

  ::onc::ONCSource onc_source_;

  // The path of field names and indices to the current value. Indices
  // are stored as strings in decimal notation.
  std::vector<std::string> path_;

  // Tracks if an error or warning occurred within validation initiated by
  // function ValidateAndRepairObject.
  bool error_or_warning_found_;

  DISALLOW_COPY_AND_ASSIGN(Validator);
};

}  // namespace onc
}  // namespace chromeos

#endif  // CHROMEOS_NETWORK_ONC_ONC_VALIDATOR_H_


text:
using ELF.NET.Attributes;

namespace ELF.NET.Sections
{
    public enum EnumSpecialSectionIndexes
    {
        [Description("Undefined Section")]
        SHN_UNDEF = 0,
        [Description("Low process section")]
        SHN_LOPROC = 0xFF00,
        [Description("High process section")]
        SHN_HIPROC = 0xFF1F,
        [Description("Low Operating System Section")]
        SHN_LOOS = 0xFF20,
        [Description("High Operating System Section")]
        SHN_HIOS = 0xFF3F,
        [Description("Absolute Values Section")]
        SHN_ABS = 0xFFF1,
        [Description("Common Symbols Section")]
        SHN_COMMON = 0xFFF2,
        [Description("Section Header Escape Value")]
        SHN_XINDEX = 0xFFFF,
    }
}


text:
class FiniteImpulseResponse
{
public:
	FiniteImpulseResponse(char *FileName);
	FiniteImpulseResponse(float *ImpulseResponse, unsigned int ImpulseResponseLength_Samples, float SampleRate_Hz);
	~FiniteImpulseResponse();

	float Filter(float Sample);

	float GetSampleRate_Hz(void);
private:
	void InitializeRingBuffer(void);
	float *RingBuffer;
	float *ImpulseResponse;
	unsigned int ImpulseResponseLength_Samples;
	float SampleRate_Hz;
	unsigned int StartIndex, EndIndex;	// Indices for the ring buffer
};

#endif


text:
var BrowserItem = Vue.component('browser-item', {
  template: '#browser-item',
  props: ['leaf'],
  data: function () {
    return { open: true }
  },
  computed: {
    isFolder: function () {
      return this.leaf.children &&
        this.leaf.children.length
    }
  },
  methods: {
    browse: function () {
      if (this.isFolder) {
        this.leaf.open = !this.leaf.open;
      }
      else {
        send([{
            'action': 'open',
            'path': this.leaf.path,
        }])
      }
    },
    addChild: function () {
      this.leaf.children.push({
        name: 'new stuff'
      })
    }
  }
})

var Browser = Vue.component('browser', {
  template: '#browser',
  components: {
    'browser-item': BrowserItem
  }
})


text:
include $(CLEAR_VARS)

TESTS_TO_BUILD := Foundation

# Makefile Entrypoint: for running `make` without an argument.
.PHONY: all
all: $(foreach t,$(TESTS_TO_BUILD),$(t).UnitTests.exe)

.PHONY: $(TESTS_TO_BUILD)

Foundation.UnitTests.exe :
	make -C Foundation Foundation.UnitTests.exe

.PHONY: clean

clean:
	make -C Foundation clean


text:
'use strict';

/**
 * Karma unit tests.
 */
describe('<%= componentName %>Controller', function(){

  var <%= componentName %>Controller;

  beforeEach(module('<%= appName %>.<%= moduleName %>'));

  beforeEach(inject(function(_$rootScope_, _$controller_) {

    <%= componentName %>Controller = _$controller_('<%= componentName %>Controller', {
      $scope: _$rootScope_.$new()
    });

  }));

});