<commit_before>/* eslint-enable */

(function (window) {
  $(document).ready(function () {
    questionAnswerCreator();
    quizInterfaceCreator();
    $('.quiz-form').on('submit', checkAnswers).on('reset', renewQuiz);
  });

  function QA(question, answer) {
    this.question = question;
    this.answer = answer;
    this.answerOptions = [];
  }

  /*
   * Details of the quiz
   */
  var quiz = {
    questionAnswerList: [], // list of all questions and answers
    score: 0, // score of the user

    /*
     * Add question and answer to list
     * @param question Question to add
     * @param answer Answer of the question
     * @param answerOptions Other invalid optional answers to question (optional)
     */
    add: function (question, answer, answerOptions) {
      var questionAnswer = new QA(question, answer);

      /* Check if answer included in answerOptions and delete them */
      if (answerOptions && answerOptions instanceof Array) {
        while (answerOptions.indexOf(answer) > -1) {
          var answerIndex = answerOptions.indexOf(answer);
          answerOptions.splice(answerIndex, 1);
        }
      }

      /* Generate three random answers using default answers list
       * if answerOptions is not given or
       * if answerOptions is not an array or
       * if answerOptions is an empty array */
      if (!answerOptions || !(answerOptions instanceof Array) || !answerOptions.length) {
        answerOptions = [];
        (function addRandAnswers() {
          while (answerOptions.length < 3) {
            /* generate a random number
             * range [0 - defaultAnswerOptions.length (exclusive)] */
            var rand = Math.floor(Math.random() * quiz.defaultAnswerOptions.length),
              answer_ = quiz.defaultAnswerOptions[rand];

            /* Add to answerOptions if generated answer is not the
             * actual answer and it's not present in the answerOptions */
            if (answer_ !== answer &&
              answerOptions.indexOf(answer_) < 0) {
              answerOptions.push(answer_);
            }
          }
        })();
      }

      questionAnswer.answerOptions = answerOptions;

      // add new question answer to questionAnswerList
      quiz.questionAnswerList.push(questionAnswer);

      return this;
    },

    /* Default answers to populate in answerOptions */
    defaultAnswerOptions: ['Vishakhapatnam', 'Guntur', 'Hyderabad', 'Khammam',
                           'Bomdilla', 'Itanagar', 'Tawang', 'Namsai',
                           'Guwahati', 'Silchar', 'Dispur', 'Dibrugarh',
                           'Muzaffarpur', 'Darbhanga', 'Aurangabad', 'Patna',
                           'Raipur', 'Durg', 'Bastar', 'Dantewara',
                           'Panaji', 'Cupa', 'Saturli', 'Chaudi',
                           'Rae Bareilly', 'Gandhinagar', 'Surat', 'Ahmedabad',
                           'gurgaon', 'Kurukshetra', 'Bhiwani', 'Chandigarh',
                           'Kullu', 'Shimla', 'Mandi', 'Bilaspur',
                           'Srinagar', 'Anantnag', 'Udhampur', 'Rajouri',
                           'Jamshedpur', 'Ranchi', 'Dhanbad', 'Hazaribag',
                           'Chikkamagaluru', 'Mysore', 'Chitradurga', 'Bengaluru',
                           'Palakkad', 'Thrissur', 'Thiruvananthapuram', 'Kozhikode',
                           'Jabalpur', 'Bhopal', 'Rajgarh', 'Udaipura',
                           'Honolulu', 'Pune', 'Nagpur', 'Mumbai',
                           'Churachandpur', 'Imphal', 'Bishnupur', 'Thoubal',
                           'Shillong', 'Nongpoh', 'Jowai', 'Baghmara',
                           'Champhai', 'Aizawl', 'Phaileng', 'Mamit',
                           'Dimapur', 'Wokha', 'Kohima', 'Phek',
                           'Bhubaneswar', 'Cuttack', 'Brahmapur', 'Sambalpur',
                           'Chandigarh', 'Ludhiana', 'Amritsar', 'Jalandhar',
                           'Ajmer', 'Jaisalmer', 'Bikaner', 'Jaipur',
                           'Namchi', 'Gangtok', 'Mangan', 'Gezing',
                           'Chennai', 'Kanchipuram', 'Tiruchirapalli', 'Madurai',
                           'Adilabad', 'Nalgonda', 'Warangal', 'Hyderabad',
                           'Kailsahar', 'Dharmanagar', 'Agartala', 'Udaipur',
                           'Lucknow', 'Noida', 'Ghaziabad', 'Mathura',
                           'Hardwar', 'Dehradun', 'Nainital', 'Almora',
                           'Alipore', 'Medinipur', 'Krishnanagar', 'Kolkata']
  };

  /*
   * Repopulate the answerOptions
   * Reset score
   */
  function renewQuiz() { // @TODO repopulate answerOptions
    quiz.score = 0;
    var questions = $('.questions').find('.question');
    questions.removeClass('wrong correct');
    var results = $('.results');
    results.hide();
  }

  /*
   * Generate question and answer sets.
   */
  function questionAnswerCreator() {
    quiz.add('What is the capital of Andhra Pradesh?', 'Hyderabad');
    quiz.add('What is the capital of Arunachal Pradesh?', 'Itanagar');
    quiz.add('What is the capital of Assam?', 'Dispur');
    quiz.add('What is the capital of Bihar?', 'Patna');
    quiz.add('What is the capital of Chhattisgarh?', 'Raipur');
    quiz.add('What is the capital of Goa?', 'Panaji');
    quiz.add('What is the capital of Gujarat?', 'Gandhinagar');
    quiz.add('What is the capital of Haryana?', 'Chandigarh');
    quiz.add('What is the capital of Himachal Pradesh?', 'Shimla');
    quiz.add('What is the capital of Jammu and Kashmir?', 'Srinagar');
    quiz.add('What is the capital of Jhakhand?', 'Ranchi');
    quiz.add('What is the capital of Karnataka?', 'Bengaluru');
    quiz.add('What is the capital of Kerala?', 'Thiruvananthapuram');
    quiz.add('What is the capital of Madhya Pradesh?', 'Bhopal');
    quiz.add('What is the capital of Maharashtra?', 'Mumbai');
    quiz.add('What is the capital of Manipur?', 'Imphal');
    quiz.add('What is the capital of Meghalaya?', 'Shillong');
    quiz.add('What is the capital of Mizoram?', 'Aizawl');
    quiz.add('What is the capital of Nagaland?', 'Kohima');
    quiz.add('What is the capital of Odisha?', 'Bhubaneswar');
    quiz.add('What is the capital of Punjab?', 'Chandigarh');
    quiz.add('What is the capital of Rajasthan?', 'Jaipur');
    quiz.add('What is the capital of Sikkim?', 'Gangtok');
    quiz.add('What is the capital of Tamil Nadu?', 'Chennai');
    quiz.add('What is the capital of Telangana?', 'Hyderabad');
    quiz.add('What is the capital of Tripura?', 'Agartala');
    quiz.add('What is the capital of Uttar Pradesh?', 'Lucknow');
    quiz.add('What is the capital of Uttarakhand?', 'Dehradun');
    quiz.add('What is the capital of West Bengal?', 'Kolkata');
  }

  /*
   * Generate quiz interface.
   */
  function quizInterfaceCreator() {
    var questions = $('.questions'); // questions container
    /* question template */
    var qTemplate = questions.find('.question[data-question-template]');

    quiz.questionAnswerList.forEach(function (qa, qaIndex) {
      var question = qTemplate.clone(true);
      question.removeAttr('data-question-template'); // remove template attr
      question.attr('data-question-id', qaIndex); // add question indexes

      question.find('.questionText').html(qa.question); // add question

      var answers = question.find('.answers'); // answers container
      /* answer template */
      var aTemplate = question.find('.answer[data-answer-template]');

      var answerList = [qa.answer]; // add real answer
      [].push.apply(answerList, qa.answerOptions); // add all optional answers

      /* shuffle answerList */
      (function shuffleAnswers() {
        var len = answerList.length;
        while (len) {
          var rand = Math.floor(Math.random() * len--);
          answerList.unshift(answerList.splice(rand, 1));
        }
      })();

      answerList.forEach(function (ans) {
        var answer = aTemplate.clone(true);
        answer.removeAttr('data-answer-template'); // remove template attr

        /* insert answer value in input */
        var input = answer.find('input');
        input.attr('name', 'qa' + qaIndex).attr('value', ans);

        /* insert answer text */
        answer.find('.answerText').html(ans);

        /* add answer to the list of answers */
        answers.append(answer);
      });

      /* append question to the bottom of questions */
      questions.append(question);
    });

  }

  /* Check answers to the question */
  function checkAnswers(ev) {
    ev.preventDefault();
    // reset score to zero (0)
    quiz.score = 0;

    /* find all checked inputs */
    var checked = $('.questions').find('input:checked');

    /* if none checked, do nothing */
    if (!checked.length) {
      return;
    }

    checked.each(function (i, ch) {
      /* get question id of checked answer */
      var questionId = Number($(ch).attr('name').replace(/qa(\d+)/, '$1')),
        answer = $(ch).attr('value'), // get the checked answer
        questionBox = $('.question[data-question-id=' + questionId + ']');

      /* check if the answer with the question id mathces the checked answer */
      if (quiz.questionAnswerList[questionId].answer === answer) {
        questionBox.removeClass('wrong');
        questionBox.addClass('correct');

        // increment the score
        quiz.score++;
      } else {
        questionBox.removeClass('correct');
        questionBox.addClass('wrong');
      }
    });

    var results = $('.results');
    results.find('.score').html(quiz.score);
    results.find('.total').html(quiz.questionAnswerList.length);
    results.show();
  }

})(this);
<commit_msg>Recreated Shuffle Algorithm<commit_after>/* eslint-enable */

