text:
var World = (function(){
    var mtable = {
        0:{ 0:100, 1:-50, 2:40, 3:30, 4:30, 5:40, 6:-50, 7:100,},
        1:{ 0:-50, 1:-30, 2:5,  3:1,  4:1,  5:5,  6:-30, 7:-50,},
        2:{ 0:40,  1:5,   2:20, 3:10, 4:10, 5:20, 6:5,   7:40,},
        3:{ 0:30,  1:1,   2:10, 3:0,  4:0,  5:10, 6:1,   7:30,},
        4:{ 0:30,  1:1,   2:10, 3:0,  4:0,  5:10, 6:1,   7:30,},
        5:{ 0:40,  1:5,   2:20, 3:10, 4:10, 5:20, 6:5,   7:40,},
        6:{ 0:-50, 1:-30, 2:5,  3:1,  4:1,  5:5,  6:-30, 7:-50,},
        7:{ 0:100, 1:-50, 2:40, 3:30, 4:30, 5:40, 6:-50, 7:100,},
    };
    var w = {
        boardTexture:{board: 'images/game_014_board.png', black: 'images/game_002_blackpc.png', white: 'images/game_003_whitepc.png', leftPieces: 'images/game_004_pcleftside.png', rightPieces: 'images/game_005_pcrightside.png', hidePieces: 'images/game_015_pcside.png', p1Image: 'images/game_011_settings1p.png', p2Image: 'images/game_010_settings2p.png',},
        board: [[],[],[],[],[],[],[],[],],
        bounder: 8,
        boardview: 'board',
        blackResultView: 'black_result',
        whiteResultView: 'white_result',
        leftPiecesView: 'left_pieces',
        rightPiecesView: 'right_pieces',
        messageview: 'message',
        result: 'result',
        isEnd: false,
        endMessage: '',
        isUserTurn: true,
        isDrawing: false,
        isLock: false,
        isInit: false,
        isConfigure: false,
        isResult: false,
        level: 3,
        hasHelp: false,
        hasInit: false,
        playerNum: 1,
        currentColor: 'black',
        step: 4,
        point: [],
        directs: [[1,0],[1,1],[1,-1],[0,1],[0,-1],[-1,0],[-1,1],[-1,-1]],
        heap: {'nextLevel':{}},
        soundSource: {
            'snd_hint':{'src':'audio/Hint.ogg'},
            'snd_navclick':{'src':'audio/NavClick.ogg'},
            'snd_navmove':{ 'src':'audio/NavMove.ogg'},
            'snd_settingsclick':{ 'src':'audio/SettingsClick.ogg'},
            'snd_theme':{ 'src':'audio/Theme.ogg'},
            'snd_tileflip':{ 'src':'audio/TileFlip.ogg'},
            'snd_tileplace':{ 'src':'audio/TilePlace.ogg'},
            'snd_victoryhorns':{ 'src':'audio/VictoryHorns.ogg'},
        },
        showWorld: function() {
            if (!this.hasInit) {
                $('#view').html(
                    '

'+
                    '
0
'+
                    '

'+
                    '

'+
                    '
0
'+
                    '

'+
                    '
'+
                      ''+
                      ''+
                    '
'+
                    '

'+
                    '

'+
                     ''+
                     ''+
                     '
'+
                       '
'+
                         '
'+
                           '

'+
                         '
'+
                         '
'+
                           '

'+
                         '
'+
                         '
'+
                           '

'+
                         '
'+
                         '
'+
                           '

'+
                         '
'+
                       '
'+
                       ''+
                     '
'+
                     '

'+
                     '
'+
                       '

'+
                       ''+
                       ''+
                       ''+
                       ''+
                       ''+
                       ''+
                       '

'+
                     '
')
                    .on('click','a.configure',function() {
                         World.configure();
                    })
                    .on('click','a.result_new_p1',function() {
                         World.playSound('snd_navclick');
                         World.init(1);
                    })
                    .on('mouseover','a.result_new_p1',function() {
                         $('img.result_new_p1_rollover').removeClass('display_none');
                         World.playSound('snd_navmove');
                    })
                    .on('mouseout','a.result_new_p1',function() {
                         $('img.result_new_p1_rollover').addClass('display_none');
                    })
                    .on('click','a.result_new_p2',function() {
                         World.playSound('snd_navclick');
                         World.init(2);
                    })
                    .on('mouseover','a.result_new_p2',function() {
                         $('img.result_new_p2_rollover').removeClass('display_none');
                         World.playSound('snd_navmove');
                    })
                    .on('mouseout','a.result_new_p2',function() {
                         $('img.result_new_p2_rollover').addClass('display_none');
                    })
                    .on('click','a.result_exit',function() {
                         window.close();
                    })
                    .on('mouseover','a.result_exit',function() {
                         $('img.result_exit_rollover').removeClass('display_none');
                         World.playSound('snd_navmove');
                    })
                    .on('mouseout','a.result_exit',function() {
                         $('img.result_exit_rollover').addClass('display_none');
                    })
                    .on('click','div.result_quit',function() {
                         World.closeResult();
                    });
                $('.play1_pieces_lable').html(getMessage('pieces', 'pieces'));
                $('.play2_pieces_lable').html(getMessage('pieces', 'pieces'));
                $('#turn').html(getMessage('turn', "'s Turn"));
                $('.result_new_p1').html(getMessage('newOneGame', 'New 1P Game'));
                $('.result_new_p2').html(getMessage('newTwoGame', 'New 2P Game'));
                $('.result_exit').html(getMessage('exit', 'Exit'));
                //$('#license').html(getMessage('license', 'License'));
                //$('#readme').html(getMessage('readme', 'Readme'));
                $('.configure_panel_startover').click(function(){
                    World.startOver();
                }).on('mouseover',function(){
                    $(this).css('background-color','#222222');
                    World.playSound('snd_navmove');
                }).on('mouseout',function(){
                    $(this).css('background-color','#000000');
                }).find('.configure_panel_text').html(getMessage('startover','Start over'));

                $('.configure_panel_newgame').on('mouseover',function(evt){
                    $(this).css('background-color','#222222');
                    World.playSound('snd_navmove');
                }).on('mouseout',function(evt){
                    $(this).css('background-color','#000000');
                }).click(function(){
                    var n = 1;
                    if ($(this).hasClass('configure_panel_new2game')){
                        n = 2;
                    }
                    World.playSound('snd_navclick');
                    World.init(n);
                });

                $('.configure_panel_help').click(function(){
                    World.showHelp();
                }).on('mouseover',function(){
                    $(this).css('background-color','#222222');
                    World.playSound('snd_navmove');
                }).on('mouseout',function(){
                    $(this).css('background-color','#000000');
                }).find('.configure_panel_text').html(getMessage('rules','Rules'));

                $('.configure_panel_exit').click(function(){
                    window.close();
                }).on('mouseover',function(){
                    $(this).css('background-color','#222222');
                    World.playSound('snd_navmove');
                }).on('mouseout',function(){
                    $(this).css('background-color','#000000');
                }).find('.configure_panel_text').html(getMessage('exit','Exit'));
                this.hasInit = true;
            }
        },
        init: function(play){
            this.showWorld();
            this.playerNum = play || 1;
            for (var i in this.board){
                for (var j=0; j<this.bounder; j++){
                    this.board[i][j] =  'board';
                }
            }
            this.board[3][3] = 'black';
            this.board[4][4] = 'black';
            this.board[3][4] = 'white';
            this.board[4][3] = 'white';

            this.isUserTurn = true;
            this.isLock = false;
            this.isConfigure = false;
            this.isResult = false;
            this.currentColor = 'white';
            this.step = 4;
            this.level = 3;
            this.point = [];
            this.heap = {'nextLevel':{}};
            var strLeft = '';
            var strRight = '';
            for (var i=0; i<32; i++) {
                strLeft += '';
                strRight += '';
            }
            $('#'+this.leftPiecesView).html(strLeft);
            $('#'+this.rightPiecesView).html(strRight);
            $('#pc00').attr('src', this.boardTexture['hidePieces']);
            $('#pc01').attr('src', this.boardTexture['hidePieces']);
            $('#pc10').attr('src', this.boardTexture['hidePieces']);
            $('#pc11').attr('src', this.boardTexture['hidePieces']);
            $('#'+this.result).addClass('display_none');
            $('div.configure_panel').addClass('display_none');
            var n = (this.playerNum == 1)?2:1;
            $('.configure_panel_newgame').removeClass('configure_panel_new'+this.playerNum+'game')
                .addClass('configure_panel_new'+n+'game').find('.configure_panel_text')
                .html(getMessage(n+'PlayerGame',n+' Player Game'));

            $('.play1_lable').html(getMessage('player', 'player')+'1');
            if (this.playerNum == 2) {
                $('.play2_lable').html(getMessage('player', 'player')+'2');
            } else {
                $('.play2_lable').html(getMessage('computer', 'comp.'));
            }
            this.isInit = true;

            document.getElementById('open').style.display="none";
            document.getElementById('view').style.display="block";

            this.endConfigure();
            this.drawBoard();
        },
        configure: function(){
            if (!this.isLock || (this.isEnd && this.isLock && !this.isResult)) {
                this.playSound('snd_settingsclick');
                if (!this.isConfigure) {
                    this.isConfigure = true;
                    $('a.configure img').attr('src', 'images/game_007_settingsbtnrollover.png');
                    $('div.configure_panel').removeClass('display_none');
                } else {
                    this.endConfigure();
                }
            }
        },
        endConfigure: function(){
            this.isConfigure = false;
            $('div.configure_panel').addClass('display_none');
            $('a.configure img').attr('src', 'images/game_006_settingsbtn.png');
        },
        startOver: function(){
            this.playSound('snd_navclick');
            this.init(this.playerNum);
            this.endConfigure();
        },
        showHelp: function(){
            this.playSound('snd_navclick');
            this.endConfigure();
            if (!this.hasHelp) {
                this.hasHelp = true;
                $('#help').html(
                    '
'+
                      '

'+
                      '

'+
                    '
'+
                    ''+
                    '')
                  .on('click','a.help_exit',function() {
                      World.exitHelp();
                  })
                  .on('mouseover','a.help_exit',function() {
                      $('img.help_exit_img').removeClass('display_none');
                      World.playSound('snd_navmove');
                  })
                  .on('mouseout','a.help_exit',function() {
                      $('img.help_exit_img').addClass('display_none');
                  });
                $('.help_title').html(getMessage('howtoPlay', 'How to Play'));
                $('.help_contain').html(getMessage('help', "Play a piece on the board so that one or more of your opponent's pieces are between two of your pieces. All of the opponent's pieces between your own turn over and become your color.
The player with the most pieces on the board at the end of the game wins!"));
                $('.help_exit').html(getMessage('goBack', 'Go Back'));
            }
            $('#help').removeClass('display_none');
        },
        exitHelp: function(){
            this.playSound('snd_navclick');
            $('#help').addClass('display_none');
        },
        getSoundSource: function(snd){
            var ret;
            if (typeof this.soundSource[snd] != 'undefined' && typeof this.soundSource[snd]['audio'] != 'undefined') {
                var source = this.soundSource[snd];
                ret = source['audio'];
            } else {
                var src = this.soundSource[snd]['src'];
                ret = new Audio(src);
                this.soundSource[snd]['audio'] = ret;
            }
            return ret;
        },
        playSound: function(snd){
            var audio = this.getSoundSource(snd);
            if (audio.paused == false) {
                audio.pause();
                //audio.currentTime = 0;
            }
            audio.play();
        },
        actionAtPoint: function(place, color){
            var path = [];
            this.heap = this.heap['nextLevel'][String(place[0])+String(place[1])] || {};
            if (typeof this.heap['value'] != 'undefined' && this.heap['color'] == color){
                path = this.heap['path'];
            } else {
                var act = this.getRevertPath(place, color);
                path = act['path'];
                this.heap = {'color':color, 'path':path, 'place':place, 'nextLevel':{}};
            }
            this.clearTips();
            $('#pc'+this.step%2+Math.floor(this.step/2)).attr('src', this.boardTexture['hidePieces']);
            this.step += 1;
            if (this.step >= 55) {
                this.level += 2;
            } else if (this.step >= 50) {
                this.level += 1;
            }
            this.playSound('snd_tileplace');
            this.setPoint(place, color);
            this.setBorder(place);
            this.drawPath(path, color);
        },
        setPoint: function(place, color){
            this.board[place[0]][place[1]] = color;
            this.drawPoint(place, color);
        },
        drawPoint: function(place, color){
            $('img#a'+place[0]+place[1]).attr('src', this.boardTexture[color]).removeClass('tip');
            $('a#l'+place[0]+place[1]).off('mouseover');
        },
        drawPath: function(path, color){
            this.isDrawing = true;
            for (var n=0; n < path.length; n++){
                this.board[path[n][0]][path[n][1]] = color;
                var str = 'World.drawPoint(['+path[n][0]+','+path[n][1]+'],\''+color+'\')';
                setTimeout(str, 100*(n+1));
            }
            setTimeout('World.drawMessage()', 100*(path.length+1));
        },
        setBorder: function(place){
            if (this.point.length > 0){
                $('img#a'+this.point[0]+this.point[1]).removeClass('img_board_select');
                $('img#a'+this.point[0]+this.point[1]).addClass('img_board');
            }
            $('img#a'+place[0]+place[1]).removeClass('img_board');
            $('img#a'+place[0]+place[1]).addClass('img_board_select');
            this.point = place;
        },
        drawMessage: function(){
            var bc = 0;
            var wc = 0;
            if (typeof this.heap['value'] != 'undefined'){
                bc = parseInt(this.heap['black']);
                wc = parseInt(this.heap['white']);
            } else {
                var count = {black:0, white:0};
                for (var i=0; i<this.bounder; i++){
                    for (var j=0; j<this.bounder; j++){
                        count[this.board[i][j]] += parseInt(1);
                    }
                }
                bc = count['black'];
                wc = count['white'];
            }
            $('#'+this.blackResultView).html(bc);
            $('#'+this.whiteResultView).html(wc);

            var bpossible;
            var wpossible;

            if (typeof this.heap['value'] != 'undefined' && this.heap['color'] == this.currentColor){
                if (this.heap['color'] == 'white') {
                    bpossible = this.heap['upossible'];
                    wpossible = this.heap['cpossible'];
                } else {
                    wpossible = this.heap['upossible'];
                    bpossible = this.heap['cpossible'];
                }
            } else {
                wpossible = this.possiblePlace('white');
                bpossible = this.possiblePlace('black');
            }
            this.isEnd = ((bpossible.length == 0 && wpossible.length == 0) || (this.step == 64));
            if (!this.isEnd) {
                var tpossible = bpossible;
                if (this.currentColor == 'black') {
                    if (wpossible.length > 0) {
                        this.currentColor = 'white';
                        tpossible = wpossible;
                    }
                } else {
                    if (bpossible.length > 0) {
                        this.currentColor = 'black';
                    } else {
                        tpossilbe = wpossible;
                    }
                }
                $('#'+this.messageview).attr('src', this.boardTexture[this.currentColor]);
                this.possible = tpossible;
                this.setTips(this.currentColor);
                if (this.playerNum == 1 && this.currentColor == 'white') {
                    this.isUserTurn = false;
                    this.computerTurn();
                } else {
                    this.isUserTurn = true;
                }
            } else {
                var p = getMessage('player', 'player');
                var w = getMessage('win', 'Wins');
                if (bc > wc) {
                    $('.result_win_text').html(p+' 1 '+w+'!');
                } else if (bc == wc) {
                    $('.result_win_text').html(getMessage('winDraw', 'Draw!'));
                } else {
                    if (this.playerNum == 2) {
                        $('.result_win_text').html(p+' 2 '+w+'!');
                    } else {
                        $('.result_win_text').html(getMessage('winComputer', 'Computer Wins!'));
                    }
                }
                this.playSound('snd_victoryhorns');
                $('#'+this.result).removeClass('display_none');
                this.isLock = true;
                this.isResult = true;
            }
            this.isDrawing = false;
        },
        closeResult: function() {
            $('#'+this.result).addClass('display_none');
            this.isResult = false;
        },
        setTips: function(color) {
            var stone = this.boardTexture[color];
            var spare = this.boardTexture['board'];
            var makeMouseOverHandler = function(id,stone) {
              return function() {
                $('#'+id+' img').attr('src',stone).addClass('tip');
              };
            };
            var makeMouseOutHandler = function(id,spare) {
              return function() {
                $('#'+id+' img').attr('src',spare).removeClass('tip');
              };
            };

            for (var n in this.possible) {
                var p = this.possible[n];
                if (this.board[p[0]][p[1]] == 'board') {
                    var id = 'l'+p[0]+p[1];
                    $('#'+id)
                      .on('mouseover',makeMouseOverHandler(id,stone))
                      .on('mouseout',makeMouseOutHandler(id,spare));
                }
            }
        },
        clearTips: function() {
            var possible = this.possible;

            for (var n in possible) {
                var p = possible[n];
                var spare = this.boardTexture[this.board[p[0]][p[1]]];
                var id = 'l'+p[0]+p[1];
                $('#'+id)
                  .off('mouseover')
                  .off('mouseout').find('img').attr('src', spare).removeClass('tip');
            }
        },
        drawBoard: function(){
            var $boardview = $('#'+this.boardview);
            var makeClickHandler = function(i,j) {
              return function() {
                World.click(i,j);
              };
            };

            var str = '';
            for (var i=0; i<this.bounder; i++){
                str += '
';
                for (var j=0; j<this.bounder; j++){
                    var ij=''+i+j;
                    var aid='l'+ij;
                    var iid='a'+ij;
                    str +=
                      ''+
                        ''+
                          ''+
                        ''+
                      '';
                    $boardview
                      .on('click','#'+iid, makeClickHandler(i,j));
                }
                str += '
';
            }
            $boardview.html(str);
            this.drawMessage();
        },

        click: function(i, j){
            if (this.board[i][j] === 'board' && !this.isEnd && this.isUserTurn && !this.isDrawing && !this.isLock && !this.isConfigure) {
                if (this.canRevert([i, j], this.currentColor)){
                    this.actionAtPoint([i,j], this.currentColor);
                    if (this.playerNum == 1) this.isUserTurn = false;
                } else {
                    this.playSound('snd_hint');
                }
            } else if ((this.isConfigure && !this.isEnd && !this.isDrawing && !this.isLock)
                       || (this.isConfigure && this.isEnd && !this.isDrawing && this.isLock && !this.isResult)) {
                this.endConfigure();
            }
        },
        computerTurn: function(){
            if (this.isDrawing) {
                setTimeout('World.computerTurn()', 500);
                return;
            }
            var possible;

            if (typeof this.heap['value'] != 'undefined'){
                if (this.heap['color'] == 'white') {
                    possible = this.heap['cpossible'];
                } else {
                    possible = this.heap['upossible'];
                }
            } else {
                possible = this.possiblePlace('white');
            }
            var place = this.bestPlace(possible);
            if (possible.length > 0 && place.length > 0) {
                this.actionAtPoint(place, 'white');
            }
        },

        isContain: function(place, _array) {
            var heat = _array || [];
            for (var i = 0; i < heat.length; i++){
                if (heat[i][0] == place[0] && heat[i][1] == place[1]) {
                    return true;
                }
            }
            return false;

        },
        possiblePlace: function(color, _board){
            var ret = [];
            var tmp = {};
            var revColor = ((color == 'white')?'black':'white');
            var board = _board || this.board;
            for (var i=0; i<this.bounder; i++){
                for (var j=0; j<this.bounder; j++){
                    if (board[i][j] === revColor) {
                        var directs = this.directs;
                        for (var n = 0; n < directs.length; n++) {
                            var ni = i+parseInt(directs[n][0]);
                            var nj = j+parseInt(directs[n][1]);
                            if (ni >= 0 && ni < this.bounder && nj >= 0 && nj < this.bounder && board[ni][nj] === 'board'){
                                if (this.canRevert([ni, nj], color, board) && !this.isContain([ni, nj], ret)){
                                    ret.push([parseInt(ni), parseInt(nj)]);
                                }
                            }
                        }
                    }
                }
            }

            return ret;
        },
        canRevert: function(place, color, _board){
            var i = parseInt(place[0]);
            var j = parseInt(place[1]);
            var revColor = ((color == 'white')?'black':'white');
            var board = _board || this.board;
            var directs = this.directs;
            for (var n = 0; n < directs.length; n++) {
                var di = parseInt(directs[n][0]);
                var dj = parseInt(directs[n][1]);
                var ni = i+di;
                var nj = j+dj;
                while (ni >= 0 && ni < this.bounder && nj >= 0 && nj < this.bounder && board[ni][nj] === revColor){
                    ni += di;
                    nj += dj;
                    if (ni >= 0 && ni < this.bounder && nj >= 0 && nj < this.bounder && board[ni][nj] === color) {
                        return true;
                    }
                }
            }
            return false;
        },
        getClone: function(obj){
            var ret = [[],[],[],[],[],[],[],[]];

            for(var i = 0; i < this.bounder; i++) {
                for(var j = 0; j < this.bounder; j++) {
                    ret[i][j] = obj[i][j];
                }
            }
            return ret;
        },

        getRevertPath: function(place, color, _board){
            var i = parseInt(place[0]);
            var j = parseInt(place[1]);
            var revColor = ((color == 'white')?'black':'white');
            var board = _board || this.board;
            var path = [];
            var directs = this.directs;
            for (var n = 0; n < directs.length; n++) {
                var ni = i+parseInt(directs[n][0]);
                var nj = j+parseInt(directs[n][1]);
                var tpath = [];
                while (ni >= 0 && ni < this.bounder && nj >= 0 && nj < this.bounder && board[ni][nj] === revColor){
                    tpath.push([ni, nj]);
                    ni += parseInt(directs[n][0]);
                    nj += parseInt(directs[n][1]);
                    if (ni >= 0 && ni < this.bounder && nj >= 0 && nj < this.bounder && board[ni][nj] === color) {
                        path = path.concat(tpath);
                    }
                }
            }
            return {place: place, path: path, color: color,};
        },

        doRevert: function(action, _board){
            var color = action['color'];
            var board = _board || this.board;
            var path = action['path'];
            for (var p in path){
                board[path[p][0]][path[p][1]] = color;
            }
            return board;
        },
        getValue: function(place, _board){
            var ret = 0;
            var board = _board || this.board;
            var i = parseInt(place[0]);
            var j = parseInt(place[1]);
            return parseInt(mtable[i][j]);
        },
        evaluate: function(place, _color, _board, _level, _heap){
            var ret = -100000;
            var level = _level || this.level;
            var heap = _heap || this.heap;
            if (typeof heap['nextLevel'][String(place[0])+String(place[1])] == 'undefined'){
                heap['nextLevel'][String(place[0])+String(place[1])] = {};
            }
            heap = heap['nextLevel'][String(place[0])+String(place[1])];
            level = parseInt(level);
            var toEndLevel = 64-parseInt(this.step);
            level = (level>toEndLevel?toEndLevel:level);
            var nextValue = 0;
/*
            var i = parseInt(place[0]);
            var j = parseInt(place[1]);*/

            var color = _color || 'white';
            var board = _board || this.board;
            board = this.getClone(board);
            var revColor = ((color == 'white')?'black':'white');
            var sym = ((color == 'white')?1:-1);

            board[place[0]][place[1]] = color;

            var path;
            var cp;
            var up;
            if (typeof heap['value'] != 'undefined'){
            path = heap['path'];
            ret = heap['value'];
            cp = heap['cpossible'];
            up = heap['upossible'];
            board = this.doRevert(heap, board);
            } else {
            var act = this.getRevertPath(place, color, board);
                heap['path'] = act['path'];
                heap['color'] = color;
                heap['place'] = place;
            board = this.doRevert(heap, board);
                cp = this.possiblePlace(color, board);
                up = this.possiblePlace(revColor, board);

                var cv = 0;
                var uv = 0;
                var cc = 0;
                var uc = 0;

                for (var i=0; i<this.bounder; i++){
                    for (var j=0; j<this.bounder; j++){
                        if (board[i][j] === color) {
                            cv += this.getValue([i, j], board);
                            cc++;
                        } else if (board[i][j] === revColor){
                            uv += this.getValue([i, j], board);
                            uc++;
                        }
                    }
                }

                ret = (cp.length-up.length)*10;
                ret += (cv-uv)*2;
                if (up.length == 0 && cp.length > 0) ret = 100000;
                heap['value'] = ret;
                heap['nextLevel'] = {};
                heap['cpossible'] = cp;
                heap['upossible'] = up;
                heap[color] = cc;
                heap[revColor] = uc;
            }

            if (level > 1 && (up.length > 0 || cp.length > 0)){
            if (up.length == 0){
                up = cp;
                revColor = color;
            }
            up = this.getBestPlaceSet(up);
            for (var p = 0; p < up.length; p++) {
                nextValue += this.evaluate(up[p], revColor, board, level-1, heap);
            }
            if (up.length > 0){
                nextValue = nextValue/up.length;
                ret = Math.round(ret*0.5+nextValue*0.5);
            }
            }

            return ret*sym;
        },
        getBestPlaceSet: function(possible){
            var best = [];
            var middle = [];
            var ret = [];
            for (var i in possible){
                var t = this.getValue(possible[i]);
                if (t == 100) {
                    best.push(possible[i]);
                } else if (t >= 0) {
                    middle.push(possible[i]);
                }
            }

            if (best.length > 0){
                ret = best;
            } else if (middle.length > 0){
                ret = middle;
            } else {
                ret = possible;
            }
            return ret;
        },
        bestPlace: function(possible){
            if (possible.length == 0)
                console.log('Error: No possible places?!!!');
            possible = this.getBestPlaceSet(possible);

            var ret = [];
            if (possible.length > 0) {
                ret = possible[0];
                var value = this.evaluate(ret);
                for (var p=1; p<possible.length; p++) {
                    var v = this.evaluate(possible[p]);
                    if (v > value){
                        value = v;
                        ret = possible[p];
                    }
                }
            } else {
                console.log('Error: No Setting place for Computer');
            }
            return ret;
        },
        showLicense: function(id, hpageid) {
            var lbtn = document.getElementById(id+"btnl");

            var lpage = document.getElementById(id+"page");
            var hpage = document.getElementById(hpageid);
            var ltext;
            var lscroll = document.getElementById(id+"scroll");
            var timer;

            var btnq = document.getElementById(id+"btnq");
            lscroll = document.getElementById(id+"scroll");
            ltext = document.getElementById(id+"text");
            /* initialize scroll rate */
            var dY = 2;
            var t0 = 0;
            var delay = 1000;

            /* set the scroller to the top position */
            lscroll.style.top = "0px";

            /* display the license page, hide its parent */
            hpage.style.display="none";
            lpage.style.display="block";

            /* calculate the scroll length when the window is shown */
            var maxY = lscroll.clientHeight - ltext.clientHeight;

            /* start the autoscroll interval */
            timer = setInterval(function() {
                /* get the actual interval, in case performance slows us down */
                var t1 = (new Date()).getTime();
                var dT = (t0 == 0)?20:(t1-t0);
                t0 = t1;

                /* delay specific number of milliseconds */
                delay -= dT;
                if(delay > 0)
                    return;

                /* calculate the new top position using dY and dT */
                var newY = Math.abs(parseInt(lscroll.style.top)) + ((dT/40)*dY);
                if(newY > 0)
                    lscroll.style.top = (-1 * newY) + "px";
                else
                    lscroll.style.top = "0px";

                /* if the lscroll has hit the limit, delay and swing */
                /* the other way */
                if(newY >= maxY)
                {
                    delay = 5000;
                    dY = -20;
                }
                else if(newY <= 0)
                {
                    delay = 5000;
                    dY = 2;
                }
            }, 40);

            btnq.onclick = function() {
                hpage.style.display="block";
                lpage.style.display="none";
                clearInterval(timer);
            }
        },
    };
    return w;
})();

function getMessage(key, alter) {
    var ret = alter || '';
    if (window.chrome && window.chrome.i18n && window.chrome.i18n.getMessage) {
        ret = chrome.i18n.getMessage(key);
    } else {
        if (typeof this.messages == 'undefined') {
            try {
                var request = new XMLHttpRequest();
                request.open("GET", "_locales/en/messages.json", false);
                request.send();
                var res = request.responseText;
                this.messages = window.eval(res);
            } catch (err) {
                return ret;
            }
        }
        if (this.messages && (this.messages.hasOwnProperty(key)) && (this.messages[key].hasOwnProperty('message'))) {
            ret = this.messages[key].message;
        }
    }
    return ret;
};

function registerEventHandlers() {
  $("body")
    .on("selectstart",function() {
      return false;
    })
    .on("dragstart",function() {
      return false;
    })
    /* #open1 */
    .on("click","#open1",function() {
       World.playSound('snd_navclick');
       World.init(1);
    })
    .on("mouseover","#open1",function() {
		   $('#open_text_bg_4').removeClass('display_none');
       World.playSound('snd_navmove');
    })
    .on("mouseout","#open1",function() {
		   $('#open_text_bg_4').addClass('display_none');
    })
    /* #open2 */
    .on("click","#open2",function() {
      World.playSound('snd_navclick');
      World.init(2);
    })
    .on("mouseover","#open2",function() {
      $('#open_text_bg_3').removeClass('display_none');
      World.playSound('snd_navmove');
    })
    .on("mouseout","#open2",function() {
      $('#open_text_bg_3').addClass('display_none');
    })
    /* #open_help */
    .on("click","#open_help",function() {
      World.showHelp();
    })
    .on("mouseover","#open_help",function() {
      $('#open_text_bg_2').removeClass('display_none');
      World.playSound('snd_navmove');
    })
    .on("mouseout","#open_help",function() {
      $('#open_text_bg_2').addClass('display_none');
    })
    /* #open_exit */
    .on("click","#open_exit",function() {
      window.close();
    })
    .on("mouseover","#open_exit",function() {
      $('#open_text_bg_1').removeClass('display_none');
      World.playSound('snd_navmove');
    })
    .on("mouseout","#open_exit",function() {
      $('#open_text_bg_1').addClass('display_none');
    })
    /* #help_exit */
    .on("click","#help_exit",function() {
      World.exitHelp();
    })
    .on("mouseover","#help_exit",function() {
      $('img.help_exit_img').removeClass('display_none');
      World.playSound('snd_navmove');
    })
    .on("mouseout","#help_exit",function() {
      $('img.help_exit_img').addClass('display_none');
    })
    .on("click","#licensebtnl",function(){
        World.showLicense("license", "open");
    })

    ;
};

window.onload = function(){
    var locale = getMessage('locale', 'en');
    if (locale != 'en') {
        var head  = $('head').q;
        var link  = document.createElement('link');
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = 'css/i18n.css';
        head.appendChild(link);
    }
    $('title').html(getMessage('name', 'Annex'));
    $('#open1').html(getMessage('1PlayerGame', '1 Player Game'));
    $('#open2').html(getMessage('2PlayerGame', '2 Player Game'));
    $('#open_help').html(getMessage('howtoPlay', 'How to Play'));
    $('#open_exit').html(getMessage('exit', 'Exit'));

    registerEventHandlers();

    scaleBody(document.getElementsByTagName("body")[0], 720);

    World.playSound('snd_theme');
};


text:
#pragma once
#include <aws/lambda/Lambda_EXPORTS.h>
#include <aws/core/utils/Array.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Lambda
{
namespace Model
{

  /**
   *
The code for the Lambda function. You can specify either an S3 location, or
   * upload a deployment package directly.

See Also:
   AWS
   * API Reference

   */
  class AWS_LAMBDA_API FunctionCode
  {
  public:
    FunctionCode();
    FunctionCode(Aws::Utils::Json::JsonView jsonValue);
    FunctionCode& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The base64-encoded contents of your zip file containing your deployment
     * package. AWS SDK and AWS CLI clients handle the encoding for you.

     */
    inline const Aws::Utils::ByteBuffer& GetZipFile() const{ return m_zipFile; }

    /**
     *
The base64-encoded contents of your zip file containing your deployment
     * package. AWS SDK and AWS CLI clients handle the encoding for you.

     */
    inline void SetZipFile(const Aws::Utils::ByteBuffer& value) { m_zipFileHasBeenSet = true; m_zipFile = value; }

    /**
     *
The base64-encoded contents of your zip file containing your deployment
     * package. AWS SDK and AWS CLI clients handle the encoding for you.

     */
    inline void SetZipFile(Aws::Utils::ByteBuffer&& value) { m_zipFileHasBeenSet = true; m_zipFile = std::move(value); }

    /**
     *
The base64-encoded contents of your zip file containing your deployment
     * package. AWS SDK and AWS CLI clients handle the encoding for you.

     */
    inline FunctionCode& WithZipFile(const Aws::Utils::ByteBuffer& value) { SetZipFile(value); return *this;}

    /**
     *
The base64-encoded contents of your zip file containing your deployment
     * package. AWS SDK and AWS CLI clients handle the encoding for you.

     */
    inline FunctionCode& WithZipFile(Aws::Utils::ByteBuffer&& value) { SetZipFile(std::move(value)); return *this;}

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline const Aws::String& GetS3Bucket() const{ return m_s3Bucket; }

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline void SetS3Bucket(const Aws::String& value) { m_s3BucketHasBeenSet = true; m_s3Bucket = value; }

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline void SetS3Bucket(Aws::String&& value) { m_s3BucketHasBeenSet = true; m_s3Bucket = std::move(value); }

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline void SetS3Bucket(const char* value) { m_s3BucketHasBeenSet = true; m_s3Bucket.assign(value); }

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline FunctionCode& WithS3Bucket(const Aws::String& value) { SetS3Bucket(value); return *this;}

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline FunctionCode& WithS3Bucket(Aws::String&& value) { SetS3Bucket(std::move(value)); return *this;}

    /**
     *
An Amazon S3 bucket in the same region as your function.

     */
    inline FunctionCode& WithS3Bucket(const char* value) { SetS3Bucket(value); return *this;}

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline const Aws::String& GetS3Key() const{ return m_s3Key; }

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline void SetS3Key(const Aws::String& value) { m_s3KeyHasBeenSet = true; m_s3Key = value; }

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline void SetS3Key(Aws::String&& value) { m_s3KeyHasBeenSet = true; m_s3Key = std::move(value); }

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline void SetS3Key(const char* value) { m_s3KeyHasBeenSet = true; m_s3Key.assign(value); }

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline FunctionCode& WithS3Key(const Aws::String& value) { SetS3Key(value); return *this;}

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline FunctionCode& WithS3Key(Aws::String&& value) { SetS3Key(std::move(value)); return *this;}

    /**
     *
The Amazon S3 key of the deployment package.

     */
    inline FunctionCode& WithS3Key(const char* value) { SetS3Key(value); return *this;}

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline const Aws::String& GetS3ObjectVersion() const{ return m_s3ObjectVersion; }

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline void SetS3ObjectVersion(const Aws::String& value) { m_s3ObjectVersionHasBeenSet = true; m_s3ObjectVersion = value; }

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline void SetS3ObjectVersion(Aws::String&& value) { m_s3ObjectVersionHasBeenSet = true; m_s3ObjectVersion = std::move(value); }

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline void SetS3ObjectVersion(const char* value) { m_s3ObjectVersionHasBeenSet = true; m_s3ObjectVersion.assign(value); }

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline FunctionCode& WithS3ObjectVersion(const Aws::String& value) { SetS3ObjectVersion(value); return *this;}

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline FunctionCode& WithS3ObjectVersion(Aws::String&& value) { SetS3ObjectVersion(std::move(value)); return *this;}

    /**
     *
For versioned objects, the version of the deployment package object to
     * use.

     */
    inline FunctionCode& WithS3ObjectVersion(const char* value) { SetS3ObjectVersion(value); return *this;}

  private:

    Aws::Utils::ByteBuffer m_zipFile;
    bool m_zipFileHasBeenSet;

    Aws::String m_s3Bucket;
    bool m_s3BucketHasBeenSet;

    Aws::String m_s3Key;
    bool m_s3KeyHasBeenSet;

    Aws::String m_s3ObjectVersion;
    bool m_s3ObjectVersionHasBeenSet;
  };

} // namespace Model
} // namespace Lambda
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hdfs;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.hadoop.conf.Configuration;

/**
 * An implementation of a protocol for accessing filesystems over HTTPS. The
 * following implementation provides a limited, read-only interface to a
 * filesystem over HTTPS.
 *
 * @see org.apache.hadoop.hdfs.server.namenode.ListPathsServlet
 * @see org.apache.hadoop.hdfs.server.namenode.FileDataServlet
 */
public class HsftpFileSystem extends HftpFileSystem {

  private static final long MM_SECONDS_PER_DAY = 1000 * 60 * 60 * 24;
  private volatile int ExpWarnDays = 0;

  @Override
  public void initialize(URI name, Configuration conf) throws IOException {
    super.initialize(name, conf);
    setupSsl(conf);
    ExpWarnDays = conf.getInt("ssl.expiration.warn.days", 30);
  }

  /**
   * Set up SSL resources
   *
   * @throws IOException
   */
  private static void setupSsl(Configuration conf) throws IOException {
    Configuration sslConf = new Configuration(false);
    sslConf.addResource(conf.get("dfs.https.client.keystore.resource",
        "ssl-client.xml"));
    FileInputStream fis = null;
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      KeyManager[] kms = null;
      TrustManager[] tms = null;
      if (sslConf.get("ssl.client.keystore.location") != null) {
        // initialize default key manager with keystore file and pass
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance(sslConf.get(
            "ssl.client.keystore.type", "JKS"));
        char[] ksPass = sslConf.get("ssl.client.keystore.password", "changeit")
            .toCharArray();
        fis = new FileInputStream(sslConf.get("ssl.client.keystore.location",
            "keystore.jks"));
        ks.load(fis, ksPass);
        kmf.init(ks, sslConf.get("ssl.client.keystore.keypassword", "changeit")
            .toCharArray());
        kms = kmf.getKeyManagers();
        fis.close();
        fis = null;
      }
      // initialize default trust manager with truststore file and pass
      if (conf.getBoolean("ssl.client.do.not.authenticate.server", false)) {
        // by pass trustmanager validation
        tms = new DummyTrustManager[] { new DummyTrustManager() };
      } else {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        KeyStore ts = KeyStore.getInstance(sslConf.get(
            "ssl.client.truststore.type", "JKS"));
        char[] tsPass = sslConf.get("ssl.client.truststore.password",
            "changeit").toCharArray();
        fis = new FileInputStream(sslConf.get("ssl.client.truststore.location",
            "truststore.jks"));
        ts.load(fis, tsPass);
        tmf.init(ts);
        tms = tmf.getTrustManagers();
      }
      sc.init(kms, tms, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
      throw new IOException("Could not initialize SSLContext", e);
    } finally {
      if (fis != null) {
        fis.close();
      }
    }
  }

  @Override
  protected HttpURLConnection openConnection(String path, String query)
      throws IOException {
    try {
      final URL url = new URI("https", null, nnAddr.getHostName(), nnAddr
          .getPort(), path, query, null).toURL();
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      // bypass hostname verification
      conn.setHostnameVerifier(new DummyHostnameVerifier());
      conn.setRequestMethod("GET");
      conn.connect();

      // check cert expiration date
      final int warnDays = ExpWarnDays;
      if (warnDays > 0) { // make sure only check once
        ExpWarnDays = 0;
        long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY
            + System.currentTimeMillis();
        X509Certificate[] clientCerts = (X509Certificate[]) conn
            .getLocalCertificates();
        if (clientCerts != null) {
          for (X509Certificate cert : clientCerts) {
            long expTime = cert.getNotAfter().getTime();
            if (expTime < expTimeThreshold) {
              StringBuffer sb = new StringBuffer();
              sb.append("\n Client certificate "
                  + cert.getSubjectX500Principal().getName());
              int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY);
              sb.append(" have " + dayOffSet + " days to expire");
              LOG.warn(sb.toString());
            }
          }
        }
      }
      return (HttpURLConnection) conn;
    } catch (URISyntaxException e) {
      throw (IOException) new IOException().initCause(e);
    }
  }

  @Override
  public URI getUri() {
    try {
      return new URI("hsftp", null, nnAddr.getHostName(), nnAddr.getPort(),
          null, null, null);
    } catch (URISyntaxException e) {
      return null;
    }
  }

  /**
   * Dummy hostname verifier that is used to bypass hostname checking
   */
  protected static class DummyHostnameVerifier implements HostnameVerifier {
    public boolean verify(String hostname, SSLSession session) {
      return true;
    }
  }

  /**
   * Dummy trustmanager that is used to trust all server certificates
   */
  protected static class DummyTrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    }

    public X509Certificate[] getAcceptedIssuers() {
      return null;
    }
  }

}


