<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var TaxonomySyntaxAPI = {};
(function() {
    var SYMBOL_OR = 'OR';
    var SYMBOL_AND = 'AND';
    var SYMBOL_EXP_START = '(';
    var SYMBOL_EXP_STOP = ')';
    TaxonomySyntaxAPI.buildExpression = function(input, clean) {
        clean = clean || function(v) {
            return v;
        };
        var expression = buildExpression(input, clean);
        if (expression.operator === SYMBOL_OR) {
            var root = new Expression();
            root.operator = SYMBOL_AND;
            root.children.push(expression);
            return root;
        }
        return expression;
    };
    TaxonomySyntaxAPI.OR = SYMBOL_OR;
    TaxonomySyntaxAPI.AND = SYMBOL_AND;
    TaxonomySyntaxAPI.Expression = Expression;

    function Operand(value) {
        this.termString = value;
        this.terms = value.split('/');
    }
    Operand.prototype.root = function() {
        return this.terms[0] || '';
    };
    Operand.prototype.matchRoot = function(other) {
        return (this.root() === other.root());
    }
    Operand.prototype.match = function(other) {
        return (this.raw() === other.raw());
    };
    Operand.prototype.raw = function() {
        return this.termString;
    }

    function Group(expression) {
        this.expression = expression;
    };
    Group.prototype.hasOperand = function(other) {
        return this.countMatchingOperands(other) > 1;
    };
    Group.prototype.hasOnlyOneOperand = function(other) {
        return this.countMatchingOperands(other) === 1;
    };
    Group.prototype.operandIndex = function(other) {
        var operands = this.expression.operands;
        var currentOp;
        var operandIndex = -1;
        operands.forEach(function(value, index) {
            currentOp = new Operand(value);
            if (currentOp.matchRoot(other)) {
                operandIndex = index;
            }
        });
        return operandIndex;
    };
    Group.prototype.operandAtIndex = function(index) {
        return this.expression.operands[index];
    };
    Group.prototype.countMatchingOperands = function(other) {
        var operands = this.expression.operands;
        var currentOp;
        var match = 0;
        operands.forEach(function(value) {
            currentOp = new Operand(value);
            if (currentOp.matchRoot(other)) {
                match++;
            }
        });
        return match;
    };
    Group.prototype.mergeOperands = function(other) {
        //Remove the matching operand
        var operandIndex = this.operandIndex(other);
        //If it is not found do not do anything
        if (operandIndex <= -1) {
            return;
        }
        var operandToBeRemoved = this.operandAtIndex(operandIndex);
        this.expression.operands.splice(operandIndex, 1);
        var newExpression = new Expression();
        newExpression.operands.push(operandToBeRemoved);
        newExpression.operands.push(other.raw());
        newExpression.operator = SYMBOL_OR;
        this.expression.children.push(newExpression);
    };
    Group.prototype.add = function(operand) {
        if (this.hasOnlyOneOperand(operand)) {
            //Merge existing operand with new and add it as a child
            this.mergeOperands(operand);
        } else {
            //Add the operand to other operands
            this.expression.operands.push(operand.raw());
        }
    };
    Group.prototype.remove = function(operand) {
        var removeIndex = -1;
        //Check if there is only one operand
        if (this.hasOnlyOneOperand(operand)) {
            removeIndex = this.operandIndex(operand);
            this.expression.operands.splice(removeIndex, 1);
        } else {
            //Find and remove the exact match
            var currentOp;
            this.expression.operands.forEach(function(current, index) {
                currentOp = new Operand(current);
                if (currentOp.match(operand)) {
                    removeIndex = index;
                }
            });
            if (removeIndex > -1) {
                this.expression.operands.splice(removeIndex, 1);
            }
        }
    };

    function Expression() {
        this.operator = '';
        this.operands = [];
        this.children = [];
    }
    Expression.prototype.hasChildren = function() {
        return this.children.length > 0;
    };
    Expression.prototype.add = function(value) {
        //Locate the expression
        var operand = new Operand(value);
        var result = rsearch(this, operand.root());
        if (!result) {
            //Add it to the existing operands
            this.operands.push(value);
            return;
        }
        var group = new Group(result);
        group.add(operand);
    };
    Expression.prototype.remove = function(value) {
        var operand = new Operand(value);
        var result = rsearch(this, operand.root());
        if (!result) {
            return;
        }
        var group = new Group(result);
        group.remove(operand);
    };
    Expression.prototype.query = function(q) {
        q = q || '';
        var terms = q.split('/');
        return rsearch(this, terms[0]);
    };
    Expression.prototype.buildExpressionString = function(decorator) {
        decorator = decorator || function(v) {
            return v;
        };
        var modifiedOperands = this.operands.map(function(v) {
            return decorator(v);
        });
        if (this.operands.length == 0) {
            return '';
        }
        if (this.operands.length === 1) {
            return modifiedOperands[0];
        }
        var content = modifiedOperands.join(' ' + this.operator + ' ');
        if (this.operator === SYMBOL_OR) {
            content = '( ' + content + ' )'
        }
        return content;
        //return '( ' + modifiedOperands.join(' ' + this.operator + ' ') + ' )';
    };
    Expression.prototype.compile = function(decorator) {
        //return rprint(this, '', decorator);
        return patch_add_braces(rprint(this, '', decorator));
    };

     /**
     * Adding url taxonomy category retrieve options with 2d array
     * @returns {Array}
     */
    Expression.prototype.groups = function() {
        var mainCol = [];
        this.operands.forEach(function(value) {
            mainCol.push([value]);
        });

        this.children.forEach(function(child) {
            mainCol.push(child.operands);
        });

        return mainCol;
    };

    function buildExpression(expression, clean) {
        symbols = expression.split(' ');
        symbols.reverse();
        if (symbols.length === 1) {
            var singleExpression = new Expression();
            singleExpression.operands.push(symbols[0]);
            singleExpression.operator = SYMBOL_AND;
            return singleExpression;
        }
        var stack = [];
        var x = rbuild(symbols, symbols.pop(), new Expression(), stack);
        var t = processStack(x);
        return t;
    }

    function processStack(stack) {
        var base = new Expression();
        base.operator = SYMBOL_AND;
        var item;
        if (stack.length === 1) {
            return stack[0];
        }
        for (var index = 0; index < stack.length; index++) {
            item = stack[index];
            // if (item !== SYMBOL_AND) {
            if (item.operator === SYMBOL_AND) {
                item.operands.forEach(function(operand) {
                    base.operands.push(operand);
                });
            } else {
                if (item.operands.length == 1) {
                    base.operands.push(item.operands[0]);
                } else {
                    base.children.push(item);
                }
            }
            //}
        }
        return base;
    }

    function rbuild(symbols, currentValue, expression, stack) {
        if (!currentValue) {
            //stack.push(expression);
            return stack;
        } else if (currentValue === SYMBOL_EXP_START) {
            var newExpression = new Expression();
            newExpression.operator = SYMBOL_AND;
            return rbuild(symbols, symbols.pop(), newExpression, stack);
        } else if (currentValue === SYMBOL_EXP_STOP) {
            stack.push(expression);
            return rbuild(symbols, symbols.pop(), new Expression(), stack);
        } else if (currentValue === SYMBOL_AND) {
            //stack.push(SYMBOL_AND);
            expression.operator = SYMBOL_AND;
            return rbuild(symbols, symbols.pop(), expression, stack);
        } else if (currentValue === SYMBOL_OR) {
            expression.operator = SYMBOL_OR;
            return rbuild(symbols, symbols.pop(), expression, stack);
        } else {
            expression.operands.push(currentValue);
            return rbuild(symbols, symbols.pop(), expression, stack);
        }
    }

    function rprint(expression, output, decorator) {
        if (!expression.hasChildren()) {
            return expression.buildExpressionString(decorator);
        } else {
            var entries = [];
            var previousExpressions = 0;
            expression.children.forEach(function(child, index) {
                var result = rprint(child, output, decorator);
                if (result != '') {
                    entries.push(result);
                }
            });
            output += entries.join(' ' + expression.operator + ' ');
            previousExpressions = entries.length;
            entries = [];
            if (output != '') {
                entries.push(output);
            }
            var thisExpression = expression.buildExpressionString(decorator);
            if (thisExpression != '') {
                entries.push(thisExpression);
            }
            output = entries.join(' ' + expression.operator + ' ');
            if (previousExpressions > 1) {
                return '( ' + output + ' )';
            }
            if (entries.length === 1) {
                return output;
            }
            return '( ' + output + ' )';
        }
    }
    /**
    Performs a recursive search on an expression object to find the expression with the matching operand
    **/
    function rsearch(expression, query) {
        if (!expression.hasChildren()) {
            var found;
            for (var index = 0; index < expression.operands.length; index++) {
                if (expression.operands[index].indexOf(query) > -1) {
                    return expression;
                }
            }
            return null;
        } else {
            var result;
            //Check if the current operands can satisfy the query
            for (var index = 0; index < expression.operands.length; index++) {
                if (expression.operands[index].indexOf(query) > -1) {
                    return expression;
                }
            }
            for (var index = 0; index < expression.children.length; index++) {
                result = rsearch(expression.children[index], query);
                if (result) {
                    return result;
                }
            }
        }
    }

    function patch_add_braces(input) {
        var hasAnd = input.indexOf(SYMBOL_AND) > -1; //This means it has more than one operand
        var hasNoEnclosingBraces = ((input.charAt(0) !== '(') || (input.charAt(input.length - 1) !== ')'));
        if (hasAnd && hasNoEnclosingBraces) {
            return '( ' + input + ' )';
        }
        return input;
    }
}());<commit_msg>Fixed an issue with parsing taxonomy expressions when single operands are provided at the start<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var TaxonomySyntaxAPI = {};
(function() {
    var SYMBOL_OR = 'OR';
    var SYMBOL_AND = 'AND';
    var SYMBOL_EXP_START = '(';
    var SYMBOL_EXP_STOP = ')';
    TaxonomySyntaxAPI.buildExpression = function(input, clean) {
        clean = clean || function(v) {
            return v;
        };
        var expression = buildExpression(input, clean);
        if (expression.operator === SYMBOL_OR) {
            var root = new Expression();
            root.operator = SYMBOL_AND;
            root.children.push(expression);
            return root;
        }
        return expression;
    };
    TaxonomySyntaxAPI.OR = SYMBOL_OR;
    TaxonomySyntaxAPI.AND = SYMBOL_AND;
    TaxonomySyntaxAPI.Expression = Expression;

    function Operand(value) {
        this.termString = value;
        this.terms = value.split('/');
    }
    Operand.prototype.root = function() {
        return this.terms[0] || '';
    };
    Operand.prototype.matchRoot = function(other) {
        return (this.root() === other.root());
    }
    Operand.prototype.match = function(other) {
        return (this.raw() === other.raw());
    };
    Operand.prototype.raw = function() {
        return this.termString;
    }

    function Group(expression) {
        this.expression = expression;
    };
    Group.prototype.hasOperand = function(other) {
        return this.countMatchingOperands(other) > 1;
    };
    Group.prototype.hasOnlyOneOperand = function(other) {
        return this.countMatchingOperands(other) === 1;
    };
    Group.prototype.operandIndex = function(other) {
        var operands = this.expression.operands;
        var currentOp;
        var operandIndex = -1;
        operands.forEach(function(value, index) {
            currentOp = new Operand(value);
            if (currentOp.matchRoot(other)) {
                operandIndex = index;
            }
        });
        return operandIndex;
    };
    Group.prototype.operandAtIndex = function(index) {
        return this.expression.operands[index];
    };
    Group.prototype.countMatchingOperands = function(other) {
        var operands = this.expression.operands;
        var currentOp;
        var match = 0;
        operands.forEach(function(value) {
            currentOp = new Operand(value);
            if (currentOp.matchRoot(other)) {
                match++;
            }
        });
        return match;
    };
    Group.prototype.mergeOperands = function(other) {
        //Remove the matching operand
        var operandIndex = this.operandIndex(other);
        //If it is not found do not do anything
        if (operandIndex <= -1) {
            return;
        }
        var operandToBeRemoved = this.operandAtIndex(operandIndex);
        this.expression.operands.splice(operandIndex, 1);
        var newExpression = new Expression();
        newExpression.operands.push(operandToBeRemoved);
        newExpression.operands.push(other.raw());
        newExpression.operator = SYMBOL_OR;
        this.expression.children.push(newExpression);
    };
    Group.prototype.add = function(operand) {
        if (this.hasOnlyOneOperand(operand)) {
            //Merge existing operand with new and add it as a child
            this.mergeOperands(operand);
        } else {
            //Add the operand to other operands
            this.expression.operands.push(operand.raw());
        }
    };
    Group.prototype.remove = function(operand) {
        var removeIndex = -1;
        //Check if there is only one operand
        if (this.hasOnlyOneOperand(operand)) {
            removeIndex = this.operandIndex(operand);
            this.expression.operands.splice(removeIndex, 1);
        } else {
            //Find and remove the exact match
            var currentOp;
            this.expression.operands.forEach(function(current, index) {
                currentOp = new Operand(current);
                if (currentOp.match(operand)) {
                    removeIndex = index;
                }
            });
            if (removeIndex > -1) {
                this.expression.operands.splice(removeIndex, 1);
            }
        }
    };

    function Expression() {
        this.operator = '';
        this.operands = [];
        this.children = [];
    }
    Expression.prototype.hasChildren = function() {
        return this.children.length > 0;
    };
    Expression.prototype.add = function(value) {
        //Locate the expression
        var operand = new Operand(value);
        var result = rsearch(this, operand.root());
        if (!result) {
            //Add it to the existing operands
            this.operands.push(value);
            return;
        }
        var group = new Group(result);
        group.add(operand);
    };
    Expression.prototype.remove = function(value) {
        var operand = new Operand(value);
        var result = rsearch(this, operand.root());
        if (!result) {
            return;
        }
        var group = new Group(result);
        group.remove(operand);
    };
    Expression.prototype.query = function(q) {
        q = q || '';
        var terms = q.split('/');
        return rsearch(this, terms[0]);
    };
    Expression.prototype.buildExpressionString = function(decorator) {
        decorator = decorator || function(v) {
            return v;
        };
        var modifiedOperands = this.operands.map(function(v) {
            return decorator(v);
        });
        if (this.operands.length == 0) {
            return '';
        }
        if (this.operands.length === 1) {
            return modifiedOperands[0];
        }
        var content = modifiedOperands.join(' ' + this.operator + ' ');
        if (this.operator === SYMBOL_OR) {
            content = '( ' + content + ' )'
        }
        return content;
        //return '( ' + modifiedOperands.join(' ' + this.operator + ' ') + ' )';
    };
    Expression.prototype.compile = function(decorator) {
        //return rprint(this, '', decorator);
        return patch_add_braces(rprint(this, '', decorator));
    };
    /**
     * Adding url taxonomy category retrieve options with 2d array
     * @returns {Array}
     */
    Expression.prototype.groups = function() {
        var mainCol = [];
        this.operands.forEach(function(value) {
            mainCol.push([value]);
        });
        this.children.forEach(function(child) {
            mainCol.push(child.operands);
        });
        return mainCol;
    };

    function buildExpression(expression, clean) {
        symbols = expression.split(' ');
        symbols.reverse();
        if (symbols.length === 1) {
            var singleExpression = new Expression();
            singleExpression.operands.push(symbols[0]);
            singleExpression.operator = SYMBOL_AND;
            return singleExpression;
        }
        var stack = [];
        var x = rbuild(symbols, symbols.pop(), null, stack);
        var t = processStack(x);
        return t;
    }

    function processStack(stack) {
        var base = new Expression();
        base.operator = SYMBOL_AND;
        var item;
        if (stack.length === 1) {
            return stack[0];
        }
        for (var index = 0; index < stack.length; index++) {
            item = stack[index];
            // if (item !== SYMBOL_AND) {
            if (item.operator === SYMBOL_AND) {
                item.operands.forEach(function(operand) {
                    base.operands.push(operand);
                });
            } else {
                if (item.operands.length == 1) {
                    base.operands.push(item.operands[0]);
                } else {
                    base.children.push(item);
                }
            }
            //}
        }
        return base;
    }

    function rbuild(symbols, currentValue, expression, stack) {
        if (!currentValue) {
            //stack.push(expression);
            return stack;
        } else if (currentValue === SYMBOL_EXP_START) {
            if (expression) {
                stack.push(expression);
            }
            var newExpression = new Expression();
            newExpression.operator = SYMBOL_AND;
            return rbuild(symbols, symbols.pop(), newExpression, stack);
        } else if (currentValue === SYMBOL_EXP_STOP) {
            stack.push(expression);
            return rbuild(symbols, symbols.pop(), new Expression(), stack);
        } else if (currentValue === SYMBOL_AND) {
            //stack.push(SYMBOL_AND);
            expression.operator = SYMBOL_AND;
            return rbuild(symbols, symbols.pop(), expression, stack);
        } else if (currentValue === SYMBOL_OR) {
            expression.operator = SYMBOL_OR;
            return rbuild(symbols, symbols.pop(), expression, stack);
        } else {
            expression.operands.push(currentValue);
            return rbuild(symbols, symbols.pop(), expression, stack);
        }
    }

    function rprint(expression, output, decorator) {
        if (!expression.hasChildren()) {
            return expression.buildExpressionString(decorator);
        } else {
            var entries = [];
            var previousExpressions = 0;
            expression.children.forEach(function(child, index) {
                var result = rprint(child, output, decorator);
                if (result != '') {
                    entries.push(result);
                }
            });
            output += entries.join(' ' + expression.operator + ' ');
            previousExpressions = entries.length;
            entries = [];
            if (output != '') {
                entries.push(output);
            }
            var thisExpression = expression.buildExpressionString(decorator);
            if (thisExpression != '') {
                entries.push(thisExpression);
            }
            output = entries.join(' ' + expression.operator + ' ');
            if (previousExpressions > 1) {
                return '( ' + output + ' )';
            }
            if (entries.length === 1) {
                return output;
            }
            return '( ' + output + ' )';
        }
    }
    /**
    Performs a recursive search on an expression object to find the expression with the matching operand
    **/
    function rsearch(expression, query) {
        if (!expression.hasChildren()) {
            var found;
            for (var index = 0; index < expression.operands.length; index++) {
                if (expression.operands[index].indexOf(query) > -1) {
                    return expression;
                }
            }
            return null;
        } else {
            var result;
            //Check if the current operands can satisfy the query
            for (var index = 0; index < expression.operands.length; index++) {
                if (expression.operands[index].indexOf(query) > -1) {
                    return expression;
                }
            }
            for (var index = 0; index < expression.children.length; index++) {
                result = rsearch(expression.children[index], query);
                if (result) {
                    return result;
                }
            }
        }
    }

    function patch_add_braces(input) {
        var hasAnd = input.indexOf(SYMBOL_AND) > -1; //This means it has more than one operand
        var hasNoEnclosingBraces = ((input.charAt(0) !== '(') || (input.charAt(input.length - 1) !== ')'));
        if (hasAnd && hasNoEnclosingBraces) {
            return '( ' + input + ' )';
        }
        return input;
    }
}());<|endoftext|>