(function (window) {
  'use strict';

  $(document).ready(function () {
    questionAnswerCreator();
    quizInterfaceCreator();
    $('.quiz-form').on('submit', checkAnswers).on('reset', renewQuiz);
  });

  function QA(question, answer) {
    this.question = question;
    this.answer = answer;
    this.answerOptions = [];
  }

  /*
   * Details of the quiz
   */
  var quiz = {
    questionAnswerList: [], // list of all questions and answers
    score: 0, // score of the user

    /*
     * Add question and answer to list
     * @param question Question to add
     * @param answer Answer of the question
     * @param answerOptions Other invalid optional answers to question (optional)
     */
    add: function (question, answer, answerOptions) {
      var questionAnswer = new QA(question, answer);

      /* Check if answer included in answerOptions and delete them */
      if (answerOptions && answerOptions instanceof Array) {
        while (answerOptions.indexOf(answer) > -1) {
          var answerIndex = answerOptions.indexOf(answer);
          answerOptions.splice(answerIndex, 1);
        }
      }

      /* Generate three random answers using default answers list
       * if answerOptions is not given or
       * if answerOptions is not an array or
       * if answerOptions is an empty array */
      if (!answerOptions || !(answerOptions instanceof Array) || !answerOptions.length) {
        answerOptions = [];
        (function addRandAnswers() {
          while (answerOptions.length < 3) {
            /* generate a random number
             * range [0 - defaultAnswerOptions.length (exclusive)] */
            var rand = Math.floor(Math.random() * quiz.defaultAnswerOptions.length),
              answer_ = quiz.defaultAnswerOptions[rand];

            /* Add to answerOptions if generated answer is not the
             * actual answer and it's not present in the answerOptions */
            if (answer_ !== answer &&
              answerOptions.indexOf(answer_) < 0) {
              answerOptions.push(answer_);
            }
          }
        })();
      }

      questionAnswer.answerOptions = answerOptions;

      // add new question answer to questionAnswerList
      quiz.questionAnswerList.push(questionAnswer);

      return this;
    },

    /* Default answers to populate in answerOptions */
    defaultAnswerOptions: ['Vishakhapatnam', 'Guntur', 'Hyderabad', 'Khammam',
                           'Bomdilla', 'Itanagar', 'Tawang', 'Namsai',
                           'Guwahati', 'Silchar', 'Dispur', 'Dibrugarh',
                           'Muzaffarpur', 'Darbhanga', 'Aurangabad', 'Patna',
                           'Raipur', 'Durg', 'Bastar', 'Dantewara',
                           'Panaji', 'Cupa', 'Saturli', 'Chaudi',
                           'Rae Bareilly', 'Gandhinagar', 'Surat', 'Ahmedabad',
                           'gurgaon', 'Kurukshetra', 'Bhiwani', 'Chandigarh',
                           'Kullu', 'Shimla', 'Mandi', 'Bilaspur',
                           'Srinagar', 'Anantnag', 'Udhampur', 'Rajouri',
                           'Jamshedpur', 'Ranchi', 'Dhanbad', 'Hazaribag',
                           'Chikkamagaluru', 'Mysore', 'Chitradurga', 'Bengaluru',
                           'Palakkad', 'Thrissur', 'Thiruvananthapuram', 'Kozhikode',
                           'Jabalpur', 'Bhopal', 'Rajgarh', 'Udaipura',
                           'Honolulu', 'Pune', 'Nagpur', 'Mumbai',
                           'Churachandpur', 'Imphal', 'Bishnupur', 'Thoubal',
                           'Shillong', 'Nongpoh', 'Jowai', 'Baghmara',
                           'Champhai', 'Aizawl', 'Phaileng', 'Mamit',
                           'Dimapur', 'Wokha', 'Kohima', 'Phek',
                           'Bhubaneswar', 'Cuttack', 'Brahmapur', 'Sambalpur',
                           'Chandigarh', 'Ludhiana', 'Amritsar', 'Jalandhar',
                           'Ajmer', 'Jaisalmer', 'Bikaner', 'Jaipur',
                           'Namchi', 'Gangtok', 'Mangan', 'Gezing',
                           'Chennai', 'Kanchipuram', 'Tiruchirapalli', 'Madurai',
                           'Adilabad', 'Nalgonda', 'Warangal', 'Hyderabad',
                           'Kailsahar', 'Dharmanagar', 'Agartala', 'Udaipur',
                           'Lucknow', 'Noida', 'Ghaziabad', 'Mathura',
                           'Hardwar', 'Dehradun', 'Nainital', 'Almora',
                           'Alipore', 'Medinipur', 'Krishnanagar', 'Kolkata']
  };

  /*
   * Repopulate the answerOptions
   * Reset score
   */
  function renewQuiz(ev) {
    // reset score to zero (0)
    quiz.score = 0;

    var questions = $('.questions').find('.question');

    // removes all questions exept the template
    questions.not('[data-question-template]').remove();

    // re-create quiz interface
    quizInterfaceCreator();

    // hide results section
    var results = $('.results');
    results.hide();
  }

  /*
   * Generate question and answer sets.
   */
  function questionAnswerCreator() {
    quiz.add('What is the capital of Andhra Pradesh?', 'Hyderabad');
    quiz.add('What is the capital of Arunachal Pradesh?', 'Itanagar');
    quiz.add('What is the capital of Assam?', 'Dispur');
    quiz.add('What is the capital of Bihar?', 'Patna');
    quiz.add('What is the capital of Chhattisgarh?', 'Raipur');
    quiz.add('What is the capital of Goa?', 'Panaji');
    quiz.add('What is the capital of Gujarat?', 'Gandhinagar');
    quiz.add('What is the capital of Haryana?', 'Chandigarh');
    quiz.add('What is the capital of Himachal Pradesh?', 'Shimla');
    quiz.add('What is the capital of Jammu and Kashmir?', 'Srinagar');
    quiz.add('What is the capital of Jhakhand?', 'Ranchi');
    quiz.add('What is the capital of Karnataka?', 'Bengaluru');
    quiz.add('What is the capital of Kerala?', 'Thiruvananthapuram');
    quiz.add('What is the capital of Madhya Pradesh?', 'Bhopal');
    quiz.add('What is the capital of Maharashtra?', 'Mumbai');
    quiz.add('What is the capital of Manipur?', 'Imphal');
    quiz.add('What is the capital of Meghalaya?', 'Shillong');
    quiz.add('What is the capital of Mizoram?', 'Aizawl');
    quiz.add('What is the capital of Nagaland?', 'Kohima');
    quiz.add('What is the capital of Odisha?', 'Bhubaneswar');
    quiz.add('What is the capital of Punjab?', 'Chandigarh');
    quiz.add('What is the capital of Rajasthan?', 'Jaipur');
    quiz.add('What is the capital of Sikkim?', 'Gangtok');
    quiz.add('What is the capital of Tamil Nadu?', 'Chennai');
    quiz.add('What is the capital of Telangana?', 'Hyderabad');
    quiz.add('What is the capital of Tripura?', 'Agartala');
    quiz.add('What is the capital of Uttar Pradesh?', 'Lucknow');
    quiz.add('What is the capital of Uttarakhand?', 'Dehradun');
    quiz.add('What is the capital of West Bengal?', 'Kolkata');
  }

  /*
   * Generate quiz interface.
   */
  function quizInterfaceCreator() {
    // shuffle questions
    shuffle(quiz.questionAnswerList);

    var questions = $('.questions'); // questions container
    /* question template */
    var qTemplate = questions.find('.question[data-question-template]');

    quiz.questionAnswerList.forEach(function (qa, qaIndex) {
      var question = qTemplate.clone(true);
      question.removeAttr('data-question-template'); // remove template attr
      question.attr('data-question-id', qaIndex); // add question indexes

      question.find('.questionText').html(qa.question); // add question

      var answers = question.find('.answers'); // answers container
      /* answer template */
      var aTemplate = question.find('.answer[data-answer-template]');

      var answerList = [qa.answer]; // add real answer
      [].push.apply(answerList, qa.answerOptions); // add all optional answers

      shuffle(answerList);

      answerList.forEach(function (ans) {
        var answer = aTemplate.clone(true);
        answer.removeAttr('data-answer-template'); // remove template attr

        /* insert answer value in input */
        var input = answer.find('input');
        input.attr('name', 'qa' + qaIndex).attr('value', ans);

        /* insert answer text */
        answer.find('.answerText').html(ans);

        /* add answer to the list of answers */
        answers.append(answer);
      });

      /* append question to the bottom of questions */
      questions.append(question);
    });

  }

  /* shuffle list
   * @param suffleArr array list to shuffle
   */
  function shuffle(shuffleArr) {
    for (var start = 0, len = shuffleArr.length; start < len; start++) {
      var rand = Math.floor(Math.random() * len);
      var question = shuffleArr.splice(rand, 1)[0];
      shuffleArr.unshift(question);
    }
  }

  /* Check answers to the question */
  function checkAnswers(ev) {
    ev.preventDefault();
    // reset score to zero (0)
    quiz.score = 0;

    /* find all checked inputs */
    var checked = $('.questions').find('input:checked');

    /* if none checked, do nothing */
    if (!checked.length) {
      return;
    }

    checked.each(function (i, ch) {
      /* get question id of checked answer */
      var questionId = Number($(ch).attr('name').replace(/qa(\d+)/, '$1')),
        answer = $(ch).attr('value'), // get the checked answer
        questionBox = $('.question[data-question-id=' + questionId + ']');

      /* check if the answer with the question id mathces the checked answer */
      if (quiz.questionAnswerList[questionId].answer === answer) {
        questionBox.removeClass('wrong');
        questionBox.addClass('correct');

        // increment the score
        quiz.score++;
      } else {
        questionBox.removeClass('correct');
        questionBox.addClass('wrong');
      }
    });

    var results = $('.results');
    results.find('.score').html(quiz.score);
    results.find('.total').html(quiz.questionAnswerList.length);
    results.show();
  }

})(this);
<|endoftext|>


