<commit_before>#import "contrib/tuneup_js/tuneup.js";
#import "buildArtifacts/environment.js"
// these are here so that everything just imports from Common.js
#import "Config.js";
#import "AppMap.js";
#import "Automator.js";
#import "Bridge.js";
#import "contrib/mechanic.js";

var target = UIATarget.localTarget();
var mainWindow = target.frontMostApp().mainWindow();

function delay(seconds) {
    target.delay(seconds);
}

function getTime() {
    var output = target.host().performTaskWithPathArgumentsTimeout("/bin/date", ["+%s"], 5);
    return parseInt(output.stdout);
}

function isMatchingVersion(input, prefix, major, minor, rev) {
    var findStr = prefix + major;

    if (undefined !== minor) {
        findStr += "." + minor;
        if (undefined !== rev) {
            findStr += "." + rev;
        }
    }

    return input.indexOf(findStr) > -1;
}

function isSimVersion(major, minor, rev) {
    return isMatchingVersion(target.systemVersion(), "", major, minor, rev);
}

function assertDesiredSimVersion() {
    var ver = target.systemVersion();
    if (("iOS " + ver).indexOf(config.automatorDesiredSimVersion) == -1) {
        throw "Simulator version " + ver + " is running, but generated-config.js " +
            "specifies " + config.automatorDesiredSimVersion;
    }
}

// for compatibility with iOS 6 that doesn't name cells, buttons, etc
function getNamedItemFromContainer(itemContainerView,
                                   itemArrayAccessor,
                                   itemMatchPredicate,
                                   itemSelector,
                                   name) {

    var items = itemArrayAccessor(itemContainerView);
    for (var i = 0; i < items.length; ++i) {
        var item = items[i];
        if (itemMatchPredicate(item)) return itemSelector(item);
    }

    return null;
}

function getNamedCellFromContainer(cellContainerView, name) {
    var ret = getNamedItemFromContainer(cellContainerView,
                                        function(c) { return c.cells(); },
                                        function(i) {
                                            var ii = i.elements()[0];
                                            return ii.isNotNil() && ii.name() == name;
                                        },
                                        function(i) { return i.elements()[0]; },
                                        name);
    return ret !== null ? ret : cellContainerView.cells().firstWithName(name).elements().firstWithName(name);
}

function dumpElements(elements) {
    for (var i in elements) {
        UIALogger.logDebug(elements[i].toString());
    }
}

// given a UI element accessor function, throw an error if the element's existence
//   doesn't match what the expectedVisibility was.  "name" is for logging purposes
function verifyUIElementVisibility(name, targetAccessorFn, expectedVisibility, timeout) {
    timeout = timeout === undefined ? 1 : timeout;
    var visibility;
    try {
        var theItem = target.waitUntilAccessorSuccess(targetAccessorFn, timeout, name);
        theItem.waitUntilVisible(timeout);
        visibility = true;
    } catch (e) {
        visibility = false;
    }

    if (expectedVisibility != visibility) {
        throw ("''" + name + "'' has visiblity '" + visibility +
               "' but expected '" + expectedVisibility + "'");
    }
}

// given a UI element accessor function, throw an error if the element's editabilty
//   doesn't match what the editabilty (keyboard use) was.  "name" is for logging purposes
function verifyUIElementEditability(name, targetAccessorFn, expectedEditability) {

    var editability;
    try {
        var theItem = target.waitUntilAccessorSuccess(targetAccessorFn, 1, name);
        theItem.tap();

        target.frontMostApp().keyboard().waitUntilVisible(2);
        editability = true;
    } catch (e) {
        editability = false;
    }

    if (expectedEditability != editability) {
        throw ("''" + name + "'' has edit-ability '" + editability +
               "' but expected '" + expectedEditability + "'");
    }

}

function mkActionForItemVisibility(name, targetAccessorFn) {
    return function(parm) {
        return verifyUIElementVisibility(name, targetAccessorFn, parm.expected);
    };
}

function mkActionForItemEditability(name, targetAccessorFn) {
    return function(parm) {
        return verifyUIElementEditability(name, targetAccessorFn, parm.expected);
    };
}

function mkActionForNavbarButton(navbar_name, button_name) {
    return function () {
        var button;
        var triesLeft = 2;
        while (triesLeft > 0) {
            triesLeft--;
            button = target.waitUntilAccessorSuccess(function(targ) {
                    if (navbar_name) {
                        return targ.frontMostApp().mainWindow().navigationBars()[navbar_name].buttons()[button_name];
                    } else {
                        return targ.frontMostApp().mainWindow().navigationBar().buttons()[button_name];
                    }
                }, 10, "'" + button_name + "' button in navbar of '" + navbar_name);
            button.waitUntilVisible(5);
            try {
                button.tap();
                return;
            } catch (e) {
                if (triesLeft > 0) {
                    UIALogger.logDebug("Error tapping (will retry) " + button_name + " in " + navbar_name + ": " + e);
                } else {
                    throw e;
                }
            }
        }
    }
}

function makeActionForVisibilityWithSelector(description, selector) {
    return function (param) {
        if (typeof(selector) === "function") {
            selector = selector(param);
        }
        verifyUIElementVisibility(description, function (targ) {
            var elts = $(selector);
            if (elts && elts.length) { return elts[0]; }
            return null;
        }, param.expected);
    };
}

function makeActionForPredicateOnElement(description, selector, predicate) {
    return function (param) {
        if (typeof(selector) === "function") {
            selector = selector(param);
        }
        verifyUIElementVisibility(description, function (targ) {
            var elts = $(selector);
            if (elts && elts.length) { return elts[0]; }
            return null;
        }, true);
        if (!predicate($(selector)[0], param)) {
            throw new Error("Predicate " + description + " did not match " + selector);
        }
    };
}

function makeActionForTapWithSelector(description, selector) {
    return function () {
        verifyUIElementVisibility(description, function (targ) {
            var elts = $(selector);
            if (elts && elts.length) { return elts[0]; }
            return null;
        }, true);
        $(selector).tap();
    }
}

function makeActionToEnterTextWithSelector(description, elementKey) {
    return function (param) {
        $(elementKey).input(param.text);
    }
}

function getPlistData(path) {

    var jsonOutput;
    var scriptPath = automatorRoot + "/scripts/plist_to_json.sh";
    UIALogger.logDebug("Running " + scriptPath + " '" + path + "'");

    var output = target.host().performTaskWithPathArgumentsTimeout(scriptPath, [path], 30);
    try {
        jsonOutput = JSON.parse(output.stdout);
    } catch(e) {
        throw ("plist_to_json.sh gave bad JSON: ```" + output.stdout + "```");
    }

    return jsonOutput;
}