text:
#ifndef TENSORFLOW_PYTHON_LIB_CORE_PY_EXCEPTION_REGISTRY_H_
#define TENSORFLOW_PYTHON_LIB_CORE_PY_EXCEPTION_REGISTRY_H_

#include <map>

#include "tensorflow/c/c_api.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/platform/logging.h"

#ifndef PyObject_HEAD
struct _object;
typedef _object PyObject;
#endif

namespace tensorflow {

// Global registry mapping C API error codes to the corresponding custom Python
// exception type. This is used to expose the exception types to C extension
// code (i.e. so we can raise custom exceptions via SWIG).
//
// Init() must be called exactly once at the beginning of the process before
// Lookup() can be used.
//
// Example usage:
//   TF_Status* status = TF_NewStatus();
//   TF_Foo(..., status);
//
//   if (TF_GetCode(status) != TF_OK) {
//     PyObject* exc_type = PyExceptionRegistry::Lookup(TF_GetCode(status));
//     // Arguments to OpError base class. Set `node_def` and `op` to None.
//     PyObject* args =
//       Py_BuildValue("sss", nullptr, nullptr, TF_Message(status));
//     PyErr_SetObject(exc_type, args);
//     Py_DECREF(args);
//     TF_DeleteStatus(status);
//     return NULL;
//   }
class PyExceptionRegistry {
 public:
  // Initializes the process-wide registry. Should be called exactly once near
  // the beginning of the process. The arguments are the various Python
  // exception types (e.g. `cancelled_exc` corresponds to
  // errors.CancelledError).
  static void Init(PyObject* code_to_exc_type_map);