<commit_before>import AbstractNode from "./abstract-node"
import Context from "../context"
import ContextTypes from "../context-types"
import Doc from "./doc"
import * as ParserStateOption from "../parser-state-option"
import * as PHPType from "../php-type"
import * as PHPError from "../php-error"
import * as ShadowTree from "../shadowtree"

/**
 * @typedef ParserPosition
 * @property {number} line
 * @property {number} column
 * @property {number} offset
 */
/**
 * @typedef ParserLocation
 * @property {?string} source
 * @property {ParserPosition} start
 * @property {ParserPosition} end
 */

/** @type {boolean} True if you want lots of debugging messages */
const DEBUG = false

/**
 * @typedef ParserNode
 * @property {function} constructor
 * @property {string} kind
 * @property {?ParserLocation} loc
 */

/**
 * @type {Function[]} The errors to ignore
 */
let ignoreErrors = []

/**
 * @type {string[]}
 */
let silenceVendor = []

export default class _Node extends AbstractNode {
    /**
     * @type {{[x: string]: (boolean|{[y: string]: boolean})}} The error classes to ignore
     */
    static get ignoreErrorMap() {
        if(!this._ignoreErrorMap) {
            let out = {}
            for(let k in PHPError) {
                if(PHPError[k] instanceof Function) {
                    Object.defineProperty(out, k, {
                        enumerable: true,
                        get: () => ignoreErrors.some(e => e === PHPError[k]),
                        set: v => {
                            ignoreErrors = ignoreErrors.filter(e => e !== PHPError[k])
                            if(v) {
                                ignoreErrors.push(PHPError[k])
                            }
                        }
                    })
                } else {
                    let out_k = {}
                    Object.defineProperty(out, k, {
                        enumerable: true,
                        get: () => out_k
                    })
                    for(let m in PHPError[k]) {
                        Object.defineProperty(out_k, m, {
                            enumerable: true,
                            get: () => ignoreErrors.some(e => e === PHPError[k][m]),
                            set: v => {
                                ignoreErrors = ignoreErrors.filter(e => e !== PHPError[k][m])
                                if(v) {
                                    ignoreErrors.push(PHPError[k][m])
                                }
                            }
                        })
                    }
                }
            }
            Object.freeze(out)
            this._ignoreErrorMap = out
        }
        return this._ignoreErrorMap
    }

    static get silenceVendor() {
        return silenceVendor
    }
    static set silenceVendor(v) {
        silenceVendor = v
    }
    /**
     * Returns the shadow tree counterpart of the given node.
     * @param {ParserNode} node
     * @returns {_Node}
     */
    static typed(node) {
        var c = ShadowTree[node.constructor.name] ||
            ShadowTree[node.constructor.name.replace(/^_/, "")]
        if(!c) {
            throw new Error(`No handler for ${node.constructor.name}`);
        }
        return new c(node);
    }
    /**
     * Builds the shadow node
     * @param {ParserNode} node
     */
    constructor(node) {
        super(node)
    }
        /**
     * Returns the types for the local name, or throws
     * @param {Context} context
     * @param {string} name
     * @returns {?PHPType.Union}
     */
    assertHasName(context, name) {
        var types = context.findName(name)
        if(!types) {
            let loc = this.loc
            if(!loc) {
                loc = Object.keys(this.node).map(
                    k => this.node[k] && this.node[k].loc
                ).find(l => l)
            }
            this.throw(new PHPError.UndefinedVariable(
                `Name ${name} is not defined in this namespace, contents are: ${context.definedVariables.join(", ")}`
            ), context)
        }
        return types
    }
    /**
     * Returns a shadow tree node wrapping the given node (caches)
     * @param {string} name
     * @returns {?_Node}
     */
    cacheNode(name) {
        return this.cacheProperty(
            name,
            subnode => subnode ?
                _Node.typed(subnode) :
                subnode
        );
    }
    /**
     * Returns a nominal array of shadow tree nodes wrapping the given nodes
     * (caches)
     * @param {string} name
     * @returns {?_Node[]}
     */
    cacheNodeArray(name) {
        return this.cacheProperty(
            name,
            subnodes => subnodes ? subnodes.map(
                subnode => _Node.typed(subnode)
            ) : subnodes
        );
    }
    /**
     * Like cacheNode, but includes cases where random other objects are present.
     * @param {string} name
     * @returns {_Node|*}
     */
    cacheOptionalNode(name) {
        if(this.node[name] && this.node[name].kind) {
            return this.cacheNode(name)
        } else {
            return this.node[name]
        }
    }
    /**
     * Checks that syntax seems ok
     * @param {Context} context
     * @param {Set<ParserStateOption.Base>} [parser_state]
     * @param {?Doc} [doc]
     * @returns {?ContextTypes} The set of types applicable to this value
     */
    check(context, parser_state = new Set(), doc = null) {
        if(DEBUG) {
            if(this.loc) {
                console.info(`Checking ${context.fileContext.filename}:${this.loc.start.line}:${this.loc.start.column}:${this.kind}`)
            } else {
                console.info(`Checking ${context.fileContext.filename}:?:?:${this.kind}`)
            }
        }
        return new ContextTypes(PHPType.Union.empty)
    }
    /**
     * Converts PHPError.Error into PHPStrictError, otherwise just rethrows.
     * @param {Error} e
     * @param {Context} context
     * @throws
     */
    handleException(e, context) {
        if(e instanceof PHPError.Error) {
            // console.log(this.node)
            this.throw(e, context)
        } else {
            throw e
        }
    }
    /**
     *
     * @param {PHPType.Union} u
     * @param {Context} context
     * @param {Doc} doc
     */
    resolveAllDocNames(u, context, doc) {
        let types = u.types
        for(let i = 0; i < types.length; i++) {
            let m = types[i]
            if(m instanceof PHPType.AssociativeArray) {
                types = types.concat(m.memberType.types)
            } else if(m instanceof PHPType.IndexedArray) {
                types = types.concat(m.memberType.types)
            } else if(m instanceof PHPType.Simple) {
                m.typeName = this.resolveDocName(m.typeName, context, doc)
            } else if(m instanceof PHPType.Function) {
                m.argTypes.forEach(atype => types = types.concat(atype.types))
                types = types.concat(m.returnType.types)
            } else {
                throw new Error(m.toString())
            }
        }
    }
    /**
     * @param {string} t
     * @param {Context} context
     * @param {Doc} doc
     * @returns {string}
     */
    resolveDocName(t, context, doc) {
        try {
            if(t.match(/^[A-Z0-9]/)) {
                return (
                    context.fileContext.resolveAliasName(t) ||
                    "\\" + t
                )
            } else if(PHPType.Core.types.hasOwnProperty(t)) {
                return context.resolveName(PHPType.Core.types[t].toString())
            } else {
                return context.resolveName(t, "uqn")
            }
        } catch(e) {
            if(e instanceof PHPType.WrongType) {
                this.throw(new PHPError.BadCoreType(e.message), context, doc.loc)
                return context.resolveName(e.realName)
            } else {
                throw e
            }
        }
    }
    /**
     * Wraps throwing. This may conditionally not throw.
     * @param {PHPError.Error} e
     * @param {Context} context
     * @param {?ParserLocation} [effective_location]
     * @throws {PHPError.Error}
     */
    throw(e, context, effective_location = null) {
        if(
            context.fileContext &&
            silenceVendor.some(
                sv => context.fileContext.filename.startsWith(
                    context.globalContext.workingDirectory + "/" + sv + "/"
                )
            )
        ) {
            // Skip
        } else if(ignoreErrors.every(o => !(e instanceof o))) {
            throw e.withContext(context, this, effective_location)
        }
    }
}