function actionCompareScreenshotToTemplate(parm) {
    var templatePath = parm.templatePath;
    var captureTitle = parm.captureTitle;

    var diff_pngPath = automatorRoot + "/scripts/diff_png.rb";
    UIATarget.localTarget().captureScreenWithName(captureTitle);

    screenshotDir  = automatorRoot + "/buildArtifacts/UIAutomationReport/Run 1"; // it's always Run 1
    screenshotFile = captureTitle + ".png";
    screenshotPath = screenshotDir + "/" + screenshotFile;
    comparePngPath = screenshotDir + "/compared_" + screenshotFile;
    compareGifPath = screenshotDir + "/compared_" + captureTitle + ".gif";

    UIALogger.logDebug("Diffing images, this may take tens of seconds: " + templatePath + " :: " + screenshotPath);
    var output = target.host().performTaskWithPathArgumentsTimeout("/usr/bin/ruby",
                                                                   [diff_pngPath, templatePath, screenshotPath, comparePngPath],
                                                                   120);

    // turn the output into key/value pairs separated by ":"
    var outputArr = output.stdout.split("\n");
    var outputObj = {};
    for (var i = 0; i < outputArr.length; ++i) {
        var sp = outputArr[i].split(": ", 2)
        if (sp.length == 2) {
            outputObj[sp[0]] = sp[1];
        }
    }

    // sanity check
    if (!outputObj["pixels changed"]) throw "actionCompareScreenshotToTemplate: diff_png.rb failed to produce 'pixels changed' output";

    // if output has no differences, return
    var wrongPixels = parseInt(outputObj["pixels changed"]);
    if (0 == wrongPixels) return;

    // generate an animated gif of the changes
    var output = target.host().performTaskWithPathArgumentsTimeout("/usr/local/bin/convert",
                                                                   ["-delay", "50",
                                                                    templatePath, screenshotPath,
                                                                    "-loop", "0",
                                                                    compareGifPath],
                                                                   120);

    throw ["Screenshot differed from", templatePath,
           "by", wrongPixels, "pixels. ",
           "Comparison image saved to:", comparePngPath,
           " and comparison animation saved to:", compareGifPath].join(" ");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Appmap additions - common capabilities
////////////////////////////////////////////////////////////////////////////////////////////////////
appmap.createOrAugmentApp("ios-automator").withScreen("do")
    .onDevice("iPhone", function() { return true; })
    .onDevice("iPad", function() { return true; })

    .withAction("delay", "Delay a given amount of time")
    .withParam("seconds", "Number of seconds to delay", true, true)
    .withImplementation(function(parm) {delay(parm.seconds);})

    .withAction("debug", "Print the results of a debug function")
    .withParam("debug_fn", "Function returning a string", true)
    .withImplementation(function(parm) { UIALogger.logMessage(parm.debug_fn()); })

    .withAction("logTree", "Log the UI element tree")
    .withImplementation(function() { UIATarget.localTarget().logElementTree(); })

    .withAction("fail", "Unconditionally fail the current test for debugging purposes")
    .withImplementation(function() { throw "purposely-thrown exception to halt the test scenario"; })

    .withAction("verifyScreenshot", "Validate a screenshot against a png template of the expected view")
    .withParam("templatePath", "The path to the file that is considered the 'expected' view", true, true)
    .withParam("captureTitle", "The title of the screenshot to capture", true, true)
    .withImplementation(actionCompareScreenshotToTemplate);
<commit_msg>must wait for animations to settle before taking screenshot<commit_after>#import "contrib/tuneup_js/tuneup.js";
#import "buildArtifacts/environment.js"
// these are here so that everything just imports from Common.js
#import "Config.js";
#import "AppMap.js";
#import "Automator.js";
#import "Bridge.js";
#import "contrib/mechanic.js";

var target = UIATarget.localTarget();
var mainWindow = target.frontMostApp().mainWindow();

function delay(seconds) {
    target.delay(seconds);
}

function getTime() {
    var output = target.host().performTaskWithPathArgumentsTimeout("/bin/date", ["+%s"], 5);
    return parseInt(output.stdout);
}

function isMatchingVersion(input, prefix, major, minor, rev) {
    var findStr = prefix + major;

    if (undefined !== minor) {
        findStr += "." + minor;
        if (undefined !== rev) {
            findStr += "." + rev;
        }
    }

    return input.indexOf(findStr) > -1;
}

function isSimVersion(major, minor, rev) {
    return isMatchingVersion(target.systemVersion(), "", major, minor, rev);
}

function assertDesiredSimVersion() {
    var ver = target.systemVersion();
    if (("iOS " + ver).indexOf(config.automatorDesiredSimVersion) == -1) {
        throw "Simulator version " + ver + " is running, but generated-config.js " +
            "specifies " + config.automatorDesiredSimVersion;
    }
}

// for compatibility with iOS 6 that doesn't name cells, buttons, etc
function getNamedItemFromContainer(itemContainerView,
                                   itemArrayAccessor,
                                   itemMatchPredicate,
                                   itemSelector,
                                   name) {

    var items = itemArrayAccessor(itemContainerView);
    for (var i = 0; i < items.length; ++i) {
        var item = items[i];
        if (itemMatchPredicate(item)) return itemSelector(item);
    }

    return null;
}

function getNamedCellFromContainer(cellContainerView, name) {
    var ret = getNamedItemFromContainer(cellContainerView,
                                        function(c) { return c.cells(); },
                                        function(i) {
                                            var ii = i.elements()[0];
                                            return ii.isNotNil() && ii.name() == name;
                                        },
                                        function(i) { return i.elements()[0]; },
                                        name);
    return ret !== null ? ret : cellContainerView.cells().firstWithName(name).elements().firstWithName(name);
}

function dumpElements(elements) {
    for (var i in elements) {
        UIALogger.logDebug(elements[i].toString());
    }
}

// given a UI element accessor function, throw an error if the element's existence
//   doesn't match what the expectedVisibility was.  "name" is for logging purposes
function verifyUIElementVisibility(name, targetAccessorFn, expectedVisibility, timeout) {
    timeout = timeout === undefined ? 1 : timeout;
    var visibility;
    try {
        var theItem = target.waitUntilAccessorSuccess(targetAccessorFn, timeout, name);
        theItem.waitUntilVisible(timeout);
        visibility = true;
    } catch (e) {
        visibility = false;
    }

    if (expectedVisibility != visibility) {
        throw ("''" + name + "'' has visiblity '" + visibility +
               "' but expected '" + expectedVisibility + "'");
    }
}

// given a UI element accessor function, throw an error if the element's editabilty
//   doesn't match what the editabilty (keyboard use) was.  "name" is for logging purposes
function verifyUIElementEditability(name, targetAccessorFn, expectedEditability) {

    var editability;
    try {
        var theItem = target.waitUntilAccessorSuccess(targetAccessorFn, 1, name);
        theItem.tap();

        target.frontMostApp().keyboard().waitUntilVisible(2);
        editability = true;
    } catch (e) {
        editability = false;
    }

    if (expectedEditability != editability) {
        throw ("''" + name + "'' has edit-ability '" + editability +
               "' but expected '" + expectedEditability + "'");
    }

}

function mkActionForItemVisibility(name, targetAccessorFn) {
    return function(parm) {
        return verifyUIElementVisibility(name, targetAccessorFn, parm.expected);
    };
}

function mkActionForItemEditability(name, targetAccessorFn) {
    return function(parm) {
        return verifyUIElementEditability(name, targetAccessorFn, parm.expected);
    };
}

function mkActionForNavbarButton(navbar_name, button_name) {
    return function () {
        var button;
        var triesLeft = 2;
        while (triesLeft > 0) {
            triesLeft--;
            button = target.waitUntilAccessorSuccess(function(targ) {
                    if (navbar_name) {
                        return targ.frontMostApp().mainWindow().navigationBars()[navbar_name].buttons()[button_name];
                    } else {
                        return targ.frontMostApp().mainWindow().navigationBar().buttons()[button_name];
                    }
                }, 10, "'" + button_name + "' button in navbar of '" + navbar_name);
            button.waitUntilVisible(5);
            try {
                button.tap();
                return;
            } catch (e) {
                if (triesLeft > 0) {
                    UIALogger.logDebug("Error tapping (will retry) " + button_name + " in " + navbar_name + ": " + e);
                } else {
                    throw e;
                }
            }
        }
    }
}

function makeActionForVisibilityWithSelector(description, selector) {
    return function (param) {
        if (typeof(selector) === "function") {
            selector = selector(param);
        }
        verifyUIElementVisibility(description, function (targ) {
            var elts = $(selector);
            if (elts && elts.length) { return elts[0]; }
            return null;
        }, param.expected);
    };
}

function makeActionForPredicateOnElement(description, selector, predicate) {
    return function (param) {
        if (typeof(selector) === "function") {
            selector = selector(param);
        }
        verifyUIElementVisibility(description, function (targ) {
            var elts = $(selector);
            if (elts && elts.length) { return elts[0]; }
            return null;
        }, true);
        if (!predicate($(selector)[0], param)) {
            throw new Error("Predicate " + description + " did not match " + selector);
        }
    };
}

function makeActionForTapWithSelector(description, selector) {
    return function () {
        verifyUIElementVisibility(description, function (targ) {
            var elts = $(selector);
            if (elts && elts.length) { return elts[0]; }
            return null;
        }, true);
        $(selector).tap();
    }
}

function makeActionToEnterTextWithSelector(description, elementKey) {
    return function (param) {
        $(elementKey).input(param.text);
    }
}

function getPlistData(path) {

    var jsonOutput;
    var scriptPath = automatorRoot + "/scripts/plist_to_json.sh";
    UIALogger.logDebug("Running " + scriptPath + " '" + path + "'");

    var output = target.host().performTaskWithPathArgumentsTimeout(scriptPath, [path], 30);
    try {
        jsonOutput = JSON.parse(output.stdout);
    } catch(e) {
        throw ("plist_to_json.sh gave bad JSON: ```" + output.stdout + "```");
    }

    return jsonOutput;
}

function actionCompareScreenshotToTemplate(parm) {
    var templatePath = parm.templatePath;
    var captureTitle = parm.captureTitle;

    delay(0.4); // wait for any animations to settle

    var diff_pngPath = automatorRoot + "/scripts/diff_png.rb";
    UIATarget.localTarget().captureScreenWithName(captureTitle);

    screenshotDir  = automatorRoot + "/buildArtifacts/UIAutomationReport/Run 1"; // it's always Run 1
    screenshotFile = captureTitle + ".png";
    screenshotPath = screenshotDir + "/" + screenshotFile;
    comparePngPath = screenshotDir + "/compared_" + screenshotFile;
    compareGifPath = screenshotDir + "/compared_" + captureTitle + ".gif";

    UIALogger.logDebug("Diffing images, this may take tens of seconds: " + templatePath + " :: " + screenshotPath);
    var output = target.host().performTaskWithPathArgumentsTimeout("/usr/bin/ruby",
                                                                   [diff_pngPath, templatePath, screenshotPath, comparePngPath],
                                                                   120);

    // turn the output into key/value pairs separated by ":"
    var outputArr = output.stdout.split("\n");
    var outputObj = {};
    for (var i = 0; i < outputArr.length; ++i) {
        var sp = outputArr[i].split(": ", 2)
        if (sp.length == 2) {
            outputObj[sp[0]] = sp[1];
        }
    }

    // sanity check
    if (!outputObj["pixels changed"]) throw "actionCompareScreenshotToTemplate: diff_png.rb failed to produce 'pixels changed' output";

    // if output has no differences, return
    var wrongPixels = parseInt(outputObj["pixels changed"]);
    if (0 == wrongPixels) return;

    // generate an animated gif of the changes
    var output = target.host().performTaskWithPathArgumentsTimeout("/usr/local/bin/convert",
                                                                   ["-delay", "50",
                                                                    templatePath, screenshotPath,
                                                                    "-loop", "0",
                                                                    compareGifPath],
                                                                   120);

    throw ["Screenshot differed from", templatePath,
           "by", wrongPixels, "pixels. ",
           "Comparison image saved to:", comparePngPath,
           " and comparison animation saved to:", compareGifPath].join(" ");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Appmap additions - common capabilities
////////////////////////////////////////////////////////////////////////////////////////////////////
appmap.createOrAugmentApp("ios-automator").withScreen("do")
    .onDevice("iPhone", function() { return true; })
    .onDevice("iPad", function() { return true; })

    .withAction("delay", "Delay a given amount of time")
    .withParam("seconds", "Number of seconds to delay", true, true)
    .withImplementation(function(parm) {delay(parm.seconds);})

    .withAction("debug", "Print the results of a debug function")
    .withParam("debug_fn", "Function returning a string", true)
    .withImplementation(function(parm) { UIALogger.logMessage(parm.debug_fn()); })

    .withAction("logTree", "Log the UI element tree")
    .withImplementation(function() { UIATarget.localTarget().logElementTree(); })

    .withAction("fail", "Unconditionally fail the current test for debugging purposes")
    .withImplementation(function() { throw "purposely-thrown exception to halt the test scenario"; })

    .withAction("verifyScreenshot", "Validate a screenshot against a png template of the expected view")
    .withParam("templatePath", "The path to the file that is considered the 'expected' view", true, true)
    .withParam("captureTitle", "The title of the screenshot to capture", true, true)
    .withImplementation(actionCompareScreenshotToTemplate);
<|endoftext|>


<commit_before>/*
 *
 * AssignmentListPage
 *
 */

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import styled from 'styled-components';
import selectAssignmentListPage from './selectors';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
import { setAppbar } from '../Header/actions';

import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn }
  from 'material-ui/Table';

import RaisedButton from 'material-ui/RaisedButton';

const tableData = [
  {
    name: 'Team Building',
    status: 'Expired',
    selected: true,
  },
  {
    name: 'Requirement Analysis',
    status: 'In Progress',
  },
  {
    name: 'Meeting',
    status: 'In Progress',
    selected: true,
  },
  {
    name: 'Presentation',
    status: 'Unpublished',
  },
];

export class AssignmentListPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    setAppbar: React.PropTypes.func,
  }
  constructor(props) {
    super(props);

    this.state = {
      fixedHeader: true,
      fixedFooter: true,
      stripedRows: false,
      showRowHover: false,
      selectable: true,
      multiSelectable: false,
      enableSelectAll: false,
      deselectOnClickaway: true,
      showCheckboxes: true,
      height: '300px',
    };
  }

  componentDidMount() {
    this.props.setAppbar({
      title: <FormattedMessage {...messages.header} />,
    });
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled,
    });
  };

  handleChange = (event) => {
    this.setState({ height: event.target.value });
  };

  render() {
    const ClassesContainer = styled.div`
      width: 100%;
      margin-top: 16px;
      display: flex;
      flex-wrap: wrap;
    `;

    const HeaderContainer = styled.div`
      display: flex;
      justify-content: space-between;
    `;
    const StyledButton = styled(RaisedButton)`
      margin: 16px;
    `;

    return (

        <Helmet
          title="Assignments"
          meta={[
            { name: 'description', content: 'Description of AssignmentListPage' },
          ]}
        />
        <ClassesContainer>

              <TableHeader
                displaySelectAll={this.state.showCheckboxes}
                adjustForCheckbox={this.state.showCheckboxes}
                enableSelectAll={this.state.enableSelectAll}
              >
                <TableRow>
                  <TableHeaderColumn colSpan="3" tooltip="Super Header">
                    <HeaderContainer>

Assignments


<commit_before>'use strict';

function draw_logic(){
    for(let object in world){
        canvas_setproperties({
          'properties': {
            'fillStyle': world[object][4],
          },
        });
        canvas_buffer.fillRect(
          world[object][0],
          world[object][1],
          world[object][2],
          world[object][3]
        );
    }
    for(let object in scenery){
        canvas_draw_path({
          'properties': {
            'fillStyle': scenery[object]['color'],
          },
          'translate': true,
          'vertices': scenery[object]['vertices'],
          'x': scenery[object]['x'],
          'y': scenery[object]['y'],
        });
    }
}

function logic(){
    for(let object in scenery){
        scenery[object]['x'] -= core_storage_data['speed'];

        if(scenery[object]['x'] > -100
          || scenery[object]['color'] === '#be6400'){
            continue;
        }

        let new_x = canvas_properties['width'] + core_random_integer({
          'max': canvas_properties['width'],
        });
        let new_y = core_random_integer({
          'max': canvas_properties['height'],
        });

        while(new_y > -80 + canvas_properties['height-half']
          && new_y < 80 + canvas_properties['height-half']){
            new_y = core_random_integer({
              'max': canvas_properties['height'],
            });
        }

        scenery[object]['x'] = new_x;
        scenery[object]['y'] = new_y;
        scenery[object - 1]['x'] = new_x;
        scenery[object - 1]['y'] = new_y + 25;
    }
}

function repo_init(){
    core_repo_init({
      'globals': {
        'scenery': [],
        'world': [],
      },
      'storage': {
        'speed': 4,
        'trees': 6,
      },
      'storage-menu': '

<input id=speed>Speed'
        + '
<input id=trees>Trees
',
      'title': 'Trains-2D.htm',
    });
    canvas_init();

    canvas_properties['clearColor'] = '#141';
}

function resize_logic(){
    world.length = 0;
    world = [
      [0, canvas_properties['height-half'] - 40, canvas_properties['width'], 80, '#432'],
      [0, canvas_properties['height-half'] + 10, canvas_properties['width'], 4, '#444'],
      [0, canvas_properties['height-half'] - 14, canvas_properties['width'], 4, '#444'],
      [canvas_properties['width-half'] - 310, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] - 100, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] + 110, canvas_properties['height-half'] - 30, 200, 60, '#555'],
    ];
    scenery.length = 0;
    let loop_counter = core_storage_data['trees'] - 1;
    do{
        prefabs_canvas_tree_2d({
          'id': loop_counter,
          'x': -canvas_properties['width'],
        });
    }while(loop_counter--);
}
<commit_msg>replaced some let with const<commit_after>'use strict';