  // Returns the Python exception type corresponding to `code`. Init() must be
  // called before using this function. `code` should not be TF_OK.
  static PyObject* Lookup(TF_Code code);

  static inline PyObject* Lookup(error::Code code) {
    return Lookup(static_cast<TF_Code>(code));
  }

 private:
  static PyExceptionRegistry* singleton_;
  PyExceptionRegistry() = default;

  // Maps error codes to the corresponding Python exception type.
  std::map<TF_Code, PyObject*> exc_types_;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_PYTHON_LIB_CORE_PY_EXCEPTION_REGISTRY_H_


text:
<?php

namespace common\modules\rapid_assessment\controllers;

use Yii;
use common\modules\rapid_assessment\models\ReportItemImpact;
use common\modules\rapid_assessment\models\search\ReportItemImpactSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ReportItemImpactController implements the CRUD actions for ReportItemImpact model.
 */
class CrudReportItemImpactController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all ReportItemImpact models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ReportItemImpactSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ReportItemImpact model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ReportItemImpact model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ReportItemImpact();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ReportItemImpact model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ReportItemImpact model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ReportItemImpact model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return ReportItemImpact the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ReportItemImpact::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionBatchUpdate()
    {
        $sourceModel = new ReportItemImpact();
    $dataProvider = $sourceModel->search(Yii::$app->request->getQueryParams());
    $models = $dataProvider->getModels();
    if (Model::loadMultiple($models, Yii::$app->request->post()) && Model::validateMultiple($models)) {
        $count = 0;
        foreach ($models as $index => $model) {
            // populate and save records for each model
            if ($model->save()) {
                $count++;
            }
        }
        Yii::$app->session->setFlash('success', "Processed {$count} records successfully.");
        return $this->redirect(['index']); // redirect to your next desired page
    } else {
        return $this->render('update', [
            'model'=>$sourceModel,
            'dataProvider'=>$dataProvider
        ]);
    }
}
}


text:
struct shell *make_shell() {
    static struct shell s;
    s.is_interactive = isatty(STDIN_FILENO);