export {Doc, Context, ContextTypes, ParserStateOption}<commit_msg>Do nothing for mixed resolution<commit_after>import AbstractNode from "./abstract-node"
import Context from "../context"
import ContextTypes from "../context-types"
import Doc from "./doc"
import * as ParserStateOption from "../parser-state-option"
import * as PHPType from "../php-type"
import * as PHPError from "../php-error"
import * as ShadowTree from "../shadowtree"

/**
 * @typedef ParserPosition
 * @property {number} line
 * @property {number} column
 * @property {number} offset
 */
/**
 * @typedef ParserLocation
 * @property {?string} source
 * @property {ParserPosition} start
 * @property {ParserPosition} end
 */

/** @type {boolean} True if you want lots of debugging messages */
const DEBUG = false

/**
 * @typedef ParserNode
 * @property {function} constructor
 * @property {string} kind
 * @property {?ParserLocation} loc
 */

/**
 * @type {Function[]} The errors to ignore
 */
let ignoreErrors = []

/**
 * @type {string[]}
 */
let silenceVendor = []

export default class _Node extends AbstractNode {
    /**
     * @type {{[x: string]: (boolean|{[y: string]: boolean})}} The error classes to ignore
     */
    static get ignoreErrorMap() {
        if(!this._ignoreErrorMap) {
            let out = {}
            for(let k in PHPError) {
                if(PHPError[k] instanceof Function) {
                    Object.defineProperty(out, k, {
                        enumerable: true,
                        get: () => ignoreErrors.some(e => e === PHPError[k]),
                        set: v => {
                            ignoreErrors = ignoreErrors.filter(e => e !== PHPError[k])
                            if(v) {
                                ignoreErrors.push(PHPError[k])
                            }
                        }
                    })
                } else {
                    let out_k = {}
                    Object.defineProperty(out, k, {
                        enumerable: true,
                        get: () => out_k
                    })
                    for(let m in PHPError[k]) {
                        Object.defineProperty(out_k, m, {
                            enumerable: true,
                            get: () => ignoreErrors.some(e => e === PHPError[k][m]),
                            set: v => {
                                ignoreErrors = ignoreErrors.filter(e => e !== PHPError[k][m])
                                if(v) {
                                    ignoreErrors.push(PHPError[k][m])
                                }
                            }
                        })
                    }
                }
            }
            Object.freeze(out)
            this._ignoreErrorMap = out
        }
        return this._ignoreErrorMap
    }

    static get silenceVendor() {
        return silenceVendor
    }
    static set silenceVendor(v) {
        silenceVendor = v
    }
    /**
     * Returns the shadow tree counterpart of the given node.
     * @param {ParserNode} node
     * @returns {_Node}
     */
    static typed(node) {
        var c = ShadowTree[node.constructor.name] ||
            ShadowTree[node.constructor.name.replace(/^_/, "")]
        if(!c) {
            throw new Error(`No handler for ${node.constructor.name}`);
        }
        return new c(node);
    }
    /**
     * Builds the shadow node
     * @param {ParserNode} node
     */
    constructor(node) {
        super(node)
    }
        /**
     * Returns the types for the local name, or throws
     * @param {Context} context
     * @param {string} name
     * @returns {?PHPType.Union}
     */
    assertHasName(context, name) {
        var types = context.findName(name)
        if(!types) {
            let loc = this.loc
            if(!loc) {
                loc = Object.keys(this.node).map(
                    k => this.node[k] && this.node[k].loc
                ).find(l => l)
            }
            this.throw(new PHPError.UndefinedVariable(
                `Name ${name} is not defined in this namespace, contents are: ${context.definedVariables.join(", ")}`
            ), context)
        }
        return types
    }
    /**
     * Returns a shadow tree node wrapping the given node (caches)
     * @param {string} name
     * @returns {?_Node}
     */
    cacheNode(name) {
        return this.cacheProperty(
            name,
            subnode => subnode ?
                _Node.typed(subnode) :
                subnode
        );
    }
    /**
     * Returns a nominal array of shadow tree nodes wrapping the given nodes
     * (caches)
     * @param {string} name
     * @returns {?_Node[]}
     */
    cacheNodeArray(name) {
        return this.cacheProperty(
            name,
            subnodes => subnodes ? subnodes.map(
                subnode => _Node.typed(subnode)
            ) : subnodes
        );
    }
    /**
     * Like cacheNode, but includes cases where random other objects are present.
     * @param {string} name
     * @returns {_Node|*}
     */
    cacheOptionalNode(name) {
        if(this.node[name] && this.node[name].kind) {
            return this.cacheNode(name)
        } else {
            return this.node[name]
        }
    }
    /**
     * Checks that syntax seems ok
     * @param {Context} context
     * @param {Set<ParserStateOption.Base>} [parser_state]
     * @param {?Doc} [doc]
     * @returns {?ContextTypes} The set of types applicable to this value
     */
    check(context, parser_state = new Set(), doc = null) {
        if(DEBUG) {
            if(this.loc) {
                console.info(`Checking ${context.fileContext.filename}:${this.loc.start.line}:${this.loc.start.column}:${this.kind}`)
            } else {
                console.info(`Checking ${context.fileContext.filename}:?:?:${this.kind}`)
            }
        }
        return new ContextTypes(PHPType.Union.empty)
    }
    /**
     * Converts PHPError.Error into PHPStrictError, otherwise just rethrows.
     * @param {Error} e
     * @param {Context} context
     * @throws
     */
    handleException(e, context) {
        if(e instanceof PHPError.Error) {
            // console.log(this.node)
            this.throw(e, context)
        } else {
            throw e
        }
    }
    /**
     *
     * @param {PHPType.Union} u
     * @param {Context} context
     * @param {Doc} doc
     */
    resolveAllDocNames(u, context, doc) {
        let types = u.types
        for(let i = 0; i < types.length; i++) {
            let m = types[i]
            if(m instanceof PHPType.AssociativeArray) {
                types = types.concat(m.memberType.types)
            } else if(m instanceof PHPType.IndexedArray) {
                types = types.concat(m.memberType.types)
            } else if(m instanceof PHPType.Simple) {
                m.typeName = this.resolveDocName(m.typeName, context, doc)
            } else if(m instanceof PHPType.Function) {
                m.argTypes.forEach(atype => types = types.concat(atype.types))
                types = types.concat(m.returnType.types)
            } else if(m instanceof PHPType.Mixed) {
                // Do nothing
            } else {
                throw new Error(m.toString())
            }
        }
    }
    /**
     * @param {string} t
     * @param {Context} context
     * @param {Doc} doc
     * @returns {string}
     */
    resolveDocName(t, context, doc) {
        try {
            if(t.match(/^[A-Z0-9]/)) {
                return (
                    context.fileContext.resolveAliasName(t) ||
                    "\\" + t
                )
            } else if(PHPType.Core.types.hasOwnProperty(t)) {
                return context.resolveName(PHPType.Core.types[t].toString())
            } else {
                return context.resolveName(t, "uqn")
            }
        } catch(e) {
            if(e instanceof PHPType.WrongType) {
                this.throw(new PHPError.BadCoreType(e.message), context, doc.loc)
                return context.resolveName(e.realName)
            } else {
                throw e
            }
        }
    }
    /**
     * Wraps throwing. This may conditionally not throw.
     * @param {PHPError.Error} e
     * @param {Context} context
     * @param {?ParserLocation} [effective_location]
     * @throws {PHPError.Error}
     */
    throw(e, context, effective_location = null) {
        if(
            context.fileContext &&
            silenceVendor.some(
                sv => context.fileContext.filename.startsWith(
                    context.globalContext.workingDirectory + "/" + sv + "/"
                )
            )
        ) {
            // Skip
        } else if(ignoreErrors.every(o => !(e instanceof o))) {
            throw e.withContext(context, this, effective_location)
        }
    }
}