function draw_logic(){
    for(const object in world){
        canvas_setproperties({
          'properties': {
            'fillStyle': world[object][4],
          },
        });
        canvas_buffer.fillRect(
          world[object][0],
          world[object][1],
          world[object][2],
          world[object][3]
        );
    }
    for(const object in scenery){
        canvas_draw_path({
          'properties': {
            'fillStyle': scenery[object]['color'],
          },
          'translate': true,
          'vertices': scenery[object]['vertices'],
          'x': scenery[object]['x'],
          'y': scenery[object]['y'],
        });
    }
}

function logic(){
    for(const object in scenery){
        scenery[object]['x'] -= core_storage_data['speed'];

        if(scenery[object]['x'] > -100
          || scenery[object]['color'] === '#be6400'){
            continue;
        }

        let new_x = canvas_properties['width'] + core_random_integer({
          'max': canvas_properties['width'],
        });
        let new_y = core_random_integer({
          'max': canvas_properties['height'],
        });

        while(new_y > -80 + canvas_properties['height-half']
          && new_y < 80 + canvas_properties['height-half']){
            new_y = core_random_integer({
              'max': canvas_properties['height'],
            });
        }

        scenery[object]['x'] = new_x;
        scenery[object]['y'] = new_y;
        scenery[object - 1]['x'] = new_x;
        scenery[object - 1]['y'] = new_y + 25;
    }
}

function repo_init(){
    core_repo_init({
      'globals': {
        'scenery': [],
        'world': [],
      },
      'storage': {
        'speed': 4,
        'trees': 6,
      },
      'storage-menu': '

<input id=speed>Speed'
        + '
<input id=trees>Trees
',
      'title': 'Trains-2D.htm',
    });
    canvas_init();

    canvas_properties['clearColor'] = '#141';
}

function resize_logic(){
    world.length = 0;
    world = [
      [0, canvas_properties['height-half'] - 40, canvas_properties['width'], 80, '#432'],
      [0, canvas_properties['height-half'] + 10, canvas_properties['width'], 4, '#444'],
      [0, canvas_properties['height-half'] - 14, canvas_properties['width'], 4, '#444'],
      [canvas_properties['width-half'] - 310, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] - 100, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] + 110, canvas_properties['height-half'] - 30, 200, 60, '#555'],
    ];
    scenery.length = 0;
    let loop_counter = core_storage_data['trees'] - 1;
    do{
        prefabs_canvas_tree_2d({
          'id': loop_counter,
          'x': -canvas_properties['width'],
        });
    }while(loop_counter--);
}
<|endoftext|>


<commit_before>'use strict';

/*
 * powertransporter is used to get power from the destroyed power bank
 *
 * Moves to the power and brings it back to the storage and destroys itself.
 */

roles.powertransporter = {};
roles.powertransporter.settings = {
  layoutString: 'MC',
  maxLayoutAmount: 20,
  fillTough: true,
};

roles.powertransporter.action = function(creep) {
  if (creep.memory.reverse) {
    creep.log('reversing');
  }
  if (creep.carry.energy) {
    creep.drop(RESOURCE_ENERGY);
  }

  if (creep.memory.reverse && creep.inBase()) {
    creep.log('Fill storage');
    creep.moveToMy(creep.room.storage);
    const returnCode = creep.transfer(creep.room.storage, RESOURCE_POWER);
    if (returnCode === OK) {
      creep.memory.target = creep.memory.old_target;
      creep.suicide();
    }
    return true;
  }

  const getResource = function(creep) {
    if (creep.carry.power > 0) {
      creep.log(creep.memory.route[creep.memory.route.length - 2].room);
      const exitDirection = creep.room.findExitTo(creep.memory.route[creep.memory.route.length - 2].room);
      const nextExits = creep.room.find(exitDirection);
      const nextExit = nextExits[Math.floor(nextExits.length / 2)];
      creep.moveTo(nextExit);
      return true;
    }
    const powerBank = creep.room.findPropertyFilter(FIND_STRUCTURES, 'structureType', [STRUCTURE_POWER_BANK]);
    if (powerBank.length > 0) {
      const range = creep.pos.getRangeTo(powerBank[0]);
      if (range > 3) {
        creep.moveTo(powerBank[0]);
      }
      return true;
    }

    const resource = creep.pos.findClosestByRangePropertyFilter(FIND_DROPPED_RESOURCES, 'resourceType', [RESOURCE_POWER]);
    if (resource === null) {
      if (creep.carry.power > 0) {
        return false;
      } else {
        creep.moveTo(25, 25);
        return false;
      }
    }

    creep.moveTo(resource, {
      ignoreCreeps: true,
    });
    const returnCode = creep.pickup(resource);
    if (returnCode === OK) {
      creep.memory.reverse = true;
    }
    return true;
  };

  getResource();
  return true;
};

roles.powertransporter.execute = function(creep) {
  creep.log('Execute!!!');
};
<commit_msg>Update role_powertransporter.js<commit_after>'use strict';

/*
 * powertransporter is used to get power from the destroyed power bank
 *
 * Moves to the power and brings it back to the storage and destroys itself.
 */

roles.powertransporter = {};
roles.powertransporter.settings = {
  layoutString: 'MC',
  maxLayoutAmount: 20,
  fillTough: true,
};