<commit_before>const DIGIT_REGEX = /^\d+$/
const readableIdPartFromWord = word => DIGIT_REGEX.test(word) ? word : word[0]
function prepareName(rawName) {
  const name = rawName.trim().toLowerCase().replace(/[^\w\d]/g, ' ').replace(/\s/g, '_')
  return name.slice(name.search(/[^\d]/))
}

function getDirectVariableNameFromName(rawName, maxOneWordLength, maxSplitWordLength) {
  const name = prepareName(rawName)

  const words = name.split(/[\_]/).filter(s => !_.isEmpty(s))

  if (words.length === 1 && name.length < maxOneWordLength) {
    return name
  } else if (words.length < maxSplitWordLength) {
    return name.slice(0, maxSplitWordLength)
  } else {
    return words.map(readableIdPartFromWord).join('')
  }
}

export function getVariableNameFromName(rawName, existingVariableNames=[], maxOneWordLength=30, maxSplitWordLength=8) {
  const directName = getDirectVariableNameFromName(rawName, maxOneWordLength, maxSplitWordLength)

  const nameRegex = new RegExp(`${directName}(?:_(\d+))?`, 'gi')

  const matchingNames = existingVariableNames.filter(v => nameRegex.test(v))
  if (_.isEmpty(matchingNames)) { return directName }

  const currentMaxSuffix = Math.max(...matchingNames.map(v => parseInt(v.match(nameRegex)[1] || '0')))
  return `${directName}${currentMaxSuffix + 1}`
}