export {Doc, Context, ContextTypes, ParserStateOption}<|endoftext|>


<commit_before>var async     = require('async');
var ripple    = require('ripple-lib');
var serverLib = require('../lib/server-lib');

const TrustSetFlags = {
  SetAuth:        { name: 'authorized', value: 0x00010000 },
  NoRipple:       { name: 'prevent_rippling', value: 0x00020000 },
  ClearNoRipple:  { name: 'allow_rippling', value: 0x00040000 }
}

exports.get = getTrustLines;

function getTrustLines($, req, res, next) {
  var remote = $.remote;

  var opts = req.params;

  Object.keys(req.query).forEach(function(param) {
    opts[param] = req.query[param];
  });

  opts.limit = opts.limit || req.body.limit;

  var currencyRE = new RegExp(opts.currency ? ('^' + opts.currency.toUpperCase() + '$') : /./);

  function validateOptions(callback) {
    if (!ripple.UInt160.is_valid(opts.account)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid Ripple address: account' });
    }

    if (opts.counterparty && !ripple.UInt160.is_valid(opts.counterparty)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid Ripple address: counterparty' });
    }

    if (opts.currency && !/^[A-Z0-9]{3}$/.test(opts.currency)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid currency: currency' });
    }

    callback();
  };

 function ensureConnected(callback) {
    serverLib.ensureConnected(remote, callback);
  };

  function getAccountLines(connected, callback) {
    if (!connected) {
      return res.json(500, { success: false, message: 'Remote is not connected' });
    }

    var request = remote.requestAccountLines(opts.account);

    if (opts.counterparty) {
      request.message.peer = opts.counterparty;
    }

    request.once('error', callback);

    request.once('success', function(res) {
      var lines = [ ];

      res.lines.forEach(function(line) {
        if (!currencyRE.test(line.currency)) return;
        lines.push({
          account: opts.account,
          counterparty: line.account,
          currency: line.currency,
          limit: line.limit,
          reciprocated__limit: line.limit_peer,
          account_allows_rippling: line.no_ripple ? !line.no_ripple : true,
          counterparty_allows_rippling: line.no_ripple_peer ? !line.no_ripple_peer : true,
        });
      });

      callback(null, lines);
    });

    request.request();
  };

  var steps = [
    validateOptions,
    ensureConnected,
    getAccountLines
  ]

  async.waterfall(steps, function(err, lines) {
    if (err) {
      next(err);
    } else {
      res.json(200, { success: true, trustlines: lines });
    }
  });
};

exports.add = addTrustLine;

function addTrustLine($, req, res, next) {
  var self = this;
  var remote = $.remote;
  var opts = req.params;

  Object.keys(req.body).forEach(function(param) {
    opts[param] = req.body[param];
  });

  function validateOptions(callback) {
    if (!ripple.UInt160.is_valid(opts.account)) {
      return res.json(400, { success: false, message: 'Parameter is not a Ripple address: account' });
    }

    if (!opts.secret) {
      return res.json(400, { success: false, message: 'Parameter missing: secret' });
    }

    if (typeof opts.trustline !== 'object') {
      return res.json(400, { success: false, message: 'Parameter missing: trustline' });
    }

    if (typeof opts.trustline.limit === 'string') {
      var spl = opts.trustline.limit.split('/');
      opts.trustline.limit = {
        value:         spl[0],
        currency:      spl[1] || opts.trustline.currency,
        counterparty:  spl[2] || opts.trustline.counterparty
      }
    }

    if (typeof opts.trustline.limit !== 'object') {
      return res.json(400, { success: false, message: 'Parameter missing: trustline.limit' });
    }

    if (isNaN(opts.trustline.limit.value)) {
      return res.json(400, { success: false, message: 'Parameter is not a number: trustline.limit.amount' });
    }

    if (!/^[A-Z0-9]{3}$/.test(opts.trustline.limit.currency)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid currency: trustline.limit.currency' });
    }

    if (!ripple.UInt160.is_valid(opts.trustline.limit.counterparty)) {
      return res.json(400, { success: false, message: 'Parameter is not a Ripple address: trustline.limit.counterparty' });
    }

    if (!/^(undefined|number)$/.test(typeof opts.trustline.quality_in)) {
      return res.json(400, { success: false, message: 'Parameter must be a number: trustline.quality_in' });
    }

    if (!/^(undefined|number)$/.test(typeof opts.trustline.quality_out)) {
      return res.json(400, { success: false, message: 'Parameter must be a number: trustline.quality_out' });
    }

    if (!/^(undefined|boolean)$/.test(typeof opts.trustline.allow_rippling)) {
      return res.json(400, { success: false, message: 'Parameter must be a boolean: trustline.allow_rippling' });
    }

    callback();
  };

  function ensureConnected(callback) {
    serverLib.ensureConnected(remote, function(err, connected) {
      if (err || !connected) {
        res.json(500, { success: false, message: 'Remote is not connected' });
      } else {
        callback();
      }
    });
  };

  function addLine(callback) {
    var limit = [
      opts.trustline.limit.value,
      opts.trustline.limit.currency,
      opts.trustline.limit.counterparty
    ].join('/');

    var transaction = remote.transaction();
    var complete = false;

    function transactionSent(m) {
      complete = true;

      var summary = transaction.summary();
      var line = summary.tx_json.LimitAmount;

      line.account = opts.account;
      line.allows_rippling = true;
      line.counterparty = line.issuer;

      delete line.issuer;

      var result = {
        success: true,
        trustline: line
      }

      if (m.tx_json.Flags & TrustSetFlags.NoRipple.value) {
        result.trustline.allows_rippling = false;
      }

      if (m.tx_json.Flags & TrustSetFlags.SetAuth) {
        result.trustline.authorized = true;
      }

      result.ledger = String(summary.submitIndex);
      result.hash = m.tx_json.hash;

      callback(null, result);
    };

    transaction.once('error', callback);

    transaction.once('proposed', transactionSent);

    transaction.once('success', function(m) {
      if (!complete) {
        transaction.removeAllListeners('proposed');
        transactionSent(m);
      }
    });

    try {
      transaction.trustSet(opts.account, limit);
      transaction.secret(opts.secret);

      if (typeof opts.quality_in === 'number') {
        transaction.tx_json.QualityIn = opts.quality_in;
      }

      if (typeof opts.quality_out === 'number') {
        transaction.tx_json.QualityOut = opts.quality_out;
      }

      if (typeof opts.allow_rippling === 'boolean') {
        if (opts.allow_rippling) {
          transaction.setFlags('ClearNoRipple');
        } else {
          transaction.setFlags('NoRipple');
        }
      }
    } catch (e) {
      return res.json(500, { success: false, message: e.message });
    }

    transaction.submit();
  };

  var steps = [
    validateOptions,
    ensureConnected,
    addLine
  ]

  async.waterfall(steps, function(err, line) {
    if (err) {
      next(err);
    } else {
      res.json(201, line);
    }
  });
};
<commit_msg>Make trustlines API more consistent<commit_after>var async     = require('async');
var ripple    = require('ripple-lib');
var serverLib = require('../lib/server-lib');