    return &s;
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Tempest;

namespace Gablarski.Tests
{
	[TestFixture]
	public class UserInfoTests
	{
		private const string Username = "Bar";
		private const string Nickname = "Foo";
		private const string Phonetic = "Phoo";
		private const int UserId = 1;
		private const int ChanId = 2;
		private const bool Muted = true;
		private const string Comment = "There's a monkey in my barrel!";
		private const UserStatus Status = UserStatus.MutedMicrophone | UserStatus.MutedSound;

		public static UserInfo GetTestUser()
		{
			return GetTestUser (0);
		}

		public static UserInfo GetTestUser (int increment)
		{
			return GetTestUser (increment, ChanId + increment, Muted);
		}

		public static UserInfo GetTestUser (int increment, int channelId, bool muted)
		{
			return new UserInfo (Nickname + increment, Phonetic + increment, Username + increment, UserId + increment,
			                     channelId, muted, Comment, Status);
		}

		public static void AssertUserInfosMatch (IUserInfo expected, IUserInfo actual)
		{
			Assert.AreEqual (expected.UserId, actual.UserId);
			Assert.AreEqual (expected.CurrentChannelId, actual.CurrentChannelId);
			Assert.AreEqual (expected.Nickname, actual.Nickname);
			Assert.AreEqual (expected.Phonetic, actual.Phonetic);
			Assert.AreEqual (expected.IsMuted, actual.IsMuted);
			Assert.AreEqual (expected.Status, actual.Status);
			Assert.AreEqual (expected.Comment, actual.Comment);
		}