export const shouldTransformName = name => !_.isEmpty(name) && name.replace(/\d/g, '').split(/\s/g).length > 1
<commit_msg>Further refinements to the name to variable name transition process.<commit_after>const DIGIT_REGEX = /^\d+$/
const readableIdPartFromWord = word => DIGIT_REGEX.test(word) ? word : word[0]
function prepareName(rawName) {
  const name = rawName.trim().toLowerCase().replace(/[^\w\d]/g, ' ')
  const firstNonDigit = name.search(/[^\d]/)
  if (firstNonDigit === -1) { return '' }
  return name.slice(firstNonDigit).trim().replace(/\s/g, '_')
}

function getDirectVariableNameFromName(rawName, maxOneWordLength, maxSplitWordLength) {
  const name = prepareName(rawName)

  const words = name.split(/[\_]/).filter(s => !_.isEmpty(s))

  if (words.length === 1 && name.length < maxOneWordLength) {
    return name
  } else if (words.length < maxSplitWordLength) {
    return name.slice(0, maxSplitWordLength)
  } else {
    return words.map(readableIdPartFromWord).join('')
  }
}

export function getVariableNameFromName(rawName, existingVariableNames=[], maxOneWordLength=30, maxSplitWordLength=8) {
  const directName = getDirectVariableNameFromName(rawName, maxOneWordLength, maxSplitWordLength)

  const nameRegex = new RegExp(`${directName}(?:_(\d+))?`, 'gi')

  const matchingNames = existingVariableNames.filter(v => nameRegex.test(v))
  if (_.isEmpty(matchingNames)) { return directName }

  const currentMaxSuffix = Math.max(...matchingNames.map(v => parseInt(v.match(nameRegex)[1] || '0')))
  return `${directName}${currentMaxSuffix + 1}`
}

export const shouldTransformName = name => !_.isEmpty(name) && name.replace(/\d/g, '').split(/\s/g).length > 1
<|endoftext|>


<commit_before>function Netflix(jq) {

	if (typeof jq !== 'undefined') {
		$ = jq;
	}
	else if (typeof jQuery !== 'undefined') {
		$ =jQuery;
	}
	else {
		throw new Error("jQuery is required for netflix.js");
	}

	var netflix = {
		// Constants
		version: '0.1',
		// Variables
		clickable: {},
		// Pages
		page: {},
		// Browse
		browse: {},
		// Player
		player: {}
	};

	// Location
	var url = window.location.href;

	netflix.page.isBrowse = function() {
		return url.indexOf('/browse/') > 0;
	};

	netflix.page.isPlayer = function() {
		return url.indexOf('/watch/') > 0;
	};

	netflix.page.isTitle = function() {
		return url.indexOf('/title/') > 0;
	}

	netflix.page.isSearch = function() {
		return url.indexOf('/search/') > 0;
	};

	netflix.page.isSettings = function() {
		var settingPages = ['ManageProfiles', 'YourAccount', 'email', 'password', 'phonenumber', 'YourAccountPayment', 'BillingActivity', 'ChangePlan', 'Subscribe', 'EmailPreferences', 'pin', 'DoNotTest', 'Activate', 'ManageDevices', 'EditProfiles', 'LanguagePreferences', 'HdToggle', 'SubtitlePreferences', 'MyListOrder', 'viewingactivity', 'MoviesYouveSeen', 'Reviews'];
		for (var i = 0; i < settingPages.length; i++) {
			if (url.indexOf('/'+settingPages[i]+'/') > 0)
				return true;
		}

		return false;
	};

	// Player Controls
	netflix.player.play = function() {
		if (netflix.is)
		if (netflix.player.isPaused())
			netflix.clickable
	};

	netflix.player.pause = function() {

	};

	netflix.player.isPlaying = function() {

	};

	netflix.player.isPaused = function() {

	};

	netflix.player.seek = function(time) {

	};

	netflix.player.currentTime = function() {

	};

	netflix.player.stabilize = function() {

	};

	netflix.player.getVolume = function() {

	};

	netflix.player.setVolume = function(volume) {

	};

	netflix.player.previousEpisode = function() {

	};

	netflix.player.nextEpisode = function() {

	};

	netflix.player.backToBrowse = function() {

	};

	netflix.player.isFullscreen = function() {

	};

	netflix.player.toggleFullscreen = function() {

	};

	// Player Information
	netflix.player.getId = function() {

	};

	netflix.player.getTitle = function() {

	};

	netflix.player.getDescription = function() {

	};

	netflix.player.getType = function() {

	};

	netflix.player.getSeason = function() {

	};

	netflix.player.getEpisode = function() {

	};

	netflix.player.getEpisodeTitle = function() {

	};

	netflix.player.getEpisodeDescription = function() {

	};

	netflix.player.getLength = function() {

	};

	// find all elements
	if (netflix.isPlayer()) {
		netflix.clickable = {

		};
	}
	else {

	}

	return t;
}<commit_msg>some changes<commit_after>function Netflix(jq) {

	if (typeof jq !== 'undefined') {
		$ = jq;
	}
	else if (typeof jQuery !== 'undefined') {
		$ =jQuery;
	}
	else {
		throw new Error("jQuery is required for netflix.js");
	}

	var netflix = {
		// Constants
		version: '0.1',
		// Variables
		elements: {},
		// Pages
		page: {},
		// Browse
		browse: {},
		// Player
		player: {
			_length: -1
		}
	};

	// Location
	var url = window.location.href;

	netflix.page.isBrowse = function() {
		return url.indexOf('/browse/') > 0;
	};

	netflix.page.isPlayer = function() {
		return url.indexOf('/watch/') > 0;
	};

	netflix.page.isTitle = function() {
		return url.indexOf('/title/') > 0;
	}

	netflix.page.isSearch = function() {
		return url.indexOf('/search/') > 0;
	};

	netflix.page.isSettings = function() {
		var settingPages = ['ManageProfiles', 'YourAccount', 'email', 'password', 'phonenumber', 'YourAccountPayment', 'BillingActivity', 'ChangePlan', 'Subscribe', 'EmailPreferences', 'pin', 'DoNotTest', 'Activate', 'ManageDevices', 'EditProfiles', 'LanguagePreferences', 'HdToggle', 'SubtitlePreferences', 'MyListOrder', 'viewingactivity', 'MoviesYouveSeen', 'Reviews'];
		for (var i = 0; i < settingPages.length; i++) {
			if (url.indexOf('/'+settingPages[i]+'/') > 0)
				return true;
		}

		return false;
	};

	// Player Controls
	netflix.player.play = function() {
		if (netflix.page.isPlayer()) {
			if (netflix.player.isPaused()) {
				netflix.elements.playPauseButton.click();
				return true;
			}
			else {
				return false;
			}
		}
	};

	netflix.player.pause = function() {
		if (netflix.page.isPlayer()) {
			if (netflix.player.isPlaying()) {
				alert('pause');
				netflix.elements.playPauseButton.click();
				return true;
			}
			else {
				return false;
			}
		}
	};

	netflix.player.isPlaying = function() {
		if (netflix.page.isPlayer()) {
			return netflix.elements.playPauseButton.attr('aria-label') == 'Pause';
		}
	};

	netflix.player.isPaused = function() {
		return !netflix.player.isPlaying();
	};

	netflix.player.seek = function(time) {
		if (netflix.page.isPlayer()) {
			var x = 369;
			var y = 587;
			var eventDetails = {
				clientX: x,
				clientY: y,
				layerX: x,
				layerY: y,
				pageX: x,
				pageY: y,
				offsetX: x,
				offsetY: y,
				x: x,
				y: y
			};
			// var mousedown = new $.Event('mousedown', eventDetails);
			// var mouseup = new $.Event('mouseup', eventDetails);
			// var click = new $.Event('click', eventDetails);
			var mousedown = new MouseEvent('mousedown', eventDetails);
			var mouseup = new MouseEvent('mouseup', eventDetails);
			var click = new MouseEvent('click', eventDetails);
			console.log(mousedown);
			console.log(mouseup);
			console.log(click);

			netflix.elements.slider.bar[0].dispatchEvent(mousedown);
			netflix.elements.slider.bar[0].dispatchEvent(mouseup);
			netflix.elements.slider.bar[0].dispatchEvent(click);
			// netflix.elements.slider.bar[0].trigger(mouseup);
			// netflix.elements.slider.bar[0].trigger(click);
		}
	};

	netflix.player.currentTime = function() {
		var progressCompleted = parseFloat(netflix.elements.slider.progressCompleted.width());
		var length = netflix.player.getLength();

		return length * progressCompleted/100;
	};

	netflix.player.getLength = function() {
		if (netflix.player._length == -1) {
			var progressCompleted = parseFloat(netflix.elements.slider.progressCompleted.width());
			var timeLeft = netflix.elements.slider.timeLeft.text();

			           // minute                                                   second
			timeLeft = parseInt(timeLeft.substring(0, timeLeft.indexOf(':')))*60 + parseInt(timeLeft.substring(timeLeft.indexOf(':')+1));

			netflix.player._length = 1/(((100 - progressCompleted)/100)/timeLeft);
		}

		return netflix.player._length;
	};

	netflix.player.stabilize = function() {

	};

	netflix.player.getVolume = function() {

	};

	netflix.player.setVolume = function(volume) {

	};

	netflix.player.previousEpisode = function() {

	};

	netflix.player.nextEpisode = function() {

	};

	netflix.player.backToBrowse = function() {

	};

	netflix.player.isFullscreen = function() {

	};

	netflix.player.toggleFullscreen = function() {
		netflix.elements.fullscreenButton.click();
	};

	// Player Information
	netflix.player.getId = function() {

	};

	netflix.player.getTitle = function() {

	};

	netflix.player.getDescription = function() {

	};

	netflix.player.getType = function() {

	};

	netflix.player.getSeason = function() {

	};

	netflix.player.getEpisode = function() {

	};

	netflix.player.getEpisodeTitle = function() {

	};

	netflix.player.getEpisodeDescription = function() {

	};

	// set up the elements
	if (netflix.page.isPlayer()) {
		netflix.elements = {
			playPauseButton: $('.player-control-button.player-play-pause'),
			slider: {
				timeLeft: $('section.player-slider > label'),
				progressCompleted: $('.player-scrubber-progress-completed'),
				bar: $('#scrubber-component'),
			},
			fullscreenButton: $('.player-control-button.player-fill-screen')
		};
	}
	else {

	}

	return netflix;
}