const TrustSetFlags = {
  SetAuth:        { name: 'authorized', value: 0x00010000 },
  NoRipple:       { name: 'prevent_rippling', value: 0x00020000 },
  ClearNoRipple:  { name: 'allow_rippling', value: 0x00040000 }
}

exports.get = getTrustLines;

function getTrustLines($, req, res, next) {
  var remote = $.remote;

  var opts = req.params;

  Object.keys(req.query).forEach(function(param) {
    opts[param] = req.query[param];
  });

  opts.limit = opts.limit || req.body.limit;

  var currencyRE = new RegExp(opts.currency ? ('^' + opts.currency.toUpperCase() + '$') : /./);

  function validateOptions(callback) {
    if (!ripple.UInt160.is_valid(opts.account)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid Ripple address: account' });
    }

    if (opts.counterparty && !ripple.UInt160.is_valid(opts.counterparty)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid Ripple address: counterparty' });
    }

    if (opts.currency && !/^[A-Z0-9]{3}$/.test(opts.currency)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid currency: currency' });
    }

    callback();
  };

 function ensureConnected(callback) {
    serverLib.ensureConnected(remote, callback);
  };

  function getAccountLines(connected, callback) {
    if (!connected) {
      return res.json(500, { success: false, message: 'Remote is not connected' });
    }

    var request = remote.requestAccountLines(opts.account);

    if (opts.counterparty) {
      request.message.peer = opts.counterparty;
    }

    request.once('error', callback);

    request.once('success', function(res) {
      var lines = [ ];

      res.lines.forEach(function(line) {
        if (!currencyRE.test(line.currency)) return;
        lines.push({
          account: opts.account,
          counterparty: line.account,
          currency: line.currency,
          limit: line.limit,
          reciprocated__limit: line.limit_peer,
          account_allows_rippling: line.no_ripple ? !line.no_ripple : true,
          counterparty_allows_rippling: line.no_ripple_peer ? !line.no_ripple_peer : true,
        });
      });

      callback(null, lines);
    });

    request.request();
  };

  var steps = [
    validateOptions,
    ensureConnected,
    getAccountLines
  ]

  async.waterfall(steps, function(err, lines) {
    if (err) {
      next(err);
    } else {
      res.json(200, { success: true, trustlines: lines });
    }
  });
};

exports.add = addTrustLine;