		[Test]
		public void InvalidCtor()
		{
			Assert.Throws<ArgumentNullException> (() => new UserInfo (null));
			Assert.Throws<ArgumentNullException> (() => new UserInfo (null, (StreamValueReader)null));

			Assert.Throws<ArgumentNullException> (() => new UserInfo (null, UserId, ChanId, Muted));
			Assert.Throws<ArgumentException> (() => new UserInfo (Username, 0, ChanId, Muted));
			Assert.Throws<ArgumentOutOfRangeException> (() => new UserInfo (Username, UserId, -1, Muted));

			//Assert.Throws<ArgumentNullException> (() => new UserInfo (null, Phonetic, Username, UserId, ChanId, Muted));
			Assert.Throws<ArgumentNullException> (() => new UserInfo (Nickname, Phonetic, null, UserId, ChanId, Muted));
			Assert.DoesNotThrow (() => new UserInfo (Nickname, null, Username, UserId, ChanId, Muted));
			Assert.Throws<ArgumentException> (() => new UserInfo (Nickname, Phonetic, Username, 0, ChanId, Muted));
			Assert.Throws<ArgumentOutOfRangeException> (() => new UserInfo (Nickname, Phonetic, Username, UserId, -1, Muted));
		}

		[Test]
		public void Ctor()
		{
			var info = new UserInfo (Username, UserId, ChanId, Muted);

			Assert.AreEqual (UserId, info.UserId);
			Assert.AreEqual (ChanId, info.CurrentChannelId);
			Assert.AreEqual (Username, info.Username);
			Assert.AreEqual (Muted, info.IsMuted);

			info = new UserInfo (Nickname, Phonetic, Username, UserId, ChanId, Muted);

			Assert.AreEqual (UserId, info.UserId);
			Assert.AreEqual (ChanId, info.CurrentChannelId);
			Assert.AreEqual (Nickname, info.Nickname);
			Assert.AreEqual (Phonetic, info.Phonetic);
			Assert.AreEqual (Username, info.Username);
			Assert.AreEqual (Muted, info.IsMuted);
		}

		[Test]
		public void SerializeDeserialize()
		{
			var stream = new MemoryStream(new byte[20480], true);
			var writer = new StreamValueWriter (stream);
			var reader = new StreamValueReader (stream);

			var info = new UserInfo (Nickname, Phonetic, Username, UserId, ChanId, Muted, Comment, Status);

			info.Serialize (null, writer);
			long length = stream.Position;
			stream.Position = 0;

			info = new UserInfo (null, reader);
			Assert.AreEqual (length, stream.Position);
			Assert.AreEqual (UserId, info.UserId);
			Assert.AreEqual (ChanId, info.CurrentChannelId);
			Assert.AreEqual (Nickname, info.Nickname);
			Assert.AreEqual (Phonetic, info.Phonetic);
			Assert.AreEqual (Muted, info.IsMuted);
			Assert.AreEqual (Comment, info.Comment);
			Assert.AreEqual (Status, info.Status);
		}

		[Test]
		public void Equals()
		{
			IUserInfo foo = new UserInfo (Nickname, Phonetic, Username, 1, 2, Muted);
			IUserInfo bar = new UserInfo (Nickname, Phonetic, Username, 1, 2, Muted);

			Assert.AreEqual (foo, bar);
		}

		[Test]
		public void HashCode()
		{
			UserInfo foo = new UserInfo (Nickname, Phonetic, Username, 1, 2, Muted);
			UserInfo bar = new UserInfo (Nickname, Phonetic, Username, 1, 2, Muted);

			Assert.AreEqual (foo.GetHashCode(), bar.GetHashCode());
		}
	}
}


text:
IMultiSourceFrameArrivedEventArgs Interface
===========================================

Arguments for a multi source frame reader's FrameArrived event.

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

interface IMultiSourceFrameArrivedEventArgs : public IUnknown

Members
=======

**IMultiSourceFrameArrivedEventArgs** has the following members.

Methods
=======

<colgroup>
<col width="30%" />
<col width="60%" />
</colgroup>

Name
Description

get_FrameReference
Gets the reference to the multi source frame for the FrameArrived event.

Requirements
============

**Header:** kinect.h
**Library:** kinect20.lib


text:
class ImageLibrary::ImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :gallery do
    process :resize_and_pad => [85, 85]
  end
end


text:
package com.getbootstrap.rorschach.auditing

object BaseAndHeadBranchesAuditor {
  def audit(baseBranch: String, headBranch: String): Seq[String] = {
    Seq(
      auditThatNotAgainstGhPages(baseBranch),
      auditThatNotMergingGhPagesIntoMaster(baseBranch = baseBranch, headBranch = headBranch)
    ).flatten
  }

  def auditThatNotAgainstGhPages(baseBranch: String): Option[String] = {
    baseBranch match {
      case "gh-pages" => Some("[Normal pull requests should never be against the `gh-pages` branch.](https://github.com/twbs/rorschach/blob/master/docs/against-gh-pages.md)")
      case _ => None
    }
  }