roles.powertransporter.action = function(creep) {
  if (creep.memory.reverse) {
    creep.log('reversing');
  }
  if (creep.carry.energy) {
    creep.drop(RESOURCE_ENERGY);
  }

  if (creep.memory.reverse && creep.inBase()) {
    creep.log('Fill storage');
    creep.moveToMy(creep.room.storage);
    const returnCode = creep.transfer(creep.room.storage, RESOURCE_POWER);
    if (returnCode === OK) {
      creep.memory.target = creep.memory.old_target;
      creep.suicide();
    }
    return true;
  }

  const getResource = function(creep) {
    if (creep.carry.power > 0) {
      creep.log(creep.memory.route[creep.memory.route.length - 2].room);
      const exitDirection = creep.room.findExitTo(creep.memory.route[creep.memory.route.length - 2].room);
      const nextExits = creep.room.find(exitDirection);
      const nextExit = nextExits[Math.floor(nextExits.length / 2)];
      creep.moveTo(nextExit);
      return true;
    }
    const powerBank = creep.room.findPropertyFilter(FIND_STRUCTURES, 'structureType', [STRUCTURE_POWER_BANK]);
    if (powerBank.length > 0) {
      const range = creep.pos.getRangeTo(powerBank[0]);
      if (range > 3) {
        creep.moveTo(powerBank[0]);
      }
      return true;
    }

    const resource = creep.pos.findClosestByRangePropertyFilter(FIND_DROPPED_RESOURCES, 'resourceType', [RESOURCE_POWER]);
    if (resource === null) {
      if (creep.carry.power > 0) {
        return false;
      } else {
        creep.moveTo(25, 25);
        return false;
      }
    }

    creep.moveTo(resource, {
      ignoreCreeps: true,
    });
    const returnCode = creep.pickup(resource);
    if (returnCode === OK) {
      creep.memory.reverse = true;
    }
    return true;
  };

  getResource(creep);
  return true;
};

roles.powertransporter.execute = function(creep) {
  creep.log('Execute!!!');
};
<|endoftext|>


<commit_before>var npm = require('npm'),
    vow = require('vow'),
    vowNode = require('vow-node'),
    childProcess = require('child_process'),
    version = process.argv.slice(2)[0] || 'patch';

vowNode.invoke(childProcess.exec, 'git pull')
    .then(function() {
        vowNode.invoke(npm.load);
    })
    .then(function(npm) {
        return vow.all([
            vowNode.invoke(npm.commands.runScript, ['build-lib']),
            vowNode.invoke(npm.commands.runScript, ['build-dist'])
        ]).then(function() {
            return vowNode.invoke(npm.commands.version, [version]);
        }).then(function() {
            return vowNode.invoke(childProcess.exec, 'git push --follow-tags');
        }).then(function() {
            return vowNode.invoke(npm.commands.publish);
        });
    })
    .done();
<commit_msg>add missed "return"<commit_after>var npm = require('npm'),
    vow = require('vow'),
    vowNode = require('vow-node'),
    childProcess = require('child_process'),
    version = process.argv.slice(2)[0] || 'patch';

vowNode.invoke(childProcess.exec, 'git pull')
    .then(function() {
        return vowNode.invoke(npm.load);
    })
    .then(function(npm) {
        return vow.all([
            vowNode.invoke(npm.commands.runScript, ['build-lib']),
            vowNode.invoke(npm.commands.runScript, ['build-dist'])
        ]).then(function() {
            return vowNode.invoke(npm.commands.version, [version]);
        }).then(function() {
            return vowNode.invoke(childProcess.exec, 'git push --follow-tags');
        }).then(function() {
            return vowNode.invoke(npm.commands.publish);
        });
    })
    .done();
<|endoftext|>