function addTrustLine($, req, res, next) {
  var self = this;
  var remote = $.remote;
  var opts = req.params;

  Object.keys(req.body).forEach(function(param) {
    opts[param] = req.body[param];
  });

  function validateOptions(callback) {
    if (!ripple.UInt160.is_valid(opts.account)) {
      return res.json(400, { success: false, message: 'Parameter is not a Ripple address: account' });
    }

    if (!opts.secret) {
      return res.json(400, { success: false, message: 'Parameter missing: secret' });
    }

    if (typeof opts.trustline !== 'object') {
      return res.json(400, { success: false, message: 'Parameter missing: trustline' });
    }

    if (isNaN(opts.trustline.limit = String(opts.trustline.limit))) {
      return res.json(400, { success: false, message: 'Parameter is not a number: trustline.limit.amount' });
    }

    if (!/^[A-Z0-9]{3}$/.test(opts.trustline.currency)) {
      return res.json(400, { success: false, message: 'Parameter is not a valid currency: trustline.limit.currency' });
    }

    if (!ripple.UInt160.is_valid(opts.trustline.counterparty)) {
      return res.json(400, { success: false, message: 'Parameter is not a Ripple address: trustline.limit.counterparty' });
    }

    if (!/^(undefined|number)$/.test(typeof opts.trustline.quality_in)) {
      return res.json(400, { success: false, message: 'Parameter must be a number: trustline.quality_in' });
    }

    if (!/^(undefined|number)$/.test(typeof opts.trustline.quality_out)) {
      return res.json(400, { success: false, message: 'Parameter must be a number: trustline.quality_out' });
    }

    if (!/^(undefined|boolean)$/.test(typeof opts.trustline.allow_rippling)) {
      return res.json(400, { success: false, message: 'Parameter must be a boolean: trustline.allow_rippling' });
    }

    callback();
  };

  function ensureConnected(callback) {
    serverLib.ensureConnected(remote, function(err, connected) {
      if (err || !connected) {
        res.json(500, { success: false, message: 'Remote is not connected' });
      } else {
        callback();
      }
    });
  };

  function addLine(callback) {
    var limit = [
      opts.trustline.limit,
      opts.trustline.currency,
      opts.trustline.counterparty
    ].join('/');

    var transaction = remote.transaction();
    var complete = false;

    function transactionSent(m) {
      complete = true;

      var summary = transaction.summary();
      var line = summary.tx_json.LimitAmount;

      var result = {
        success: true,
        trustline: {
          account: opts.account,
          limit: line.value,
          currency: line.currency,
          counterparty: line.issuer,
          account_allows_rippling: true
        }
      }

      if (m.tx_json.Flags & TrustSetFlags.NoRipple.value) {
        result.trustline.account_allows_rippling = false;
      }

      if (m.tx_json.Flags & TrustSetFlags.SetAuth) {
        result.trustline.authorized = true;
      }

      result.ledger = String(summary.submitIndex);
      result.hash = m.tx_json.hash;

      callback(null, result);
    };

    transaction.once('error', callback);

    transaction.once('proposed', transactionSent);

    transaction.once('success', function(m) {
      if (!complete) {
        transaction.removeAllListeners('proposed');
        transactionSent(m);
      }
    });

    try {
      transaction.trustSet(opts.account, limit);
      transaction.secret(opts.secret);

      if (typeof opts.trustline.quality_in === 'number') {
        transaction.tx_json.QualityIn = opts.trustline.quality_in;
      }

      if (typeof opts.trustline.quality_out === 'number') {
        transaction.tx_json.QualityOut = opts.trustline.quality_out;
      }

      if (typeof opts.trustline.allow_rippling === 'boolean') {
        if (opts.trustline.allow_rippling) {
          transaction.setFlags('ClearNoRipple');
        } else {
          transaction.setFlags('NoRipple');
        }
      }
    } catch (e) {
      return res.json(500, { success: false, message: e.message });
    }

    transaction.submit();
  };

  var steps = [
    validateOptions,
    ensureConnected,
    addLine
  ]

  async.waterfall(steps, function(err, line) {
    if (err) {
      next(err);
    } else {
      res.json(201, line);
    }
  });
};
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        document.getElementById("paintbtn").onclick = paint;

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * ((pw/2) - 2 + 1) + 2) );
            var randh = Math.floor((Math.random() * ((ph/2) - 2 + 1) + 2) );
            alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;

           //alert(pathWidth + ", " + pathHeight);

            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){
                    var randRoom = Math.floor((Math.random() * 19));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.lineWidth = 3;
                        c.strokeRect(i*30, j*30, roomDim[0]*30, roomDim[1]*30);
                        c.stroke();
                    }

                    //c.lineWidth = 1;
                    //c.rect(i*30, j*30, 30, 30);
                    //c.stroke();
                }
            }
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        document.getElementById("paintbtn").onclick = paint;

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * ((pw/2) - 2 + 1) + 2) );
            var randh = Math.floor((Math.random() * ((ph/2) - 2 + 1) + 2) );
            alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;

           //alert(pathWidth + ", " + pathHeight);

            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){
                    var randRoom = Math.floor((Math.random() * 49));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.lineWidth = 3;
                        c.strokeRect(i*30, j*30, roomDim[0]*30, roomDim[1]*30);
                        c.stroke();
                    }

                    //c.lineWidth = 1;
                    //c.rect(i*30, j*30, 30, 30);
                    //c.stroke();
                }
            }
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>$(document).ready(function() {
    if (navigator.appName == 'Microsoft Internet Explorer' || window.navigator.userAgent.indexOf("Edge") > -1 || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {
        swal('Unsupported', 'Please note that IE and Edge are not supported', 'warning');
    }
    $.get("domains.json", function(data) {
        $(".scan").removeClass("disabled");
        $(".infotext").html($(".infotext").html().replace("list of domains", "list of " + data.domains.length + " domains"));
        $(".scan").click(function() {
            var domains = data.domains;
            var faileddomains = {};
            var doublecheck = {};
            var cnt = 0;
            $(".count").html("0 / " + domains.length);
            $(".scanbutton").hide();
            $(".loadingbar").show();
            $.each(domains.reverse(), function(i, data) {
                var image = new Image();
                image.setAttribute("domain", data.domain.replace("~", ""));
                image.setAttribute("title", data.title);
                image.onerror = function() {
                    if (!(data.domain in doublecheck)) {
                        doublecheck[data.domain] = 1;
                    }
                    if ((data.domain in doublecheck) && doublecheck[data.domain] < 4) {
                        doublecheck[data.domain]++;
                        setTimeout(function() {
                            image.src = this.src;
                        }, 1000);
                    } else if ((data.domain in doublecheck) && doublecheck[data.domain] > 3) {
                        cnt++;
                        $(".count").html(cnt + " / " + domains.length);
                        /* This is a server-side check to determine if a domain might be fully offline. The server just replies '1' or '0' depending if it can reach the domain. Keep in mind that CensorRadar will never rely on this backup server. It's just an extra feature for the end user. Source code: https://pastebin.com/bsGuBHxt */
                        $.get("https://luithollander.nl/censorradar.php?url=" + encodeURIComponent(image.src), function(online) {
                            faileddomains[data.title] = parseInt(online);
                        }.bind(this)).fail(function() {
                            faileddomains[data.title] = 2;
                        }.bind(this)).always(function() {
                            $(".bar").width(((cnt / domains.length) * 100) + '%');
                            $(".failedresults").fadeIn(500);
                            if (Object.keys(faileddomains).length == 1) {
                                $(".failed").html(Object.keys(faileddomains).length + ' domain could not be reached');
                            } else {
                                $(".failed").html(Object.keys(faileddomains).length + ' domains could not be reached');
                            }
                            if (cnt == domains.length) {
                                $(".loadingbar").fadeOut(500);
                            }
                            if (faileddomains[data.title] == 0) {
                                new_row = $("
" + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached on both server and client. This probably means the website is offline.','warning');\">

");
                            } else if (faileddomains[data.title] == 1 || faileddomains[data.title] == 2) {
                                new_row = $("
 " + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached','error');\">

");
                            }
                            new_row.hide();
                            $(".table tbody").prepend(new_row);
                            new_row.fadeIn(200);
                        })
                    }
                };

                image.onload = function() {
                    cnt++;
                    $(".count").html(cnt + " / " + domains.length);
                    $(".bar").width(((cnt / domains.length) * 100) + '%');
                    if (cnt == domains.length && Object.keys(faileddomains).length == 0) {
                        $(".loadingbar").fadeOut(500);
                        $(".successresults").fadeIn(500);
                    } else if (cnt == domains.length) {
                        $(".loadingbar").fadeOut(500);
                    }
                };
                if (data.domain.match("^~")) {
                    image.src = 'http://' + data.domain.replace("~", "") + '/' + data.img + '?no-cache=' + (new Date).getTime();
                } else {
                    image.src = 'http://www.' + data.domain + '/' + data.img + '?no-cache=' + (new Date).getTime();
                }
            });
        });
    }).fail(function() {
        swal('Connection error', 'The domains database could not be loaded', 'error');
    })
});<commit_msg>Undefined var fix<commit_after>$(document).ready(function() {
    if (navigator.appName == 'Microsoft Internet Explorer' || window.navigator.userAgent.indexOf("Edge") > -1 || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {
        swal('Unsupported', 'Please note that IE and Edge are not supported', 'warning');
    }
    $.get("domains.json", function(data) {
        $(".scan").removeClass("disabled");
        $(".infotext").html($(".infotext").html().replace("list of domains", "list of " + data.domains.length + " domains"));
        $(".scan").click(function() {
            var domains = data.domains;
            var faileddomains = {};
            var doublecheck = {};
            var cnt = 0;
            $(".count").html("0 / " + domains.length);
            $(".scanbutton").hide();
            $(".loadingbar").show();
            $.each(domains.reverse(), function(i, data) {
                var image = new Image();
                image.setAttribute("domain", data.domain.replace("~", ""));
                image.setAttribute("title", data.title);
                image.onerror = function() {
                    if (!(data.domain in doublecheck)) {
                        doublecheck[data.domain] = 1;
                    }
                    if ((data.domain in doublecheck) && doublecheck[data.domain] < 4) {
                        doublecheck[data.domain]++;
						var src = this.src
                        setTimeout(function() {
                            image.src = src;
                        }, 1000);
                    } else if ((data.domain in doublecheck) && doublecheck[data.domain] > 3) {
                        cnt++;
                        $(".count").html(cnt + " / " + domains.length);
                        /* This is a server-side check to determine if a domain might be fully offline. The server just replies '1' or '0' depending if it can reach the domain. Keep in mind that CensorRadar will never rely on this backup server. It's just an extra feature for the end user. Source code: https://pastebin.com/bsGuBHxt */
                        $.get("https://luithollander.nl/censorradar.php?url=" + encodeURIComponent(image.src), function(online) {
                            faileddomains[data.title] = parseInt(online);
                        }.bind(this)).fail(function() {
                            faileddomains[data.title] = 2;
                        }.bind(this)).always(function() {
                            $(".bar").width(((cnt / domains.length) * 100) + '%');
                            $(".failedresults").fadeIn(500);
                            if (Object.keys(faileddomains).length == 1) {
                                $(".failed").html(Object.keys(faileddomains).length + ' domain could not be reached');
                            } else {
                                $(".failed").html(Object.keys(faileddomains).length + ' domains could not be reached');
                            }
                            if (cnt == domains.length) {
                                $(".loadingbar").fadeOut(500);
                            }
                            if (faileddomains[data.title] == 0) {
                                new_row = $("
" + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached on both server and client. This probably means the website is offline.','warning');\">

");
                            } else if (faileddomains[data.title] == 1 || faileddomains[data.title] == 2) {
                                new_row = $("
 " + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached','error');\">

");
                            }
                            new_row.hide();
                            $(".table tbody").prepend(new_row);
                            new_row.fadeIn(200);
                        })
                    }
                };

                image.onload = function() {
                    cnt++;
                    $(".count").html(cnt + " / " + domains.length);
                    $(".bar").width(((cnt / domains.length) * 100) + '%');
                    if (cnt == domains.length && Object.keys(faileddomains).length == 0) {
                        $(".loadingbar").fadeOut(500);
                        $(".successresults").fadeIn(500);
                    } else if (cnt == domains.length) {
                        $(".loadingbar").fadeOut(500);
                    }
                };
                if (data.domain.match("^~")) {
                    image.src = 'http://' + data.domain.replace("~", "") + '/' + data.img + '?no-cache=' + (new Date).getTime();
                } else {
                    image.src = 'http://www.' + data.domain + '/' + data.img + '?no-cache=' + (new Date).getTime();
                }
            });
        });
    }).fail(function() {
        swal('Connection error', 'The domains database could not be loaded', 'error');
    })
});<|endoftext|>


<commit_before>/*
 * Created by marekfort on 13/04/16.
 */

$(document).ready(function(){
    // Setting summary to be centered to the iphone mockup
    $('.section-swipe .summary').css('margin-top', ($('.section-swipe img').height() / 2 - $('.section-swipe .summary').height() / 2 ));
    $('.section-supl .summary').css('margin-top', ($('.section-supl img').height() / 2 - $('.section-supl .summary').height() / 2 ));
});

lastScroll = 0;
shouldAnimate = tre;
lastColor = "#3C9BFF";
shouldSlide = true;
$(window).on('scroll', function(){
    scrollTop = $('body').scrollTop();
    scrollingUp = scrollTop < lastScroll;
    lastScroll = scrollTop;
    heightOfTransition = $('.section-supl').height();

    /*
     suplTop = (scrollTop - $('.section-supl').offset().top) / 14;
     $('.section-supl img').css('top', (suplTop));
     swipeTop = (scrollTop - $('.section-swipe').offset().top) / 14;
     $('.section-swipe img').css('top', (swipeTop));
     */

    if  ($('.section-supl').offset().top + heightOfTransition - heightOfTransition / 3 - scrollTop < 0 && lastColor != "#FF3D97" && scrollingUp == false && shouldAnimate ) {
        lastColor = "#FF3D97";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#FF3D97"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }
    else if ($('.section-supl').offset().top + heightOfTransition + heightOfTransition / 3 - scrollTop > 0 && lastColor != "#3C9BFF" && scrollingUp && shouldAnimate) {
        lastColor = "#3C9BFF";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#3C9BFF"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }

    if (scrollTop >= $('.section-me').offset().top - $('.section-me').height() && shouldSlide) {
        $('.slide').addClass('animated fadeInUp');
        shouldSlide = false;
    }

});

$('.portfolio-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-supl').offset().top}, 600);
});

$('#about-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-me').offset().top}, 600);
});