  def auditThatNotMergingGhPagesIntoMaster(baseBranch: String, headBranch: String): Option[String] = {
    (headBranch, baseBranch) match {
      case ("gh-pages", "master") => Some("[Normally, the `gh-pages` branch should never be merged into `master` branch.](https://github.com/twbs/rorschach/blob/master/docs/gh-pages-into-master.md)")
      case _ => None
    }
  }
}


text:
Рассмотрим на конкретном примере работу библиотеки CliApplication. Тестовая задача: имеется Интернет-магазин,
необходимо сформировать для него прайс-лист для Яндекс.Маркет. При этом необходимо учитывать, что необходимы разные
прайс-листы для различных прайс-агрегаторов, то есть возможность формировать прайс-листы для отдельных категорий.

Сначала проведем некоторую подготовительную работу. Поставим gem [yml_builder](https://rubygems.org/gems/yml_builder)
предназначенный для генерации прайс-листов в формате Yandex.Market.

```text
gem install yml_builder
```

Затем, создадим тестовый класс `CliExample`, наследованный от `CliApplication`. Поскольку мы не вводим никаких специфических
функций, то базовый класс занимает всего несколько строк.

```ruby
require 'cli_application'

class CliExample < CliApplication::App

  def initialize(argv, folder, lang = :ru)
    super(argv, folder, __dir__, lang)
  end

end
```

Затем, в той же директории, в которой находится базовый класс, разместим конфиг. В качестве тестового хранилища
будем использовать sqllite.

```yml
cli:
  timezone: "Moscow"

  databases:
    example:
      adapter: 'sqlite3'
      database: 'example.db'
```

Теперь создадим приложение, которое заполнит базу данных тестовыми данными. Его тоже построим на базе гема
`cli_application`. Запишем файл под именем `build_test_data.rb`.

```ruby
#!/usr/bin/env ruby
#encoding: utf-8
require '../class/cli_example.rb'

class Category < ActiveRecord::Base
  has_many :offer
end

class Offer < ActiveRecord::Base
  belongs_to :category
end

class BuildTestData < CliExample

  def main
    ActiveRecord::Base.logger = Logger.new(STDERR)
    ActiveRecord::Base.establish_connection(databases[:example])

    ActiveRecord::Schema.define do
      drop_table :offers if table_exists? :offers
      drop_table :categories if table_exists? :categories

      create_table :offers do |table|
        table.column :name, :string
        table.column :url, :string
        table.column :description, :string
        table.column :photo, :string
        table.column :category_id, :integer
        table.column :price, :integer
      end

      create_table :categories do |table|
        table.column :title, :string
      end
    end

    category = Category.create(title: 'Игрушки')
    category.offer.create(name: 'Пони', url: 'http://test/pony', description: 'Любимая игрушка для детей', photo: 'http://test/image1', price: 100)
    category.offer.create(name: 'Машинка', url: 'http://test/car', description: 'Любимая игрушка для мальчиков', photo: 'http://test/image2', price: 200)
    category.offer.create(name: 'Кукла', url: 'http://test/toy', description: 'Кукла для девочек', photo: 'http://test/image3', price: 230)

    category = Category.create(title: 'Одежда')
    category.offer.create(name: 'Кофта', url: 'http://test/wear', description: 'Красивая кофта', photo: 'http://test/image4', price: 3100)
    category.offer.create(name: 'Ботинки', url: 'http://test/boots', description: 'Элегантные ботинки', photo: 'http://test/image5', price: 8900)

    0
  end

end

app = BuildTestData.new(ARGV, __dir__)

app.version = '1.0'
app.releasedate = '2015-05-14'
app.shortdescription = 'Подготовка тестовых данных для генерации прайс-листа для Yandex.Market'
app.description = "CliApplication gem демо. #{app.shortdescription}"

app.run
exit(app.exitcode)
```

И, наконец, делаем завершающий шаг, и пишем приложение, формирующее прайс-лист. Запишем его под именем `price.rb`.
Модели таблиц базы данных включены прямо в код данного скрипта, но их можно вынести в отдельные файлы или подключить
модели Rails-проекта. Для этого в классе `GenerateYandexPriceList` необходимо добавить функцию
[init_active_records](http://www.rubydoc.info/gems/cli_application/0.1.1/CliApplication/App:init_active_records).

```ruby
#!/usr/bin/env ruby
#encoding: utf-8
require '../class/cli_example.rb'
require 'yml_builder'

class Category < ActiveRecord::Base
  has_many :offer
end

class Offer < ActiveRecord::Base
  belongs_to :category
end

class GenerateYandexPriceList < CliExample

  def add_category(id)
    unless @price.categories.has?(id)
      one = Category.where(id: id).first
      @price.categories.add(id: one.id, name: one.title)
    end
  end

  def main
    ActiveRecord::Base.establish_connection(databases[:example])

    @price = YmlBuilder::Yml.new
    @price.categories.filter = argv.categories
    @price.shop.name = 'Тестовый магазин'
    @price.shop.company = "ООО 'Рога & Копыта'"
    @price.shop.url = 'http://test'
    @price.shop.email = 'info@test.ru'
    @price.shop.phone = '+7 (495) 123-4567'

    @price.currencies.rub = 1
    @price.local_delivery_cost = 300

    Offer.all.each do |offer|
      one = YmlBuilder::Offer.new('simple')
      one.id = offer.id
      one.name = offer.name
      one.url = offer.url
      one.category_id = offer.category_id
      one.description = offer.description
      one.price = offer.price
      one.currency_id = 'RUB'
      one.delivery = true
      one.add_cover_picture(offer.photo)

      @price.offers.add(one)
      add_category(one.category_id)
    end

    @price.save(File.join(folders[:app], 'price-list.xml'))
    0
  end

end

app = GenerateYandexPriceList.new(ARGV, __dir__)

app.version = '1.0'
app.releasedate = '2015-05-14'
app.shortdescription = 'Генерация прайс-листа для Yandex.Market'
app.description = "CliApplication gem демо. #{app.shortdescription}"

app.set_argv(:range, 'categories', '', 'Список категорий, включенных в прайс-лист')

app.help

app.run
exit(app.exitcode)
```

Запускаем приложение, и директории, где расположен файл `price.rb` и находим в нем фпйл `price-list.xml` следующего
соджержания (обратите внимание, что оригинальный файл - в кодировке windows-1251).

```xml
<?xml version="1.0" encoding="windows-1251"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog date="2015-05-14 19:06">
  <shop>
    <name>Тестовый магазин</name>
    <company>ООО 'Рога & Копыта'</company>
    <url>http://test</url>
    <phone>+7 (495) 123-4567</phone>
    <email>info@test.ru</email>
    <currencies>
      <currency id="RUB" rate="1"/>
    </currencies>
    <categories>
      <category id="1">Игрушки</category>
      <category id="2">Одежда</category>
    </categories>
    <local_delivery_cost>300</local_delivery_cost>
    <offers>
      <offer id="1" available="false">
        <url>http://test/pony</url>
        <price>100</price>
        <currencyId>RUB</currencyId>
        <categoryId>1</categoryId>
        <picture>http://test/image1</picture>
        <delivery>true</delivery>
        <name>Пони</name>
        <description>Любимая игрушка для детей</description>
      </offer>
      <offer id="2" available="false">
        <url>http://test/car</url>
        <price>200</price>
        <currencyId>RUB</currencyId>
        <categoryId>1</categoryId>
        <picture>http://test/image2</picture>
        <delivery>true</delivery>
        <name>Машинка</name>
        <description>Любимая игрушка для мальчиков</description>
      </offer>
      <offer id="3" available="false">
        <url>http://test/toy</url>
        <price>230</price>
        <currencyId>RUB</currencyId>
        <categoryId>1</categoryId>
        <picture>http://test/image3</picture>
        <delivery>true</delivery>
        <name>Кукла</name>
        <description>Кукла для девочек</description>
      </offer>
      <offer id="4" available="false">
        <url>http://test/wear</url>
        <price>3100</price>
        <currencyId>RUB</currencyId>
        <categoryId>2</categoryId>
        <picture>http://test/image4</picture>
        <delivery>true</delivery>
        <name>Кофта</name>
        <description>Красивая кофта</description>
      </offer>
      <offer id="5" available="false">
        <url>http://test/boots</url>
        <price>8900</price>
        <currencyId>RUB</currencyId>
        <categoryId>2</categoryId>
        <picture>http://test/image5</picture>
        <delivery>true</delivery>
        <name>Ботинки</name>
        <description>Элегантные ботинки</description>
      </offer>
    </offers>
  </shop>
</yml_catalog>
```


text:
<?php

declare(strict_types=1);

namespace Tests\Boulzy\ManagerBundle\DataProvider\Adapter\Symfony;

use Boulzy\ManagerBundle\Exception\DataProvider\IdentifierNotFoundException;
use Boulzy\ManagerBundle\Exception\DataProvider\UnsupportedClassException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Tests\Boulzy\ManagerBundle\Fixtures\Fixtures;
use Tests\Boulzy\ManagerBundle\Fixtures\Stats;
use Tests\Boulzy\ManagerBundle\Fixtures\User;

final class CacheAdapterTest extends TestCase
{
    public function test_to_find_an_existing_user()
    {
        $dataProvider = Fixtures::getCacheAdapter(true);

        $user = $dataProvider->find(User::class, 1);

        $this->assertInstanceOf(User::class, $user);
        $this->assertSame(1, $user->getId());
    }

    public function test_to_find_a_nonexistent_user()
    {
        $dataProvider = Fixtures::getCacheAdapter(true);

        $user = $dataProvider->find(User::class, 4);

        $this->assertNull($user);
    }

    public function test_to_save_an_user()
    {
        $dataProvider = Fixtures::getCacheAdapter();
        $user = (new User())
            ->setId(4)
            ->setFirstName('Xavier')
            ->setLastName('Bartlett')
            ->setEmail('xavier.bartlett@gmail.com')
            ->setEnabled(true)
        ;

        $dataProvider->save($user);
        $user = $dataProvider->find(User::class, 4);

        $this->assertInstanceOf(User::class, $user);
        $this->assertSame(4, $user->getId());
    }

    public function test_to_save_an_user_without_id()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $this->expectException(IdentifierNotFoundException::class);

        $dataProvider->save(new User());
    }

    public function test_to_save_unsupported_data()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $this->expectException(UnsupportedClassException::class);

        $dataProvider->save(new Stats());
    }

    public function test_to_save_and_find_an_user_with_expiration_date_in_the_future()
    {
        $dataProvider = Fixtures::getCacheAdapter();
        $expirationDate = new \DateTime('+10 minutes');
        $user = (new User())
            ->setId(4)
            ->setFirstName('Xavier')
            ->setLastName('Bartlett')
            ->setEmail('xavier.bartlett@gmail.com')
            ->setEnabled(true)
        ;

        $dataProvider->save($user, $expirationDate);
        $user = $dataProvider->find(User::class, 4);

        $this->assertInstanceOf(User::class, $user);
        $this->assertSame(4, $user->getId());
    }

    public function test_to_save_and_find_an_user_with_expiration_date_in_the_past()
    {
        $dataProvider = Fixtures::getCacheAdapter();
        $expirationDate = new \DateTime('-10 minutes');
        $user = (new User())
            ->setId(4)
            ->setFirstName('Xavier')
            ->setLastName('Bartlett')
            ->setEmail('xavier.bartlett@gmail.com')
            ->setEnabled(true)
        ;

        $dataProvider->save($user, $expirationDate);
        $user = $dataProvider->find(User::class, 4);

        $this->assertNull($user);
    }

    public function test_to_refresh_an_user()
    {
        $dataProvider = Fixtures::getCacheAdapter(true);

        $user = $dataProvider->find(User::class, 1);
        $user->setLastName('Altherton');
        $user = $dataProvider->refresh($user);

        $this->assertSame('Torres', $user->getLastName());
    }

    public function test_to_refresh_not_persisted_user()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $user = $dataProvider->refresh(new User());

        $this->assertNull($user);
    }