<commit_before>function queryObj() {
	var result = {}, queryString = location.search.slice(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	return result;
}

(function () {

	Logo = {
	};

	Logo.randomColor = function() {
		var color = ''
		for(var i = 0; i < 3; i++) {
			var r = Math.floor(Math.random() * 15);
			color += r < 9 ? r : String.fromCharCode(65 + r - 9);
		}
		return color;
	};

	Logo.queryObj = new queryObj();

	Logo.backStyles = new Array('blank', 'striped', 'diag', 'exed', 'habs', 'roundel', 'dots');
	Logo.fontFamilies = new Array("Calibri", "Times New Roman", "Comic Sans MS", "Palatino Linotype", "Arial", "Helvetica", "Tahoma");

	Logo.letters = new Array();
		if(Logo.queryObj.letters) {
			Logo.letters = Logo.queryObj.letters.split("|");
		} else {
			var letterLength = 1 + Math.floor(Math.random() * 2);
			for(var i = 0; i < letterLength; i++) {
				Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
			}
		}
		Logo.backColor = Logo.queryObj.backColor ? Logo.queryObj.backColor : Logo.randomColor();
		Logo.fontColor = Logo.queryObj.fontColor ? Logo.queryObj.fontColor : Logo.randomColor();
		Logo.fontStroke = Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor;
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.stripeColor = Logo.queryObj.stripeColor ? Logo.queryObj.stripeColor : Logo.randomColor();
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : (Logo.letters.length > 1? (Math.random() * 50) : 0);
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];

	Logo.url = 'http://' + window.location.hostname +
		'/?backColor=' + Logo.backColor +
		'&fontColor=' + Logo.fontColor +
		'&fontStroke=' + Logo.fontStroke +
		'&backStyle=' + Logo.backStyle +
		'&stripeColor=' + Logo.stripeColor +
		'&letters=' + Logo.letters.join('|') +
		'&offsetX=' + Logo.offsetX +
		'&fontFamily=' + encodeURIComponent(Logo.fontFamily);

	Logo.kinetic = {}; // All kinetic object references go in here

	Logo.kinetic.stage = new Kinetic.Stage( {
		container: 'logo',
		width: Logo.queryObj.width? Logo.queryObj.width : 275, //Math.min(window.innerWidth, window.innerHeight),
		height: Logo.queryObj.height? Logo.queryObj.height : 275 //Math.min(window.innerWidth, window.innerHeight)
	});

	Logo.kinetic.layer = new Kinetic.Layer();

	Logo.kinetic.wrapper = new Kinetic.Rect( {
		x:0,
		y:0,
		width: Logo.kinetic.stage.getWidth(),
		height: Logo.kinetic.stage.getHeight(),
		fill: '#' + Logo.backColor
	});

	Logo.kinetic.layer.add(Logo.kinetic.wrapper);

	Logo.kinetic.stripes = new Array();

	if(Logo.backStyle == 'striped') {
		for(var i = 0; i < 2; i++) {
			var x = (i % 2 == 0)? Logo.kinetic.stage.getWidth() * .2 : Logo.kinetic.stage.getWidth() - (Logo.kinetic.stage.getWidth() * .2);
			var stripe = new Kinetic.Line({
				points: [ x, 0, x, Logo.kinetic.stage.getHeight() ],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .1
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'diag' || Logo.backStyle == 'exed') {
		var count = Logo.backStyle == 'diag' ? 1 : 2;
		for(var i = 0; i < count; i++) {
			var stripe = new Kinetic.Line({
				points: (i % 2 == 0) ? [0, 0, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()] : [0, Logo.kinetic.stage.getHeight(), Logo.kinetic.stage.getWidth(), 0],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .2
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'habs') {
		var stripe = new Kinetic.Line({
			points: [0, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight() * .5],
			stroke: '#' + Logo.stripeColor,
			strokeWidth: Logo.kinetic.stage.getWidth() * .25
		});
		Logo.kinetic.stripes.push(stripe);
		Logo.kinetic.layer.add(stripe);
	}
	if(Logo.backStyle == 'roundel') {
		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			fill: '#' + Logo.stripeColor,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .2
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);

		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			strokeWidth: Logo.kinetic.stage.getWidth() * .15,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .4,
			stroke: '#' + Logo.stripeColor
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);
	}
	if(Logo.backStyle == 'dots') {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				var circle = new Kinetic.Circle({
					x: (Logo.kinetic.stage.getWidth() / 3*( i )) + ((j%2) * Logo.kinetic.stage.getWidth()/6),
					y: Logo.kinetic.stage.getHeight() / 3 * (j ),
					radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .1,
					fill: '#' + Logo.stripeColor
				});
				Logo.kinetic.stripes.push(circle);
				Logo.kinetic.layer.add(circle);
			}
		}
	}
	Logo.kinetic.letters = new Array();
	for(var i = Logo.letters.length-1; i >= 0; i--) {
		var y = i * Logo.kinetic.stage.getHeight() * .1;
		var x = 0;
		if(Logo.letters.length > 1) {
			x = (i == 0? -1 : 1) * Logo.offsetX * Logo.kinetic.stage.getWidth() / 200;
		}
		if(Logo.letters.length == 2) {
			y  -= Logo.kinetic.stage.getHeight() * (i == 0? .1 : -.02);
		}
		var letter = new Kinetic.Text({
			x: x,
			y: y,
			width: Logo.kinetic.stage.getWidth(),
			fill: '#' + Logo.fontColor,
			fontFamily: Logo.fontFamily,
			fontSize: Logo.kinetic.stage.getHeight() - 25,
			text: Logo.letters[i],
			align: 'center',
			fontStyle: 'bold',
			strokeWidth: 2,
			stroke: '#' + Logo.fontStroke
		});
		Logo.kinetic.letters.push(letter);
		Logo.kinetic.layer.add(letter);
	}

     Logo.kinetic.gloss = new Kinetic.Shape({
		drawFunc: function(canvas) {
			var borderSize = Logo.kinetic.stage.getWidth() * .03;
			var context = canvas.getContext();
			context.beginPath();
			context.moveTo(borderSize, borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize , borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .3);
			context.quadraticCurveTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth() * .5, Logo.kinetic.stage.getHeight() * .5);
			context.quadraticCurveTo(borderSize, Logo.kinetic.stage.getWidth() * .5, borderSize, Logo.kinetic.stage.getWidth() * .6);
			context.closePath();
			canvas.fillStroke(this);
		},
		fill: "f8f8f0",
		opacity: .10
	});

	Logo.kinetic.layer.add(Logo.kinetic.gloss);

	Logo.kinetic.stage.add(Logo.kinetic.layer);

	Logo.kinetic.stage.toDataURL({
		callback: function(dataUrl) {
			query = new queryObj();
			if(query.mode == 'png') {
				pngLogo = new Image();
				pngLogo.src = dataUrl;
				console.log('dataUrl:'+dataUrl);
				$('#logo').replaceWith(pngLogo);
			}
		}
	});

})();<commit_msg>Kinda better gloss?<commit_after>function queryObj() {
	var result = {}, queryString = location.search.slice(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	return result;
}

(function () {

	Logo = {
	};

	Logo.randomColor = function() {
		var color = ''
		for(var i = 0; i < 3; i++) {
			var r = Math.floor(Math.random() * 15);
			color += r < 9 ? r : String.fromCharCode(65 + r - 9);
		}
		return color;
	};

	Logo.queryObj = new queryObj();

	Logo.backStyles = new Array('blank', 'striped', 'diag', 'exed', 'habs', 'roundel', 'dots');
	Logo.fontFamilies = new Array("Calibri", "Times New Roman", "Comic Sans MS", "Palatino Linotype", "Arial", "Helvetica", "Tahoma");

	Logo.letters = new Array();
		if(Logo.queryObj.letters) {
			Logo.letters = Logo.queryObj.letters.split("|");
		} else {
			var letterLength = 1 + Math.floor(Math.random() * 2);
			for(var i = 0; i < letterLength; i++) {
				Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
			}
		}
		Logo.backColor = Logo.queryObj.backColor ? Logo.queryObj.backColor : Logo.randomColor();
		Logo.fontColor = Logo.queryObj.fontColor ? Logo.queryObj.fontColor : Logo.randomColor();
		Logo.fontStroke = Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor;
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.stripeColor = Logo.queryObj.stripeColor ? Logo.queryObj.stripeColor : Logo.randomColor();
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : (Logo.letters.length > 1? (Math.random() * 50) : 0);
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];

	Logo.url = 'http://' + window.location.hostname +
		'/?backColor=' + Logo.backColor +
		'&fontColor=' + Logo.fontColor +
		'&fontStroke=' + Logo.fontStroke +
		'&backStyle=' + Logo.backStyle +
		'&stripeColor=' + Logo.stripeColor +
		'&letters=' + Logo.letters.join('|') +
		'&offsetX=' + Logo.offsetX +
		'&fontFamily=' + encodeURIComponent(Logo.fontFamily);

	Logo.kinetic = {}; // All kinetic object references go in here

	Logo.kinetic.stage = new Kinetic.Stage( {
		container: 'logo',
		width: Logo.queryObj.width? Logo.queryObj.width : 275, //Math.min(window.innerWidth, window.innerHeight),
		height: Logo.queryObj.height? Logo.queryObj.height : 275 //Math.min(window.innerWidth, window.innerHeight)
	});

	Logo.kinetic.layer = new Kinetic.Layer();

	Logo.kinetic.wrapper = new Kinetic.Rect( {
		x:0,
		y:0,
		width: Logo.kinetic.stage.getWidth(),
		height: Logo.kinetic.stage.getHeight(),
		fill: '#' + Logo.backColor
	});

	Logo.kinetic.layer.add(Logo.kinetic.wrapper);

	Logo.kinetic.stripes = new Array();

	if(Logo.backStyle == 'striped') {
		for(var i = 0; i < 2; i++) {
			var x = (i % 2 == 0)? Logo.kinetic.stage.getWidth() * .2 : Logo.kinetic.stage.getWidth() - (Logo.kinetic.stage.getWidth() * .2);
			var stripe = new Kinetic.Line({
				points: [ x, 0, x, Logo.kinetic.stage.getHeight() ],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .1
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'diag' || Logo.backStyle == 'exed') {
		var count = Logo.backStyle == 'diag' ? 1 : 2;
		for(var i = 0; i < count; i++) {
			var stripe = new Kinetic.Line({
				points: (i % 2 == 0) ? [0, 0, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()] : [0, Logo.kinetic.stage.getHeight(), Logo.kinetic.stage.getWidth(), 0],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .2
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'habs') {
		var stripe = new Kinetic.Line({
			points: [0, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight() * .5],
			stroke: '#' + Logo.stripeColor,
			strokeWidth: Logo.kinetic.stage.getWidth() * .25
		});
		Logo.kinetic.stripes.push(stripe);
		Logo.kinetic.layer.add(stripe);
	}
	if(Logo.backStyle == 'roundel') {
		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			fill: '#' + Logo.stripeColor,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .2
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);

		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			strokeWidth: Logo.kinetic.stage.getWidth() * .15,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .4,
			stroke: '#' + Logo.stripeColor
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);
	}
	if(Logo.backStyle == 'dots') {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				var circle = new Kinetic.Circle({
					x: (Logo.kinetic.stage.getWidth() / 3*( i )) + ((j%2) * Logo.kinetic.stage.getWidth()/6),
					y: Logo.kinetic.stage.getHeight() / 3 * (j ),
					radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .1,
					fill: '#' + Logo.stripeColor
				});
				Logo.kinetic.stripes.push(circle);
				Logo.kinetic.layer.add(circle);
			}
		}
	}
	Logo.kinetic.letters = new Array();
	for(var i = Logo.letters.length-1; i >= 0; i--) {
		var y = i * Logo.kinetic.stage.getHeight() * .1;
		var x = 0;
		if(Logo.letters.length > 1) {
			x = (i == 0? -1 : 1) * Logo.offsetX * Logo.kinetic.stage.getWidth() / 200;
		}
		if(Logo.letters.length == 2) {
			y  -= Logo.kinetic.stage.getHeight() * (i == 0? .1 : -.02);
		}
		var letter = new Kinetic.Text({
			x: x,
			y: y,
			width: Logo.kinetic.stage.getWidth(),
			fill: '#' + Logo.fontColor,
			fontFamily: Logo.fontFamily,
			fontSize: Logo.kinetic.stage.getHeight() - 25,
			text: Logo.letters[i],
			align: 'center',
			fontStyle: 'bold',
			strokeWidth: 2,
			stroke: '#' + Logo.fontStroke
		});
		Logo.kinetic.letters.push(letter);
		Logo.kinetic.layer.add(letter);
	}

     Logo.kinetic.gloss = new Kinetic.Shape({
		drawFunc: function(canvas) {
			var borderSize = Logo.kinetic.stage.getWidth() * .03;
			var context = canvas.getContext();
			context.beginPath();
			context.moveTo(borderSize, borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize , borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .3);
			context.quadraticCurveTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth() * .5, Logo.kinetic.stage.getHeight() * .5);
			context.quadraticCurveTo(borderSize, Logo.kinetic.stage.getWidth() * .5, borderSize, Logo.kinetic.stage.getWidth() * .6);
			context.closePath();
			canvas.fillStroke(this);
			// Gradient fill
			var grd = context.createLinearGradient(0, 0, Logo.kinetic.stage.getWidth()/2, Logo.kinetic.stage.getHeight());
			grd.addColorStop(0, '#bbb');
			grd.addColorStop(1, '#f8f8f0');
			context.fillStyle = grd;
			context.fill()

		},
		opacity: .10
	});

	Logo.kinetic.layer.add(Logo.kinetic.gloss);

	Logo.kinetic.stage.add(Logo.kinetic.layer);

	Logo.kinetic.stage.toDataURL({
		callback: function(dataUrl) {
			query = new queryObj();
			if(query.mode == 'png') {
				pngLogo = new Image();
				pngLogo.src = dataUrl;
				console.log('dataUrl:'+dataUrl);
				$('#logo').replaceWith(pngLogo);
			}
		}
	});

})();<|endoftext|>


<commit_before>/*    Copyright 2016-2019 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

let instance = null;

const execSync = require('child_process').execSync;

class PlatformLoader {
  constructor() {
    if (instance === null) {
      instance = this;
    }
    return instance;
  }

  getPlatformName() {
    if (!this.platformName) {
      const uname = execSync("uname -m", {encoding: 'utf8'}).trim();
      this.platformName = uname;
    }

    return this.platformName;
  }

  getBoardName() {
    if (!this.boardName) {
      this.boardName = execSync("awk -F= '/BOARD=/ {print $2}' /etc/firewalla-release",{encoding:'utf8'}).trim();
    }
    return this.boardName
  }

  getPlatform() {
    if (this.platform) {
      return this.platform;
    }

    const uname = this.getPlatformName();

    switch (uname) {
      case "aarch64": {
        const boardName = this.getBoardName();
        switch (boardName) {
          case "navy": {
            const NavyPlatform = require('./navy/NavyPlatform.js');
            this.platform = new NavyPlatform();
            break;
          }
          default: {
            const BluePlatform = require('./blue/BluePlatform.js');
            this.platform = new BluePlatform();
            break;
          }
        }
        break;
      }
      case "armv7l": {
        const RedPlatform = require('./red/RedPlatform.js');
        this.platform = new RedPlatform();
        break;
      }
      case "x86_64": {
        const GoldPlatform = require('./gold/GoldPlatform.js');
        this.platform = new GoldPlatform();
        break;
      }
      default:
        return null;
    }

    return this.platform;
  }
}

module.exports = new PlatformLoader();
<commit_msg>fix error handling for non-existing /etc/firewalla-release case<commit_after>/*    Copyright 2016-2019 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

let instance = null;

const execSync = require('child_process').execSync;

class PlatformLoader {
  constructor() {
    if (instance === null) {
      instance = this;
    }
    return instance;
  }

  getPlatformName() {
    if (!this.platformName) {
      try {
        const uname = execSync("uname -m", {encoding: 'utf8'}).trim();
        this.platformName = uname;
      } catch (err) {
        this.platformName = 'unknown';
      }
    }

    return this.platformName;
  }

  getBoardName() {
    if (!this.boardName) {
      try {
        this.boardName = execSync("awk -F= '/BOARD=/ {print $2}' /etc/firewalla-release",{encoding:'utf8'}).trim();
      } catch (err) {
        this.boardName = 'unknown';
      }
    }
    return this.boardName
  }

  getPlatform() {
    if (this.platform) {
      return this.platform;
    }

    const uname = this.getPlatformName();

    switch (uname) {
      case "aarch64": {
        const boardName = this.getBoardName();
        switch (boardName) {
          case "navy": {
            const NavyPlatform = require('./navy/NavyPlatform.js');
            this.platform = new NavyPlatform();
            break;
          }
          default: {
            const BluePlatform = require('./blue/BluePlatform.js');
            this.platform = new BluePlatform();
            break;
          }
        }
        break;
      }
      case "armv7l": {
        const RedPlatform = require('./red/RedPlatform.js');
        this.platform = new RedPlatform();
        break;
      }
      case "x86_64": {
        const GoldPlatform = require('./gold/GoldPlatform.js');
        this.platform = new GoldPlatform();
        break;
      }
      default:
        return null;
    }

    return this.platform;
  }
}

module.exports = new PlatformLoader();
<|endoftext|>


<commit_before>function keygen(data) {
    value = '\
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.    \n\
; #Warn  ; Enable warnings to assist with detecting common errors.                          \n\
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.    \n\
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.                     \n\
setTitleMatchMode, 2 ; set title match mode to "contains"                                   \n\
\n\n'

    //value = 'test\ncheck'
    // load in data
    //console.log(data)
    for (i in data) {
        //console.log("Key " + i)
        key = ''

        //console.log(data[i])

        if (data[i]['func'] == 'KEY') {
            // hotkey
            if (data[i]['modifiers[]'].includes('CTRL')) {
                key += '^'
            }
            if (data[i]['modifiers[]'].includes('SHIFT')) {
                key += '+'
            }
            if (data[i]['modifiers[]'].includes('ALT')) {
                key += '!'
            }

            key += data[i]['skeyValue']
            key += '::'

            func = "\nreturn";
            option = data[i]['option'];
            if (option == 'Send' || option == 'Replace') { // replace doesn't make sense for hotkey, so treat like send
                func = 'send, ' + data[i]["input"];
            } else if (option == 'ActivateOrOpen') {
                func = 'ActivateOrOpen("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")';
            } else if (option == 'ActivateOrOpenChrome') {
                func = 'ActivateOrOpenChrome("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")';
            } else if (option == 'Custom') {
                func = data[i]['Code']
            } else if (option == 'SendUnicodeChar') {
                func = 'SendUnicodeChar(' + data[i]['input'] + ')';
            }

            key += func
        } else {
            // hotstring
            key += ':*c:' + data[i]['skeyValue'] + "::"

            func = "\nreturn";
            if (option == 'Send') { // replace doesn't make sense for hotkey, so treat like send
                func = '\nsend, ' + data[i]["input"] + '\nreturn';
            } else if (option == 'ActivateOrOpen') {
                func = '\nActivateOrOpen("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")\nreturn';
            } else if (option == 'Replace') {
                func = data[i]["input"];
            } else if (option == 'ActivateOrOpenChrome') {
                func = '\nActivateOrOpenChrome("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")\nreturn';
            } else if (option == 'Custom') {
                func = data[i]['Code']
            } else if (option == 'SendUnicodeChar') {
                func = '\nSendUnicodeChar(' + data[i]['input'] + ')\nreturn';
            }

            key += func
        }

        value += key + "\n\n"
    }
    // append custom functions
    value += 'ActivateOrOpen(window, program)                   \n\
{                                                               \n\
	; check if window exists                                    \n\
	if WinExist(window)                                         \n\
	{                                                           \n\
		WinActivate  ; Uses the last found window.              \n\
	}                                                           \n\
	else                                                        \n\
	{   ; else start requested program                          \n\
		 Run %program%                                          \n\
		 IfWinNotActive, %window%, , WinActivate, %window%      \n\
		 {                                                      \n\
			  WinActivate  ; Uses the last found window.        \n\
		 }                                                      \n\
	}                                                           \n\
	return                                                      \n\
}                                                               \n\
                                                                \n\
ActivateOrOpenChrome(tab, url)                                  \n\
{                                                               \n\
    chrome := "- Google Chrome"                                 \n\
    found := "false"                                            \n\
    tabSearch := tab                                            \n\
    curWinNum := 0                                              \n\
                                                                \n\
    SetTitleMatchMode, 2                                        \n\
    if WinExist(Chrome)                                         \n\
	{                                                           \n\
		WinGet, numOfChrome, Count, %chrome% ; Get the number of chrome windows         \n\
		WinActivateBottom, %chrome% ; Activate the least recent window                  \n\
		WinWaitActive %chrome% ; Wait until the window is active                        \n\
                                                                                \n\
		ControlFocus, Chrome_RenderWidgetHostHWND1 ; Set the focus to tab control ???   \n\
                                                                                \n\
		; Loop until all windows are tried, or until we find it                         \n\
		while (curWinNum < numOfChrome and found = "false") {                           \n\
			WinGetTitle, firstTabTitle, A ; The initial tab title                       \n\
			title := firstTabTitle                                                      \n\
			Loop                                                                        \n\
			{                                                                           \n\
				if(InStr(title, tabSearch)>0){                                          \n\
					found := "true"                                                     \n\
					break                                                               \n\
				}                                                                       \n\
				Send {Ctrl down}{Tab}{Ctrl up}                                          \n\
				Sleep, 50                                                               \n\
				WinGetTitle, title, A  ;get active window title                         \n\
				if(title = firstTabTitle){                                              \n\
					break                                                               \n\
				}                                                                       \n\
			}                                                                           \n\
			WinActivateBottom, %chrome%                                                 \n\
			curWinNum := curWinNum + 1                                                  \n\
		}                                                                               \n\
	}                                                                                \n\
                                                                                \n\
    ; If we did not find it, start it                                                   \n\
    if(found = "false"){                                                                \n\
        Run chrome.exe %url%                                                            \n\
    }                                                                                \n\
	return                                                                              \n\
}                                                                                \n\
                                                                                \n\
SendUnicodeChar(charCode)					                                            \n\
{											                                            \n\
	VarSetCapacity(ki, 28 * 2, 0)			                                            \n\
	EncodeInteger(&ki + 0, 1)				                                            \n\
	EncodeInteger(&ki + 6, charCode)		                                            \n\
	EncodeInteger(&ki + 8, 4)				                                            \n\
	EncodeInteger(&ki +28, 1)				                                            \n\
	EncodeInteger(&ki +34, charCode)		                                            \n\
	EncodeInteger(&ki +36, 4|2)				                                            \n\
											                                            \n\
	DllCall("SendInput", "UInt", 2, "UInt", &ki, "Int", 28)	                            \n\
}											                                            \n\
											                                            \n\
EncodeInteger(ref, val)						                                            \n\
{											                                            \n\
	DllCall("ntdll\\RtlFillMemoryUlong", "Uint", ref, "Uint", 4, "Uint", val)            \n\
}                                                                                \n\
'

    //return script
    return value
}<commit_msg>adding section headers<commit_after>function keygen(data) {
    value = '\
; Header - some configuration                                                               \n\
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.    \n\
; #Warn  ; Enable warnings to assist with detecting common errors.                          \n\
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.    \n\
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.                     \n\
setTitleMatchMode, 2 ; set title match mode to "contains"                                   \n\
\n\n; Configured region - selected functions\n\n'

    //value = 'test\ncheck'
    // load in data
    //console.log(data)
    for (i in data) {
        //console.log("Key " + i)
        key = ''

        //console.log(data[i])

        if (data[i]['func'] == 'KEY') {
            // hotkey
            if (data[i]['modifiers[]'].includes('CTRL')) {
                key += '^'
            }
            if (data[i]['modifiers[]'].includes('SHIFT')) {
                key += '+'
            }
            if (data[i]['modifiers[]'].includes('ALT')) {
                key += '!'
            }

            key += data[i]['skeyValue']
            key += '::'

            func = "\nreturn";
            option = data[i]['option'];
            if (option == 'Send' || option == 'Replace') { // replace doesn't make sense for hotkey, so treat like send
                func = 'send, ' + data[i]["input"];
            } else if (option == 'ActivateOrOpen') {
                func = 'ActivateOrOpen("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")';
            } else if (option == 'ActivateOrOpenChrome') {
                func = 'ActivateOrOpenChrome("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")';
            } else if (option == 'Custom') {
                func = data[i]['Code']
            } else if (option == 'SendUnicodeChar') {
                func = 'SendUnicodeChar(' + data[i]['input'] + ')';
            }

            key += func
        } else {
            // hotstring
            key += ':*c:' + data[i]['skeyValue'] + "::"

            func = "\nreturn";
            if (option == 'Send') { // replace doesn't make sense for hotkey, so treat like send
                func = '\nsend, ' + data[i]["input"] + '\nreturn';
            } else if (option == 'ActivateOrOpen') {
                func = '\nActivateOrOpen("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")\nreturn';
            } else if (option == 'Replace') {
                func = data[i]["input"];
            } else if (option == 'ActivateOrOpenChrome') {
                func = '\nActivateOrOpenChrome("' + data[i]["Window"] + '", "' + data[i]["Program"] + '")\nreturn';
            } else if (option == 'Custom') {
                func = data[i]['Code']
            } else if (option == 'SendUnicodeChar') {
                func = '\nSendUnicodeChar(' + data[i]['input'] + ')\nreturn';
            }

            key += func
        }

        value += key + "\n\n"
    }
    // append custom functions
    value += '\n\n; Provided Functions -\n\nActivateOrOpen(window, program)                   \n\
{                                                               \n\
	; check if window exists                                    \n\
	if WinExist(window)                                         \n\
	{                                                           \n\
		WinActivate  ; Uses the last found window.              \n\
	}                                                           \n\
	else                                                        \n\
	{   ; else start requested program                          \n\
		 Run %program%                                          \n\
		 IfWinNotActive, %window%, , WinActivate, %window%      \n\
		 {                                                      \n\
			  WinActivate  ; Uses the last found window.        \n\
		 }                                                      \n\
	}                                                           \n\
	return                                                      \n\
}                                                               \n\
                                                                \n\
ActivateOrOpenChrome(tab, url)                                  \n\
{                                                               \n\
    chrome := "- Google Chrome"                                 \n\
    found := "false"                                            \n\
    tabSearch := tab                                            \n\
    curWinNum := 0                                              \n\
                                                                \n\
    SetTitleMatchMode, 2                                        \n\
    if WinExist(Chrome)                                         \n\
	{                                                           \n\
		WinGet, numOfChrome, Count, %chrome% ; Get the number of chrome windows         \n\
		WinActivateBottom, %chrome% ; Activate the least recent window                  \n\
		WinWaitActive %chrome% ; Wait until the window is active                        \n\
                                                                                \n\
		ControlFocus, Chrome_RenderWidgetHostHWND1 ; Set the focus to tab control ???   \n\
                                                                                \n\
		; Loop until all windows are tried, or until we find it                         \n\
		while (curWinNum < numOfChrome and found = "false") {                           \n\
			WinGetTitle, firstTabTitle, A ; The initial tab title                       \n\
			title := firstTabTitle                                                      \n\
			Loop                                                                        \n\
			{                                                                           \n\
				if(InStr(title, tabSearch)>0){                                          \n\
					found := "true"                                                     \n\
					break                                                               \n\
				}                                                                       \n\
				Send {Ctrl down}{Tab}{Ctrl up}                                          \n\
				Sleep, 50                                                               \n\
				WinGetTitle, title, A  ;get active window title                         \n\
				if(title = firstTabTitle){                                              \n\
					break                                                               \n\
				}                                                                       \n\
			}                                                                           \n\
			WinActivateBottom, %chrome%                                                 \n\
			curWinNum := curWinNum + 1                                                  \n\
		}                                                                               \n\
	}                                                                                \n\
                                                                                \n\
    ; If we did not find it, start it                                                   \n\
    if(found = "false"){                                                                \n\
        Run chrome.exe "%url%"                                                          \n\
    }                                                                                \n\
	return                                                                              \n\
}                                                                                \n\
                                                                                \n\
SendUnicodeChar(charCode)					                                            \n\
{											                                            \n\
	VarSetCapacity(ki, 28 * 2, 0)			                                            \n\
	EncodeInteger(&ki + 0, 1)				                                            \n\
	EncodeInteger(&ki + 6, charCode)		                                            \n\
	EncodeInteger(&ki + 8, 4)				                                            \n\
	EncodeInteger(&ki +28, 1)				                                            \n\
	EncodeInteger(&ki +34, charCode)		                                            \n\
	EncodeInteger(&ki +36, 4|2)				                                            \n\
											                                            \n\
	DllCall("SendInput", "UInt", 2, "UInt", &ki, "Int", 28)	                            \n\
}											                                            \n\
											                                            \n\
EncodeInteger(ref, val)						                                            \n\
{											                                            \n\
	DllCall("ntdll\\RtlFillMemoryUlong", "Uint", ref, "Uint", 4, "Uint", val)           \n\
}                                                                                \n\
'

    //return script
    return value
}<|endoftext|>


<commit_before>/* tslint:disable: no-console */
const exec = require('shell-utils').exec;
const semver = require('semver');
const fs = require('fs');
const _ = require('lodash');

const ONLY_ON_BRANCH = 'origin/master';
const VERSION_TAG = process.env.RELEASE_BUILD ? 'latest' : 'snapshot';
const VERSION_INC = 'patch';

function run() {
  if (!validateEnv()) {
    return;
  }
  setupGit();
  createNpmRc();
  versionTagAndPublish();
}

function validateEnv() {
  if (!process.env.JENKINS_CI) {
    throw new Error(`releasing is only available from CI`);
  }

  if (!process.env.JENKINS_MASTER) {
    console.log(`not publishing on a different build`);
    return false;
  }

  if (process.env.GIT_BRANCH !== ONLY_ON_BRANCH) {
    console.log(`not publishing on branch ${process.env.GIT_BRANCH}`);
    return false;
  }

  return true;
}

function setupGit() {
  exec.execSyncSilent(`git config --global push.default simple`);
  exec.execSyncSilent(`git config --global user.email "${process.env.GIT_EMAIL}"`);
  exec.execSyncSilent(`git config --global user.name "${process.env.GIT_USER}"`);
  const remoteUrl = new RegExp(`https?://(\\S+)`).exec(exec.execSyncRead(`git remote -v`))[1];
  exec.execSyncSilent(`git remote add deploy "https://${process.env.GIT_USER}:${process.env.GIT_TOKEN}@${remoteUrl}"`);
  exec.execSync(`git checkout ${ONLY_ON_BRANCH}`);
}

function createNpmRc() {
  exec.execSync(`rm -f package-lock.json`);
  const content = `
email=\${NPM_EMAIL}
//registry.npmjs.org/:_authToken=\${NPM_TOKEN}
`;
  fs.writeFileSync(`.npmrc`, content);
}

function versionTagAndPublish() {
  const currentPublished = findCurrentPublishedVersion();
  console.log(`current published version: ${currentPublished}`);
  console.log(`Release ?`, process.env.RELEASE_BUILD);
  console.log(`!Release ?`, !process.env.RELEASE_BUILD);
  console.log(`!!Release ?`, !!process.env.RELEASE_BUILD);
  console.log(`!!!Release ?`, !!!process.env.RELEASE_BUILD);

  const version = process.env.RELEASE_BUILD ? process.env.VERSION : `${currentPublished}-snapshot.${process.env.BUILD_ID}`;
  console.log(`Publishing version: ${version}`);

  tryPublishAndTag(version);
}

function findCurrentPublishedVersion() {
  return exec.execSyncRead(`npm view ${process.env.npm_package_name} dist-tags.latest`);
}

function tryPublishAndTag(version) {
  let theCandidate = version;
  for (let retry = 0; retry < 5; retry++) {
    try {
      tagAndPublish(theCandidate);
      console.log(`Released ${theCandidate}`);
      return;
    } catch (err) {
      const alreadyPublished = _.includes(err.toString(), 'You cannot publish over the previously published version');
      if (!alreadyPublished) {
        throw err;
      }
      console.log(`previously published. retrying with increased ${VERSION_INC}...`);
      theCandidate = semver.inc(theCandidate, VERSION_INC);
    }
  }
}

function tagAndPublish(newVersion) {
  console.log(`trying to publish ${newVersion}...`);
  exec.execSync(`npm --no-git-tag-version version ${newVersion}`);
  exec.execSyncRead(`npm publish --tag ${VERSION_TAG}`);
  exec.execSync(`git tag -a ${newVersion} -m "${newVersion}"`);
  exec.execSyncSilent(`git push deploy ${newVersion} || true`);
}

run();
<commit_msg>Last test release<commit_after>/* tslint:disable: no-console */
const exec = require('shell-utils').exec;
const semver = require('semver');
const fs = require('fs');
const _ = require('lodash');

const ONLY_ON_BRANCH = 'origin/master';
const VERSION_TAG = process.env.RELEASE_BUILD ? 'latest' : 'snapshot';
const VERSION_INC = 'patch';

// Workaround JS
const release = !!!process.env.RELEASE_BUILD;

function run() {
  if (!validateEnv()) {
    return;
  }
  setupGit();
  createNpmRc();
  versionTagAndPublish();
}

function validateEnv() {
  if (!process.env.JENKINS_CI) {
    throw new Error(`releasing is only available from CI`);
  }

  if (!process.env.JENKINS_MASTER) {
    console.log(`not publishing on a different build`);
    return false;
  }

  if (process.env.GIT_BRANCH !== ONLY_ON_BRANCH) {
    console.log(`not publishing on branch ${process.env.GIT_BRANCH}`);
    return false;
  }

  return true;
}

function setupGit() {
  exec.execSyncSilent(`git config --global push.default simple`);
  exec.execSyncSilent(`git config --global user.email "${process.env.GIT_EMAIL}"`);
  exec.execSyncSilent(`git config --global user.name "${process.env.GIT_USER}"`);
  const remoteUrl = new RegExp(`https?://(\\S+)`).exec(exec.execSyncRead(`git remote -v`))[1];
  exec.execSyncSilent(`git remote add deploy "https://${process.env.GIT_USER}:${process.env.GIT_TOKEN}@${remoteUrl}"`);
  exec.execSync(`git checkout ${ONLY_ON_BRANCH}`);
}

function createNpmRc() {
  exec.execSync(`rm -f package-lock.json`);
  const content = `
email=\${NPM_EMAIL}
//registry.npmjs.org/:_authToken=\${NPM_TOKEN}
`;
  fs.writeFileSync(`.npmrc`, content);
}

function versionTagAndPublish() {
  const currentPublished = findCurrentPublishedVersion();
  console.log(`current published version: ${currentPublished}`);
  console.log(`Release ?`, process.env.RELEASE_BUILD);
  console.log(`!Release ?`, !process.env.RELEASE_BUILD);
  console.log(`!!Release ?`, !!process.env.RELEASE_BUILD);
  console.log(`!!!Release ?`, !!!process.env.RELEASE_BUILD);

  const version = release ? process.env.VERSION : `${currentPublished}-snapshot.${process.env.BUILD_ID}`;
  console.log(`Publishing version: ${version}`);

  tryPublishAndTag(version);
}

function findCurrentPublishedVersion() {
  return exec.execSyncRead(`npm view ${process.env.npm_package_name} dist-tags.latest`);
}

function tryPublishAndTag(version) {
  let theCandidate = version;
  for (let retry = 0; retry < 5; retry++) {
    try {
      tagAndPublish(theCandidate);
      console.log(`Released ${theCandidate}`);
      return;
    } catch (err) {
      const alreadyPublished = _.includes(err.toString(), 'You cannot publish over the previously published version');
      if (!alreadyPublished) {
        throw err;
      }
      console.log(`previously published. retrying with increased ${VERSION_INC}...`);
      theCandidate = semver.inc(theCandidate, VERSION_INC);
    }
  }
}

function tagAndPublish(newVersion) {
  console.log(`trying to publish ${newVersion}...`);
  exec.execSync(`npm --no-git-tag-version version ${newVersion}`);
  exec.execSyncRead(`npm publish --tag ${VERSION_TAG}`);
  exec.execSync(`git tag -a ${newVersion} -m "${newVersion}"`);
  exec.execSyncSilent(`git push deploy ${newVersion} || true`);
}

run();
<|endoftext|>


<commit_before>(function(global) {
	global.required = {};
	global.require = function(name) {
		if(!global.required[name]) {
			global.required[name] = null;
			http = new XMLHttpRequest();
			http.open("GET","/modules/"+name+".js",false);
			http.send();
			global.required[name] = new Function(
				"var module=null;\n"+
				"try{\n"+
				http.responseText+
				";\n} catch(exception) {\n"+
				"console.log(exception);\n"+
				"}\n"+
				"return module;"
			);
		}
		return global.required[name]();
	}
	if(document && document.currentScript && document.currentScript.getAttribute("data-after")) {
		var scripts = (document.currentScript.getAttribute('data-after')).split(",");
		var attach = document.currentScript.parentNode;
		for(var count=0;count<scripts.length;count++) {
			var s=document.createElement('script');
			s.setAttribute("src","/scripts/"+scripts[count]+".js");
			attach.appendChild(s);
		}
	}
}(this));
<commit_msg>Update loader.js<commit_after>(function(global) {
	global.required = {};
	global.require = function(name) {
		if(!global.required[name]) {
			global.required[name] = null;
			http = new XMLHttpRequest();
			http.open("GET","/modules/"+name+".js",false);
			http.send();
			global.required[name] = new Function(
				"var module={exports:null};\n"+
				"var exports=module.exports;\n"+
				"try{\n"+
				http.responseText+
				";\n} catch(exception) {\n"+
				"console.log(exception);\n"+
				"}\n"+
				"return module.exports;"
			);
		}
		return global.required[name]();
	}
	if(document && document.currentScript && document.currentScript.getAttribute("data-after")) {
		var scripts = (document.currentScript.getAttribute('data-after')).split(",");
		var attach = document.currentScript.parentNode;
		for(var count=0;count<scripts.length;count++) {
			var s=document.createElement('script');
			s.setAttribute("src","/scripts/"+scripts[count]+".js");
			attach.appendChild(s);
		}
	}
}(this));
<|endoftext|>


<commit_before>game.state.add('menu', { preload:preload, create:create } );
game.state.start('menu');

function preload() {
  game.load.image( 'menu', '/assets/start_button.png')
}

function create() {
  menu = game.add.sprite(0, 380, 'menu');
  menu.inputEnabled = true;
  menu.events.onInputDown.add(startGame, this);
  var ENTER = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
  ENTER.onDown.add(startGame)
}

function startGame () {
  game.state.start('playgame');
}<commit_msg>added client id retention to server<commit_after>var myId=0;
var ready = false;
var eurecaServer;

var eurecaClientSetup = function() {
    //create an instance of eureca.io client
    var eurecaClient = new Eureca.Client();
    eurecaClient.ready(function (proxy) {
        eurecaServer = proxy;
    });
    //methods defined under "exports" namespace become available in the server side
    eurecaClient.exports.setId = function(id) {
        //create() is moved here to make sure nothing is created before uniq id assignation
        myId = id;
        create();
        eurecaServer.handshake();
        ready = true;
    }
    eurecaClient.exports.kill = function(id){
        if (tanksList[id]) {
            tanksList[id].kill();
            console.log('killing ', id, tanksList[id]);
        }
    }
    eurecaClient.exports.spawnEnemy = function(i, x, y){
        if (i == myId) return; //this is me
        console.log('SPAWN');
        var tnk = new Tank(i, game, tank);
        tanksList[i] = tnk;
    }
    eurecaClient.exports.updateState = function(id, state)
    {
        if (tanksList[id])  {
            tanksList[id].cursor = state;
            tanksList[id].tank.x = state.x;
            tanksList[id].tank.y = state.y;
            tanksList[id].tank.angle = state.angle;
            tanksList[id].turret.rotation = state.rot;
            tanksList[id].update();
        }
    }
}

game.state.add('menu', { preload:preload, create:eurecaClientSetup } );
game.state.start('menu');

function preload() {
  game.load.image( 'menu', '/assets/start_button.png')
}

function create() {
  menu = game.add.sprite(0, 380, 'menu');
  menu.inputEnabled = true;
  menu.events.onInputDown.add(startGame, this);
  var ENTER = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
  ENTER.onDown.add(startGame)
}

function startGame () {
  game.state.start('playgame');
}<|endoftext|>


<commit_before>just setting up for now...
<commit_msg>updating with an attempt at chess<commit_after>(function(window){

var initBoard = [
    ['R','N','B','Q','K','B','N','R'],
    ['P','P','P','P','P','P','P','P'],
    [' ',' ',' ',' ',' ',' ',' ',' '],
    [' ',' ',' ',' ',' ',' ',' ',' '],
    [' ',' ',' ',' ',' ',' ',' ',' '],
    [' ',' ',' ',' ',' ',' ',' ',' '],
    ['p','p','p','p','p','p','p','p'],
    ['r','n','b','q','k','b','n','r'] ];

    function move(board.join('\n') + '\n\n') {
      console.log(board.join('\n'));
    }

  function moves([]){

    }

)}(window);

board[1][1] = board[2][1];
board[2][1] = ' ';
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   Ember - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

require("ember-views/system/event_dispatcher");

var get = Ember.get, set = Ember.set;

/**
  @class

  An Ember.Application instance serves as the namespace in which you define your
  application's classes. You can also override the configuration of your
  application.

  By default, Ember.Application will begin listening for events on the document.
  If your application is embedded inside a page, instead of controlling the
  entire document, you can specify which DOM element to attach to by setting
  the `rootElement` property:

      MyApp = Ember.Application.create({
        rootElement: $('#my-app')
      });

  The root of an Ember.Application must not be removed during the course of the
  page's lifetime. If you have only a single conceptual application for the
  entire page, and are not embedding any third-party Ember applications
  in your page, use the default document root for your application.

  You only need to specify the root if your page contains multiple instances
  of Ember.Application.

  @since Ember 2.0
  @extends Ember.Object
*/
Ember.Application = Ember.Namespace.extend(
/** @scope Ember.Application.prototype */{

  /**
    The root DOM element of the Application.

    Can be specified as DOMElement or a selector string.

    @type DOMElement
    @default 'body'
  */
  rootElement: 'body',

  /**
    @type Ember.EventDispatcher
    @default null
  */
  eventDispatcher: null,

  /**
    @type Object
    @default null
  */
  customEvents: null,

  /** @private */
  init: function() {
    var eventDispatcher,
        rootElement = get(this, 'rootElement');
    this._super();

    eventDispatcher = Ember.EventDispatcher.create({
      rootElement: rootElement
    });

    set(this, 'eventDispatcher', eventDispatcher);

    // jQuery 1.7 doesn't call the ready callback if already ready
    if (Ember.$.isReady) {
      this.didBecomeReady();
    } else {
      var self = this;
      Ember.$(document).ready(function() {
        self.didBecomeReady();
      });
    }

    this._super();
  },

  /** @private */
  didBecomeReady: function() {
    var eventDispatcher = get(this, 'eventDispatcher'),
        customEvents    = get(this, 'customEvents');

    eventDispatcher.setup(customEvents);

    this.ready();
  },

  /**
    Called when the Application has become ready.
    The call will be delayed until the DOM has become ready.
  */
  ready: Ember.K,

  /** @private */
  destroy: function() {
    get(this, 'eventDispatcher').destroy();
    return this._super();
  }
});

<commit_msg>remove duplicate call to `this._super()`<commit_after>// ==========================================================================
// Project:   Ember - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

require("ember-views/system/event_dispatcher");

var get = Ember.get, set = Ember.set;

/**
  @class

  An Ember.Application instance serves as the namespace in which you define your
  application's classes. You can also override the configuration of your
  application.

  By default, Ember.Application will begin listening for events on the document.
  If your application is embedded inside a page, instead of controlling the
  entire document, you can specify which DOM element to attach to by setting
  the `rootElement` property:

      MyApp = Ember.Application.create({
        rootElement: $('#my-app')
      });

  The root of an Ember.Application must not be removed during the course of the
  page's lifetime. If you have only a single conceptual application for the
  entire page, and are not embedding any third-party Ember applications
  in your page, use the default document root for your application.

  You only need to specify the root if your page contains multiple instances
  of Ember.Application.

  @since Ember 2.0
  @extends Ember.Object
*/
Ember.Application = Ember.Namespace.extend(
/** @scope Ember.Application.prototype */{

  /**
    The root DOM element of the Application.

    Can be specified as DOMElement or a selector string.

    @type DOMElement
    @default 'body'
  */
  rootElement: 'body',

  /**
    @type Ember.EventDispatcher
    @default null
  */
  eventDispatcher: null,

  /**
    @type Object
    @default null
  */
  customEvents: null,

  /** @private */
  init: function() {
    var eventDispatcher,
        rootElement = get(this, 'rootElement');
    this._super();

    eventDispatcher = Ember.EventDispatcher.create({
      rootElement: rootElement
    });

    set(this, 'eventDispatcher', eventDispatcher);

    // jQuery 1.7 doesn't call the ready callback if already ready
    if (Ember.$.isReady) {
      this.didBecomeReady();
    } else {
      var self = this;
      Ember.$(document).ready(function() {
        self.didBecomeReady();
      });
    }
  },

  /** @private */
  didBecomeReady: function() {
    var eventDispatcher = get(this, 'eventDispatcher'),
        customEvents    = get(this, 'customEvents');

    eventDispatcher.setup(customEvents);

    this.ready();
  },

  /**
    Called when the Application has become ready.
    The call will be delayed until the DOM has become ready.
  */
  ready: Ember.K,

  /** @private */
  destroy: function() {
    get(this, 'eventDispatcher').destroy();
    return this._super();
  }
});

<|endoftext|>