<commit_msg>Finally<commit_after>/*
 * Created by marekfort on 13/04/16.
 */

$(document).ready(function(){
    // Setting summary to be centered to the iphone mockup
    $('.section-swipe .summary').css('margin-top', ($('.section-swipe img').height() / 2 - $('.section-swipe .summary').height() / 2 ));
    $('.section-supl .summary').css('margin-top', ($('.section-supl img').height() / 2 - $('.section-supl .summary').height() / 2 ));
});

lastScroll = 0;
shouldAnimate = true;
lastColor = "#3C9BFF";
shouldSlide = true;
$(window).on('scroll', function(){
    scrollTop = $('body').scrollTop();
    scrollingUp = scrollTop < lastScroll;
    lastScroll = scrollTop;
    heightOfTransition = $('.section-supl').height();

    /*
     suplTop = (scrollTop - $('.section-supl').offset().top) / 14;
     $('.section-supl img').css('top', (suplTop));
     swipeTop = (scrollTop - $('.section-swipe').offset().top) / 14;
     $('.section-swipe img').css('top', (swipeTop));
     */

    if  ($('.section-supl').offset().top + heightOfTransition - heightOfTransition / 3 - scrollTop < 0 && lastColor != "#FF3D97" && scrollingUp == false && shouldAnimate ) {
        lastColor = "#FF3D97";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#FF3D97"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }
    else if ($('.section-supl').offset().top + heightOfTransition + heightOfTransition / 3 - scrollTop > 0 && lastColor != "#3C9BFF" && scrollingUp && shouldAnimate) {
        lastColor = "#3C9BFF";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#3C9BFF"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }

    if (scrollTop >= $('.section-me').offset().top - $('.section-me').height() && shouldSlide) {
        $('.slide').addClass('animated fadeInUp');
        shouldSlide = false;
    }

});

$('.portfolio-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-supl').offset().top}, 600);
});

$('#about-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-me').offset().top}, 600);
});

<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 11/04/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic-site

*/

var Webtwic = Webtwic || {};

var browser = bowser;

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic-site',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser.name.toLowerCase() : b.toLowerCase();
		$( 'body' ).addClass( b + ' ' + b + parseInt( browser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,

	 $$ = Webtwic,

	 close_button = '',

	 browser_link = ' ' + 'browser.' + ' ',

	 notif_text = 'Some features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else if ( !window.Modernizr )
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection

	browser.ie = browser.msie;

	if ( browser.chrome )
		Webtwic.showBrowser();

	else if ( browser.msedge )
		Webtwic.showBrowser();

	else if ( browser.firefox )
		Webtwic.showBrowser();

	else if ( browser.msie )
		Webtwic.showBrowser();

	else if ( browser.safari )
		Webtwic.showBrowser();

	else if ( browser.opera )
		Webtwic.showBrowser();
	else /* do nothing */ ;

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/
	var M = Modernizr;

	if ( window.Modernizr )
		if ( !M.flexbox || !M.inlinesvg || !M.svg || !M.svgclippaths || !M.fontface || !M.boxshadow || !M.borderradius || !M.csstransforms )
			Webtwic.showNotif();
		else /* do nothing */ ;
	 else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).click(function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).scroll(function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.eq(1)
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.eq(1)
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeIn(400)
		.addClass( 'is_open' );
	}

	function closeUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeOut(400)
		.removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).focus(function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).blur(function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).keydown(function( e ) {
		if ( e.keyCode == 27 )
			closeUiOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Update script.js<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 11/04/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic-site

*/

var Webtwic = Webtwic || {};

var browser = bowser;

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic-site',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser.name.toLowerCase() : b.toLowerCase();
		$( 'body' ).addClass( b + ' ' + b + parseInt( browser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,

	 $$ = Webtwic,

	 close_button = '',

	 browser_link = ' ' + 'browser.' + ' ',

	 notif_text = 'Some features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else if ( !window.Modernizr )
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection

	browser.ie = function() {
		return browser.msie;
	};

	if (browser.chrome)
		Webtwic.showBrowser();

	else if (browser.msedge)
		Webtwic.showBrowser();

	else if (browser.firefox)
		Webtwic.showBrowser();

	else if (browser.msie)
		Webtwic.showBrowser();

	else if (browser.safari)
		Webtwic.showBrowser();

	else if (browser.opera)
		Webtwic.showBrowser();
	else /* do nothing */ ;

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/
	var M = Modernizr;

	if ( window.Modernizr )
		if ( !M.flexbox || !M.inlinesvg || !M.svg || !M.svgclippaths || !M.fontface || !M.boxshadow || !M.borderradius || !M.csstransforms )
			Webtwic.showNotif();
		else /* do nothing */ ;
	 else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).click(function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).scroll(function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.eq(1)
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.eq(1)
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeIn(400)
		.addClass( 'is_open' );
	}

	function closeUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeOut(400)
		.removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).focus(function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).blur(function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).keydown(function( e ) {
		if ( e.keyCode == 27 )
			closeUiOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>var game = {
    answer: 0,
    chances: 3,
}

$(document).ready(function() {
    $("input[type=button], input[type=text]").attr('disabled', true);
    $("#newGame").click(function() {
        $("input[type=text]").val("");
        $("input[type=button], input[type=text]").removeAttr('disabled');
        $(this).animate({
            "right": "0"
        }, {
            duration: 400
        });
        start();
    });
});

function start() {
    $("#newGame").text("Restart");
    $("#round").text(game.answer = 1);
    $("#error").hide('slow/400/fast', function() {

    });
    $("#round").show();
    nextRound();
}

function nextRound() {
    $("#chances").text(game.chances = 3);
    $("[round]").text(++game.answer);
}

function checkAnswer() {
    if (game.chances > 1) {
        if (calc.display.value.length < 7) {
            $("#error").show().delay(200).fadeOut();;
        } else if (calc.display.value == game.answer) {
            calc.display.value = eval(calc.display.value);
        } else {
            $("#chances").text(--game.chances);
        }
    } else {
        //gameover
    }
}

$("#body").click(function() {
    $("#error").hide();
});

<commit_msg>error function was not needed<commit_after>var game = {
    answer: 0,
    chances: 3,
    previousAnswer: 0,
}

$(document).ready(function() {
    $("input[type=button], input[type=text]").attr('disabled', true);
    $("#newGame").click(function() {
        $("input[type=text]").val("");
        $("input[type=button], input[type=text]").removeAttr('disabled');
        $(this).animate({"right": "0"}, {duration: 400});
        start();
    });
});

function start() {
    $("#newGame").text("Restart");
    $("#round").text(game.answer = 1);
    $("#error").hide('slow/400/fast', function() {

    });
    $("#round").show();
    nextRound();
}

function nextRound() {
    $("#chances").text(game.chances = 3);
    $("[round]").text(++game.answer);
}

function checkAnswer() {
	/*
	if (calc.display.value == game.previousAnswer) {
}
	else {
		$("input[type=text]").val("");
}
*/
	$("#guess").text(eval(calc.display.value));
    if (game.chances > 1) {
        if (calc.display.value.length < 7) {
            $("#error").show().delay(400).fadeOut();
        } else if (eval(calc.display.value) == game.answer) {
            calc.display.value = eval(calc.display.value);
            nextRound();
        } else {
            $("#chances").text(--game.chances);
        }
    } else {
        gameOver();
    }
}

function gameOver() {
	$("round").hide();
	$("guess").text("?");

}

<|endoftext|>


<commit_before>import GameState from 'states/GameState';

class Game extends Phaser.Game {

  constructor() {
    super(500, 200, Phaser.AUTO, 'content', null);
    this.state.add('Game', GameState, false);
    this.state.start('Game');
  }
}

new Game();
<commit_msg>change size<commit_after>import GameState from 'states/GameState';

class Game extends Phaser.Game {

  constructor() {
    super(640, 480, Phaser.AUTO, 'content', null);
    this.state.add('Game', GameState, false);
    this.state.start('Game');
  }
}

new Game();
<|endoftext|>