    public function test_to_refresh_unsupported_data()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $this->expectException(UnsupportedClassException::class);

        $dataProvider->refresh(new Stats());
    }

    public function test_to_refresh_an_expired_user()
    {
        $dataProvider = Fixtures::getCacheAdapter();
        $expirationDate = new \DateTime('-10 minutes');
        $user = (new User())
            ->setId(4)
            ->setFirstName('Xavier')
            ->setLastName('Bartlett')
            ->setEmail('xavier.bartlett@gmail.com')
            ->setEnabled(true)
        ;

        $dataProvider->save($user, $expirationDate);
        $user = $dataProvider->refresh($user);

        $this->assertNull($user);
    }

    public function test_to_delete_an_user()
    {
        $dataProvider = Fixtures::getCacheAdapter(true);

        $user = $dataProvider->find(User::class, 1);
        $dataProvider->delete($user);
        $user = $dataProvider->find(User::class, 1);

        $this->assertNull($user);
    }

    public function test_to_delete_unsupported_data()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $this->expectException(UnsupportedClassException::class);

        $dataProvider->delete(new Stats());
    }

    public function test_to_get_the_cache_service()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $cache = $dataProvider->getCache();

        $this->assertInstanceOf(AdapterInterface::class, $cache);
    }

    public function test_if_supports_supported_class()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $this->assertTrue($dataProvider->supports(User::class));
        $this->assertTrue($dataProvider->supports(new User()));
    }

    public function test_if_supports_not_supported_class()
    {
        $dataProvider = Fixtures::getCacheAdapter();

        $this->assertFalse($dataProvider->supports(Stats::class));
        $this->assertFalse($dataProvider->supports(new Stats()));
    }

    public function test_if_supports_unexpected_value()
    {
        $dataProvider = Fixtures::getCacheAdapter(true);

        $this->assertFalse($dataProvider->supports('imnotaclass'));
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Primitives;
using Azure.Messaging.EventHubs.Processor;
using Microsoft.Azure.WebJobs.Host.Scale;
using Microsoft.Extensions.Logging;

namespace Microsoft.Azure.WebJobs.EventHubs.Listeners
{
    internal class EventHubsScaleMonitor : IScaleMonitor<EventHubsTriggerMetrics>
    {
        private const int PartitionLogIntervalInMinutes = 5;

        private readonly string _functionId;
        private readonly IEventHubConsumerClient _client;
        private readonly ILogger _logger;
        private readonly BlobsCheckpointStore _checkpointStore;

        private DateTime _nextPartitionLogTime;
        private DateTime _nextPartitionWarningTime;

        public EventHubsScaleMonitor(
            string functionId,
            IEventHubConsumerClient client,
            BlobsCheckpointStore checkpointStore,
            ILogger logger)
        {
            _functionId = functionId;
            _logger = logger;
            _checkpointStore = checkpointStore;
            _nextPartitionLogTime = DateTime.UtcNow;
            _nextPartitionWarningTime = DateTime.UtcNow;
            _client = client;

            Descriptor = new ScaleMonitorDescriptor($"{_functionId}-EventHubTrigger-{_client.EventHubName}-{_client.ConsumerGroup}".ToLowerInvariant());
        }

        public ScaleMonitorDescriptor Descriptor { get; }

        /// <summary>
        /// Returns the state of the event hub for scaling purposes.
        /// </summary>
        async Task<ScaleMetrics> IScaleMonitor.GetMetricsAsync()
        {
            return await GetMetricsAsync().ConfigureAwait(false);
        }

        public async Task<EventHubsTriggerMetrics> GetMetricsAsync()
        {
            EventHubsTriggerMetrics metrics = new EventHubsTriggerMetrics();
            string[] partitions = null;

            try
            {
                partitions = await _client.GetPartitionsAsync().ConfigureAwait(false);
                metrics.PartitionCount = partitions.Length;
            }
            catch (Exception e)
            {
                _logger.LogWarning($"Encountered an exception while checking EventHub '{_client.EventHubName}'. Error: {e.Message}");
                return metrics;
            }

            // Get the PartitionRuntimeInformation for all partitions
            _logger.LogInformation($"Querying partition information for {partitions.Length} partitions.");
            var tasks = new Task<PartitionProperties>[partitions.Length];

            for (int i = 0; i < partitions.Length; i++)
            {
                tasks[i] = _client.GetPartitionPropertiesAsync(partitions[i]);
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            IEnumerable<EventProcessorCheckpoint> checkpoints;
            try
            {
                checkpoints = await _checkpointStore.ListCheckpointsAsync(
                        _client.FullyQualifiedNamespace,
                        _client.EventHubName,
                        _client.ConsumerGroup,
                        default)
                    .ConfigureAwait(false);
            }
            catch
            {
                // ListCheckpointsAsync would log
                return metrics;
            }

            return CreateTriggerMetrics(tasks.Select(t => t.Result).ToList(), checkpoints.ToArray());
        }

        private EventHubsTriggerMetrics CreateTriggerMetrics(List<PartitionProperties> partitionRuntimeInfo, EventProcessorCheckpoint[] checkpoints, bool alwaysLog = false)
        {
            long totalUnprocessedEventCount = 0;
            bool logPartitionInfo = alwaysLog ? true : DateTime.UtcNow >= _nextPartitionLogTime;
            bool logPartitionWarning = alwaysLog ? true : DateTime.UtcNow >= _nextPartitionWarningTime;

            // For each partition, get the last enqueued sequence number.
            // If the last enqueued sequence number does not equal the SequenceNumber from the lease info in storage,
            // accumulate new event counts across partitions to derive total new event counts.
            List<string> partitionErrors = new List<string>();
            for (int i = 0; i < partitionRuntimeInfo.Count; i++)
            {
                var partitionProperties = partitionRuntimeInfo[i];

                var checkpoint = (BlobsCheckpointStore.BlobStorageCheckpoint)checkpoints.SingleOrDefault(c => c.PartitionId == partitionProperties.Id);
                if (checkpoint == null)
                {
                    partitionErrors.Add($"Unable to find a checkpoint information for partition: {partitionProperties.Id}");
                    continue;
                }

                // Check for the unprocessed messages when there are messages on the event hub partition
                // In that case, LastEnqueuedSequenceNumber will be >= 0
                if ((partitionProperties.LastEnqueuedSequenceNumber != -1 && partitionProperties.LastEnqueuedSequenceNumber != checkpoint.SequenceNumber)
                    || (checkpoint.Offset == null && partitionProperties.LastEnqueuedSequenceNumber >= 0))
                {
                    long partitionUnprocessedEventCount = GetUnprocessedEventCount(partitionProperties, checkpoint);
                    totalUnprocessedEventCount += partitionUnprocessedEventCount;
                }
            }

            // Only log if not all partitions are failing or it's time to log
            if (partitionErrors.Count > 0 && (partitionErrors.Count != partitionRuntimeInfo.Count || logPartitionWarning))
            {
                _logger.LogWarning($"Function '{_functionId}': Unable to deserialize partition or lease info with the " +
                    $"following errors: {string.Join(" ", partitionErrors)}");
                _nextPartitionWarningTime = DateTime.UtcNow.AddMinutes(PartitionLogIntervalInMinutes);
            }

            if (totalUnprocessedEventCount > 0 && logPartitionInfo)
            {
                _logger.LogInformation($"Function '{_functionId}', Total new events: {totalUnprocessedEventCount}");
                _nextPartitionLogTime = DateTime.UtcNow.AddMinutes(PartitionLogIntervalInMinutes);
            }

            return new EventHubsTriggerMetrics
            {
                Timestamp = DateTime.UtcNow,
                PartitionCount = partitionRuntimeInfo.Count,
                EventCount = totalUnprocessedEventCount
            };
        }

        // Get the number of unprocessed events by deriving the delta between the server side info and the partition lease info,
        private static long GetUnprocessedEventCount(PartitionProperties partitionInfo, BlobsCheckpointStore.BlobStorageCheckpoint partitionLeaseInfo)
        {
            long partitionLeaseInfoSequenceNumber = partitionLeaseInfo.SequenceNumber ?? 0;

            // This handles two scenarios:
            //   1. If the partition has received its first message, Offset will be null and LastEnqueuedSequenceNumber will be 0
            //   2. If there are no instances set to process messages, Offset will be null and LastEnqueuedSequenceNumber will be >= 0
            if (partitionLeaseInfo.Offset == null && partitionInfo.LastEnqueuedSequenceNumber >= 0)
            {
                return (partitionInfo.LastEnqueuedSequenceNumber + 1);
            }

            if (partitionInfo.LastEnqueuedSequenceNumber > partitionLeaseInfoSequenceNumber)
            {
                return (partitionInfo.LastEnqueuedSequenceNumber - partitionLeaseInfoSequenceNumber);
            }

            // Partition is a circular buffer, so it is possible that
            // LastEnqueuedSequenceNumber < SequenceNumber
            long count = 0;
            unchecked
            {
                count = (long.MaxValue - partitionInfo.LastEnqueuedSequenceNumber) + partitionLeaseInfoSequenceNumber;
            }

            // It's possible for checkpointing to be ahead of the partition's LastEnqueuedSequenceNumber,
            // especially if checkpointing is happening often and load is very low.
            // If count is negative, we need to know that this read is invalid, so return 0.
            // e.g., (9223372036854775807 - 10) + 11 = -9223372036854775808
            return (count < 0) ? 0 : count;
        }

        /// <summary>
        /// Return the current scaling decision based on the EventHub status.
        /// </summary>
        ScaleStatus IScaleMonitor.GetScaleStatus(ScaleStatusContext context)
        {
            return GetScaleStatusCore(context.WorkerCount, context.Metrics?.Cast<EventHubsTriggerMetrics>().ToArray());
        }

        public ScaleStatus GetScaleStatus(ScaleStatusContext<EventHubsTriggerMetrics> context)
        {
            return GetScaleStatusCore(context.WorkerCount, context.Metrics?.ToArray());
        }

        private ScaleStatus GetScaleStatusCore(int workerCount, EventHubsTriggerMetrics[] metrics)
        {
            ScaleStatus status = new ScaleStatus
            {
                Vote = ScaleVote.None
            };

            const int NumberOfSamplesToConsider = 5;

            // Unable to determine the correct vote with no metrics.
            if (metrics == null || metrics.Length == 0)
            {
                return status;
            }

            // We shouldn't assign more workers than there are partitions
            // This check is first, because it is independent of load or number of samples.
            int partitionCount = metrics.Last().PartitionCount;
            if (partitionCount > 0 && partitionCount < workerCount)
            {
                status.Vote = ScaleVote.ScaleIn;
                _logger.LogInformation($"WorkerCount ({workerCount}) > PartitionCount ({partitionCount}).");
                _logger.LogInformation($"Number of instances ({workerCount}) is too high relative to number " +
                                       $"of partitions ({partitionCount}) for EventHubs entity ({_client.EventHubName}, {_client.ConsumerGroup}).");
                return status;
            }

            // At least 5 samples are required to make a scale decision for the rest of the checks.
            if (metrics.Length < NumberOfSamplesToConsider)
            {
                return status;
            }

            // Maintain a minimum ratio of 1 worker per 1,000 unprocessed events.
            long latestEventCount = metrics.Last().EventCount;
            if (latestEventCount > workerCount * 1000)
            {
                status.Vote = ScaleVote.ScaleOut;
                _logger.LogInformation($"EventCount ({latestEventCount}) > WorkerCount ({workerCount}) * 1,000.");
                _logger.LogInformation($"Event count ({latestEventCount}) for EventHubs entity ({_client.EventHubName}, {_client.ConsumerGroup}) " +
                                       $"is too high relative to the number of instances ({workerCount}).");
                return status;
            }

            // Check to see if the EventHub has been empty for a while. Only if all metrics samples are empty do we scale down.
            bool isIdle = metrics.All(m => m.EventCount == 0);
            if (isIdle)
            {
                status.Vote = ScaleVote.ScaleIn;
                _logger.LogInformation($"'{_client.EventHubName}' is idle.");
                return status;
            }

            // Samples are in chronological order. Check for a continuous increase in unprocessed event count.
            // If detected, this results in an automatic scale out for the site container.
            if (metrics[0].EventCount > 0)
            {
                bool eventCountIncreasing =
                IsTrueForLastN(
                    metrics,
                    NumberOfSamplesToConsider,
                    (prev, next) => prev.EventCount < next.EventCount);
                if (eventCountIncreasing)
                {
                    status.Vote = ScaleVote.ScaleOut;
                    _logger.LogInformation($"Event count is increasing for '{_client.EventHubName}'.");
                    return status;
                }
            }

            bool eventCountDecreasing =
                IsTrueForLastN(
                    metrics,
                    NumberOfSamplesToConsider,
                    (prev, next) => prev.EventCount > next.EventCount);
            if (eventCountDecreasing)
            {
                status.Vote = ScaleVote.ScaleIn;
                _logger.LogInformation($"Event count is decreasing for '{_client.EventHubName}'.");
                return status;
            }

            _logger.LogInformation($"EventHubs entity '{_client.EventHubName}' is steady.");

            return status;
        }

        private static bool IsTrueForLastN(IList<EventHubsTriggerMetrics> samples, int count, Func<EventHubsTriggerMetrics, EventHubsTriggerMetrics, bool> predicate)
        {
            // Walks through the list from left to right starting at len(samples) - count.
            for (int i = samples.Count - count; i < samples.Count - 1; i++)
            {
                if (!predicate(samples[i], samples[i + 1]))
                {
                    return false;
                }
            }

            return true;
        }
    }
}


text:
<?php declare(strict_types = 1);

namespace Dms\Web\Laravel\Renderer\Table;

use Dms\Core\Common\Crud\IReadModule;
use Dms\Core\Common\Crud\Table\ISummaryTable;
use Dms\Core\Exception\InvalidArgumentException;
use Dms\Core\Model\Criteria\Condition\ConditionOperator;
use Dms\Core\Module\ITableDisplay;
use Dms\Core\Table\IDataTable;
use Dms\Core\Table\ITableDataSource;
use Dms\Web\Laravel\Http\ModuleContext;
use Dms\Web\Laravel\Renderer\Action\ActionButton;
use Dms\Web\Laravel\Renderer\Action\ObjectActionButtonBuilder;

/**
 * The table renderer class.
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class TableRenderer
{
    /**
     * @var ColumnRendererFactoryCollection
     */
    protected $columnRendererFactories;

    /**
     * @var ObjectActionButtonBuilder
     */
    private $actionButtonBuilder;

    /**
     * TableRenderer constructor.
     *
     * @param ColumnRendererFactoryCollection $columnRendererFactories
     * @param ObjectActionButtonBuilder       $actionButtonBuilder
     */
    public function __construct(ColumnRendererFactoryCollection $columnRendererFactories, ObjectActionButtonBuilder $actionButtonBuilder)
    {
        $this->columnRendererFactories = $columnRendererFactories;
        $this->actionButtonBuilder     = $actionButtonBuilder;
    }

    /**
     * Renders the supplied data table as a html string.
     *
     * @param ModuleContext       $moduleContext
     * @param ITableDisplay       $table
     * @param IDataTable          $tableData
     * @param string              $viewName
     * @param bool                $isFiltered
     * @param ActionButton[]|null $actionButtons
     *
     * @return string
     * @throws UnrenderableColumnComponentException
     * @throws \Exception
     * @throws \Throwable
     */
    public function renderTableData(
        ModuleContext $moduleContext,
        ITableDisplay $table,
        IDataTable $tableData,
        string $viewName = null,
        bool $isFiltered = false,
        array $actionButtons = null
    ) : string
    {
        $columnRenderers = [];

        foreach ($tableData->getStructure()->getColumns() as $column) {
            $columnRenderers[$column->getName()] = $this->columnRendererFactories->buildRendererFor($column);
        }

        $rowActionButtons = [];
        if ($actionButtons) {
            InvalidArgumentException::verifyAllInstanceOf(__METHOD__, 'actionButtons', $actionButtons, ActionButton::class);

            foreach ($actionButtons as $actionButton) {
                $rowActionButtons[$actionButton->getName()] = $actionButton;
            }
        } else {
            if ($moduleContext->getModule() instanceof IReadModule && $table instanceof ISummaryTable) {
                foreach ($this->actionButtonBuilder->buildActionButtons($moduleContext) as $actionButton) {
                    $rowActionButtons[$actionButton->getName()] = $actionButton;
                }
            }
        }

        return view('dms::components.table.data-table')
            ->with([
                'dataSource'       => $table->getDataSource(),
                'columns'          => $tableData->getStructure()->getColumns(),
                'columnRenderers'  => $columnRenderers,
                'sections'         => $tableData->getSections(),
                'rowActionButtons' => $rowActionButtons,
                'allowsReorder'    => !$isFiltered && $viewName && $this->allowsRowReorder($table, $viewName),
            ])
            ->render();
    }

    /**
     * Renders the supplied table control as a html string.
     *
     * @param ModuleContext $moduleContext
     * @param ITableDisplay $table
     * @param string        $viewName
     *
     * @return string
     */
    public function renderTableControl(ModuleContext $moduleContext, ITableDisplay $table, string $viewName = null) : string
    {
        $viewName = $viewName ?? $table->getDefaultView()->getName();
        $columns  = $table->getDataSource()->getStructure()->getColumns();

        if ($moduleContext->getModule() instanceof IReadModule && $table instanceof ISummaryTable) {
            unset($columns[IReadModule::SUMMARY_TABLE_ID_COLUMN]);
        }

        if ($this->allowsRowReorder($table, $viewName)) {
            $reorderRowActionUrl = $moduleContext->getUrl('action.run', [$table->getReorderAction($viewName)->getName()]);
        } else {
            $reorderRowActionUrl = null;
        }

        return view('dms::components.table.table-control')
            ->with([
                'columns'                      => $columns,
                'tableDataSource'              => $table->getDataSource(),
                'table'                        => $table->getView($viewName),
                'loadRowsUrl'                  => $moduleContext->getUrl('table.view.load', [$table->getName(), $viewName]),
                'reorderRowActionUrl'          => $reorderRowActionUrl,
                'stringFilterableComponentIds' => $this->getStringFilterableColumnComponentIds($table->getDataSource()),
                'defaultAmount'                => $moduleContext->getModule()->getMetadata('default-items-per-page'),
            ])
            ->render();
    }

    protected function getStringFilterableColumnComponentIds(ITableDataSource $tableDataSource) : array
    {
        $componentIds = [];

        foreach ($tableDataSource->getStructure()->getColumns() as $column) {
            foreach ($column->getComponents() as $component) {
                $componentId = $column->getName() . '.' . $component->getName();
                if ($component->getType()->hasOperator(ConditionOperator::STRING_CONTAINS_CASE_INSENSITIVE)
                    && $tableDataSource->canUseColumnComponentInCriteria($componentId)
                ) {
                    $componentIds[] = $componentId;
                }
            }
        }

        return $componentIds;
    }

    /**
     * @param ITableDisplay $table
     * @param string        $viewName
     *
     * @return bool
     */
    protected function allowsRowReorder(ITableDisplay $table, string $viewName) : bool
    {
        return $table instanceof ISummaryTable
        && $table->hasReorderAction($viewName)
        && $table->getReorderAction($viewName)->isAuthorized();
    }
}


text:
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

import React, { PropTypes } from 'react';
import styles from './EffectWish.less';
import withStyles from '../../../decorators/withStyles';
var CSlider = require('react-slick');
import $ from 'jquery'

@withStyles(styles)

class EffectWish {

    static contextTypes = {
        onSetTitle: PropTypes.func.isRequired
    };

    render() {
        var settings = {
            dots: true,
            infinite: true,
            speed: 500,
            slidesToShow: 3,
            slidesToScroll: 3,
            autoplay: false,
        };
        return (

实现留学梦想的他们说

                    <CSlider {...settings}>

人人留学的老师们都很热心、细心...

非常感谢人人留学帮过我的老师们

非常感谢人人留学帮过我的老师们

人人留学的老师们都很热心、细心1...

非常感谢人人留学帮过我的老师们1

非常感谢人人留学帮过我的老师们1

                    </CSlider>

        );
    }
    componentDidMount() {
        $(document).ready(function(){
            $(".effect-wish").find(".cSliderItem").hover(function () {
                $(this).find(".bg").animate({ opacity: 0 }, 300).css({ flter: "Alpha(Opacity=0)" });
                $(this).find(".title-box").animate({ marginTop: "-40px" }, 300);

            }, function () {
                $(this).find(".bg").stop();
                $(this).find(".title-box").stop();
                $(this).find(".bg").animate({ opacity: 0.4 }, 300).css({ flter: "Alpha(Opacity=40)" });
                $(this).find(".title-box").animate({ marginTop: "0px" }, 300);
            });
        });
    }
}

export default EffectWish;