n = Netflix();
n.player.seek(100);<|endoftext|>


<commit_before>const chalk = require('chalk');

module.exports = {
    askForInsightOptIn,
    askForApplicationType,
    askForModuleName,
    askFori18n,
    askForTestOpts,
    askForMoreModules
};

function askForInsightOptIn() {
    if (this.existingProject) return;

    const done = this.async();
    const insight = this.insight();

    this.prompt({
        when: () => insight.optOut === undefined,
        type: 'confirm',
        name: 'insight',
        message: `May ${chalk.cyan('JHipster')} anonymously report usage statistics to improve the tool over time?`,
        default: true
    }).then((prompt) => {
        if (prompt.insight !== undefined) {
            insight.optOut = !prompt.insight;
        }
        done();
    });
}

function askForApplicationType() {
    if (this.existingProject) return;

    const DEFAULT_APPTYPE = 'monolith';
    if (this.skipServer) {
        this.applicationType = this.configOptions.applicationType = DEFAULT_APPTYPE;
        return;
    }

    const done = this.async();

    this.prompt({
        type: 'list',
        name: 'applicationType',
        message: response => this.getNumberedQuestion('Which *type* of application would you like to create?', true),
        choices: [
            {
                value: DEFAULT_APPTYPE,
                name: 'Monolithic application (recommended for simple projects)'
            },
            {
                value: 'microservice',
                name: 'Microservice application'
            },
            {
                value: 'gateway',
                name: 'Microservice gateway'
            },
            {
                value: 'uaa',
                name: '[BETA] JHipster UAA server (for microservice OAuth2 authentication)'
            }
        ],
        default: DEFAULT_APPTYPE
    }).then((prompt) => {
        this.applicationType = this.configOptions.applicationType = prompt.applicationType;
        done();
    });
}

function askForModuleName() {
    if (this.existingProject) return;

    this.askModuleName(this);
    this.configOptions.lastQuestion = this.currentQuestion;
    this.configOptions.totalQuestions = this.totalQuestions;
}

function askFori18n() {
    this.currentQuestion = this.configOptions.lastQuestion;
    this.totalQuestions = this.configOptions.totalQuestions;
    if (this.skipI18n || this.existingProject) return;
    this.aski18n(this);
}

function askForTestOpts() {
    if (this.existingProject) return;

    const choices = [];
    const defaultChoice = [];
    if (!this.skipServer) {
        // all server side test frameworks should be added here
        choices.push(
            { name: 'Gatling', value: 'gatling' },
            { name: 'Cucumber', value: 'cucumber' }
        );
    }
    if (!this.skipClient) {
        // all client side test frameworks should be added here
        choices.push(
            { name: 'Protractor', value: 'protractor' }
        );
    }
    const done = this.async();

    this.prompt({
        type: 'checkbox',
        name: 'testFrameworks',
        message: response => this.getNumberedQuestion('Besides JUnit and Karma, which testing frameworks would you like to use?', true),
        choices,
        default: defaultChoice
    }).then((prompt) => {
        this.testFrameworks = prompt.testFrameworks;
        done();
    });
}

function askForMoreModules() {
    if (this.existingProject) {
        return;
    }

    const done = this.async();
    this.prompt({
        type: 'confirm',
        name: 'installModules',
        message: response => this.getNumberedQuestion('Would you like to install other generators from the JHipster Marketplace?', true),
        default: false
    }).then((prompt) => {
        if (prompt.installModules) {
            askModulesToBeInstalled(done, this);
        } else {
            done();
        }
    });
}

function askModulesToBeInstalled(done, generator) {
    generator.httpsGet('https://api.npms.io/v2/search?q=keywords:jhipster-module&from=0&size=50', (body) => {
        const moduleResponse = JSON.parse(body);
        const choices = [];
        moduleResponse.results.forEach((modDef) => {
            choices.push({
                value: { name: modDef.package.name, version: modDef.package.version },
                name: `(${modDef.package.name}-${modDef.package.version}) ${modDef.package.description} [${modDef.package.author.name}]`
            });
        });
        if (choices.length > 0) {
            generator.prompt({
                type: 'checkbox',
                name: 'otherModules',
                message: 'Which other modules would you like to use?',
                choices,
                default: []
            }).then((prompt) => {
                // [ {name: [moduleName], version:[version]}, ...]
                generator.otherModules = [];
                prompt.otherModules.forEach((module) => {
                    generator.otherModules.push({ name: module.name, version: module.version });
                });
                generator.configOptions.otherModules = generator.otherModules;
                done();
            });
        } else {
            done();
        }
    }, (error) => {
        generator.warning(`Unable to contact server to fetch additional modules: ${error.message}`);
        done();
    });
}
<commit_msg>Fix marketplace when there is an empty author<commit_after>const chalk = require('chalk');

module.exports = {
    askForInsightOptIn,
    askForApplicationType,
    askForModuleName,
    askFori18n,
    askForTestOpts,
    askForMoreModules
};

function askForInsightOptIn() {
    if (this.existingProject) return;

    const done = this.async();
    const insight = this.insight();

    this.prompt({
        when: () => insight.optOut === undefined,
        type: 'confirm',
        name: 'insight',
        message: `May ${chalk.cyan('JHipster')} anonymously report usage statistics to improve the tool over time?`,
        default: true
    }).then((prompt) => {
        if (prompt.insight !== undefined) {
            insight.optOut = !prompt.insight;
        }
        done();
    });
}

function askForApplicationType() {
    if (this.existingProject) return;

    const DEFAULT_APPTYPE = 'monolith';
    if (this.skipServer) {
        this.applicationType = this.configOptions.applicationType = DEFAULT_APPTYPE;
        return;
    }

    const done = this.async();

    this.prompt({
        type: 'list',
        name: 'applicationType',
        message: response => this.getNumberedQuestion('Which *type* of application would you like to create?', true),
        choices: [
            {
                value: DEFAULT_APPTYPE,
                name: 'Monolithic application (recommended for simple projects)'
            },
            {
                value: 'microservice',
                name: 'Microservice application'
            },
            {
                value: 'gateway',
                name: 'Microservice gateway'
            },
            {
                value: 'uaa',
                name: '[BETA] JHipster UAA server (for microservice OAuth2 authentication)'
            }
        ],
        default: DEFAULT_APPTYPE
    }).then((prompt) => {
        this.applicationType = this.configOptions.applicationType = prompt.applicationType;
        done();
    });
}

function askForModuleName() {
    if (this.existingProject) return;

    this.askModuleName(this);
    this.configOptions.lastQuestion = this.currentQuestion;
    this.configOptions.totalQuestions = this.totalQuestions;
}

function askFori18n() {
    this.currentQuestion = this.configOptions.lastQuestion;
    this.totalQuestions = this.configOptions.totalQuestions;
    if (this.skipI18n || this.existingProject) return;
    this.aski18n(this);
}

function askForTestOpts() {
    if (this.existingProject) return;

    const choices = [];
    const defaultChoice = [];
    if (!this.skipServer) {
        // all server side test frameworks should be added here
        choices.push(
            { name: 'Gatling', value: 'gatling' },
            { name: 'Cucumber', value: 'cucumber' }
        );
    }
    if (!this.skipClient) {
        // all client side test frameworks should be added here
        choices.push(
            { name: 'Protractor', value: 'protractor' }
        );
    }
    const done = this.async();

    this.prompt({
        type: 'checkbox',
        name: 'testFrameworks',
        message: response => this.getNumberedQuestion('Besides JUnit and Karma, which testing frameworks would you like to use?', true),
        choices,
        default: defaultChoice
    }).then((prompt) => {
        this.testFrameworks = prompt.testFrameworks;
        done();
    });
}

function askForMoreModules() {
    if (this.existingProject) {
        return;
    }

    const done = this.async();
    this.prompt({
        type: 'confirm',
        name: 'installModules',
        message: response => this.getNumberedQuestion('Would you like to install other generators from the JHipster Marketplace?', true),
        default: false
    }).then((prompt) => {
        if (prompt.installModules) {
            askModulesToBeInstalled(done, this);
        } else {
            done();
        }
    });
}

function askModulesToBeInstalled(done, generator) {
    generator.httpsGet('https://api.npms.io/v2/search?q=keywords:jhipster-module&from=0&size=50', (body) => {
        const moduleResponse = JSON.parse(body);
        const choices = [];
        moduleResponse.results.forEach((modDef) => {
            choices.push({
                value: { name: modDef.package.name, version: modDef.package.version },
                name: `(${modDef.package.name}-${modDef.package.version}) ${modDef.package.description}`
            });
        });
        if (choices.length > 0) {
            generator.prompt({
                type: 'checkbox',
                name: 'otherModules',
                message: 'Which other modules would you like to use?',
                choices,
                default: []
            }).then((prompt) => {
                // [ {name: [moduleName], version:[version]}, ...]
                generator.otherModules = [];
                prompt.otherModules.forEach((module) => {
                    generator.otherModules.push({ name: module.name, version: module.version });
                });
                generator.configOptions.otherModules = generator.otherModules;
                done();
            });
        } else {
            done();
        }
    }, (error) => {
        generator.warning(`Unable to contact server to fetch additional modules: ${error.message}`);
        done();
    });
}
<|endoftext|>


<commit_before>var config = require('./config')
 , file_details = require('./get_file_details')
 , read = require('./read_css')
 , Build = require('./build_folder')
var Watch = require('@djforth/ap_utils').watcher;

function processCSS(name, path, cb){
  if (name.match(/^_/)){
    Build();
  } else {
    var details = file_details(path, name);
    read(details, cb);
  }
}

module.exports = function(cb){
  var watcher = Watch(config.get('input'));
  watcher.onAdd(function(name, path){
    if (!name.match(/^_/)){
      Build();
    }
  })
  .addChange(function(name, path){
    processCSS(name, path, cb);
  });
};

