<commit_before>// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Comment Helper
 * @author Dongsheng Cai <dongsheng@moodle.com>
 */
M.core_comment = {
    /**
     * Initialize commenting system
     */
    init: function(Y, options) {
        var CommentHelper = function(args) {
            CommentHelper.superclass.constructor.apply(this, arguments);
        }
        CommentHelper.NAME = "COMMENT";
        CommentHelper.ATTRS = {
            options: {},
            lang: {}
        };
        Y.extend(CommentHelper, Y.Base, {
            api: M.cfg.wwwroot+'/comment/comment_ajax.php',
            initializer: function(args) {
                var scope = this;
                this.client_id = args.client_id;
                this.itemid = args.itemid;
                this.commentarea = args.commentarea;
                this.courseid = args.courseid;
                this.contextid = args.contextid;
                if (args.autostart) {
                    this.view(args.page);
                }
                if (args.notoggle) {
                    Y.one('#comment-link-'+this.client_id).setStyle('display', 'none');
                }
                // load comments
                Y.one('#comment-link-'+this.client_id).on('click', function(e) {
                    e.preventDefault();
                    this.view(0);
                    return false;
                }, this);
            },
            post: function() {
                var ta = Y.one('#dlg-content-'+this.client_id);
                var scope = this;
                var value = ta.get('value');
                if (value && value != mstr.moodle.addcomment) {
                    var params = {'content': value};
                    this.request({
                        action: 'add',
                        scope: scope,
                        params: params,
                        callback: function(id, obj, args) {
                            var scope = args.scope;
                            var cid = scope.client_id;
                            var ta = Y.one('#dlg-content-'+cid);
                            ta.set('value', '');
                            var container = Y.one('#comment-list-'+cid);
                            var result = scope.render([obj], true);
                            var newcomment = Y.Node.create(result.html);
                            container.appendChild(newcomment);
                            var ids = result.ids;
                            var linktext = Y.one('#comment-link-text-'+cid);
                            linktext.set('innerHTML', mstr.moodle.comments + ' ('+obj.count+')');
                            for(var i in ids) {
                                var attributes = {
                                    color: { to: '#06e' },
                                    backgroundColor: { to: '#FFE390' }
                                };
                                var anim = new YAHOO.util.ColorAnim(ids[i], attributes);
                                anim.animate();
                            }
                        }
                    }, true);
                } else {
                    var attributes = {
                        backgroundColor: { from: '#FFE390', to:'#FFFFFF' }
                    };
                    var anim = new YAHOO.util.ColorAnim('dlg-content-'+cid, attributes);
                    anim.animate();
                }
            },
            request: function(args, noloading) {
                var params = {};
                var scope = this;
                if (args['scope']) {
                    scope = args['scope'];
                }
                //params['page'] = args.page?args.page:'';
                params['env']       = '';
                // the form element only accept certain file types
                params['sesskey']   = M.cfg.sesskey;
                params['action']    = args.action?args.action:'';
                params['client_id'] = this.client_id;
                params['itemid']    = this.itemid;
                params['area']      = this.commentarea;
                params['courseid']  = this.courseid;
                params['contextid'] = this.contextid;
                if (args['params']) {
                    for (i in args['params']) {
                        params[i] = args['params'][i];
                    }
                }
                var cfg = {
                    method: 'POST',
                    on: {
                        complete: function(id,o,p) {
                            if (!o) {
                                alert('IO FATAL');
                                return;
                            }
                            var data = Y.JSON.parse(o.responseText);
                            if (data.error) {
                                alert(data.error);
                                return false;
                            } else {
                                args.callback(id,data,p);
                                return true;
                            }
                        }
                    },
                    arguments: {
                        scope: scope
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'User-Agent': 'MoodleComment/3.0'
                    },
                    data: build_querystring(params)
                };
                if (args.form) {
                    cfg.form = args.form;
                }
                Y.io(this.api, cfg);
                if (!noloading) {
                    this.wait();
                }
            },
            render: function(list, newcmt) {
                var ret = {};
                ret.ids = [];
                var template = Y.one('#cmt-tmpl');
                var html = '';
                for(var i in list) {
                    var htmlid = 'comment-'+list[i].id+'-'+this.client_id;
                    var val = template.get('innerHTML');
                    val = val.replace('___name___', list[i].username);
                    if (list[i]['delete']||newcmt) {
                        list[i].content = '

' + list[i].content;
                    }
                    val = val.replace('___time___', list[i].time);
                    val = val.replace('___picture___', list[i].avatar);
                    val = val.replace('___content___', list[i].content);
                    val = '
'+val+'
';
                    ret.ids.push(htmlid);
                    html = (val+html);
                }
                ret.html = html;
                return ret;
            },
            load: function(page) {
                var scope = this;
                var container = Y.one('#comment-ctrl-'+this.client_id);
                var params = {
                    'page': page,
                }
                this.request({
                    scope: scope,
                    params: params,
                    callback: function(id, ret, args) {
                        var linktext = Y.one('#comment-link-text-'+scope.client_id);
                        linktext.set('innerHTML', mstr.moodle.comments + ' ('+ret.count+')');
                        var container = Y.one('#comment-list-'+scope.client_id);
                        var pagination = Y.one('#comment-pagination-'+scope.client_id);
                        if (ret.pagination) {
                            pagination.set('innerHTML', ret.pagination);
                        } else {
                            //empty paging bar
                            pagination.set('innerHTML', '');
                        }
                        var result = scope.render(ret.list);
                        container.set('innerHTML', result.html);
                        args.scope.register_pagination();
                        args.scope.register_delete_buttons();
                    }
                });
            },

            delete: function(id) {
                var scope = this;
                var params = {'commentid': id};

                function remove_dom(type, anmi, cmt) {
                    cmt.remove();
                }
                this.request({
                    action: 'delete',
                    scope: scope,
                    params: params,
                    callback: function(id, resp, args) {
                        var htmlid= 'comment-'+resp.commentid+'-'+resp.client_id;
                        var attributes = {
                            width:{to:0},
                            height:{to:0}
                        };
                        var cmt = Y.one('#'+htmlid);
                        cmt.setStyle('overflow', 'hidden');
                        var anim = new YAHOO.util.Anim(htmlid, attributes, 1, YAHOO.util.Easing.easeOut);
                        anim.onComplete.subscribe(remove_dom, cmt, this);
                        anim.animate();
                    }
                }, true);
            },
            register_actions: function() {
                // add new comment
                Y.one('#comment-action-post-'+this.client_id).on('click', function(e) {
                    e.preventDefault();
                    this.post();
                    return false;
                }, this);
                // cancel comment box
                var cancel = Y.one('#comment-action-cancel-'+this.client_id);
                if (cancel) {
                    cancel.on('click', function(e) {
                        e.preventDefault();
                        this.view(0);
                        return false;
                    }, this);
                }
            },
            register_delete_buttons: function() {
                var scope = this;
                // page buttons
                Y.all('div.comment-content a').each(
                    function(node, id) {
                        node.on('click', function(e, node) {
                            var id = node.get('id');
                            var re = new RegExp("comment-delete-"+this.client_id+"-(\\d+)", "i");
                            var result = id.match(re);
                            if (result[1]) {
                                this.delete(result[1]);
                            }
                            //this.load(result[1]);
                        }, scope, node);
                    }
                );
            },
            register_pagination: function() {
                var scope = this;
                // page buttons
                Y.all('#comment-paging-'+this.client_id+' a').each(
                    function(node, id) {
                        node.on('click', function(e, node) {
                            var id = node.get('id');
                            var re = new RegExp("comment-page-"+this.client_id+"-(\\d+)", "i");
                            var result = id.match(re);
                            this.load(result[1]);
                        }, scope, node);
                    }
                );
            },
            view: function(page) {
                var container = Y.one('#comment-ctrl-'+this.client_id);
                var ta = Y.one('#dlg-content-'+this.client_id);
                var img = Y.one('#comment-img-'+this.client_id);
                var d = container.getStyle('display');
                if (d=='none'||d=='') {
                    // show
                    this.load(page);
                    container.setStyle('display', 'block');
                    img.src=M.util.image_url('t/expanded', 'core');
                } else {
                    // hide
                    container.setStyle('display', 'none');
                    img.src=M.util.image_url('t/collapsed', 'core');
                    ta.set('value','');
                }
                //toggle_textarea.apply(ta, [false]);
                //// reset textarea size
                ta.on('click', function() {
                    this.toggle_textarea(true);
                }, this)
                //ta.onkeypress = function() {
                    //if (this.scrollHeight > this.clientHeight && !window.opera)
                        //this.rows += 1;
                //}
                ta.on('blur', function() {
                    this.toggle_textarea(false);
                }, this);
                this.register_actions();
                return false;
            },
            toggle_textarea: function(focus) {
                var t = Y.one('#dlg-content-'+this.client_id);
                if (focus) {
                    if (t.get('value') == mstr.moodle.addcomment) {
                        t.set('value', '');
                        t.setStyle('color', 'black');
                    }
                }else{
                    if (t.get('value') == '') {
                        t.set('value', mstr.moodle.addcomment);
                        t.setStyle('color','grey');
                        t.set('rows', 1);
                    }
                }
            },
            wait: function() {
                var container = Y.one('#comment-list-'+this.client_id);
                container.set('innerHTML', '

');
            }
        });

        new CommentHelper(options);
    }
};
<commit_msg>MDL-21400 fixed regression in chrome, safary etc. - it is not allowed to use reserved "delete" keyword as method name<commit_after>// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Comment Helper
 * @author Dongsheng Cai <dongsheng@moodle.com>
 */
M.core_comment = {
    /**
     * Initialize commenting system
     */
    init: function(Y, options) {
        var CommentHelper = function(args) {
            CommentHelper.superclass.constructor.apply(this, arguments);
        }
        CommentHelper.NAME = "COMMENT";
        CommentHelper.ATTRS = {
            options: {},
            lang: {}
        };
        Y.extend(CommentHelper, Y.Base, {
            api: M.cfg.wwwroot+'/comment/comment_ajax.php',
            initializer: function(args) {
                var scope = this;
                this.client_id = args.client_id;
                this.itemid = args.itemid;
                this.commentarea = args.commentarea;
                this.courseid = args.courseid;
                this.contextid = args.contextid;
                if (args.autostart) {
                    this.view(args.page);
                }
                if (args.notoggle) {
                    Y.one('#comment-link-'+this.client_id).setStyle('display', 'none');
                }
                // load comments
                Y.one('#comment-link-'+this.client_id).on('click', function(e) {
                    e.preventDefault();
                    this.view(0);
                    return false;
                }, this);
            },
            post: function() {
                var ta = Y.one('#dlg-content-'+this.client_id);
                var scope = this;
                var value = ta.get('value');
                if (value && value != mstr.moodle.addcomment) {
                    var params = {'content': value};
                    this.request({
                        action: 'add',
                        scope: scope,
                        params: params,
                        callback: function(id, obj, args) {
                            var scope = args.scope;
                            var cid = scope.client_id;
                            var ta = Y.one('#dlg-content-'+cid);
                            ta.set('value', '');
                            var container = Y.one('#comment-list-'+cid);
                            var result = scope.render([obj], true);
                            var newcomment = Y.Node.create(result.html);
                            container.appendChild(newcomment);
                            var ids = result.ids;
                            var linktext = Y.one('#comment-link-text-'+cid);
                            linktext.set('innerHTML', mstr.moodle.comments + ' ('+obj.count+')');
                            for(var i in ids) {
                                var attributes = {
                                    color: { to: '#06e' },
                                    backgroundColor: { to: '#FFE390' }
                                };
                                var anim = new YAHOO.util.ColorAnim(ids[i], attributes);
                                anim.animate();
                            }
                        }
                    }, true);
                } else {
                    var attributes = {
                        backgroundColor: { from: '#FFE390', to:'#FFFFFF' }
                    };
                    var anim = new YAHOO.util.ColorAnim('dlg-content-'+cid, attributes);
                    anim.animate();
                }
            },
            request: function(args, noloading) {
                var params = {};
                var scope = this;
                if (args['scope']) {
                    scope = args['scope'];
                }
                //params['page'] = args.page?args.page:'';
                params['env']       = '';
                // the form element only accept certain file types
                params['sesskey']   = M.cfg.sesskey;
                params['action']    = args.action?args.action:'';
                params['client_id'] = this.client_id;
                params['itemid']    = this.itemid;
                params['area']      = this.commentarea;
                params['courseid']  = this.courseid;
                params['contextid'] = this.contextid;
                if (args['params']) {
                    for (i in args['params']) {
                        params[i] = args['params'][i];
                    }
                }
                var cfg = {
                    method: 'POST',
                    on: {
                        complete: function(id,o,p) {
                            if (!o) {
                                alert('IO FATAL');
                                return;
                            }
                            var data = Y.JSON.parse(o.responseText);
                            if (data.error) {
                                alert(data.error);
                                return false;
                            } else {
                                args.callback(id,data,p);
                                return true;
                            }
                        }
                    },
                    arguments: {
                        scope: scope
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'User-Agent': 'MoodleComment/3.0'
                    },
                    data: build_querystring(params)
                };
                if (args.form) {
                    cfg.form = args.form;
                }
                Y.io(this.api, cfg);
                if (!noloading) {
                    this.wait();
                }
            },
            render: function(list, newcmt) {
                var ret = {};
                ret.ids = [];
                var template = Y.one('#cmt-tmpl');
                var html = '';
                for(var i in list) {
                    var htmlid = 'comment-'+list[i].id+'-'+this.client_id;
                    var val = template.get('innerHTML');
                    val = val.replace('___name___', list[i].username);
                    if (list[i]['delete']||newcmt) {
                        list[i].content = '

' + list[i].content;
                    }
                    val = val.replace('___time___', list[i].time);
                    val = val.replace('___picture___', list[i].avatar);
                    val = val.replace('___content___', list[i].content);
                    val = '
'+val+'
';
                    ret.ids.push(htmlid);
                    html = (val+html);
                }
                ret.html = html;
                return ret;
            },
            load: function(page) {
                var scope = this;
                var container = Y.one('#comment-ctrl-'+this.client_id);
                var params = {
                    'page': page,
                }
                this.request({
                    scope: scope,
                    params: params,
                    callback: function(id, ret, args) {
                        var linktext = Y.one('#comment-link-text-'+scope.client_id);
                        linktext.set('innerHTML', mstr.moodle.comments + ' ('+ret.count+')');
                        var container = Y.one('#comment-list-'+scope.client_id);
                        var pagination = Y.one('#comment-pagination-'+scope.client_id);
                        if (ret.pagination) {
                            pagination.set('innerHTML', ret.pagination);
                        } else {
                            //empty paging bar
                            pagination.set('innerHTML', '');
                        }
                        var result = scope.render(ret.list);
                        container.set('innerHTML', result.html);
                        args.scope.register_pagination();
                        args.scope.register_delete_buttons();
                    }
                });
            },

            dodelete: function(id) { // note: delete is a reserved work in javascript!
                var scope = this;
                var params = {'commentid': id};

                function remove_dom(type, anmi, cmt) {
                    cmt.remove();
                }
                this.request({
                    action: 'delete',
                    scope: scope,
                    params: params,
                    callback: function(id, resp, args) {
                        var htmlid= 'comment-'+resp.commentid+'-'+resp.client_id;
                        var attributes = {
                            width:{to:0},
                            height:{to:0}
                        };
                        var cmt = Y.one('#'+htmlid);
                        cmt.setStyle('overflow', 'hidden');
                        var anim = new YAHOO.util.Anim(htmlid, attributes, 1, YAHOO.util.Easing.easeOut);
                        anim.onComplete.subscribe(remove_dom, cmt, this);
                        anim.animate();
                    }
                }, true);
            },
            register_actions: function() {
                // add new comment
                Y.one('#comment-action-post-'+this.client_id).on('click', function(e) {
                    e.preventDefault();
                    this.post();
                    return false;
                }, this);
                // cancel comment box
                var cancel = Y.one('#comment-action-cancel-'+this.client_id);
                if (cancel) {
                    cancel.on('click', function(e) {
                        e.preventDefault();
                        this.view(0);
                        return false;
                    }, this);
                }
            },
            register_delete_buttons: function() {
                var scope = this;
                // page buttons
                Y.all('div.comment-content a').each(
                    function(node, id) {
                        node.on('click', function(e, node) {
                            var id = node.get('id');
                            var re = new RegExp("comment-delete-"+this.client_id+"-(\\d+)", "i");
                            var result = id.match(re);
                            if (result[1]) {
                                this.dodelete(result[1]);
                            }
                            //this.load(result[1]);
                        }, scope, node);
                    }
                );
            },
            register_pagination: function() {
                var scope = this;
                // page buttons
                Y.all('#comment-paging-'+this.client_id+' a').each(
                    function(node, id) {
                        node.on('click', function(e, node) {
                            var id = node.get('id');
                            var re = new RegExp("comment-page-"+this.client_id+"-(\\d+)", "i");
                            var result = id.match(re);
                            this.load(result[1]);
                        }, scope, node);
                    }
                );
            },
            view: function(page) {
                var container = Y.one('#comment-ctrl-'+this.client_id);
                var ta = Y.one('#dlg-content-'+this.client_id);
                var img = Y.one('#comment-img-'+this.client_id);
                var d = container.getStyle('display');
                if (d=='none'||d=='') {
                    // show
                    this.load(page);
                    container.setStyle('display', 'block');
                    img.src=M.util.image_url('t/expanded', 'core');
                } else {
                    // hide
                    container.setStyle('display', 'none');
                    img.src=M.util.image_url('t/collapsed', 'core');
                    ta.set('value','');
                }
                //toggle_textarea.apply(ta, [false]);
                //// reset textarea size
                ta.on('click', function() {
                    this.toggle_textarea(true);
                }, this)
                //ta.onkeypress = function() {
                    //if (this.scrollHeight > this.clientHeight && !window.opera)
                        //this.rows += 1;
                //}
                ta.on('blur', function() {
                    this.toggle_textarea(false);
                }, this);
                this.register_actions();
                return false;
            },
            toggle_textarea: function(focus) {
                var t = Y.one('#dlg-content-'+this.client_id);
                if (focus) {
                    if (t.get('value') == mstr.moodle.addcomment) {
                        t.set('value', '');
                        t.setStyle('color', 'black');
                    }
                }else{
                    if (t.get('value') == '') {
                        t.set('value', mstr.moodle.addcomment);
                        t.setStyle('color','grey');
                        t.set('rows', 1);
                    }
                }
            },
            wait: function() {
                var container = Y.one('#comment-list-'+this.client_id);
                container.set('innerHTML', '

');
            }
        });

        new CommentHelper(options);
    }
};
<|endoftext|>


<commit_before>var typewriter = function () {

   var input = document.getElementById('input'),
       output = document.getElementById('output');

   output.onkeydown = function (e) {

      var keyCode = e.which;

      if (e.which === 8) {
         e.preventDefault();
         strikeOut();
         sync(input, output)
         return setFocus(input);
      }

      if (keyCode === 16) {
         return
      }

      if (!isArrowKey(keyCode) && e.shiftKey) {
         e.preventDefault();
         return setFocus(input)
      }

      if (isArrowKey(keyCode) && !e.shiftKey) {
         return setFocus(input)
      }

      if (isArrowKey(keyCode) && e.shiftKey) {
         return ''
      }

      if (e.metaKey) {
         return setFocus(input)
      }

      if (selectedText()) {
         e.preventDefault()
      }

      return setFocus(input)

   }

   output.onkeyup = function (e) {
      if (!selectedText()) {
         return setFocus(input)
      }
   };

   input.onkeydown = function (e) {

      var keyCode = e.which;

      // Disable delete key
      if (keyCode === 8) {
         e.preventDefault()
      };

      // Disable copy paste and shit
      if (e.metaKey && keyCode !== 82) {
         e.preventDefault()
      }

      // Handle arrow keys
      if (keyCode <= 40 && keyCode >= 37) {

         // If shift is held allow user to make selection in output
         if (e.shiftKey) {
            return setFocus(output);

         // Otherwise disable the arrow keys
         } else {
            e.preventDefault();
         }

      };

      // Handle return key
      if (keyCode === 13) {
         input.innerHTML += '

'; // zero width char to fix contenteditable focus bug
         e.preventDefault();
      };

      // We make a setTImeout because
      // input.innerHTML is not yet updated with e.char
      // and waiting for onkeypress is too slow
      return setTimeout(function(){

         sync(output, input);
         setFocus(input);
         return moveViewportToBottom();

      }, 0);

   }

   document.onmouseup = function (e) {

      // We need to keep focus on input unless there's selected text
      if (!selectedText()) {
         setFocus(input);
      }

      // Since theres selected text,
      // perhaps prepare for strikeout?

   }

   function buildGUIMenu () {
      return
   }

   // Used to check if the user has selected text
   function selectedText() {
      var selection = window.getSelection();
      return selection.type === 'Range' ? selection : false
   }

   function sync (oldNode, newNode) {
      return oldNode.innerHTML = newNode.innerHTML
   }

   function inDesktop () {
      return typeof require !== 'undefined' ? true : false
   }

   function isArrowKey (keyCode) {
      return (keyCode <= 40 && keyCode >= 37) ? true : false
   }

   function moveViewportToBottom () {
      window.scrollTo(0, document.body.offsetHeight);
   }

   function strikeOut() {

      var selectedText = window.getSelection().getRangeAt();

      console.log(window.getSelection());
      console.log(window.getSelection().getRangeAt());

      // The black line through the text
      var strike = document.createElement('span');
          strike.className = 'strike';

      selectedText.surroundContents(strike);

      // The 'empty' span is to counter
      // weird behaviour when setting focus of contenteditable
      // Without it, you can keep typing within strike out text
      var emptySpan = document.createElement('span');
          emptySpan.innerHTML = ''; // zero width character

      // Adds empty span after strike
      selectedText.collapse(false);
      selectedText.insertNode(emptySpan);

   }

   function setFocus (el) {

      var range = document.createRange();
          range.selectNodeContents(el);
          range.collapse(false);

      var selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
   }

   // This starts the typewriter
   return function init () {
      if (inDesktop()) {
         console.log('Running in desktop environment!')
      }

      sync(output, input);

      setFocus(input);
   }();

}

// GO GO GADGET
typewriter();<commit_msg>ensured delete returned something<commit_after>var typewriter = function () {

   var input = document.getElementById('input'),
       output = document.getElementById('output');

   output.onkeydown = function (e) {

      var keyCode = e.which;

      if (e.which === 8) {
         e.preventDefault();
         strikeOut();
         sync(input, output)
         return setFocus(input);
      }

      if (keyCode === 16) {
         return
      }

      if (!isArrowKey(keyCode) && e.shiftKey) {
         e.preventDefault();
         return setFocus(input)
      }

      if (isArrowKey(keyCode) && !e.shiftKey) {
         return setFocus(input)
      }

      if (isArrowKey(keyCode) && e.shiftKey) {
         return ''
      }

      if (e.metaKey) {
         return setFocus(input)
      }

      if (selectedText()) {
         e.preventDefault()
      }

      return setFocus(input)

   }

   output.onkeyup = function (e) {
      if (!selectedText()) {
         return setFocus(input)
      }
   };

   input.onkeydown = function (e) {

      var keyCode = e.which;

      // Delete key
      if (keyCode === 8) {
         return e.preventDefault();
      };

      // Disable copy paste and shit
      if (e.metaKey && keyCode !== 82) {
         e.preventDefault()
      }

      // Handle arrow keys
      if (keyCode <= 40 && keyCode >= 37) {

         // If shift is held allow user to make selection in output
         if (e.shiftKey) {
            return setFocus(output);

         // Otherwise disable the arrow keys
         } else {
            e.preventDefault();
         }

      };

      // Handle return key
      if (keyCode === 13) {
         input.innerHTML += '

'; // zero width char to fix contenteditable focus bug
         e.preventDefault();
      };

      // We make a setTImeout because
      // input.innerHTML is not yet updated with e.char
      // and waiting for onkeypress is too slow
      return setTimeout(function(){

         sync(output, input);
         setFocus(input);
         return moveViewportToBottom();

      }, 0);

   }

   document.onmouseup = function (e) {

      // We need to keep focus on input unless there's selected text
      if (!selectedText()) {
         setFocus(input);
      }

      // Since theres selected text,
      // perhaps prepare for strikeout?

   }

   function buildGUIMenu () {
      return
   }

   // Used to check if the user has selected text
   function selectedText() {
      var selection = window.getSelection();
      return selection.type === 'Range' ? selection : false
   }

   function sync (oldNode, newNode) {
      return oldNode.innerHTML = newNode.innerHTML
   }

   function inDesktop () {
      return typeof require !== 'undefined' ? true : false
   }

   function isArrowKey (keyCode) {
      return (keyCode <= 40 && keyCode >= 37) ? true : false
   }

   function moveViewportToBottom () {
      window.scrollTo(0, document.body.offsetHeight);
   }

   function strikeOut() {

      var selectedText = window.getSelection().getRangeAt();

      console.log(window.getSelection());
      console.log(window.getSelection().getRangeAt());

      // The black line through the text
      var strike = document.createElement('span');
          strike.className = 'strike';

      selectedText.surroundContents(strike);

      // The 'empty' span is to counter
      // weird behaviour when setting focus of contenteditable
      // Without it, you can keep typing within strike out text
      var emptySpan = document.createElement('span');
          emptySpan.innerHTML = ''; // zero width character

      // Adds empty span after strike
      selectedText.collapse(false);
      selectedText.insertNode(emptySpan);

   }

   function setFocus (el) {

      var range = document.createRange();
          range.selectNodeContents(el);
          range.collapse(false);

      var selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
   }

   // This starts the typewriter
   return function init () {
      if (inDesktop()) {
         console.log('Running in desktop environment!')
      }

      sync(output, input);

      setFocus(input);
   }();

}

// GO GO GADGET
typewriter();<|endoftext|>


<commit_before>/*
    TimelineJS - ver. 2.35.5 - 2015-02-26
    Copyright (c) 2012-2013 Northwestern University
    a project of the Northwestern University Knight Lab, originally created by Zach Wise
    https://github.com/NUKnightLab/TimelineJS
    This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
    If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
if(typeof VMM!="undefined"){VMM.Language={lang:"zh-cn",api:{wikipedia:"zh"},date:{month:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],month_abbr:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],day:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],day_abbr:["周日","周一","周二","周三","周四","周五","周六"]},dateformats:{year:"yyyy年",month_short:"mmm",month:"yyyy年 mmmm",full_short:"mmm d日",full:"yyyy年mmmm d日",time_short:"HH:MM:ss",time_no_seconds_short:"HH:MM",time_no_seconds_small_date:"HH:MM'
'yyyy年mmmm d日''",full_long:"dddd',' yyyy年 mmm d日'um' HH:MM",full_long_small_date:"HH:MM'
'dddd',' yyyy年 mmm d日''"},messages:{loading_timeline:"加载时间线... ",return_to_title:"回到开头",expand_timeline:"伸展时间",contract_timeline:"缩短时间",wikipedia:"来自维基百科，自由的百科全书",loading_content:"正在加载内容",loading:"加载中",swipe_nav:"Swipe to Navigate"}}}<commit_msg>Update zh-cn.js<commit_after>/*
    TimelineJS - ver. 2.35.5 - 2015-02-26
    Copyright (c) 2012-2013 Northwestern University
    a project of the Northwestern University Knight Lab, originally created by Zach Wise
    https://github.com/NUKnightLab/TimelineJS
    This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
    If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
if(typeof VMM!="undefined"){VMM.Language={lang:"zh-cn",api:{wikipedia:"zh"},date:{month:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],month_abbr:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],day:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],day_abbr:["周日","周一","周二","周三","周四","周五","周六"]},dateformats:{year:"yyyy年",month_short:"mmm",month:"yyyy年 mmmm",full_short:"mmm d日",full:"yyyy年mmmmd日",time_short:"HH:MM:ss",time_no_seconds_short:"HH:MM",time_no_seconds_small_date:"HH:MM'
'yyyy年mmmmd日''",full_long:"dddd',' yyyy年mmmd日'um' HH:MM",full_long_small_date:"HH:MM'
'dddd',' yyyy年mmmd日''"},messages:{loading_timeline:"加载时间线... ",return_to_title:"回到开头",expand_timeline:"伸展时间",contract_timeline:"缩短时间",wikipedia:"来自维基百科，自由的百科全书",loading_content:"正在加载内容",loading:"加载中",swipe_nav:"Swipe to Navigate"}}}
<|endoftext|>


<commit_before>var API_URL = '/api/';

var categories = [];
var beers = [];

var current_page = 1;
var page_count = 1;

//Add all the checkboxes to the categories menu
function buildCategoriesMenu() {
  for (i in categories) {
    var cat = categories[i];

    var label = $("<label>", {
      for: "cat" + cat["id"]
    }).text(cat["name"]);

    var checkbox = $("<input>", {
      type: "checkbox",
      id: "cat" + cat["id"],
      value: cat["id"],
      name: "category",
      click: function() {
        updateBeers(1);
      }
    })

    var li = $("<li>").append(checkbox.add(label));

    $("#category").append(li);
    //$("#category").append(label);
  }
}

//Fetch all the available beer categories
function getCategories() {
  $.get(API_URL + 'categories', function(result) {
    categories = result['data'];
    buildCategoriesMenu();
  })
}

//Get the currently selected categories
function selectedCategories() {
  var selected_categories = [];
  $.each($("input[name='category']:checked"), function() {
    selected_categories.push($(this).val());
  })
  return selected_categories;
}

//Build the section that displays the currently selected beer
function buildSelectedSection(beer) {
  $("#label").attr("src", "labels" in beer ? beer["labels"]["medium"] : ""),
  $("#title").text(beer["name"]);
  $("#description").text(beer["description"]);
  $("#abv").text("abv" in beer ? beer["abv"] : "?");
  $("#ibu").text("ibu" in beer ? beer["ibu"] : "?");
  $("#srm").text("srm" in beer ? beer["srm"]["name"] : "?");
  $("#og").text("originalGravity" in beer ? beer["originalGravity"] : "?");
  $("#style").text("style" in beer ? beer["style"]["name"] : "");
}

//Get the details of a beer
function selectBeer(id) {
  $.get(API_URL + 'beer/' + id, function(result) {
    buildSelectedSection(result['data']);
  })
}

//Build the list of beers
function buildBeersList() {
  $("#beers").html(""); //Clear the current results

  for (i in beers) {
    beer = beers[i];

    var link = $("<a>", {
      onclick: "selectBeer('" + beer['id'] + "')"
    }).text(beer["name"]);

    $("#beers").append(link);
  }

  if (current_page < page_count) {

    var show_more = $("<a>", {
      class: "show-more",
      click: showMoreBeers
    }).text("Show more...");

    $("#beers").append(show_more);

  }
}

//Go to the next "page" of beers from the API
function showMoreBeers() {
  current_page++;
  updateBeers(current_page);
}

//Get beers from the API
function updateBeers(page) {
  var url = API_URL + 'beers?';
  var cats = selectedCategories();

  //Attach query parameters
  cats = cats.map(function(cat) {return 'styleId=' + cat});
  url += cats.join("&");

  if (page == 1) {
    beers = []
  } else {
    url += "&p=" + page;
  }

  if (cats.length) { //Not if empty
    $.get(url, function(result) {
      current_page = result['currentPage'];
      page_count = result['numberOfPages'];
      beers = beers.concat(result['data']);
      buildBeersList();
    })
  }
}

getCategories();
//Avoid race condition between page load and API request
$(document).ready(buildCategoriesMenu);
<commit_msg>Get large image<commit_after>var API_URL = '/api/';

var categories = [];
var beers = [];

var current_page = 1;
var page_count = 1;

//Add all the checkboxes to the categories menu
function buildCategoriesMenu() {
  for (i in categories) {
    var cat = categories[i];

    var label = $("<label>", {
      for: "cat" + cat["id"]
    }).text(cat["name"]);

    var checkbox = $("<input>", {
      type: "checkbox",
      id: "cat" + cat["id"],
      value: cat["id"],
      name: "category",
      click: function() {
        updateBeers(1);
      }
    })

    var li = $("<li>").append(checkbox.add(label));

    $("#category").append(li);
    //$("#category").append(label);
  }
}

//Fetch all the available beer categories
function getCategories() {
  $.get(API_URL + 'categories', function(result) {
    categories = result['data'];
    buildCategoriesMenu();
  })
}

//Get the currently selected categories
function selectedCategories() {
  var selected_categories = [];
  $.each($("input[name='category']:checked"), function() {
    selected_categories.push($(this).val());
  })
  return selected_categories;
}

//Build the section that displays the currently selected beer
function buildSelectedSection(beer) {
  $("#label").attr("src", "labels" in beer ? beer["labels"]["large"] : ""),
  $("#title").text(beer["name"]);
  $("#description").text(beer["description"]);
  $("#abv").text("abv" in beer ? beer["abv"] : "?");
  $("#ibu").text("ibu" in beer ? beer["ibu"] : "?");
  $("#srm").text("srm" in beer ? beer["srm"]["name"] : "?");
  $("#og").text("originalGravity" in beer ? beer["originalGravity"] : "?");
  $("#style").text("style" in beer ? beer["style"]["name"] : "");
}

//Get the details of a beer
function selectBeer(id) {
  $.get(API_URL + 'beer/' + id, function(result) {
    buildSelectedSection(result['data']);
  })
}

//Build the list of beers
function buildBeersList() {
  $("#beers").html(""); //Clear the current results

  for (i in beers) {
    beer = beers[i];

    var link = $("<a>", {
      onclick: "selectBeer('" + beer['id'] + "')"
    }).text(beer["name"]);

    $("#beers").append(link);
  }

  if (current_page < page_count) {

    var show_more = $("<a>", {
      class: "show-more",
      click: showMoreBeers
    }).text("Show more...");

    $("#beers").append(show_more);

  }
}

//Go to the next "page" of beers from the API
function showMoreBeers() {
  current_page++;
  updateBeers(current_page);
}

//Get beers from the API
function updateBeers(page) {
  var url = API_URL + 'beers?';
  var cats = selectedCategories();

  //Attach query parameters
  cats = cats.map(function(cat) {return 'styleId=' + cat});
  url += cats.join("&");

  if (page == 1) {
    beers = []
  } else {
    url += "&p=" + page;
  }

  if (cats.length) { //Not if empty
    $.get(url, function(result) {
      current_page = result['currentPage'];
      page_count = result['numberOfPages'];
      beers = beers.concat(result['data']);
      buildBeersList();
    })
  }
}

getCategories();
//Avoid race condition between page load and API request
$(document).ready(buildCategoriesMenu);
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import url from 'url';
import { content_views } from './globals';
import { Auth0, HistoryAndTriggers } from './mixins';
import { NavbarMixin, Nav, Navbar, NavItem } from '../libs/bootstrap/navigation';
import jsonScriptEscape from '../libs/jsonScriptEscape';
import { RestMixin } from './rest';
import AffiliationModal from './affiliation/modal';
const AffiliationsList = require('./affiliation/affiliations.json');

var routes = {
    'curator': require('./curator').Curator
};

// Site information, including navigation
var portal = {
    portal_title: 'ClinGen',
    navUser: [
        {id: 'help', title: 'Help', url: '#'}, // dropdown Help menu button to both gene and variant help docs
        {id: 'variant', title: 'New Variant Curation', url: '/select-variant/'}, // link to VCI page /select-variant/
        {id: 'gene', title: 'New Gene Curation', url: '/create-gene-disease/'}, // link to GCI page /create-gene-disease/
        {id: 'space', title: 'space'}, // white space between
        {id: 'dashboard', title: 'Dashboard', icon: 'icon-home', url: '/dashboard/'},
        {id: 'demo', title: 'Demo Login'},
        {id: 'loginout', title: 'Login'}
        //{id: 'account', title: 'Account', url: '/account/'},
    ]
};

// Renders HTML common to all pages.
var App = module.exports = createReactClass({
    mixins: [Auth0, HistoryAndTriggers, RestMixin],

    triggers: {
        demo: 'triggerAutoLogin',
        login: 'triggerLogin',
        logout: 'triggerLogout'
    },

    // Note on context. state.context set from initial props. Navigating to other pages sets this state.
    // This state gets passed as a property to ContentView, so it should be referenced as props.context
    // from there.
    getInitialState: function() {
        var demoWarning = false;
        var productionWarning = false;
        if (/production.clinicalgenome.org/.test(url.parse(this.props.href).hostname)) {
            // check if production URL. Enable productionWarning if it is.
            productionWarning = true;
        } else if (!/^(www\.)?curation.clinicalgenome.org/.test(url.parse(this.props.href).hostname)) {
            // if neither production nor curation URL, enable demoWarning.
            demoWarning = true;
        }
        return {
            context: this.props.context, // Close to anti-pattern, but puts *initial* context into state
            slow: this.props.slow,
            href: this.props.href,
            errors: [],
            portal: portal,
            demoWarning: demoWarning,
            productionWarning: productionWarning,
            tempAffiliation: null, // Placeholder when user selects an option in the affiliation dropdown
            affiliation: {}, // Confirmed affiliation when user selects to continue in the modal
            buttonDisabled: true,
            isAffiliationModalOpen: true
        };
    },

    currentAction: function() {
        var href_url = url.parse(this.state.href);
        var hash = href_url.hash || '';
        var name;
        if (hash.slice(0, 2) === '#!') {
            name = hash.slice(2);
        }
        return name;
    },

    /**
     * Method to set states when the affiliation selection is changed
     * @param {event} e - Selection change event
     */
    handleOnChange(e) {
        this.setState({
            tempAffiliation: e.target.value !== 'Individual' ? JSON.parse(e.target.value) : {},
            buttonDisabled: false
        });
    },

    createCookie(name, value, days) {
        let expires = "";
        if (days) {
            let date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    toggleAffiliationModal() {
        this.setState({
            affiliation: this.state.tempAffiliation,
            isAffiliationModalOpen: !this.state.isAffiliationModalOpen
        }, () => {
            this.createCookie('affiliation', JSON.stringify(this.state.affiliation));
            this.setState({tempAffiliation: null});
        });
    },

    /**
     * Method to trim affiliation URIs and return an array of IDs
     * @param {array} affiliations - List of affiliation URIs
     */
    getAffiliationIds(affiliations) {
        let idArray = [];
        affiliations.forEach(item => {
            let id = item.substr(14, 5);
            idArray.push(id);
        });
        return idArray;
    },

    getUserAffiliations(affiliationIds, staticAffiliations) {
        let affiliationArray = [];
        affiliationIds.forEach(id=> {
            for (let affiliation of staticAffiliations) {
                if (affiliation.affiliation_id === id) {
                    affiliationArray.push(affiliation);
                }
            }
        });
        return affiliationArray;
    },

    renderAffiliationModal(affiliations) {
        let affiliationIds = this.getAffiliationIds(affiliations);
        let userAffiliations = this.getUserAffiliations(affiliationIds, AffiliationsList);
        return (
            <AffiliationModal show={this.state.isAffiliationModalOpen} onClose={this.toggleAffiliationModal}
                buttonDisabled={this.state.buttonDisabled}>

Continue as an individual or as a member of an affiliation.

                    <select className="form-control" defaultValue="none" onChange={this.handleOnChange}>
                        <option value="none" disabled="disabled">Select</option>
                        <option value="" disabled="disabled"></option>
                        <option value="Individual">Individual</option>
                        {userAffiliations.map((affiliation, i) => {
                            return <option key={i} value={JSON.stringify(affiliation)}>{affiliation.affiliation_abbreviation}</option>;
                        })}
                    </select>

            </AffiliationModal>
        );
    },

    render: function() {
        var content;
        var context = this.state.context;
        let session = this.state.session;
        let user_properties = session && session.user_properties;
        var href_url = url.parse(this.state.href);
        // Switching between collections may leave component in place
        var key = context && context['@id'];
        var current_action = this.currentAction();
        if (!current_action && context.default_page) {
            context = context.default_page;
        }
        if (context) {
            var ContentView = content_views.lookup(context, current_action);
            content = <ContentView {...this.props} context={context} href={this.state.href}
                loadingComplete={this.state.loadingComplete} session={session}
                portal={this.state.portal} navigate={this.navigate} href_url={href_url}
                demoVersion={this.state.demoWarning} affiliation={this.state.affiliation} />;
        }
        var errors = this.state.errors.map(function (error) {
            return

;
        });

        var appClass = 'done';
        if (this.state.slow) {
            appClass = 'communicating';
        }

        var title = context.title || context.name || context.accession || context['@id'];
        if (title && title != 'Home') {
            title = title + ' – ' + portal.portal_title;
        } else {
            title = portal.portal_title;
        }

        var canonical = this.props.href;
        if (context.canonical_uri) {
            if (href_url.host) {
                canonical = (href_url.protocol || '') + '//' + href_url.host + context.canonical_uri;
            } else {
                canonical = context.canonical_uri;
            }
        }

        let affiliation_cookie = this.state.affiliation_cookie;

        return (

                    <meta charSet="utf-8" />
                    <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
                    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                    <title>ClinGen</title>
                    <link rel="canonical" href={canonical} />

                    <link rel="stylesheet" href="@@cssFile" />

                        {this.state.demoWarning ?
                            <Notice noticeType='demo' noticeMessage={Note: This is a demo version of the site. Any data you enter will not be permanently saved.} />
                            : null}
                        {this.state.productionWarning ?
                            <Notice noticeType='production' noticeMessage={Do not use this URL for entering data. Please use curation.clinicalgenome.org instead.} />
                            : null}
                        {(this.state.affiliation && Object.keys(this.state.affiliation).length && affiliation_cookie) ?

                                    Curator: {user_properties.title}
                                    Affiliation: {this.state.affiliation.affiliation_fullname}

                                        <button type="button" className="btn btn-primary" onClick={this.renderAffiliationModal.bind(null, user_properties.affiliation)}>Change Affiliation</button>

                            : null}
                        {user_properties && user_properties.affiliation && user_properties.affiliation.length && !affiliation_cookie ?
                            this.renderAffiliationModal(user_properties.affiliation)
                            : null}
                        {content}

        );
    },

    statics: {
        // Get data to display from page

                    <link rel="stylesheet" href="@@cssFile" />

                        {this.state.demoWarning ?
                            <Notice noticeType='demo' noticeMessage={Note: This is a demo version of the site. Any data you enter will not be permanently saved.} />
                            : null}
                        {this.state.productionWarning ?
                            <Notice noticeType='production' noticeMessage={Do not use this URL for entering data. Please use curation.clinicalgenome.org instead.} />
                            : null}
                        {this.state.affiliation && Object.keys(this.state.affiliation).length ?

                                    Curator: {user_properties.title}
                                    Affiliation: {this.state.affiliation.affiliation_fullname}

                                        <button type="button" className="btn btn-primary" onClick={this.renderAffiliationModal.bind(null, user_properties.affiliation)}>Change Affiliation</button>

                            : null}
                        {user_properties && user_properties.affiliation && user_properties.affiliation.length && !affiliation_cookie ?
                            this.renderAffiliationModal(user_properties.affiliation)
                            : null}
                        {content}

        );
    },

    statics: {
        // Get data to display from page


<commit_before>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { StyleSheet } from 'react-native';
import { Page, NoProjectFound } from 'DailyScrum/src/components';
import { currentProjectSelector } from '../../modules/projects/reducer';
import type { ProjectType } from '../../types/Project';
import { isSyncingSelector } from '../../modules/sync';
import SuccessMatrix from './components/SuccessMatrix';
import appStyle from '../../appStyle';

class Summary extends Component {
  props: PropsType;

  render() {
    const { project, isSyncing } = this.props;
    if (!project) {
      if (isSyncing) return <Page isLoading />;
      // TODO show less generic placeholder
      return (
        <Page>
          <NoProjectFound />
        </Page>
      );
    }

    return (
      <Page style={styles.container}>
        <SuccessMatrix style={styles.matrix} />
      </Page>
    );
  }
}

type PropsType = {
  navigation: any,
  project: ProjectType,
  isSyncing: boolean,
};

const styles = StyleSheet.create({
  container: {
    paddingTop: appStyle.margin,
    paddingHorizontal: appStyle.margin - appStyle.shadow.radius,
  },
  matrix: {
    marginVertical: appStyle.margin,
  },
});

const mapStateToProps = state => ({
  project: currentProjectSelector(state),
  isSyncing: isSyncingSelector(state, 'projects', 'current'),
});

export default connect(mapStateToProps)(Summary);
<commit_msg>Project page is scrollable<commit_after>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { StyleSheet, ScrollView } from 'react-native';
import { Page, NoProjectFound } from 'DailyScrum/src/components';
import { currentProjectSelector } from '../../modules/projects/reducer';
import type { ProjectType } from '../../types/Project';
import { isSyncingSelector } from '../../modules/sync';
import SuccessMatrix from './components/SuccessMatrix';
import appStyle from '../../appStyle';

class Summary extends Component {
  props: PropsType;

  render() {
    const { project, isSyncing } = this.props;
    if (!project) {
      if (isSyncing) return <Page isLoading />;
      // TODO show less generic placeholder
      return (
        <Page>
          <NoProjectFound />
        </Page>
      );
    }

    return (
      <Page noMargin style={styles.container}>
        <ScrollView contentContainerStyle={styles.scrollViewContent} showsVerticalScrollIndicator={false}>
          <SuccessMatrix style={styles.matrix} />
        </ScrollView>
      </Page>
    );
  }
}

type PropsType = {
  navigation: any,
  project: ProjectType,
  isSyncing: boolean,
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: appStyle.margin - appStyle.shadow.radius,
  },
  scrollViewContent: {
    paddingVertical: appStyle.margin,
  },
  matrix: {
    marginVertical: appStyle.margin,
  },
});

const mapStateToProps = state => ({
  project: currentProjectSelector(state),
  isSyncing: isSyncingSelector(state, 'projects', 'current'),
});

export default connect(mapStateToProps)(Summary);
<|endoftext|>


<commit_before>class PlayerAI {
    constructor() {
        this.have_ball = false
        this.toball_cnt = 0
        this.agressive_cnt = 0
        this.tofront_cnt = 0
        this.togoal_cnt = 0
        this.managed = []
        for (var p in this.players) {
            if (p.ball) this.have_ball = true
        }
    }

    step(dt) {

    }

    manage(player, dt, delta) {
        if (this.managed[player] == null) {
            this.managed[player] = {
                "mode": "toball",
                "lastmode_ts": 0,
            }
        }
        var infos = this.managed[player]
        let managed = this.managed[player]
        var mode_duration = 3
        var goals = [
            [106, -101, -114], // goal area on left side
            [283, -101, -114], // goal area on right side
        ]

        // set  ai behaviour
        if (player.ball) {
            // when near the goal and have ball
            if (player.pos.x < (goals[0][0] + 40) &&
                player.pos.y < goals[0][1] &&
                player.pos.y > goals[0][2]) {
                infos.mode = "togoal"
                this.togoal_cnt = this.togoal_cnt + 1
            } else {
                infos.mode = 'tofrontgoal'
                this.tofront_cnt = managed.tofront_cnt + 1
            }
        } else {
            if (this.have_ball) { // an another ennemy player have the ball
                infos.mode = 'agressive'
                this.agressive_cnt = managed.agressive_cnt + 1
            } else if (infos.lastmode == null || infos.lastmode_ts > mode_duration) {
                infos.lastmode_ts = 0
                if (this.toball_cnt > 0 && (Math.random() < 0.5 || this.toball_cnt == 0)) {
                    infos.mode = 'agressive' // make one agressive,  random
                    this.agressive_cnt = this.agressive_cnt + 1
                } else {
                    infos.mode = 'toball'
                    this.toball_cnt = this.toball_cnt + 1
                }

            } else {
                infos.lastmode_ts = infos.lastmode_ts + dt
                infos.mode = infos.lastmode
            }

        }

        // now apply the behavior according to the chosen mode
        var x = null
        var y = null

        if (infos.mode == "aggressive") {
            var tgt, dist
        }

        // MOVE RANDOMLY FOR NOW
        if (Math.random() < 0.6)
            player.forward(delta);
        if (Math.random() < 0.3)
            player.left(delta)
        if (Math.random() < 0.3)
            player.right(delta);

    }

    clear() {

    }
}
<commit_msg>dudes try to look for the targets<commit_after>class PlayerAI {
    constructor() {
        this.have_ball = false
        this.toball_cnt = 0
        this.aggressive_cnt = 0
        this.tofront_cnt = 0
        this.togoal_cnt = 0
        this.managed = []
        for (var p in this.players) {
            if (p.ball) this.have_ball = true
        }
    }

    step(dt) {

    }

    manage(player, dt, delta) {
        if (this.managed[player] == null) {
            this.managed[player] = {
                "mode": "toball",
                "lastmode_ts": 0,
            }
        }
        var infos = this.managed[player]
        let managed = this.managed[player]
        var mode_duration = 3
        var goals = [
            [106, -101, -114], // goal area on left side
            [283, -101, -114], // goal area on right side
        ]

        // set  ai behaviour
        if (player.ball) {
            // when near the goal and have ball
            if (player.pos.x < (goals[0][0] + 40) &&
                player.pos.y < goals[0][1] &&
                player.pos.y > goals[0][2]) {
                infos.mode = "togoal"
                this.togoal_cnt = this.togoal_cnt + 1
            } else {
                infos.mode = 'tofrontgoal'
                this.tofront_cnt = managed.tofront_cnt + 1
            }
        } else {
            if (this.have_ball) { // an another ennemy player have the ball
                infos.mode = 'aggressive'
                this.aggressive_cnt = managed.aggressive_cnt + 1
            } else if (infos.lastmode == null || infos.lastmode_ts > mode_duration) {
                infos.lastmode_ts = 0
                if (this.toball_cnt > 0 && (Math.random() < 0.5 || this.toball_cnt == 0)) {
                    infos.mode = 'aggressive' // make one aggressive,  random
                    this.aggressive_cnt = this.aggressive_cnt + 1
                } else {
                    infos.mode = 'toball'
                    this.toball_cnt = this.toball_cnt + 1
                }

            } else {
                infos.lastmode_ts = infos.lastmode_ts + dt
                infos.mode = infos.lastmode
            }

        }

        // now apply the behavior according to the chosen mode
        var x = null
        var y = null
        if (infos.mode == "aggressive") {
           let random_player = app.menus[0].enemies[Math.floor(Math.random(1, app.config.DUDES))]
          //  let random_player = app.menus[0].enemies[0]
            var dist = player.distance_from(random_player.pos)
            let targets = player.targets(random_player.pos)
            console.log(targets);
            if (dist < 10 && !targets[0]) {
              if (targets[1] > 0) {
                player.left(0.1)
              } else {
                player.right(0.1)
              }
            } else if (dist > 10 && targets[0]) {
                player.forward(delta)
            }
        }

        // MOVE RANDOMLY FOR NOW
        // if (Math.random() < 0.6)
        //     player.forward(delta);
        // if (Math.random() < 0.3)
        //     player.left(delta)
        // if (Math.random() < 0.3)
        //     player.right(delta);

    }

    clear() {

    }
}
<|endoftext|>


<commit_before>/* eslint-disable
    handle-callback-err,
    no-return-assign,
    no-undef,
    no-unused-vars,
    node/no-deprecated-api,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
let OutputFileOptimiser
const fs = require('fs')
const Path = require('path')
const { spawn } = require('child_process')
const logger = require('logger-sharelatex')
const Metrics = require('./Metrics')
const _ = require('lodash')

module.exports = OutputFileOptimiser = {
  optimiseFile(src, dst, callback) {
    // check output file (src) and see if we can optimise it, storing
    // the result in the build directory (dst)
    if (callback == null) {
      callback = function (error) {}
    }
    if (src.match(/\/output\.pdf$/)) {
      return OutputFileOptimiser.checkIfPDFIsOptimised(src, function (
        err,
        isOptimised
      ) {
        if (err != null || isOptimised) {
          return callback(null)
        }
        return OutputFileOptimiser.optimisePDF(src, dst, callback)
      })
    } else {
      return callback(null)
    }
  },

  checkIfPDFIsOptimised(file, callback) {
    const SIZE = 16 * 1024 // check the header of the pdf
    const result = Buffer.alloc(SIZE) // fills with zeroes by default
    return fs.open(file, 'r', function (err, fd) {
      if (err != null) {
        return callback(err)
      }
      return fs.read(fd, result, 0, SIZE, 0, (errRead, bytesRead, buffer) =>
        fs.close(fd, function (errClose) {
          if (errRead != null) {
            return callback(errRead)
          }
          if (typeof errReadClose !== 'undefined' && errReadClose !== null) {
            return callback(errClose)
          }
          const isOptimised =
            buffer.toString('ascii').indexOf('/Linearized 1') >= 0
          return callback(null, isOptimised)
        })
      )
    })
  },

  optimisePDF(src, dst, callback) {
    if (callback == null) {
      callback = function (error) {}
    }
    const tmpOutput = dst + '.opt'
    const args = ['--linearize', src, tmpOutput]
    logger.log({ args }, 'running qpdf command')

    const timer = new Metrics.Timer('qpdf')
    const proc = spawn('qpdf', args)
    let stdout = ''
    proc.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk))
    callback = _.once(callback) // avoid double call back for error and close event
    proc.on('error', function (err) {
      logger.warn({ err, args }, 'qpdf failed')
      return callback(null)
    }) // ignore the error
    return proc.on('close', function (code) {
      timer.done()
      if (code !== 0) {
        logger.warn({ code, args }, 'qpdf returned error')
        return callback(null) // ignore the error
      }
      return fs.rename(tmpOutput, dst, function (err) {
        if (err != null) {
          logger.warn(
            { tmpOutput, dst },
            'failed to rename output of qpdf command'
          )
        }
        return callback(null)
      })
    })
  } // ignore the error
}
<commit_msg>Add flag to qpdf, to preserve PDF/A compliance<commit_after>/* eslint-disable
    handle-callback-err,
    no-return-assign,
    no-undef,
    no-unused-vars,
    node/no-deprecated-api,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
let OutputFileOptimiser
const fs = require('fs')
const Path = require('path')
const { spawn } = require('child_process')
const logger = require('logger-sharelatex')
const Metrics = require('./Metrics')
const _ = require('lodash')

module.exports = OutputFileOptimiser = {
  optimiseFile(src, dst, callback) {
    // check output file (src) and see if we can optimise it, storing
    // the result in the build directory (dst)
    if (callback == null) {
      callback = function (error) {}
    }
    if (src.match(/\/output\.pdf$/)) {
      return OutputFileOptimiser.checkIfPDFIsOptimised(src, function (
        err,
        isOptimised
      ) {
        if (err != null || isOptimised) {
          return callback(null)
        }
        return OutputFileOptimiser.optimisePDF(src, dst, callback)
      })
    } else {
      return callback(null)
    }
  },

  checkIfPDFIsOptimised(file, callback) {
    const SIZE = 16 * 1024 // check the header of the pdf
    const result = Buffer.alloc(SIZE) // fills with zeroes by default
    return fs.open(file, 'r', function (err, fd) {
      if (err != null) {
        return callback(err)
      }
      return fs.read(fd, result, 0, SIZE, 0, (errRead, bytesRead, buffer) =>
        fs.close(fd, function (errClose) {
          if (errRead != null) {
            return callback(errRead)
          }
          if (typeof errReadClose !== 'undefined' && errReadClose !== null) {
            return callback(errClose)
          }
          const isOptimised =
            buffer.toString('ascii').indexOf('/Linearized 1') >= 0
          return callback(null, isOptimised)
        })
      )
    })
  },

  optimisePDF(src, dst, callback) {
    if (callback == null) {
      callback = function (error) {}
    }
    const tmpOutput = dst + '.opt'
    const args = ['--linearize', '--newline-before-endstream', src, tmpOutput]
    logger.log({ args }, 'running qpdf command')

    const timer = new Metrics.Timer('qpdf')
    const proc = spawn('qpdf', args)
    let stdout = ''
    proc.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk))
    callback = _.once(callback) // avoid double call back for error and close event
    proc.on('error', function (err) {
      logger.warn({ err, args }, 'qpdf failed')
      return callback(null)
    }) // ignore the error
    return proc.on('close', function (code) {
      timer.done()
      if (code !== 0) {
        logger.warn({ code, args }, 'qpdf returned error')
        return callback(null) // ignore the error
      }
      return fs.rename(tmpOutput, dst, function (err) {
        if (err != null) {
          logger.warn(
            { tmpOutput, dst },
            'failed to rename output of qpdf command'
          )
        }
        return callback(null)
      })
    })
  } // ignore the error
}
<|endoftext|>


<commit_before>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';
module.exports = function (content, file, conf) {
    var options = file.jswrapper;

    if (file.isMod || conf.wrapAll || options) {

        var template = getConfig('template', options, conf);
        var type = getConfig('type', options, conf);

        // wrap
        if (template) {
            content = String(template)
                .split('${content}').join(content)
                .split('${id}').join(file.getId());
        } else if (type === 'amd') {
            if (!/^\s*define\s*\(/.test(content)) {
                content = 'define(\'' + file.getId() + '\', function(require, exports, module){ ' + content +
                    ' \r\n});';
            }
        } else {
            if (!/^\s*(?:[!(]\s*|void\s+)function\(/.test(content)) {
                content = '!function(){try{ ' + content + ' \r\n}catch(e){}}();';
            }
        }
    }
    return content;
};

function getConfig(key, local, global) {
    return local && typeof local[key] !== 'undefined' ? local[key] : global[key];
}<commit_msg>增强配置，支持template是function类型及增加hash支持<commit_after>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';
module.exports = function (content, file, conf) {
    var options = file.jswrapper;

    if (file.isMod || conf.wrapAll || options) {

        var template = getConfig('template', options, conf);
        var type = getConfig('type', options, conf);

        //扩展template能力，支持function
        if(typeof template==='function'){
            var temp = template(file);
            if(temp){
                template = temp;
            }
        }
        // wrap
        if (template) {
            content = String(template)
                .split('${content}').join(content)
                .split('${id}').join(file.getId())
                .split('${hash}').join(file.getHash());
                //增加md5
        } else if (type === 'amd') {
            if (!/^\s*define\s*\(/.test(content)) {
                content = 'define(\'' + file.getId() + '\', function(require, exports, module){ ' + content +
                    ' \r\n});';
            }
        } else {
            if (!/^\s*(?:[!(]\s*|void\s+)function\(/.test(content)) {
                content = '!function(){try{ ' + content + ' \r\n}catch(e){}}();';
            }
        }
    }
    return content;
};

function getConfig(key, local, global) {
    return local && typeof local[key] !== 'undefined' ? local[key] : global[key];
}
<|endoftext|>


<commit_before>/**
 * mixins/gatekeeper.js
 *
 * Used to extend the ToriiSession with ArcGIS specific helper methods
 *
 */
import Ember from 'ember';

export default Ember.Mixin.create({
  /**
   * Check if the current user is in a specific role
   * In ArcGIS Online, users can only have a single role.
   */
  isInRole(role){
    let user = this.get('currentUser');

    if(user){
      return user.role === role;
    }else{
      return false;
    }
  },

  /**
   * Is the specified priviledge is the list of priviledges
   * assigned to the current user?
   */
  hasPrivilege(privilege){
    let user = this.get('currentUser');
    if(user){
      return (user.privileges.indexOf(privilege) > -1);
    }else{
      return false;
    }
  },

  /**
   * Does the current user have any of the passed in privileges
   */
  hasAnyPrivilege(privileges){
    let result = false;
    //check that we have an array
    if(Ember.isArray(privileges)){

      for (var i = 0; i < privileges.length; i++) {
        if (this.hasPrivilege(privileges[i])) {
          result =  true;
        }
      }

    }else{
      Ember.warn('Session.hasAnyPrivilege was not passed an array. Please use .hasPrivilege instead.');
    }
    return result;
  },

  /**
   * Allows for quick check if a user is in a set of roles
   */
  isInAnyRole(roles){
    let result = false;
    //check that we have an array
    if(Ember.isArray(roles)){

      for (var i = 0; i < roles.length; i++) {
        if (this.isInRole(roles[i])) {
          result =  true;
        }
      }

    }else{
      Ember.warn('Session.isInAnyRole was not passed an array. Please use .isInRole instead.');
    }
    return result;
  },

  /**
   * Check if the user is in a specific org.
   * This is used in conjunction with feature flags
   * to control access to features under development
   */
  isInOrg(orgId){
    let portal = this.get('portal');
    if(portal){
      return (portal.id === orgId);
    }else{
      return false;
    }
  },

  /**
   * Allows for a quick check if a user is a member of
   * any of a set of orgs
   */
  isInAnyOrg(orgs){
    let result = false;
    //check that we have an array
    if(Ember.isArray(orgs)){

      for (var i = 0; i < orgs.length; i++) {
        if (this.isInOrg(orgs[i])) {
          result =  true;
        }
      }

    }else{
      Ember.warn('Session.isInAnyOrg was not passed an array. Please use .isInOrg instead.');
    }
    return result;
  }
});
<commit_msg>add orgPortalUrl to session service mixin<commit_after>/**
 * mixins/gatekeeper.js
 *
 * Used to extend the ToriiSession with ArcGIS specific helper methods
 *
 */
import Ember from 'ember';

export default Ember.Mixin.create({
  /**
   * Check if the current user is in a specific role
   * In ArcGIS Online, users can only have a single role.
   */
  isInRole(role){
    let user = this.get('currentUser');

    if(user){
      return user.role === role;
    }else{
      return false;
    }
  },

  /**
   * Is the specified priviledge is the list of priviledges
   * assigned to the current user?
   */
  hasPrivilege(privilege){
    let user = this.get('currentUser');
    if(user){
      return (user.privileges.indexOf(privilege) > -1);
    }else{
      return false;
    }
  },

  /**
   * Does the current user have any of the passed in privileges
   */
  hasAnyPrivilege(privileges){
    let result = false;
    //check that we have an array
    if(Ember.isArray(privileges)){

      for (var i = 0; i < privileges.length; i++) {
        if (this.hasPrivilege(privileges[i])) {
          result =  true;
        }
      }

    }else{
      Ember.warn('Session.hasAnyPrivilege was not passed an array. Please use .hasPrivilege instead.');
    }
    return result;
  },

  /**
   * Allows for quick check if a user is in a set of roles
   */
  isInAnyRole(roles){
    let result = false;
    //check that we have an array
    if(Ember.isArray(roles)){

      for (var i = 0; i < roles.length; i++) {
        if (this.isInRole(roles[i])) {
          result =  true;
        }
      }

    }else{
      Ember.warn('Session.isInAnyRole was not passed an array. Please use .isInRole instead.');
    }
    return result;
  },

  /**
   * Check if the user is in a specific org.
   * This is used in conjunction with feature flags
   * to control access to features under development
   */
  isInOrg(orgId){
    let portal = this.get('portal');
    if(portal){
      return (portal.id === orgId);
    }else{
      return false;
    }
  },

  /**
   * Allows for a quick check if a user is a member of
   * any of a set of orgs
   */
  isInAnyOrg(orgs){
    let result = false;
    //check that we have an array
    if(Ember.isArray(orgs)){

      for (var i = 0; i < orgs.length; i++) {
        if (this.isInOrg(orgs[i])) {
          result =  true;
        }
      }

    }else{
      Ember.warn('Session.isInAnyOrg was not passed an array. Please use .isInOrg instead.');
    }
    return result;
  },

  orgPortalUrl: Ember.computed('portal', function () {
    const portal = this.get('portal');
    const urlKey = portal.urlKey;
    let result = portal.portalHostName;

    if (urlKey) {
      const customUrl = portal.customBaseUrl;
      result = `${urlKey}.${customUrl}`;
    } else {
      const portalHostName = portal.portalHostname;
      result = `${portalHostName}`;
    }
    return result;
  }),
});
<|endoftext|>


<commit_before>// players / get_players()

function get_fighters_by_gender(gender) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if (fighterData[i].gender === gender) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

function get_fighters_by_promotion(promotion) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if (fighterData[i].promotion === promotion) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

function get_fighters_by_weight(weight) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if ((fighterData[i].weight.split(" ")[0]) === "Women" &&
        (fighterData[i].weight.split(" ")[1]) === weight) {
      fighters.push(fighterData[i]);
    } else if (fighterData[i].weight === weight) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

function get_fighters_by_name(name) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if ((fighterData[i].last_name + ", " + fighterData[i].first_name) === name) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

// ensure consistency
// this means that we have to validate if fighters can fight each other
// for instance, fighters of different genders can't fight each other
// and so on.

function validate_pairs(red_fighter, blue_fighter) {
  // returns true when it's a valid fight
  // returns false when it's an illegal fight

  // note: syntax for accessing gender field may change
  if( red_fighter === blue_fighter ) {
  return true;
  }

  return false;
}

function get_weight_class(fighter) {
  if( fighter.gender === "female" ) {
  return fighter.weight.split(" ")[1];
  }

  return fighter.weight;
}

function get_img_path(fighter) {
  return fighter.fighter_image;
}

function get_fighter_name(fighter) {
  return (fighter.first_name + " " + fighter.last_name);
}

function get_fighter_nickname(fighter) {
  return fighter.nickname;
}

function get_fighter_promotion(fighter) {
  return fighter.promotion;
}

function get_fighter_record(fighter) {
  return (fighter.win + "-" + fighter.loss + "-" + fighter.draw);
}<commit_msg>removed extra whitespace<commit_after>// players / get_players()

function get_fighters_by_gender(gender) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if (fighterData[i].gender === gender) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

function get_fighters_by_promotion(promotion) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if (fighterData[i].promotion === promotion) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

function get_fighters_by_weight(weight) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if ((fighterData[i].weight.split(" ")[0]) === "Women" &&
        (fighterData[i].weight.split(" ")[1]) === weight) {
      fighters.push(fighterData[i]);
    } else if (fighterData[i].weight === weight) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

function get_fighters_by_name(name) {
  var fighters = [];
  for (var i=0; i<fighterData.length; i++) {
    if ((fighterData[i].last_name + ", " + fighterData[i].first_name) === name) {
      fighters.push(fighterData[i]);
    }
  }
  return fighters;
}

// ensure consistency
// this means that we have to validate if fighters can fight each other
// for instance, fighters of different genders can't fight each other
// and so on.

function validate_pairs(red_fighter, blue_fighter) {
  // returns true when it's a valid fight
  // returns false when it's an illegal fight

  // note: syntax for accessing gender field may change
  if( red_fighter === blue_fighter ) {
  return true;
  }

  return false;
}

function get_weight_class(fighter) {
  if( fighter.gender === "female" ) {
  return fighter.weight.split(" ")[1];
  }

  return fighter.weight;
}

function get_img_path(fighter) {
  return fighter.fighter_image;
}

function get_fighter_name(fighter) {
  return (fighter.first_name + " " + fighter.last_name);
}

function get_fighter_nickname(fighter) {
  return fighter.nickname;
}

function get_fighter_promotion(fighter) {
  return fighter.promotion;
}

function get_fighter_record(fighter) {
  return (fighter.win + "-" + fighter.loss + "-" + fighter.draw);
}
<|endoftext|>