<commit_msg>fixing watcher for browsersync<commit_after>var config = require('./config')
 , file_details = require('./get_file_details')
 , read = require('./read_css')
 , Build = require('./build_folder');
var Watch = require('@djforth/ap_utils').watcher;

function processCSS(name, path, cb){
  if (name.match(/^_/)){
    Build(cb);
  } else {
    var details = file_details(path, name);
    read(details, cb);
  }
}

module.exports = function(cb){
  var watcher = Watch(config.get('input'));
  watcher.onAdd(function(name, path){
    if (!name.match(/^_/)){
      Build(cb);
    }
  })
  .addChange(function(name, path){
    processCSS(name, path, cb);
  });
};

<|endoftext|>


<commit_before>'use strict'

import React, {
  Component,
  StyleSheet,
  ActivityIndicatorIOS,
  Text,
  View,
  Image,
  Dimensions,
} from 'react-native';

import moment from 'moment';
import weathericons from 'react-native-iconic-font/weathericons';
import ForecastView from './ForecastView';

const { width, height } = Dimensions.get('window');

class WeatherView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      city: '',
      temperature: '',
      icon: '',
      forecasts: [],
      isLoading: false,
      message: ''
    };
  }

  componentDidMount() {
    this.queryOpenWeatherMap();
  }

  render() {
    let spinner = this.state.isLoading ?
      ( <ActivityIndicatorIOS
          hidden='true'
          size='large'/> ) :
      ( <View/>);

    return (
      <Image style={styles.backgroundImage} source={require('../img/background.png')}>
        <View style={styles.container}>
          {spinner}
          <Text style={[styles.city, styles.whiteText]}>
            {this.state.city}
          </Text>
          <Text style={[styles.icon, styles.whiteText]}>
            {this.state.icon}
          </Text>
          <Text style={[styles.temperature, styles.whiteText]}>
            {this.state.temperature}
          </Text>
          <View style={styles.forecastContainer}>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[0]}/>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[1]}/>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[2]}/>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[3]}/>
          </View>
        </View>
      </Image>
    );
  }

  queryOpenWeatherMap() {
    // TODO: temporarily used
    const url = 'http://api.openweathermap.org/data/2.5/forecast?lat=-33.8634&lon=151.211&appid=fcc9c74f4b63e290811cb0d0d93d796f'
    fetch(url)
    .then((response) => response.json())
    .then((json) => {
      let weatherList = json.list[0];
      let tempDegrees = weatherList.main.temp;
      let country = json.city.country;
      let city = json.city.name;
      let degrees = this.convertTemperature(country, tempDegrees);
      let weatherCondition = weatherList.weather[0].id;
      let iconString = weatherList.weather[0].icon;

      let forecasts = [];
      // Get the first four forecasts
      for (let i=0; i<4; ++i) {
        let forecastList = json.list[i];

        let forecast = {};
        forecast.time = moment.unix(forecastList.dt).format('H:mm');
        let forecastTempDegrees = forecastList.main.temp;
        forecast.degrees = this.convertTemperature(country, forecastTempDegrees);
        forecast.icon = weathericons('day-sunny'); // TODO: hardcoded here
        forecasts[i] = forecast;
      }

      this.setState({
        city: city,
        temperature: degrees,
        icon: weathericons('day-sunny'), // TODO: hardcoded here
        isLoading: false,
        forecasts: forecasts,
      });
    })
    .catch(function (error) {
      // console.error('An error occured');
      console.error(error.message);
    });
  }

  convertTemperature(country, openWeatherMapDegrees) {
    if (country === 'US') {
      // Convert temperature to Fahrenheit if user is within the US
      return Math.round(((openWeatherMapDegrees - 273.15) * 1.8) + 32) + '\u00B0 F'
    } else {
      // Otherwise, convert temperature to Celsius
      return Math.round(openWeatherMapDegrees - 273.15) + '\u00B0 C'
    }
  }
}

const styles = StyleSheet.create({
  backgroundImage: {
    alignSelf: 'center',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#000000',
    opacity: 0.8,
  },
  whiteText: {
    color: 'white',
  },
  city: {
    fontSize: 40,
  },
  icon: {
    fontFamily: 'Weather Icons',
    fontSize: 100,
  },
  temperature: {
    fontSize: 60,
  },
  forecastContainer: {
    width: width,
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  forecast: {
    flex: 1,
  }
});

export default WeatherView;
<commit_msg>Update the weather icon.<commit_after>'use strict'

import React, {
  Component,
  StyleSheet,
  ActivityIndicatorIOS,
  Text,
  View,
  Image,
  Dimensions,
} from 'react-native';

import moment from 'moment';
import weathericons from 'react-native-iconic-font/weathericons';
import ForecastView from './ForecastView';

const { width, height } = Dimensions.get('window');

class WeatherView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      city: '',
      temperature: '',
      icon: '',
      forecasts: [],
      isLoading: false,
      message: ''
    };
  }

  componentDidMount() {
    this.queryOpenWeatherMap();
  }

  render() {
    let spinner = this.state.isLoading ?
      ( <ActivityIndicatorIOS
          hidden='true'
          size='large'/> ) :
      ( <View/>);

    return (
      <Image style={styles.backgroundImage} source={require('../img/background.png')}>
        <View style={styles.container}>
          {spinner}
          <Text style={[styles.city, styles.whiteText]}>
            {this.state.city}
          </Text>
          <Text style={[styles.icon, styles.whiteText]}>
            {this.state.icon}
          </Text>
          <Text style={[styles.temperature, styles.whiteText]}>
            {this.state.temperature}
          </Text>
          <View style={styles.forecastContainer}>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[0]}/>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[1]}/>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[2]}/>
            <ForecastView style={styles.forecast} forecast={this.state.forecasts[3]}/>
          </View>
        </View>
      </Image>
    );
  }

  queryOpenWeatherMap() {
    // TODO: temporarily used
    const url = 'http://api.openweathermap.org/data/2.5/forecast?lat=-33.8634&lon=151.211&appid=fcc9c74f4b63e290811cb0d0d93d796f'
    fetch(url)
    .then((response) => response.json())
    .then((json) => {
      let weatherList = json.list[0];
      let tempDegrees = weatherList.main.temp;
      let country = json.city.country;
      let city = json.city.name;
      let degrees = this.convertTemperature(country, tempDegrees);
      let weatherCondition = weatherList.weather[0].id;
      let iconString = weatherList.weather[0].icon;

      let forecasts = [];
      // Get the first four forecasts
      for (let i=0; i<4; ++i) {
        let forecastList = json.list[i];

        let forecast = {};
        forecast.time = moment.unix(forecastList.dt).format('H:mm');
        let forecastTempDegrees = forecastList.main.temp;
        forecast.degrees = this.convertTemperature(country, forecastTempDegrees);
        let forecastCondition = forecastList.weather[0].id;
        let forecastIconString = forecastList.weather[0].icon;
        forecast.icon = this.weatherIcon(forecastCondition, forecastIconString);
        forecasts[i] = forecast;
      }

      this.setState({
        city: city,
        temperature: degrees,
        icon: this.weatherIcon(weatherCondition, iconString),
        isLoading: false,
        forecasts: forecasts,
      });
    })
    .catch(function (error) {
      // console.error('An error occured');
      console.error(error.message);
    });
  }

  convertTemperature(country, openWeatherMapDegrees) {
    if (country === 'US') {
      // Convert temperature to Fahrenheit if user is within the US
      return Math.round(((openWeatherMapDegrees - 273.15) * 1.8) + 32) + '\u00B0 F';
    } else {
      // Otherwise, convert temperature to Celsius
      return Math.round(openWeatherMapDegrees - 273.15) + '\u00B0 C';
    }
  }

  weatherIcon(condition, iconString) {
    if (iconString.includes('n')) {
      return weathericons('owm-night-' + condition);
    }
    return weathericons('owm-day-' + condition);
  }
}

const styles = StyleSheet.create({
  backgroundImage: {
    alignSelf: 'center',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#000000',
    opacity: 0.8,
  },
  whiteText: {
    color: 'white',
  },
  city: {
    fontSize: 40,
  },
  icon: {
    fontFamily: 'Weather Icons',
    fontSize: 100,
  },
  temperature: {
    fontSize: 60,
  },
  forecastContainer: {
    width: width,
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  forecast: {
    flex: 1,
  }
});

export default WeatherView;
<|endoftext|>


<commit_before>import Harness from '../test/harness';
import Wizard from './Wizard';
import assert from 'power-assert';
import { expect } from 'chai';

const wizard = {
  title: 'Wizard Form',
  components: [
    {
      title: 'Page 1',
      label: 'Page 1',
      type: 'panel',
      key: 'page1',
      components: [
        {
          label: 'a',
          labelPosition: 'top',
          placeholder: '',
          description: '',
          tooltip: '',
          prefix: '',
          suffix: '',
          widget: {
            type: 'input'
          },
          inputMask: '',
          allowMultipleMasks: false,
          customClass: '',
          tabindex: '',
          hidden: false,
          hideLabel: false,
          showWordCount: false,
          showCharCount: false,
          mask: false,
          autofocus: false,
          spellcheck: true,
          disabled: false,
          tableView: true,
          modalEdit: false,
          multiple: false,
          persistent: true,
          inputFormat: 'plain',
          'protected': false,
          dbIndex: false,
          'case': '',
          encrypted: false,
          redrawOn: '',
          clearOnHide: true,
          customDefaultValue: '',
          calculateValue: '',
          calculateServer: false,
          allowCalculateOverride: false,
          validateOn: 'change',
          validate: {
            required: false,
            pattern: '',
            customMessage: '',
            custom: '',
            customPrivate: false,
            json: '',
            minLength: 4,
            maxLength: '',
            strictDateValidation: false,
            multiple: false,
            unique: false
          },
          unique: false,
          errorLabel: '',
          key: 'a',
          tags: [],
          properties: {},
          conditional: {
            show: null,
            when: null,
            eq: '',
            json: ''
          },
          customConditional: '',
          logic: [],
          attributes: {},
          overlay: {
            style: '',
            page: '',
            left: '',
            top: '',
            width: '',
            height: ''
          },
          type: 'textfield',
          input: true,
          refreshOn: '',
          inputType: 'text',
          id: 'eap4fh',
          defaultValue: ''
        }
      ],
      input: false,
      placeholder: '',
      prefix: '',
      customClass: '',
      suffix: '',
      multiple: false,
      defaultValue: null,
      'protected': false,
      unique: false,
      persistent: false,
      hidden: false,
      clearOnHide: false,
      refreshOn: '',
      redrawOn: '',
      tableView: false,
      modalEdit: false,
      labelPosition: 'top',
      description: '',
      errorLabel: '',
      tooltip: '',
      hideLabel: false,
      tabindex: '',
      disabled: false,
      autofocus: false,
      dbIndex: false,
      customDefaultValue: '',
      calculateValue: '',
      widget: null,
      attributes: {},
      validateOn: 'change',
      validate: {
        required: false,
        custom: '',
        customPrivate: false,
        strictDateValidation: false,
        multiple: false,
        unique: false
      },
      conditional: {
        show: null,
        when: null,
        eq: ''
      },
      overlay: {
        style: '',
        left: '',
        top: '',
        width: '',
        height: ''
      },
      allowCalculateOverride: false,
      encrypted: false,
      showCharCount: false,
      showWordCount: false,
      properties: {},
      allowMultipleMasks: false,
      tree: false,
      theme: 'default',
      breadcrumb: 'default',
      id: 'etrhlbe'
    },
    {
      title: 'Page 2',
      label: 'Page 2',
      type: 'panel',
      key: 'page2',
      components: [
        {
          label: 'b',
          labelPosition: 'top',
          placeholder: '',
          description: '',
          tooltip: '',
          prefix: '',
          suffix: '',
          widget: {
            type: 'input'
          },
          inputMask: '',
          allowMultipleMasks: false,
          customClass: '',
          tabindex: '',
          hidden: false,
          hideLabel: false,
          showWordCount: false,
          showCharCount: false,
          mask: false,
          autofocus: false,
          spellcheck: true,
          disabled: false,
          tableView: true,
          modalEdit: false,
          multiple: false,
          persistent: true,
          inputFormat: 'plain',
          'protected': false,
          dbIndex: false,
          'case': '',
          encrypted: false,
          redrawOn: '',
          clearOnHide: true,
          customDefaultValue: '',
          calculateValue: '',
          calculateServer: false,
          allowCalculateOverride: false,
          validateOn: 'change',
          validate: {
            required: false,
            pattern: '',
            customMessage: '',
            custom: '',
            customPrivate: false,
            json: '',
            minLength: '',
            maxLength: 4,
            strictDateValidation: false,
            multiple: false,
            unique: false
          },
          unique: false,
          errorLabel: '',
          key: 'textField',
          tags: [],
          properties: {},
          conditional: {
            show: null,
            when: null,
            eq: '',
            json: ''
          },
          customConditional: '',
          logic: [],
          attributes: {},
          overlay: {
            style: '',
            page: '',
            left: '',
            top: '',
            width: '',
            height: ''
          },
          type: 'textfield',
          input: true,
          refreshOn: '',
          inputType: 'text',
          id: 'eo1khi9',
          defaultValue: ''
        }
      ],
      input: false,
      placeholder: '',
      prefix: '',
      customClass: '',
      suffix: '',
      multiple: false,
      defaultValue: null,
      'protected': false,
      unique: false,
      persistent: false,
      hidden: false,
      clearOnHide: false,
      refreshOn: '',
      redrawOn: '',
      tableView: false,
      modalEdit: false,
      labelPosition: 'top',
      description: '',
      errorLabel: '',
      tooltip: '',
      hideLabel: false,
      tabindex: '',
      disabled: false,
      autofocus: false,
      dbIndex: false,
      customDefaultValue: '',
      calculateValue: '',
      widget: null,
      attributes: {},
      validateOn: 'change',
      validate: {
        required: false,
        custom: '',
        customPrivate: false,
        strictDateValidation: false,
        multiple: false,
        unique: false
      },
      conditional: {
        show: null,
        when: null,
        eq: ''
      },
      overlay: {
        style: '',
        left: '',
        top: '',
        width: '',
        height: ''
      },
      allowCalculateOverride: false,
      encrypted: false,
      showCharCount: false,
      showWordCount: false,
      properties: {},
      allowMultipleMasks: false,
      tree: false,
      theme: 'default',
      breadcrumb: 'default',
      id: 'eij9ua'
    },
    {
      title: 'Page 3',
      label: 'Page 3',
      type: 'panel',
      key: 'page3',
      components: [
        {
          label: 'c',
          labelPosition: 'top',
          placeholder: '',
          description: '',
          tooltip: '',
          prefix: '',
          suffix: '',
          widget: {
            type: 'input'
          },
          inputMask: '',
          allowMultipleMasks: false,
          customClass: '',
          tabindex: '',
          hidden: false,
          hideLabel: false,
          showWordCount: false,
          showCharCount: false,
          mask: false,
          autofocus: false,
          spellcheck: true,
          disabled: false,
          tableView: true,
          modalEdit: false,
          multiple: false,
          persistent: true,
          inputFormat: 'plain',
          'protected': false,
          dbIndex: false,
          'case': '',
          encrypted: false,
          redrawOn: '',
          clearOnHide: true,
          customDefaultValue: '',
          calculateValue: '',
          calculateServer: false,
          allowCalculateOverride: false,
          validateOn: 'change',
          validate: {
            required: false,
            pattern: '',
            customMessage: '',
            custom: '',
            customPrivate: false,
            json: '',
            minLength: '',
            maxLength: '',
            strictDateValidation: false,
            multiple: false,
            unique: false
          },
          unique: false,
          errorLabel: '',
          key: 'c',
          tags: [],
          properties: {},
          conditional: {
            show: null,
            when: null,
            eq: '',
            json: ''
          },
          customConditional: '',
          logic: [],
          attributes: {},
          overlay: {
            style: '',
            page: '',
            left: '',
            top: '',
            width: '',
            height: ''
          },
          type: 'textfield',
          input: true,
          refreshOn: '',
          inputType: 'text',
          id: 'euovhcc',
          defaultValue: ''
        }
      ],
      input: false,
      placeholder: '',
      prefix: '',
      customClass: '',
      suffix: '',
      multiple: false,
      defaultValue: null,
      'protected': false,
      unique: false,
      persistent: false,
      hidden: false,
      clearOnHide: false,
      refreshOn: '',
      redrawOn: '',
      tableView: false,
      modalEdit: false,
      labelPosition: 'top',
      description: '',
      errorLabel: '',
      tooltip: '',
      hideLabel: false,
      tabindex: '',
      disabled: false,
      autofocus: false,
      dbIndex: false,
      customDefaultValue: '',
      calculateValue: '',
      widget: null,
      attributes: {},
      validateOn: 'change',
      validate: {
        required: false,
        custom: '',
        customPrivate: false,
        strictDateValidation: false,
        multiple: false,
        unique: false
      },
      conditional: {
        show: null,
        when: null,
        eq: ''
      },
      overlay: {
        style: '',
        left: '',
        top: '',
        width: '',
        height: ''
      },
      allowCalculateOverride: false,
      encrypted: false,
      showCharCount: false,
      showWordCount: false,
      properties: {},
      allowMultipleMasks: false,
      tree: false,
      theme: 'default',
      breadcrumb: 'default',
      id: 'ebug75q'
    }
  ],
}

describe('Wizard tests', () => {
  let wizardForm = null;
  it('Should set components to invalid after page was changed', (done) => {
    const formElement = document.createElement('div');
    wizardForm = new Wizard(formElement);
    wizardForm.setForm(wizard).then(() => {
      Harness.testSetInput(wizardForm.pages[wizardForm.page].components[0], '1', '1', true);
      wizardForm.setPage(2).then(() => {
        wizardForm.setPage(0).then(() => {
          const aInput = wizardForm.currentPage.getComponent('a');
          assert.equal(aInput.errors.length, 1);
          done();
        }).catch((err) => done(err));
      });
    })
    .catch((err) => done(err));
  });
});
<commit_msg>Added Wizard test for validation after page was changed with navigation<commit_after>import Harness from '../test/harness';
import Wizard from './Wizard';
import assert from 'power-assert';
import { expect } from 'chai';

const wizard = {
  title: 'Wizard Form',
  components: [
    {
      title: 'Page 1',
      label: 'Page 1',
      type: 'panel',
      key: 'page1',
      components: [
        {
          label: 'a',
          labelPosition: 'top',
          placeholder: '',
          description: '',
          tooltip: '',
          prefix: '',
          suffix: '',
          widget: {
            type: 'input'
          },
          inputMask: '',
          allowMultipleMasks: false,
          customClass: '',
          tabindex: '',
          hidden: false,
          hideLabel: false,
          showWordCount: false,
          showCharCount: false,
          mask: false,
          autofocus: false,
          spellcheck: true,
          disabled: false,
          tableView: true,
          modalEdit: false,
          multiple: false,
          persistent: true,
          inputFormat: 'plain',
          'protected': false,
          dbIndex: false,
          'case': '',
          encrypted: false,
          redrawOn: '',
          clearOnHide: true,
          customDefaultValue: '',
          calculateValue: '',
          calculateServer: false,
          allowCalculateOverride: false,
          validateOn: 'change',
          validate: {
            required: false,
            pattern: '',
            customMessage: '',
            custom: '',
            customPrivate: false,
            json: '',
            minLength: 4,
            maxLength: '',
            strictDateValidation: false,
            multiple: false,
            unique: false
          },
          unique: false,
          errorLabel: '',
          key: 'a',
          tags: [],
          properties: {},
          conditional: {
            show: null,
            when: null,
            eq: '',
            json: ''
          },
          customConditional: '',
          logic: [],
          attributes: {},
          overlay: {
            style: '',
            page: '',
            left: '',
            top: '',
            width: '',
            height: ''
          },
          type: 'textfield',
          input: true,
          refreshOn: '',
          inputType: 'text',
          id: 'eap4fh',
          defaultValue: ''
        }
      ],
      input: false,
      placeholder: '',
      prefix: '',
      customClass: '',
      suffix: '',
      multiple: false,
      defaultValue: null,
      'protected': false,
      unique: false,
      persistent: false,
      hidden: false,
      clearOnHide: false,
      refreshOn: '',
      redrawOn: '',
      tableView: false,
      modalEdit: false,
      labelPosition: 'top',
      description: '',
      errorLabel: '',
      tooltip: '',
      hideLabel: false,
      tabindex: '',
      disabled: false,
      autofocus: false,
      dbIndex: false,
      customDefaultValue: '',
      calculateValue: '',
      widget: null,
      attributes: {},
      validateOn: 'change',
      validate: {
        required: false,
        custom: '',
        customPrivate: false,
        strictDateValidation: false,
        multiple: false,
        unique: false
      },
      conditional: {
        show: null,
        when: null,
        eq: ''
      },
      overlay: {
        style: '',
        left: '',
        top: '',
        width: '',
        height: ''
      },
      allowCalculateOverride: false,
      encrypted: false,
      showCharCount: false,
      showWordCount: false,
      properties: {},
      allowMultipleMasks: false,
      tree: false,
      theme: 'default',
      breadcrumb: 'default',
      id: 'etrhlbe'
    },
    {
      title: 'Page 2',
      label: 'Page 2',
      type: 'panel',
      key: 'page2',
      components: [
        {
          label: 'b',
          labelPosition: 'top',
          placeholder: '',
          description: '',
          tooltip: '',
          prefix: '',
          suffix: '',
          widget: {
            type: 'input'
          },
          inputMask: '',
          allowMultipleMasks: false,
          customClass: '',
          tabindex: '',
          hidden: false,
          hideLabel: false,
          showWordCount: false,
          showCharCount: false,
          mask: false,
          autofocus: false,
          spellcheck: true,
          disabled: false,
          tableView: true,
          modalEdit: false,
          multiple: false,
          persistent: true,
          inputFormat: 'plain',
          'protected': false,
          dbIndex: false,
          'case': '',
          encrypted: false,
          redrawOn: '',
          clearOnHide: true,
          customDefaultValue: '',
          calculateValue: '',
          calculateServer: false,
          allowCalculateOverride: false,
          validateOn: 'change',
          validate: {
            required: false,
            pattern: '',
            customMessage: '',
            custom: '',
            customPrivate: false,
            json: '',
            minLength: '',
            maxLength: 4,
            strictDateValidation: false,
            multiple: false,
            unique: false
          },
          unique: false,
          errorLabel: '',
          key: 'textField',
          tags: [],
          properties: {},
          conditional: {
            show: null,
            when: null,
            eq: '',
            json: ''
          },
          customConditional: '',
          logic: [],
          attributes: {},
          overlay: {
            style: '',
            page: '',
            left: '',
            top: '',
            width: '',
            height: ''
          },
          type: 'textfield',
          input: true,
          refreshOn: '',
          inputType: 'text',
          id: 'eo1khi9',
          defaultValue: ''
        }
      ],
      input: false,
      placeholder: '',
      prefix: '',
      customClass: '',
      suffix: '',
      multiple: false,
      defaultValue: null,
      'protected': false,
      unique: false,
      persistent: false,
      hidden: false,
      clearOnHide: false,
      refreshOn: '',
      redrawOn: '',
      tableView: false,
      modalEdit: false,
      labelPosition: 'top',
      description: '',
      errorLabel: '',
      tooltip: '',
      hideLabel: false,
      tabindex: '',
      disabled: false,
      autofocus: false,
      dbIndex: false,
      customDefaultValue: '',
      calculateValue: '',
      widget: null,
      attributes: {},
      validateOn: 'change',
      validate: {
        required: false,
        custom: '',
        customPrivate: false,
        strictDateValidation: false,
        multiple: false,
        unique: false
      },
      conditional: {
        show: null,
        when: null,
        eq: ''
      },
      overlay: {
        style: '',
        left: '',
        top: '',
        width: '',
        height: ''
      },
      allowCalculateOverride: false,
      encrypted: false,
      showCharCount: false,
      showWordCount: false,
      properties: {},
      allowMultipleMasks: false,
      tree: false,
      theme: 'default',
      breadcrumb: 'default',
      id: 'eij9ua'
    },
    {
      title: 'Page 3',
      label: 'Page 3',
      type: 'panel',
      key: 'page3',
      components: [
        {
          label: 'c',
          labelPosition: 'top',
          placeholder: '',
          description: '',
          tooltip: '',
          prefix: '',
          suffix: '',
          widget: {
            type: 'input'
          },
          inputMask: '',
          allowMultipleMasks: false,
          customClass: '',
          tabindex: '',
          hidden: false,
          hideLabel: false,
          showWordCount: false,
          showCharCount: false,
          mask: false,
          autofocus: false,
          spellcheck: true,
          disabled: false,
          tableView: true,
          modalEdit: false,
          multiple: false,
          persistent: true,
          inputFormat: 'plain',
          'protected': false,
          dbIndex: false,
          'case': '',
          encrypted: false,
          redrawOn: '',
          clearOnHide: true,
          customDefaultValue: '',
          calculateValue: '',
          calculateServer: false,
          allowCalculateOverride: false,
          validateOn: 'change',
          validate: {
            required: false,
            pattern: '',
            customMessage: '',
            custom: '',
            customPrivate: false,
            json: '',
            minLength: '',
            maxLength: '',
            strictDateValidation: false,
            multiple: false,
            unique: false
          },
          unique: false,
          errorLabel: '',
          key: 'c',
          tags: [],
          properties: {},
          conditional: {
            show: null,
            when: null,
            eq: '',
            json: ''
          },
          customConditional: '',
          logic: [],
          attributes: {},
          overlay: {
            style: '',
            page: '',
            left: '',
            top: '',
            width: '',
            height: ''
          },
          type: 'textfield',
          input: true,
          refreshOn: '',
          inputType: 'text',
          id: 'euovhcc',
          defaultValue: ''
        }
      ],
      input: false,
      placeholder: '',
      prefix: '',
      customClass: '',
      suffix: '',
      multiple: false,
      defaultValue: null,
      'protected': false,
      unique: false,
      persistent: false,
      hidden: false,
      clearOnHide: false,
      refreshOn: '',
      redrawOn: '',
      tableView: false,
      modalEdit: false,
      labelPosition: 'top',
      description: '',
      errorLabel: '',
      tooltip: '',
      hideLabel: false,
      tabindex: '',
      disabled: false,
      autofocus: false,
      dbIndex: false,
      customDefaultValue: '',
      calculateValue: '',
      widget: null,
      attributes: {},
      validateOn: 'change',
      validate: {
        required: false,
        custom: '',
        customPrivate: false,
        strictDateValidation: false,
        multiple: false,
        unique: false
      },
      conditional: {
        show: null,
        when: null,
        eq: ''
      },
      overlay: {
        style: '',
        left: '',
        top: '',
        width: '',
        height: ''
      },
      allowCalculateOverride: false,
      encrypted: false,
      showCharCount: false,
      showWordCount: false,
      properties: {},
      allowMultipleMasks: false,
      tree: false,
      theme: 'default',
      breadcrumb: 'default',
      id: 'ebug75q'
    }
  ],
};

describe('Wizard tests', () => {
  let wizardForm = null;
  it('Should set components errors if they are after page was changed with navigation', (done) => {
      const formElement = document.createElement('div');
      wizardForm = new Wizard(formElement);
      wizardForm.setForm(wizard).then(() => {
        Harness.testErrors(wizardForm, {
          data: {
            a: '1',
            c: '',
            textField: ''
          }
        },
        [{
          component: 'a',
          message: 'a must be longer than 3 characters.'
        }], done);
        Harness.clickElement(wizardForm, wizardForm.refs[`${wizardForm.wizardKey}-link`][2]);
        assert.equal(wizardForm.page, 2);
        Harness.clickElement(wizardForm, wizardForm.refs[`${wizardForm.wizardKey}-link`][0]);
        assert.equal(wizardForm.page, 0);
        const aInput = wizardForm.currentPage.getComponent('a');
        assert.equal(aInput.errors.length, 1);
        assert.equal(aInput.errors[0].message, 'a must be longer than 3 characters.');
        done();
    })
    .catch((err) => done(err));
  });

  it('Should not set components errors if in readOnly mode', (done) => {
    const formElement = document.createElement('div');
    wizardForm = new Wizard(formElement, { readOnly: true });
    wizardForm.setForm(wizard).then(() => {
      Harness.testSubmission(wizardForm, {
        data: {
          a: '1',
          textField: 'aaa',
          c: '0'
        }
      });

      Harness.clickElement(wizardForm, wizardForm.refs[`${wizardForm.wizardKey}-link`][2]);
      assert.equal(wizardForm.page, 2);
      Harness.clickElement(wizardForm, wizardForm.refs[`${wizardForm.wizardKey}-link`][0]);
      assert.equal(wizardForm.page, 0);
      const aInput = wizardForm.currentPage.getComponent('a');
      assert.equal(aInput.errors.length, 0);
      done();
    });
  });
});
<|endoftext|>


<commit_before>import { collisionArrayStatus, GamePlayers, GameEnemies, socket } from '../sockets'
import loadMaps from './utils/loadMaps'
import createMap from './utils/createMap'
import makeCollisionMap from './utils/makeCollisionMap'
import createPlayer from './utils/createPlayer'
import enemyCollision from './utils/enemyCollision'
import mapTransition from './utils/mapTransition'
import itemCollision from './utils/itemCollision'
import playerClass from '../classes/Player'
import Loot from '../classes/Loot'

/* global StackQuest, Phaser */

let map
  , playerObject
  , player
  , graveyard = []
  , lootGeneratedCounter = 0

// TODO get rid of this (put in sockets) ?
const localState = {
  loot: []
}

const fantasyState = {
  init(character) {
    if (character) player = character
  },

  preload() {
    loadMaps.fantasy()
  },

  create() {
    this.physics.startSystem(Phaser.Physics.ARCADE)

    map = createMap.fantasy()

    socket.emit('setupState', player, 'fantasyState')

    playerObject = createPlayer(player)

    if (!collisionArrayStatus) {
      makeCollisionMap(map)
    }

    // this.spawnLoot()

    this.physics.setBoundsToWorld(true, true, true, true, false)

    StackQuest.game.input.onDown.add(() => playerObject.attack())
  },

  update() {
    StackQuest.game.physics.arcade.collide(playerObject, StackQuest.game.layers.collisions)
    StackQuest.game.physics.arcade.collide(playerObject, StackQuest.game.layers.collisions_2)

    graveyard.forEach(enemy => {
      enemy.destroy()
      socket.emit('killEnemy', enemy.name)
    })
    graveyard = []

    // spawn loot
    if (Math.random() * 1000 <= 1) this.spawnLoot()

    playerObject.movePlayer()

    itemCollision(playerObject, localState.loot)
    enemyCollision(playerObject, graveyard)
    mapTransition(player, playerObject, 'spaceState')
  },

  spawnLoot() {
    localState.loot[lootGeneratedCounter++] = new Loot(this.game, 'Item', { x: Math.random() * 1920, y: Math.random() * 1080 }, 'item')
  }
}

export default fantasyState
<commit_msg>Update fantasyState.js<commit_after>import { collisionArrayStatus, GamePlayers, GameEnemies, socket } from '../sockets'
import loadMaps from './utils/loadMaps'
import createMap from './utils/createMap'
import makeCollisionMap from './utils/makeCollisionMap'
import createPlayer from './utils/createPlayer'
import enemyCollision from './utils/enemyCollision'
import mapTransition from './utils/mapTransition'
import itemCollision from './utils/itemCollision'
import playerClass from '../classes/Player'
import Loot from '../classes/Loot'

/* global StackQuest, Phaser */

let map
  , playerObject
  , player
  , graveyard = []
  , lootGeneratedCounter = 0

// TODO get rid of this (put in sockets) ?
const localState = {
  loot: []
}

const fantasyState = {
  init(character) {
    if (character) player = character
  },

  preload() {
    loadMaps.fantasy()
  },

  create() {
    this.physics.startSystem(Phaser.Physics.ARCADE)

    map = createMap.fantasy()

    socket.emit('setupState', player, 'fantasyState')

    playerObject = createPlayer(player)

    if (!collisionArrayStatus) {
      makeCollisionMap(map)
    }

    // this.spawnLoot()

    this.physics.setBoundsToWorld(true, true, true, true, false)

    StackQuest.game.input.onDown.add(() => playerObject.attack())
  },

  update() {
    StackQuest.game.physics.arcade.collide(playerObject, StackQuest.game.layers.collisions)
    StackQuest.game.physics.arcade.collide(playerObject, StackQuest.game.layers.collisions_2)

    graveyard.forEach(enemy => {
      enemy.destroy()
      socket.emit('killEnemy', enemy.name)
    })
    graveyard = []

    // spawn loot
    if (Math.random() * 1000 <= 1) this.spawnLoot()

    playerObject.movePlayer()

    itemCollision(playerObject, localState.loot)
    enemyCollision(playerObject, graveyard, localState.loot)
    mapTransition(player, playerObject, 'spaceState')
  },

  spawnLoot() {
    localState.loot[lootGeneratedCounter++] = new Loot(this.game, 'Item', { x: Math.random() * 1920, y: Math.random() * 1080 }, 'item')
  }
}

export default fantasyState
<|endoftext|>


<commit_before>// adapted from Jim W's code: http://stackoverflow.com/a/17494943
// change layout based on amount of Y scroll
var minimizeTriggerPosition=-1;

function moveThings() {
    // video position is used as reference point
    var vid = document.getElementById('video-frame');

    // desktop view involves moving around lots of things
    if(window.innerWidth > 960) {
        var minimizeTrigger = document.getElementById('phoneme-explanation');
        var videoLimitElement = document.getElementById('whats-next');
        var videoLimit = findPosY(videoLimitElement) - 700;

        // adjust top margin to TfCS header position (header stops being fixed at 1242px)
        var marginTop;
        if(window.innerWidth > 1242){
            marginTop = 125;
        }else{
            marginTop = 75;
        }

        if(minimizeTriggerPosition<0)minimizeTriggerPosition=findPosY(minimizeTrigger);

        if(pageYOffset>minimizeTriggerPosition-300){
            $('#video-navigation').addClass('minimized');
            $('#video-frame').addClass('minimized');
            $('#video').addClass('minimized');
            $('.entry-content').addClass('shifted');
            vid.style.top=marginTop+'px';
            if(pageYOffset>videoLimit){
                vid.style.top=(marginTop-pageYOffset+videoLimit)+'px';
            }
        }else{
            $('#video-navigation').removeClass('minimized');
            $('#video-frame').removeClass('minimized');
            $('#video').removeClass('minimized');
            $('.entry-content').removeClass('shifted');
            vid.style.top=0;
        }
    }else{
        // mobile view is much simpler
        if(pageYOffset>vid.offsetTop){
            $('.video-navigation-mobile').addClass('minimized');
        }else{
            $('.video-navigation-mobile').removeClass('minimized');
        }

        // things need to be reset when window shrinks from desktop view to mobile view
        $('#video-navigation').removeClass('minimized');
        $('#video-frame').removeClass('minimized');
        $('#video').removeClass('minimized');
        $('.entry-content').removeClass('shifted');
        vid.style.top=0;

    }
}

// function snapToExercise() {
//     var exercises = document.getElementsByClassName("exercise");
//     for (var i = 0; i < exercises.length; i++) {
//         if (Math.abs(pageYOffset - exercises[i].offsetTop) < 100) {
//             $('html, body').animate({
//                 scrollTop: exercises[i].offsetTop
//             }, 500, function() {});
//         }
//     }
// }

window.onscroll=function(){
    moveThings();
    // setTimeout(function() {
    //     snapToExercise();
    // }, 200);
};

window.onresize=function(){
    moveThings();
};

function findPosY(obj) {
    var curtop = 0;
    if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

// add current page's title (which should be the phoneme) to navigation menu
$(document).ready(function() {
    $('#phoneme').html(document.title);
    $('a[href$="#in-words"]').html(document.title + ' ' + $('a[href$="#in-words"]').html())
    $('a[href$="#in-sentences"]').html(document.title + ' ' + $('a[href$="#in-sentences"]').html())
    $(".help-text").toggleClass('display-none');
    setTimeout(function() {
        $(".help-text").toggleClass('display-none');
    }, 2000);

    $('.playback-slow').on('click', function(e) {
        document.getElementById('video').playbackRate = 0.5;
        document.getElementById('video').play();
        $('.playback-slow').css("font-weight", "bold")
        $('.playback-normal').css("font-weight", "normal")
        return false;
    });
    $('.playback-normal').on('click', function() {
        document.getElementById('video').playbackRate = 1;
        document.getElementById('video').play();
        $('.playback-slow').css("font-weight", "normal")
        $('.playback-normal').css("font-weight", "bold")
        return false;
    });
    $('.playback-normal').css("font-weight", "bold")
});

<commit_msg>some spans trigger button transform<commit_after>// adapted from Jim W's code: http://stackoverflow.com/a/17494943
// change layout based on amount of Y scroll
var minimizeTriggerPosition=-1;

function moveThings() {
    // video position is used as reference point
    var vid = document.getElementById('video-frame');

    // desktop view involves moving around lots of things
    if(window.innerWidth > 960) {
        var minimizeTrigger = document.getElementById('phoneme-explanation');
        var videoLimitElement = document.getElementById('whats-next');
        var videoLimit = findPosY(videoLimitElement) - 700;

        // adjust top margin to TfCS header position (header stops being fixed at 1242px)
        var marginTop;
        if(window.innerWidth > 1242){
            marginTop = 125;
        }else{
            marginTop = 75;
        }

        if(minimizeTriggerPosition<0)minimizeTriggerPosition=findPosY(minimizeTrigger);

        if(pageYOffset>minimizeTriggerPosition-300){
            $('#video-navigation').addClass('minimized');
            $('#video-frame').addClass('minimized');
            $('#video').addClass('minimized');
            $('.entry-content').addClass('shifted');
            vid.style.top=marginTop+'px';
            if(pageYOffset>videoLimit){
                vid.style.top=(marginTop-pageYOffset+videoLimit)+'px';
            }
        }else{
            $('#video-navigation').removeClass('minimized');
            $('#video-frame').removeClass('minimized');
            $('#video').removeClass('minimized');
            $('.entry-content').removeClass('shifted');
            vid.style.top=0;
        }
    }else{
        // mobile view is much simpler
        if(pageYOffset>vid.offsetTop){
            $('.video-navigation-mobile').addClass('minimized');
        }else{
            $('.video-navigation-mobile').removeClass('minimized');
        }

        // things need to be reset when window shrinks from desktop view to mobile view
        $('#video-navigation').removeClass('minimized');
        $('#video-frame').removeClass('minimized');
        $('#video').removeClass('minimized');
        $('.entry-content').removeClass('shifted');
        vid.style.top=0;

    }
}

// function snapToExercise() {
//     var exercises = document.getElementsByClassName("exercise");
//     for (var i = 0; i < exercises.length; i++) {
//         if (Math.abs(pageYOffset - exercises[i].offsetTop) < 100) {
//             $('html, body').animate({
//                 scrollTop: exercises[i].offsetTop
//             }, 500, function() {});
//         }
//     }
// }

window.onscroll=function(){
    moveThings();
    // setTimeout(function() {
    //     snapToExercise();
    // }, 200);
};

window.onresize=function(){
    moveThings();
};

function findPosY(obj) {
    var curtop = 0;
    if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

// add current page's title (which should be the phoneme) to navigation menu
$(document).ready(function() {
    $('#phoneme').html(document.title);
    $('a[href$="#in-words"]').html(document.title + ' ' + $('a[href$="#in-words"]').html())
    $('a[href$="#in-sentences"]').html(document.title + ' ' + $('a[href$="#in-sentences"]').html())
    $(".help-text").toggleClass('display-none');
    setTimeout(function() {
        $(".help-text").toggleClass('display-none');
    }, 2000);

    $('.playback-slow').on('click', function(e) {
        document.getElementById('video').playbackRate = 0.5;
        document.getElementById('video').play();
        $('.playback-slow').css("font-weight", "bold")
        $('.playback-normal').css("font-weight", "normal")
        return false;
    });
    $('.playback-normal').on('click', function() {
        document.getElementById('video').playbackRate = 1;
        document.getElementById('video').play();
        $('.playback-slow').css("font-weight", "normal")
        $('.playback-normal').css("font-weight", "bold")
        return false;
    });
    $('.playback-normal').css("font-weight", "bold")

    $('.trigger-hover').hover(function(e) {
        $('.recorder').css("transform", "scale(1.1)");
        setTimeout(function(){$('.recorder').css("transform", "scale(1)");}, 300);
    });
});

<|endoftext|>