<commit_before>// Copyright (c) 2012 Aaron Roth
// See the file license.txt for copying permission.
//

// ------------------ Globals ------------------ //

// Canvas.
var canvasX = 250;
var canvasY = 250;

// Wheel positioning.
var arc = Math.PI / 18.5;
var context;
var insideRadius = 175;
var outsideRadius = 200;
var startAngle = -89.6;
var textRadius = 184;

// Wheel style and content.
var black = '#000000';
var fontStyle = 'bold 12px sans-serif';
var green = '#006600';
var lineWidth = 2;
var red = '#ff0000';
var white = '#ffffff';
var numbers = ['0', '32', '15', '19', '4', '21', '2', '25', '17', '34', '6',
               '27', '13', '36', '11', '30', '8', '23', '10', '5', '24', '16',
               '33', '1', '20', '14', '31', '9', '22', '18', '29', '7', '28',
               '12', '35', '3', '26'];

// Wheel spinning.
var spinAngle = 0;
var spinAngleStart = 10;
var spinTime = 0;
var spinTimeout = null;
var spinTimeTotal = 0;

// --------------------------------------------- //

$(document).ready(function() {
  $('#start-button').click(start_game);
  $('#spin-button').click(spin);
});

function draw_wheel() {
  var canvas = document.getElementById('wheel');

  // Make sure the browser supports canvas.
  if (canvas.getContext) {
    context = canvas.getContext('2d');
    context.clearRect(0, 0, 500, 500);

    // Set wheel styles.
    context.strokeStyle = black;
    context.lineWidth = lineWidth;
    context.font = fontStyle;

    // Draw entire wheel.
    for (var i = 0; i < 37; i++) {
      var angle = startAngle + i * arc;

      // Set colors.
      if (i == 0) {
        context.fillStyle = green;
      } else if (i % 2 != 0) {
        context.fillStyle = red;
      } else {
        context.fillStyle = black;
      }

      // Draw wheel.
      context.beginPath();
      context.arc(canvasX, canvasY, outsideRadius, angle, angle + arc, false);
      context.arc(canvasX, canvasY, insideRadius, angle + arc, angle, true);
      context.stroke();
      context.fill();
      context.save();

      // Draw numbers on the wheel.
      var text = numbers[i];
      var transX = canvasX + Math.cos(angle + arc / 2) * textRadius;
      var transY = canvasY + Math.sin(angle + arc / 2) * textRadius;
      var rotateVal = angle + arc / 2 + Math.PI / 2;

      context.translate(transX, transY);
      context.rotate(rotateVal);
      context.fillStyle = white;
      context.fillText(text, -context.measureText(text).width / 2, 0);
      context.restore();
    }

    // Draw arrow.
    context.fillStyle = white;
    context.beginPath();
    context.moveTo(250 - 0, 250 - (outsideRadius + 5));
    context.lineTo(250 + 0, 250 - (outsideRadius + 5));
    context.lineTo(250 + 0, 250 - (outsideRadius - 5));
    context.lineTo(250 + 9, 250 - (outsideRadius - 5));
    context.lineTo(250 + 0, 250 - (outsideRadius - 13));
    context.lineTo(250 - 9, 250 - (outsideRadius - 5));
    context.lineTo(250 - 0, 250 - (outsideRadius - 5));
    context.lineTo(250 - 0, 250 - (outsideRadius + 5));
    context.fill();
  } else {
    alert('Your browser does not support this game! ' +
          'Try Safari, Chrome, Firefox, or Opera.');
  }
}

function ease_out(t, b, c, d) {
  var ts = (t /= d) * t;
  var tc = ts * t;

  return b + c * (tc + -3 * ts + 3 * t);
}

function rotate_wheel() {
  spinTime += 30;

  if (spinTime >= spinTimeTotal) {
    stop_wheel();
  } else {
    spinAngle = spinAngleStart -
                ease_out(spinTime, 0, spinAngleStart, spinTimeTotal);

    startAngle += spinAngle * Math.PI / 180;
    draw_wheel();
    spinTimeout = setTimeout('rotate_wheel()', 30);
  }
}

function spin() {
  spinAngleStart = Math.random() * 10 + 10;
  spinTime = 0;
  spinTimeTotal = (Math.random() * 10 + 2) * 1000;
  rotate_wheel();
}

function start_game() {
  var startBank = $('#starting-bank').val();
  var minBet = $('#min-bet').val();
  var maxBet = $('#max-bet').val();

  $('#form').fadeOut(100, 'linear', function() {
    $('#form').remove();
  });
  $('#title').fadeOut(100, 'linear', function() {
    $('#title').remove();
  });

  $('#game-board').fadeIn(100, 'linear');
  draw_wheel();
}

function stop_wheel() {
  clearTimeout(spinTimeout);

  var degrees = startAngle * (-1) * 180 / Math.PI + 90;
  var arcDegrees = arc * 180 / Math.PI;
  var index = Math.floor((360 - degrees % 360) / arcDegrees);
  context.save();
  var winningNumber = numbers[index];
}<commit_msg>determining number choice working<commit_after>// Copyright (c) 2012 Aaron Roth
// See the file license.txt for copying permission.
//
// This code is based on and at times copied verbatim from a tutorial
// written by Charlie Key. His tutorial is hosted on www.switchonthecode.com
// and is titled "Creating a Roulette Wheel Using HTML5 Canvas."
//

// ------------------ Globals ------------------ //

// Canvas.
var canvasX = 250;
var canvasY = 250;

// Wheel positioning.
var arc = Math.PI / 18.5;
var context;
var insideRadius = 175;
var outsideRadius = 200;
var startAngle = 1.5 * Math.PI;
var textRadius = 184;

// Wheel style and content.
var black = '#000000';
var fontStyle = 'bold 12px sans-serif';
var green = '#006600';
var lineWidth = 2;
var red = '#ff0000';
var white = '#ffffff';
var numbers = ['0', '32', '15', '19', '4', '21', '2', '25', '17', '34', '6',
               '27', '13', '36', '11', '30', '8', '23', '10', '5', '24', '16',
               '33', '1', '20', '14', '31', '9', '22', '18', '29', '7', '28',
               '12', '35', '3', '26'];

// Wheel spinning.
var spinAngle = 0;
var spinAngleStart = 0;
var spinTime = 0;
var spinTimeout = null;
var spinTimeTotal = 0;

// --------------------------------------------- //

$(document).ready(function() {
  $('#start-button').click(start_game);
  $('#spin-button').click(spin);
});

function draw_wheel() {
  var canvas = document.getElementById('wheel');

  // Make sure the browser supports canvas.
  if (canvas.getContext) {
    context = canvas.getContext('2d');
    context.clearRect(0, 0, 500, 500);

    // Set wheel styles.
    context.strokeStyle = black;
    context.lineWidth = lineWidth;
    context.font = fontStyle;

    // Draw entire wheel.
    for (var i = 0; i < 37; i++) {
      var angle = startAngle + i * arc;

      // Set colors.
      if (i == 0) {
        context.fillStyle = green;
      } else if (i % 2 != 0) {
        context.fillStyle = red;
      } else {
        context.fillStyle = black;
      }

      // Draw wheel.
      context.beginPath();
      context.arc(canvasX, canvasY, outsideRadius, angle, angle + arc, false);
      context.arc(canvasX, canvasY, insideRadius, angle + arc, angle, true);
      context.stroke();
      context.fill();
      context.save();

      // Draw numbers on the wheel.
      var text = numbers[i];
      var transX = canvasX + Math.cos(angle + arc / 2) * textRadius;
      var transY = canvasY + Math.sin(angle + arc / 2) * textRadius;
      var rotateVal = angle + arc / 2 + Math.PI / 2;

      context.translate(transX, transY);
      context.rotate(rotateVal);
      context.fillStyle = white;
      context.fillText(text, -context.measureText(text).width / 2, 0);
      context.restore();
    }

    // Draw arrow.
    context.fillStyle = white;
    context.beginPath();
    context.moveTo(250 - 0, 250 - (outsideRadius + 5));
    context.lineTo(250 + 0, 250 - (outsideRadius + 5));
    context.lineTo(250 + 0, 250 - (outsideRadius - 5));
    context.lineTo(250 + 9, 250 - (outsideRadius - 5));
    context.lineTo(250 + 0, 250 - (outsideRadius - 13));
    context.lineTo(250 - 9, 250 - (outsideRadius - 5));
    context.lineTo(250 - 0, 250 - (outsideRadius - 5));
    context.lineTo(250 - 0, 250 - (outsideRadius + 5));
    context.fill();
  } else {
    alert('Your browser does not support this game! ' +
          'Try Safari, Chrome, Firefox, or Opera.');
  }
}

function ease_out(t, b, c, d) {
  var ts = (t /= d) * t;
  var tc = ts * t;

  return b + c * (tc + -3 * ts + 3 * t);
}

function rotate_wheel() {
  spinTime += 30;

  if (spinTime >= spinTimeTotal) {
    stop_wheel();
  } else {
    spinAngle = spinAngleStart -
                ease_out(spinTime, 0, spinAngleStart, spinTimeTotal);

    startAngle += spinAngle * Math.PI / 180;
    draw_wheel();
    spinTimeout = setTimeout('rotate_wheel()', 30);
  }
}

function spin() {
  spinAngleStart = Math.random() * 10 + 10;
  spinTime = 0;
  spinTimeTotal = (Math.random() * 10 + 2) * 1000;
  rotate_wheel();
}

function start_game() {
  var startBank = $('#starting-bank').val();
  var minBet = $('#min-bet').val();
  var maxBet = $('#max-bet').val();

  $('#form').fadeOut(100, 'linear', function() {
    $('#form').remove();
  });
  $('#title').fadeOut(100, 'linear', function() {
    $('#title').remove();
  });

  $('#game-board').fadeIn(100, 'linear');
  draw_wheel();
}

function stop_wheel() {
  clearTimeout(spinTimeout);

  // Calculate what number the ball landed on.
  var radiansSpun = startAngle - (1.5 * Math.PI);
  var unitsSpun = radiansSpun / arc;
  var number = Math.ceil((unitsSpun % 37));
  if (number == 0) {
    number = 37;
  }
  var index = 37 - number;
  context.save();
  var winningNumber = numbers[index];
  alert('The winning number is ' + winningNumber + '!');
}<|endoftext|>


<commit_before>if (require('electron-squirrel-startup')) return
const child_process = require('child_process')
const fs = require('fs')
const http = require('http')
const path = require('path')
const urlJoin = require('url-join')

const electron = require('electron')
const rp = require('request-promise')
const {app, BrowserWindow} = electron

const {addMenu} = require('./menu.js')
const {getLogger} = require('./logging.js')
const {initAutoUpdater} = require('./updater.js')
const {ServerManager} = require('./servermanager.js')
const {PythonEnvManager} = require('./envmanager.js')
const {waitUntilServerResponds} = require('./util.js')

let serverManager = new ServerManager()
let pythonEnvManager = new PythonEnvManager()
let mainWindow
let pyRunProcess

const STATIC_ASSETS_BASE_URL = process.env.STATIC_ASSETS_BASE_URL || 'https://s3.amazonaws.com/ot-app-builds/'
const STATIC_ASSETS_BRANCH = process.env.STATIC_ASSETS_BRANCH || 'stable'
const STATIC_ASSETS_URL = urlJoin(STATIC_ASSETS_BASE_URL, STATIC_ASSETS_BRANCH)

if (process.env.NODE_ENV === 'development'){
  require('electron-debug')({showDevTools: 'undocked'});
}

function createWindow (windowUrl) {
  mainWindow = new BrowserWindow({width: 1060, height: 750})
  mainWindow.loadURL(windowUrl)
  mainWindow.on('closed', function () {
    mainWindow = null
    app.quit()
  })
}

function createAndSetAppDataDir () {
  if (!app.isReady()) {
    throw Error('Attempting to create otone_data dir when app is not ready')
  }
  const appDataDir = path.join(app.getPath('userData'), 'otone_data')

  if (!fs.existsSync(appDataDir)) {
    fs.mkdirSync(appDataDir)
  }
  process.env['APP_DATA_DIR'] = appDataDir
}

function spawnProcess(cp, file, args, options) {
  cp = child_process.spawn(file, args, options)
  cp.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
  });
  cp.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
  });
  cp.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
  });
}

app.on('python-env-ready', function () {
  console.log('Run pip update')
  let envLoc = pythonEnvManager.getEnvAppDataDirPath()
  let pyRunScript = path.join(envLoc, 'pyrun.sh')
  let wheelNameFile = urlJoin(STATIC_ASSETS_URL, 'whl-name')

  rp(wheelNameFile).then(wheelName => {
    console.log(`Found: "${wheelName}"`)
    let wheelNameURIEncoded = encodeURIComponent(wheelName.trim())
    spawnProcess(pyRunProcess, pyRunScript, [STATIC_ASSETS_BASE_URL + wheelNameURIEncoded], {cwd: envLoc})
  })
})

function startUp () {
  // Prepare app data dir (necessary for logging errors that occur during setup)
  createAndSetAppDataDir()

  const mainLogger = getLogger('electron-main')
  process.on('uncaughtException', (error) => {
    if (process.listeners('uncaughtException').length > 1) {
      console.log(error)
      mainLogger.info(error)
    }
  })
  if (process.env.NODE_ENV === 'development') {
    require('vue-devtools').install()
  }

  // Startup Actions
  pythonEnvManager.setupEnvironment()
  // serverManager.start()
  let _createWindow = () => {
    return createWindow('http://s3.amazonaws.com/ot-app-builds/assets/stable/index.html')
  }
  waitUntilServerResponds(_createWindow, 'http://localhost:31950/robot/serial/list')
  addMenu()
  initAutoUpdater()
}

app.on('ready', startUp)

app.on('quit', function () {
  serverManager.shutdown()
  child_process.spawnSync(
    'pkill',
    ['-9', path.basename(pyRunProcess.serverProcess.spawnfile)]
  )
})
<commit_msg>url join wheel address<commit_after>if (require('electron-squirrel-startup')) return
const child_process = require('child_process')
const fs = require('fs')
const http = require('http')
const path = require('path')
const urlJoin = require('url-join')

const electron = require('electron')
const rp = require('request-promise')
const {app, BrowserWindow} = electron

const {addMenu} = require('./menu.js')
const {getLogger} = require('./logging.js')
const {initAutoUpdater} = require('./updater.js')
const {ServerManager} = require('./servermanager.js')
const {PythonEnvManager} = require('./envmanager.js')
const {waitUntilServerResponds} = require('./util.js')

let serverManager = new ServerManager()
let pythonEnvManager = new PythonEnvManager()
let mainWindow
let pyRunProcess

const STATIC_ASSETS_BASE_URL = process.env.STATIC_ASSETS_BASE_URL || 'https://s3.amazonaws.com/ot-app-builds/'
const STATIC_ASSETS_BRANCH = process.env.STATIC_ASSETS_BRANCH || 'stable'
const STATIC_ASSETS_URL = urlJoin(STATIC_ASSETS_BASE_URL, STATIC_ASSETS_BRANCH)

if (process.env.NODE_ENV === 'development'){
  require('electron-debug')({showDevTools: 'undocked'});
}

function createWindow (windowUrl) {
  mainWindow = new BrowserWindow({width: 1060, height: 750})
  mainWindow.loadURL(windowUrl)
  mainWindow.on('closed', function () {
    mainWindow = null
    app.quit()
  })
}

function createAndSetAppDataDir () {
  if (!app.isReady()) {
    throw Error('Attempting to create otone_data dir when app is not ready')
  }
  const appDataDir = path.join(app.getPath('userData'), 'otone_data')

  if (!fs.existsSync(appDataDir)) {
    fs.mkdirSync(appDataDir)
  }
  process.env['APP_DATA_DIR'] = appDataDir
}

function spawnProcess(cp, file, args, options) {
  cp = child_process.spawn(file, args, options)
  cp.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
  });
  cp.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
  });
  cp.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
  });
}

app.on('python-env-ready', function () {
  console.log('Run pip update')
  let envLoc = pythonEnvManager.getEnvAppDataDirPath()
  let pyRunScript = path.join(envLoc, 'pyrun.sh')
  let wheelNameFile = urlJoin(STATIC_ASSETS_URL, 'whl-name')

  rp(wheelNameFile).then(wheelName => {
    console.log(`Found: "${wheelName}"`)
    let wheelNameURIEncoded = encodeURIComponent(wheelName.trim())
    spawnProcess(pyRunProcess, pyRunScript, [urlJoin(STATIC_ASSETS_URL, wheelNameURIEncoded)], {cwd: envLoc})
  })
})

function startUp () {
  // Prepare app data dir (necessary for logging errors that occur during setup)
  createAndSetAppDataDir()

  const mainLogger = getLogger('electron-main')
  process.on('uncaughtException', (error) => {
    if (process.listeners('uncaughtException').length > 1) {
      console.log(error)
      mainLogger.info(error)
    }
  })
  if (process.env.NODE_ENV === 'development') {
    require('vue-devtools').install()
  }

  // Startup Actions
  pythonEnvManager.setupEnvironment()
  // serverManager.start()
  let _createWindow = () => {
    return createWindow('http://s3.amazonaws.com/ot-app-builds/assets/stable/index.html')
  }
  waitUntilServerResponds(_createWindow, 'http://localhost:31950/robot/serial/list')
  addMenu()
  initAutoUpdater()
}

app.on('ready', startUp)

app.on('quit', function () {
  serverManager.shutdown()
  child_process.spawnSync(
    'pkill',
    ['-9', path.basename(pyRunProcess.serverProcess.spawnfile)]
  )
})
<|endoftext|>


<commit_before>
var $arrayToString= function( value, options ) {
    return '[ ' + value.$array.map(function(v) { return valueToString(v, options); } ).join(', ') + ' ]';
};

var $rangeToString= function( value, options ) {
    return 'From: ' + valueToString(value.$range.from, options)
        + ' To: '   + valueToString(value.$range.to, options)
        + ' Step: ' + valueToString(value.$range.step, options);
};

var pad= function( value ) {
    return +value < 10 ? "0" + value : String(value);
};
var dateToString= function( value, options ) {
    return pad(value.getUTCDate()) + '.' + pad(value.getUTCMonth() + 1) + '.' + value.getUTCFullYear();
};
var timeToString= function( value, options ) {
    return pad(value.getHours()) + ':' + pad(value.getMinutes()) + ':' + pad(value.getSeconds());
};

var locationToString= function( value, options ) {
    var result= 'lat(' + value[1] + ')/lon(' + value[0] + ')';

    if ( options && 'locationFn' in options ) {
        var locationFn= typeof options.locationFn === 'function' ? options.locationFn : defaultLocationFn;
        return locationFn(result, value);
    }

    return result;
};

var getObject= {
    'Model': SpongeTools.getCachedData('getModel'),
    'AgroObj': SpongeTools.getCachedData('getAgroObject'),
};

var dataObjectToString= function( value, options ) {
    var collection= value.$ref;
    var id= (value.selector || {})._id;

    var name;
    if ( collection in getObject && id ) {
        var object= getObject[collection](id);
        if ( object ) name= object.name;
    }
    if ( !name ) name= valueToString(id);

    if ( collection === 'AgroObj' ) return name;

    return collection + ' ' + name;
};

var selectorToString= function( sel ) {
    if ( !sel ) return '';

    var result= '';
    var simpleVersion= 'objectType' in sel && 'version' in sel;
    if ( simpleVersion ) {
        var version= sel.version;
        if ( typeof version === 'object' && '$in' in version ) {
            version= '[' + version.$in.join(',') + ']';
        }
        result+= sel.objectType + '/' + version;
    }
    var args= [];
    for ( var prop in sel ) {
        if ( simpleVersion && (prop === 'objectType' || prop === 'version') ) continue;

        args.push(prop + '="' + valueToString(sel[prop]) + '"');
    }
    if ( args.length ) {
        result+= ' (' + args.join(', ') + ')';
    }
    return result;
};

var mapToString= function( value, options ) {
    return 'Map ' + selectorToString(value.selector);
};

var nearestToString= function( value, options ) {
    return 'Nearest ' + selectorToString(value.selector);
};

var arrayToString= function( value, options ) {
    if ( !value.length ) return '<empty Array>';

    var keys;
    var table= true;
    for ( var i in value ) {
        var v= value[i];
        if ( typeof v !== 'object' ) {
            table= false;
            break;
        };
        var _keys= Object.keys(v);
        if ( !+i ) {
            keys= _keys;
            continue;
        }
        if ( !_.difference(keys, _keys).length ) continue;

        table= false;
        break;
    }
    if ( table ) {
        return '
'
            + '
i	' + keys.map(function( k ) { return '' + k + '	'; }).join('') + '
'
            + value.map(function( o, i ) {
                return '
' + i + '	' + keys.map(function( k ) { return '' + valueToString(o[k], options) + '	' }).join('') + '
';
            }).join('')
            + '
'
            ;
    }

    return '
'
        + value.map(function( v, i ) { return '
' + i + '	' + valueToString(v, options) + '
'; }).join('')
        + '
';
};

var objectToString= function( value, options ) {
    var keys= Object.keys(value);
    if ( !keys.length ) return '<empty Object>';

    return '
'
        + keys.map(function( key ) { return '
' + key + '	' + valueToString(value[key], options) + '
'; }).join('')
        + '
';
};

var valueToString= function( value, options ) {
    if ( value === undefined || value === null ) return '<empty>';

    if ( typeof value === 'object' ) {
        if ( value instanceof Date )    return dateToString(value, options);
        if ( value instanceof Meteor.Collection.ObjectID )
                                        return 'ObjectId("' + value + '")';
        if ( _.isArray(value) ) {
            if ( value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'number' ) return locationToString(value, options);

            return options && 'returnOnArray' in options ? options.returnOnArray : arrayToString(value, options);
        }
        if ( '$array' in value )        return $arrayToString(value, options);
        if ( '$range' in value )        return $rangeToString(value, options);
        if ( String(value.type).toLowerCase() === 'map' )
                                        return mapToString(value, options);
        if ( String(value.type).toLowerCase() === 'nearest' )
                                        return nearestToString(value, options);
        if ( '$ref' in value )          return dataObjectToString(value, options);

        if ( value.constructor === Object ) {
            return options && 'returnOnObject' in options ? options.returnOnObject : objectToString(value, options);
        }
    }

    if ( value === '' ) return '<empty string>'

    return String(value);
};

var buildValue= function( name, type, valueFn, info ) {
    var result= {
        name: name,
        type: type,
        valueText: function() {
            return valueToString(valueFn());
        },
        getValue: function() { return valueFn(); },
        setValue: function( newValue ) { valueFn(newValue); }
    };
    if ( info ) result.info= info;

    return result;
};

var buildValues= function( args, property, valueContext ) {
    var info= args.info && args.info[property] || {};

    var injectPrefix= 'args.' + property + '.';
    return Object.keys(args[property]).map(function( name ) {
        return buildValue(
            name,
            args[property][name], // type
            SpongeTools.injectVar(valueContext, injectPrefix + name, (info[name] || {}).default),
            info[name] // info
        );
    });
};

var defaultLocationFn= function( text, location ) {
    return '' + text + '';
};

SpongeTools.valueToString= valueToString;
SpongeTools.buildValues= buildValues;
SpongeTools.buildValue= buildValue;

SpongeTools.dateToString= dateToString;
SpongeTools.timeToString= timeToString;

SpongeTools.defaultLocationFn= defaultLocationFn;
<commit_msg>some more formatting changes for Nearest and Map values<commit_after>
var $arrayToString= function( value, options ) {
    return '[ ' + value.$array.map(function(v) { return valueToString(v, options); } ).join(', ') + ' ]';
};

var $rangeToString= function( value, options ) {
    return 'From: ' + valueToString(value.$range.from, options)
        + ' To: '   + valueToString(value.$range.to, options)
        + ' Step: ' + valueToString(value.$range.step, options);
};

var pad= function( value ) {
    return +value < 10 ? "0" + value : String(value);
};
var dateToString= function( value, options ) {
    return pad(value.getUTCDate()) + '.' + pad(value.getUTCMonth() + 1) + '.' + value.getUTCFullYear();
};
var timeToString= function( value, options ) {
    return pad(value.getHours()) + ':' + pad(value.getMinutes()) + ':' + pad(value.getSeconds());
};

var locationToString= function( value, options ) {
    var result= 'lat(' + value[1] + ')/lon(' + value[0] + ')';

    if ( options && 'locationFn' in options ) {
        var locationFn= typeof options.locationFn === 'function' ? options.locationFn : defaultLocationFn;
        return locationFn(result, value);
    }

    return result;
};

var getObject= {
    'Model': SpongeTools.getCachedData('getModel'),
    'AgroObj': SpongeTools.getCachedData('getAgroObject'),
};

var dataObjectToString= function( value, options ) {
    var collection= value.$ref;
    var id= (value.selector || {})._id;

    var name;
    if ( collection in getObject && id ) {
        var object= getObject[collection](id);
        if ( object ) name= object.name;
    }
    if ( !name ) name= valueToString(id);

    if ( collection === 'AgroObj' ) return name;

    return collection + ' ' + name;
};

var selectorToString= function( sel, nameProperty ) {
    if ( !sel ) return '';

    var result= [];

    var hasName= nameProperty && nameProperty in sel;
    if ( hasName ) {
        result.push(valueToString(sel[nameProperty], { quoteStrings: true }));
    }

    var hasTypeVersion= 'objectType' in sel && 'version' in sel;
    if ( hasTypeVersion ) {
        var version= sel.version;
        if ( typeof version === 'object' && '$in' in version ) {
            version= '[' + version.$in.join(',') + ']';
        }
        result.push(sel.objectType + '/' + version);
    }
    var args= [];
    for ( var prop in sel ) {
        if ( hasName && prop === nameProperty ) continue;

        if ( hasTypeVersion && (prop === 'objectType' || prop === 'version') ) continue;

        var value= sel[prop];
        if ( value && typeof value === 'object' && '$in' in value ) {
            args.push(prop + '=' + $arrayToString({ $array: value.$in }));
            continue;
        }

        args.push(prop + '=' + valueToString(value, { quoteStrings: true }));
    }
    if ( args.length ) {
        result.push('(' + args.join(', ') + ')');
    }
    return result.join(' ');
};

var mapToString= function( value, options ) {
    return 'Map ' + selectorToString(value.selector, 'mapname');
};

var nearestToString= function( value, options ) {
    return 'Nearest ' + selectorToString(value.selector, 'tags');
};

var arrayToString= function( value, options ) {
    if ( !value.length ) return '<empty Array>';

    var keys;
    var table= true;
    for ( var i in value ) {
        var v= value[i];
        if ( typeof v !== 'object' ) {
            table= false;
            break;
        };
        var _keys= Object.keys(v);
        if ( !+i ) {
            keys= _keys;
            continue;
        }
        if ( !_.difference(keys, _keys).length ) continue;

        table= false;
        break;
    }
    if ( table ) {
        return '
'
            + '
i	' + keys.map(function( k ) { return '' + k + '	'; }).join('') + '
'
            + value.map(function( o, i ) {
                return '
' + i + '	' + keys.map(function( k ) { return '' + valueToString(o[k], options) + '	' }).join('') + '
';
            }).join('')
            + '
'
            ;
    }

    return '
'
        + value.map(function( v, i ) { return '
' + i + '	' + valueToString(v, options) + '
'; }).join('')
        + '
';
};

var objectToString= function( value, options ) {
    var keys= Object.keys(value);
    if ( !keys.length ) return '<empty Object>';

    return '
'
        + keys.map(function( key ) { return '
' + key + '	' + valueToString(value[key], options) + '
'; }).join('')
        + '
';
};

var valueToString= function( value, options ) {
    if ( value === undefined || value === null ) return '<empty>';

    if ( typeof value === 'object' ) {
        if ( value instanceof Date )    return dateToString(value, options);
        if ( value instanceof Meteor.Collection.ObjectID )
                                        return 'ObjectId("' + value + '")';
        if ( _.isArray(value) ) {
            if ( value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'number' ) return locationToString(value, options);

            return options && 'returnOnArray' in options ? options.returnOnArray : arrayToString(value, options);
        }
        if ( '$array' in value )        return $arrayToString(value, options);
        if ( '$range' in value )        return $rangeToString(value, options);
        if ( String(value.type).toLowerCase() === 'map' )
                                        return mapToString(value, options);
        if ( String(value.type).toLowerCase() === 'nearest' )
                                        return nearestToString(value, options);
        if ( '$ref' in value )          return dataObjectToString(value, options);

        if ( value.constructor === Object ) {
            return options && 'returnOnObject' in options ? options.returnOnObject : objectToString(value, options);
        }
    }
    if ( options && options.quoteStrings && typeof value === 'string' ) return '"' + value + '"'

    if ( value === '' ) return '<empty string>'

    return String(value);
};

var buildValue= function( name, type, valueFn, info ) {
    var result= {
        name: name,
        type: type,
        valueText: function() {
            return valueToString(valueFn());
        },
        getValue: function() { return valueFn(); },
        setValue: function( newValue ) { valueFn(newValue); }
    };
    if ( info ) result.info= info;

    return result;
};

var buildValues= function( args, property, valueContext ) {
    var info= args.info && args.info[property] || {};

    var injectPrefix= 'args.' + property + '.';
    return Object.keys(args[property]).map(function( name ) {
        return buildValue(
            name,
            args[property][name], // type
            SpongeTools.injectVar(valueContext, injectPrefix + name, (info[name] || {}).default),
            info[name] // info
        );
    });
};

var defaultLocationFn= function( text, location ) {
    return '' + text + '';
};

SpongeTools.valueToString= valueToString;
SpongeTools.buildValues= buildValues;
SpongeTools.buildValue= buildValue;

SpongeTools.dateToString= dateToString;
SpongeTools.timeToString= timeToString;

SpongeTools.defaultLocationFn= defaultLocationFn;
<|endoftext|>


<commit_before>(function($){
    $(document).ready(function($) {
        $(".chosen-select").chosen({
            allow_single_deselect: true
        });

    });

})( jQuery );
<commit_msg>Switcher script<commit_after>(function($){
    $(document).ready(function($) {
        $(".chosen-select").chosen({
            allow_single_deselect: true
        });

        $(".switcher").click(function(){
            $(this).parent().toggleClass("off-element");
            $(this).addClass("on-element");
            $(this).toggleClass("switcher-off");
        });

    });

})( jQuery );
<|endoftext|>


<commit_before>var moreMenuStyle = {
  position: 'absolute',
  display: 'block',
  top: '26px',
  left: '-13px',
};
var MyFilesRowMoreMenu = React.createClass({
  onRevealClicked: function() {
    lbry.revealFile(this.props.path);
  },
  onRemoveClicked: function() {
    lbry.deleteFile(this.props.lbryUri, false);
  },
  onDeleteClicked: function() {
    var alertText = 'Are you sure you\'d like to delete "' + this.props.title + '?" This will ' +
      (this.completed ? ' stop the download and ' : '') +
      'permanently remove the file from your system.';

    if (confirm(alertText)) {
      lbry.deleteFile(this.props.lbryUri);
    }
  },
  render: function() {
    return (

        <Menu {...this.props}>
          <MenuItem onClick={this.onRevealClicked} label="Reveal file" /> {/* @TODO: Switch to OS specific wording */}
          <MenuItem onClick={this.onRemoveClicked} label="Remove from LBRY" />
          <MenuItem onClick={this.onDeleteClicked} label="Remove and delete file" />
        </Menu>

    );
  }
});

var moreButtonColumnStyle = {
    height: '120px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  moreButtonContainerStyle = {
    display: 'block',
    position: 'relative',
  },
  moreButtonStyle = {
    fontSize: '1.3em',
  },
  progressBarStyle = {
    height: '15px',
    width: '230px',
    backgroundColor: '#444',
    border: '2px solid #eee',
    display: 'inline-block',
  },
  artStyle = {
    maxHeight: '100px',
    display: 'block',
    marginLeft: 'auto',
    marginRight: 'auto',
  };
var MyFilesRow = React.createClass({
  onPauseResumeClicked: function() {
    if (this.props.stopped) {
      lbry.startFile(this.props.lbryUri);
    } else {
      lbry.stopFile(this.props.lbryUri);
    }
  },
  render: function() {
    //@TODO: Convert progress bar to reusable component

    var progressBarWidth = 230;

    if (this.props.completed) {
      var pauseLink = null;
      var curProgressBarStyle = {display: 'none'};
    } else {
      var pauseLink = <Link icon={this.props.stopped ? 'icon-play' : 'icon-pause'}
                            label={this.props.stopped ? 'Resume download' : 'Pause download'}
                            onClick={() => { this.onPauseResumeClicked() }} />;

      var curProgressBarStyle = Object.assign({}, progressBarStyle);
      curProgressBarStyle.width = Math.floor(this.props.ratioLoaded * progressBarWidth) + 'px';
      curProgressBarStyle.borderRightWidth = progressBarWidth - Math.ceil(this.props.ratioLoaded * progressBarWidth) + 2;
    }

    if (this.props.showWatchButton) {
      var watchButton = <WatchLink streamName={this.props.lbryUri} />
    } else {
      var watchButton = null;
    }

    return (

          {this.props.imgUrl ?  : null}

{this.props.pending ? this.props.title : {this.props.title}}

          {this.props.pending ? This file is pending confirmation
            : (

               { ' ' }
               {this.props.completed ? 'Download complete' : (parseInt(this.props.ratioLoaded * 100) + '%')}

{ pauseLink }

{ watchButton }

           )
          }

          {this.props.pending ? null :

             <Link style={moreButtonStyle} ref="moreButton" icon="icon-ellipsis-h" title="More Options" />
             <MyFilesRowMoreMenu toggleButton={this.refs.moreButton} title={this.props.title}
                                 lbryUri={this.props.lbryUri} fileName={this.props.fileName}
                                 path={this.props.path}/>

          }

    );
  }
});

var MyFilesPage = React.createClass({
  getInitialState: function() {
    return {
      filesInfo: null,
    };
  },
  componentWillMount: function() {
    this.updateFilesInfo();
  },
  updateFilesInfo: function() {
    lbry.getFilesInfo((filesInfo) => {
      this.setState({
        filesInfo: (filesInfo ? filesInfo : []),
      });
      setTimeout(() => { this.updateFilesInfo() }, 1000);
    });
  },
  render: function() {
    if (this.state.filesInfo === null) {
      return null;
    }

    if (!this.state.filesInfo.length) {
      var content = You haven't downloaded anything from LBRY yet. Go <Link href="/" label="search for your first download" />!;
    } else {
      var content = [],
          keyIndex = 0;
      for (let fileInfo of this.state.filesInfo) {
        let {completed, written_bytes, total_bytes, lbry_uri, file_name, download_path,
          stopped, metadata} = fileInfo;

        if (!metadata)
        {
          continue;
        }

        let {title, thumbnail} = metadata;

        if (!fileInfo.pending && typeof metadata == 'object') {
          var {title, thumbnail} = metadata;
          var pending = false;
        } else {
          var title = null;
          var thumbnail = null;
          var pending = true;
        }

        var ratioLoaded = written_bytes / total_bytes;
        var showWatchButton = (lbry.getMediaType(file_name) == 'video' || lbry.getMediaType(file_name) == 'audio');

        content.push(<MyFilesRow key={lbry_uri + (++keyIndex)} lbryUri={lbry_uri} title={title || ('lbry://' + lbry_uri)} completed={completed} stopped={stopped}
                                 ratioLoaded={ratioLoaded} imgUrl={thumbnail} path={download_path}
                                 showWatchButton={showWatchButton} pending={pending} />);
      }
    }
    return (

        <SubPageLogo />

My Files

          {content}

          <Link href="/" label="<< Return" />

    );
  }
});
<commit_msg>only print an item in my_files once<commit_after>var moreMenuStyle = {
  position: 'absolute',
  display: 'block',
  top: '26px',
  left: '-13px',
};
var MyFilesRowMoreMenu = React.createClass({
  onRevealClicked: function() {
    lbry.revealFile(this.props.path);
  },
  onRemoveClicked: function() {
    lbry.deleteFile(this.props.lbryUri, false);
  },
  onDeleteClicked: function() {
    var alertText = 'Are you sure you\'d like to delete "' + this.props.title + '?" This will ' +
      (this.completed ? ' stop the download and ' : '') +
      'permanently remove the file from your system.';

    if (confirm(alertText)) {
      lbry.deleteFile(this.props.lbryUri);
    }
  },
  render: function() {
    return (

        <Menu {...this.props}>
          <MenuItem onClick={this.onRevealClicked} label="Reveal file" /> {/* @TODO: Switch to OS specific wording */}
          <MenuItem onClick={this.onRemoveClicked} label="Remove from LBRY" />
          <MenuItem onClick={this.onDeleteClicked} label="Remove and delete file" />
        </Menu>

    );
  }
});

var moreButtonColumnStyle = {
    height: '120px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  moreButtonContainerStyle = {
    display: 'block',
    position: 'relative',
  },
  moreButtonStyle = {
    fontSize: '1.3em',
  },
  progressBarStyle = {
    height: '15px',
    width: '230px',
    backgroundColor: '#444',
    border: '2px solid #eee',
    display: 'inline-block',
  },
  artStyle = {
    maxHeight: '100px',
    display: 'block',
    marginLeft: 'auto',
    marginRight: 'auto',
  };
var MyFilesRow = React.createClass({
  onPauseResumeClicked: function() {
    if (this.props.stopped) {
      lbry.startFile(this.props.lbryUri);
    } else {
      lbry.stopFile(this.props.lbryUri);
    }
  },
  render: function() {
    //@TODO: Convert progress bar to reusable component

    var progressBarWidth = 230;

    if (this.props.completed) {
      var pauseLink = null;
      var curProgressBarStyle = {display: 'none'};
    } else {
      var pauseLink = <Link icon={this.props.stopped ? 'icon-play' : 'icon-pause'}
                            label={this.props.stopped ? 'Resume download' : 'Pause download'}
                            onClick={() => { this.onPauseResumeClicked() }} />;

      var curProgressBarStyle = Object.assign({}, progressBarStyle);
      curProgressBarStyle.width = Math.floor(this.props.ratioLoaded * progressBarWidth) + 'px';
      curProgressBarStyle.borderRightWidth = progressBarWidth - Math.ceil(this.props.ratioLoaded * progressBarWidth) + 2;
    }

    if (this.props.showWatchButton) {
      var watchButton = <WatchLink streamName={this.props.lbryUri} />
    } else {
      var watchButton = null;
    }

    return (

          {this.props.imgUrl ?  : null}

{this.props.pending ? this.props.title : {this.props.title}}

          {this.props.pending ? This file is pending confirmation
            : (

               { ' ' }
               {this.props.completed ? 'Download complete' : (parseInt(this.props.ratioLoaded * 100) + '%')}

{ pauseLink }

{ watchButton }

           )
          }

          {this.props.pending ? null :

             <Link style={moreButtonStyle} ref="moreButton" icon="icon-ellipsis-h" title="More Options" />
             <MyFilesRowMoreMenu toggleButton={this.refs.moreButton} title={this.props.title}
                                 lbryUri={this.props.lbryUri} fileName={this.props.fileName}
                                 path={this.props.path}/>

          }

    );
  }
});

var MyFilesPage = React.createClass({
  getInitialState: function() {
    return {
      filesInfo: null,
    };
  },
  componentWillMount: function() {
    this.updateFilesInfo();
  },
  updateFilesInfo: function() {
    lbry.getFilesInfo((filesInfo) => {
      this.setState({
        filesInfo: (filesInfo ? filesInfo : []),
      });
      setTimeout(() => { this.updateFilesInfo() }, 1000);
    });
  },
  render: function() {
    if (this.state.filesInfo === null) {
      return null;
    }

    if (!this.state.filesInfo.length) {
      var content = You haven't downloaded anything from LBRY yet. Go <Link href="/" label="search for your first download" />!;
    } else {
      var content = [],
          seenUris = {};

      for (let fileInfo of this.state.filesInfo) {
        let {completed, written_bytes, total_bytes, lbry_uri, file_name, download_path,
          stopped, metadata} = fileInfo;

        if (!metadata || seenUris[lbry_uri])
        {
          continue;
        }

        seenUris[lbry_uri] = true;

        let {title, thumbnail} = metadata;

        if (!fileInfo.pending && typeof metadata == 'object') {
          var {title, thumbnail} = metadata;
          var pending = false;
        } else {
          var title = null;
          var thumbnail = null;
          var pending = true;
        }

        var ratioLoaded = written_bytes / total_bytes;
        var showWatchButton = (lbry.getMediaType(file_name) == 'video' || lbry.getMediaType(file_name) == 'audio');

        content.push(<MyFilesRow key={lbry_uri} lbryUri={lbry_uri} title={title || ('lbry://' + lbry_uri)} completed={completed} stopped={stopped}
                                 ratioLoaded={ratioLoaded} imgUrl={thumbnail} path={download_path}
                                 showWatchButton={showWatchButton} pending={pending} />);
      }
    }
    return (

        <SubPageLogo />

My Files

          {content}

          <Link href="/" label="<< Return" />

    );
  }
});
<|endoftext|>


<commit_before>var ParticleField = (function(options) {
  var particle = {
    vx: 0,
    vy: 0,
    x: 0,
    y: 0
  };

  var opts = {
    rows: 100,
    cols: 240,
    num_particles: null,
    spacing: 4,
    margin: 40,
    radius: Math.pow(50, 2),
    mouse: true,
    color: [0, 0, 0, 255]
  };

  var canvas;
  var ctx;
  var width;
  var height;
  var customAnim;

  var particles = [];
  var mx = 0;
  var my = 0;
  var alt = false;
  var manual = false;
  var running = false;

  setOptions(options);

  function draw(holder) {
    if (!holder) {
      throw "You need to specify a canvas element";
    }

    canvas = holder;
    opts.num_particles = (opts.rows * opts.cols);

    ctx = canvas.getContext('2d');

    width = canvas.width = opts.cols * opts.spacing + opts.margin * 2;
    height = canvas.height = opts.rows * opts.spacing + opts.margin * 2;

    for (var i = 0; i < opts.num_particles; i++) {
      var p = Object.create(particle);
      p.x = p.orig_x = opts.margin + opts.spacing * (i % opts.cols);
      p.y = p.orig_y = opts.margin + opts.spacing * Math.floor(i / opts.cols);
      particles[i] = p;
    }

    if (opts.mouse) {
      canvas.addEventListener('mousemove', function(e) {
        manual = true;
        var bounds = canvas.getBoundingClientRect();
        mx = e.clientX - bounds.left;
        my = e.clientY - bounds.top;
      });
    }

    frame();
  }

  function frame() {
    if (alt) {
      if (!manual) {
        var movement = animation();
        mx = movement.mx;
        my = movement.my;
      }

      for (var o = 0; o < opts.num_particles; o++) {
        var p = particles[o];

        // Determine distance travelled
        var dx = mx - p.x;
        var dy = my - p.y;
        var dist = (dx * dx) + (dy * dy);

        if (dist < opts.radius) {
          var tmp = Math.atan2(dy, dx);
          var f = -opts.radius / dist;

          p.vx += f * Math.cos(tmp);
          p.vy += f * Math.sin(tmp);
        }

        p.x += (p.vx *= .95) + (p.orig_x - p.x) * .25;
        p.y += (p.vy *= .95) + (p.orig_y - p.y) * .25;
      }

      alt = !alt;
    } else {
      var image = ctx.createImageData(width, height);
      for (var i = 0; i < opts.num_particles; i++) {
        var p = particles[i];
        var index = (Math.floor(p.x)  + (Math.floor(p.y) * width)) * 4;
        image.data[index] = opts.color[0];
        image.data[index+1] = opts.color[1];
        image.data[index+2] = opts.color[2];
        image.data[index+3] = opts.color[3];
      }

      ctx.putImageData(image, 0, 0);
      alt = !alt;
    }

    if (running)
      requestAnimationFrame(frame);
  }

  function animation() {
    if (customAnim) {
      return customAnim(mx, my, width, height, opts);
    }

    var time = Date.now() * 0.0015;
    mx = width * 0.5 + (0.4 * width * Math.cos(time))
    my = height * 0.5 + (0.6 * height * Math.cos(time) * Math.sin(time))
    return {mx: mx, my: my}
  }

  function getOptions() {
    return opts;
  }

  function setOptions(options) {
    console.log('here');
    for (var key in options) {
      opts[key] = options[key];
    }
  }

  function getMouseState() {
    return opts.mouse;
  }

  function setMouseState(state) {
    opts.mouse = state;
    return opts.mouse;
  }

  function start() {
    running = true;
    frame();
  }

  function stop() {
    running = false;
  }

  function setCustomAnimation(func) {
    customAnim = func;
  }

  return {
    draw: draw,
    start: start,
    stop: stop,
    getMouseState: getMouseState,
    setMouseState: setMouseState,
    getOptions: getOptions,
    setOptions: setOptions,
    setCustomAnimation: setCustomAnimation
  };
});

// RequestAnimationFrame shim taken from Opera
//     http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());
<commit_msg>Lint fixes<commit_after>var ParticleField = (function(options) {
  var particle = {
    vx: 0,
    vy: 0,
    x: 0,
    y: 0
  };

  var opts = {
    rows: 100,
    cols: 240,
    num_particles: null,
    spacing: 4,
    margin: 40,
    radius: Math.pow(50, 2),
    mouse: true,
    color: [0, 0, 0, 255]
  };

  var canvas;
  var ctx;
  var width;
  var height;
  var customAnim;

  var particles = [];
  var mx = 0;
  var my = 0;
  var alt = false;
  var manual = false;
  var running = false;

  setOptions(options);

  function draw(holder) {
    if (!holder) {
      throw 'You need to specify a canvas element';
    }

    canvas = holder;
    opts.num_particles = (opts.rows * opts.cols);

    ctx = canvas.getContext('2d');

    width = canvas.width = opts.cols * opts.spacing + opts.margin * 2;
    height = canvas.height = opts.rows * opts.spacing + opts.margin * 2;

    for (var i = 0; i < opts.num_particles; i++) {
      var p = Object.create(particle);
      p.x = p.orig_x = opts.margin + opts.spacing * (i % opts.cols);
      p.y = p.orig_y = opts.margin + opts.spacing * Math.floor(i / opts.cols);
      particles[i] = p;
    }

    if (opts.mouse) {
      canvas.addEventListener('mousemove', function(e) {
        manual = true;
        var bounds = canvas.getBoundingClientRect();
        mx = e.clientX - bounds.left;
        my = e.clientY - bounds.top;
      });
    }

    frame();
  }

  function frame() {
    if (alt) {
      if (!manual) {
        var movement = animation();
        mx = movement.mx;
        my = movement.my;
      }

      for (var o = 0; o < opts.num_particles; o++) {
        var p = particles[o];

        // Determine distance travelled
        var dx = mx - p.x;
        var dy = my - p.y;
        var dist = (dx * dx) + (dy * dy);

        if (dist < opts.radius) {
          var tmp = Math.atan2(dy, dx);
          var f = -opts.radius / dist;

          p.vx += f * Math.cos(tmp);
          p.vy += f * Math.sin(tmp);
        }

        p.x += (p.vx *= 0.95) + (p.orig_x - p.x) * 0.25;
        p.y += (p.vy *= 0.95) + (p.orig_y - p.y) * 0.25;
      }

      alt = !alt;
    } else {
      var image = ctx.createImageData(width, height);
      for (var i = 0; i < opts.num_particles; i++) {
        var p = particles[i];
        var index = (Math.floor(p.x)  + (Math.floor(p.y) * width)) * 4;
        image.data[index] = opts.color[0];
        image.data[index+1] = opts.color[1];
        image.data[index+2] = opts.color[2];
        image.data[index+3] = opts.color[3];
      }

      ctx.putImageData(image, 0, 0);
      alt = !alt;
    }

    if (running)
      requestAnimationFrame(frame);
  }

  function animation() {
    if (customAnim) {
      return customAnim(mx, my, width, height, opts);
    }

    var time = Date.now() * 0.0015;
    mx = width * 0.5 + (0.4 * width * Math.cos(time));
    my = height * 0.5 + (0.6 * height * Math.cos(time) * Math.sin(time));
    return {mx: mx, my: my}
  }

  function getOptions() {
    return opts;
  }

  function setOptions(options) {
    console.log('here');
    for (var key in options) {
      opts[key] = options[key];
    }
  }

  function getMouseState() {
    return opts.mouse;
  }

  function setMouseState(state) {
    opts.mouse = state;
    return opts.mouse;
  }

  function start() {
    running = true;
    frame();
  }

  function stop() {
    running = false;
  }

  function setCustomAnimation(func) {
    customAnim = func;
  }

  return {
    draw: draw,
    start: start,
    stop: stop,
    getMouseState: getMouseState,
    setMouseState: setMouseState,
    getOptions: getOptions,
    setOptions: setOptions,
    setCustomAnimation: setCustomAnimation
  };
});

// RequestAnimationFrame shim taken from Opera
//     http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 7,
    sourceType: 'module',
  },
  rules: {
    // possible errors
    'no-cond-assign': [2, 'always'],
    'no-console': 1,
    'no-constant-condition': 2,
    'no-control-regex': 2,
    'no-debugger': 1,
    'no-dupe-args': 2,
    'no-dupe-keys': 2,
    'no-duplicate-case': 2,
    'no-empty': [2, {allowEmptyCatch: true}],
    'no-empty-character-class': 2,
    'no-ex-assign': 2,
    'no-extra-boolean-cast': 2,
    // issue: https://github.com/eslint/eslint/issues/3107
    'no-extra-parens': [2, 'functions'],
    'no-extra-semi': 2,
    'no-func-assign': 2,
    'no-inner-declarations': 2,
    'no-invalid-regexp': 2,
    'no-irregular-whitespace': 2,
    'no-negated-in-lhs': 2,
    'no-obj-calls': 2,
    'no-prototype-builtins': 2,
    'no-regex-spaces': 2,
    'no-sparse-arrays': 2,
    'no-unexpected-multiline': 2,
    'no-unreachable': 2,
    'no-unsafe-finally': 2,
    'use-isnan': 2,
    'valid-jsdoc': 0,
    'valid-typeof': 2,

    // best practices
    'accessor-pairs': 2,
    'array-callback-return': 2,
    'block-scoped-var': 2, // rely on `no-var` rule
    'complexity': [1, 11],
    'consistent-return': 2,
    'curly': 2,
    'default-case': 2,
    'dot-location': [2, 'property'],
    'dot-notation': 2,
    'eqeqeq': 2,
    'guard-for-in': 2, // rely on `no-restricted-syntax` rule
    'no-alert': 1,
    'no-caller': 2,
    'no-case-declarations': 2,
    'no-div-regex': 0,
    'no-else-return': 2,
    'no-empty-function': 2,
    'no-empty-pattern': 2,
    'no-eq-null': 2, // rely on `eqeqeq` rule
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-extra-label': 2,
    'no-fallthrough': 2,
    'no-floating-decimal': 2,
    'no-implicit-coercion': [2, {boolean: false}],
    'no-implicit-globals': 2,
    'no-implied-eval': 2,
    // issue: https://github.com/babel/eslint-plugin-babel/issues/12
    // 'no-invalid-this': 2,
    'no-iterator': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-loop-func': 2,
    'no-magic-numbers': 0,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-native-reassign': 2,
    'no-new': 2,
    'no-new-func': 2,
    'no-new-wrappers': 2,
    'no-octal': 2,
    'no-octal-escape': 2,
    'no-param-reassign': [2, {props: true}],
    'no-proto': 2,
    'no-redeclare': 2,
    'no-return-assign': [2, 'always'],
    'no-script-url': 0,
    'no-self-assign': 2,
    'no-self-compare': 2,
    'no-sequences': 2,
    'no-throw-literal': 2,
    'no-unmodified-loop-condition': 2,
    'no-unused-expressions': 2,
    'no-unused-labels': 2,
    'no-useless-call': 2,
    'no-useless-concat': 2,
    'no-useless-escape': 2,
    'no-void': 2,
    'no-warning-comments': 1,
    'no-with': 2,
    'radix': [2, 'as-needed'],
    'vars-on-top': 2, // rely on `one-var` rule
    'wrap-iife': [2, 'inside'],
    'yoda': 2,

    // strict mode
    'strict': 0,

    // variables
    'init-declarations': 2,
    'no-catch-shadow': 0,
    'no-delete-var': 2,
    'no-label-var': 2,
    'no-restricted-globals': 0,
    'no-shadow': 2,
    'no-shadow-restricted-names': 2,
    'no-undef': 2,
    'no-undef-init': 2,
    'no-undefined': 0,
    'no-unused-vars': 2,
    'no-use-before-define': [2, 'nofunc'],

    // node.js and commonjs
    'callback-return': 0,
    'global-require': 0,
    'handle-callback-err': 2,
    'no-mixed-requires': 2, // rely on `one-var` rule
    'no-new-require': 2,
    'no-path-concat': 2,
    'no-process-env': 0,
    'no-process-exit': 0,
    'no-restricted-modules': 0,
    'no-sync': 0,

    // stylistic issues
    'array-bracket-spacing': 2,
    'block-spacing': 2,
    'brace-style': [2, '1tbs', {allowSingleLine: true}],
    'camelcase': [2, {properties: 'never'}],
    'comma-dangle': [2, 'always-multiline'],
    'comma-spacing': 2,
    'comma-style': [2, 'last'],
    'computed-property-spacing': 2,
    'consistent-this': 0,
    'eol-last': 2,
    'func-names': [2, 'never'],
    'func-style': [2, 'declaration', {allowArrowFunctions: true}],
    'id-blacklist': 0,
    'id-length': 0,
    'id-match': 0,
    'indent': [2, 2, {SwitchCase: 1}],
    'jsx-quotes': 0,
    'key-spacing': 2,
    'keyword-spacing': 2,
    'linebreak-style': 2,
    'lines-around-comment': 0,
    'max-depth': 1,
    'max-len': 0,
    'max-lines': 1,
    'max-nested-callbacks': [1, 4],
    'max-params': [1, 5],
    'max-statements': 0,
    'max-statements-per-line': 1,
    'multiline-ternary': 0,
    'new-cap': 2,
    'new-parens': 2,
    'newline-after-var': 2,
    'newline-before-return': 2,
    'newline-per-chained-call': 2,
    'no-array-constructor': 2,
    'no-bitwise': 0,
    'no-continue': 2,
    'no-inline-comments': 0,
    'no-lonely-if': 2,
    'no-mixed-operators': [2, {allowSamePrecedence: true}],
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, {max: 1, maxBOF: 0}],
    'no-negated-condition': 2,
    // IMO, there is no better alternatives
    // http://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js
    'no-nested-ternary': 0,
    'no-new-object': 2,
    'no-plusplus': 0,
    // use for-of with Object.keys() instead of for-in
    // https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
    'no-restricted-syntax': [2, 'WithStatement', 'ForInStatement'],
    'no-spaced-func': 2,
    'no-tabs': 2,
    'no-ternary': 0,
    'no-trailing-spaces': [2, {skipBlankLines: true}],
    'no-underscore-dangle': [2, {allowAfterThis: true, allowAfterSuper: true}],
    'no-unneeded-ternary': [2, {defaultAssignment: false}],
    'no-whitespace-before-property': 2,
    // TODO: ENABLE ?
    // issue: https://github.com/eslint/eslint/issues/6488
    // 'object-curly-newline': [2, {multiline: true, minProperties: 4}],
    'object-curly-spacing': 2,
    'object-property-newline': [2, {allowMultiplePropertiesPerLine: true}],
    'one-var': [2, 'never'],
    'one-var-declaration-per-line': 2, // rely on `one-var` rule
    'operator-assignment': [2, 'always'],
    'operator-linebreak': 2,
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'as-needed'],
    'quotes': [2, 'single'],
    'require-jsdoc': 0,
    'semi': 2,
    'semi-spacing': 2,
    'sort-vars': 0,
    'space-before-blocks': 2,
    'space-before-function-paren': [2, {anonymous: 'always', named: 'never'}],
    'space-in-parens': 2,
    'space-infix-ops': 2,
    'space-unary-ops': 2,
    'spaced-comment': 2,
    'unicode-bom': 2,
    'wrap-regex': 0,

    // ecmascript 6 rules
    'arrow-body-style': [2, 'as-needed'],
    'arrow-parens': 2,
    'arrow-spacing': 2,
    'constructor-super': 2,
    'generator-star-spacing': 2,
    'no-class-assign': 2,
    'no-confusing-arrow': 0,
    'no-const-assign': 2,
    'no-dupe-class-members': 2,
    'no-duplicate-imports': [2, {includeExports: true}],
    'no-new-symbol': 2,
    'no-restricted-imports': 0,
    'no-this-before-super': 2,
    'no-useless-computed-key': 2,
    'no-useless-constructor': 2,
    'no-useless-rename': 2,
    'no-var': 2,
    'object-shorthand': 2,
    'prefer-arrow-callback': 2,
    'prefer-const': 2,
    'prefer-reflect': 2,
    'prefer-rest-params': 2,
    'prefer-spread': 2,
    'prefer-template': 2,
    'require-yield': 2,
    'rest-spread-spacing': 2,
    'sort-imports': 0,
    'template-curly-spacing': 2,
    'yield-star-spacing': 2,
  },
};
<commit_msg>Add `balanced` option for `block` in `spaced-comment` rule<commit_after>'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 7,
    sourceType: 'module',
  },
  rules: {
    // possible errors
    'no-cond-assign': [2, 'always'],
    'no-console': 1,
    'no-constant-condition': 2,
    'no-control-regex': 2,
    'no-debugger': 1,
    'no-dupe-args': 2,
    'no-dupe-keys': 2,
    'no-duplicate-case': 2,
    'no-empty': [2, {allowEmptyCatch: true}],
    'no-empty-character-class': 2,
    'no-ex-assign': 2,
    'no-extra-boolean-cast': 2,
    // issue: https://github.com/eslint/eslint/issues/3107
    'no-extra-parens': [2, 'functions'],
    'no-extra-semi': 2,
    'no-func-assign': 2,
    'no-inner-declarations': 2,
    'no-invalid-regexp': 2,
    'no-irregular-whitespace': 2,
    'no-negated-in-lhs': 2,
    'no-obj-calls': 2,
    'no-prototype-builtins': 2,
    'no-regex-spaces': 2,
    'no-sparse-arrays': 2,
    'no-unexpected-multiline': 2,
    'no-unreachable': 2,
    'no-unsafe-finally': 2,
    'use-isnan': 2,
    'valid-jsdoc': 0,
    'valid-typeof': 2,

    // best practices
    'accessor-pairs': 2,
    'array-callback-return': 2,
    'block-scoped-var': 2, // rely on `no-var` rule
    'complexity': [1, 11],
    'consistent-return': 2,
    'curly': 2,
    'default-case': 2,
    'dot-location': [2, 'property'],
    'dot-notation': 2,
    'eqeqeq': 2,
    'guard-for-in': 2, // rely on `no-restricted-syntax` rule
    'no-alert': 1,
    'no-caller': 2,
    'no-case-declarations': 2,
    'no-div-regex': 0,
    'no-else-return': 2,
    'no-empty-function': 2,
    'no-empty-pattern': 2,
    'no-eq-null': 2, // rely on `eqeqeq` rule
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-extra-label': 2,
    'no-fallthrough': 2,
    'no-floating-decimal': 2,
    'no-implicit-coercion': [2, {boolean: false}],
    'no-implicit-globals': 2,
    'no-implied-eval': 2,
    // issue: https://github.com/babel/eslint-plugin-babel/issues/12
    // 'no-invalid-this': 2,
    'no-iterator': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-loop-func': 2,
    'no-magic-numbers': 0,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-native-reassign': 2,
    'no-new': 2,
    'no-new-func': 2,
    'no-new-wrappers': 2,
    'no-octal': 2,
    'no-octal-escape': 2,
    'no-param-reassign': [2, {props: true}],
    'no-proto': 2,
    'no-redeclare': 2,
    'no-return-assign': [2, 'always'],
    'no-script-url': 0,
    'no-self-assign': 2,
    'no-self-compare': 2,
    'no-sequences': 2,
    'no-throw-literal': 2,
    'no-unmodified-loop-condition': 2,
    'no-unused-expressions': 2,
    'no-unused-labels': 2,
    'no-useless-call': 2,
    'no-useless-concat': 2,
    'no-useless-escape': 2,
    'no-void': 2,
    'no-warning-comments': 1,
    'no-with': 2,
    'radix': [2, 'as-needed'],
    'vars-on-top': 2, // rely on `one-var` rule
    'wrap-iife': [2, 'inside'],
    'yoda': 2,

    // strict mode
    'strict': 0,

    // variables
    'init-declarations': 2,
    'no-catch-shadow': 0,
    'no-delete-var': 2,
    'no-label-var': 2,
    'no-restricted-globals': 0,
    'no-shadow': 2,
    'no-shadow-restricted-names': 2,
    'no-undef': 2,
    'no-undef-init': 2,
    'no-undefined': 0,
    'no-unused-vars': 2,
    'no-use-before-define': [2, 'nofunc'],

    // node.js and commonjs
    'callback-return': 0,
    'global-require': 0,
    'handle-callback-err': 2,
    'no-mixed-requires': 2, // rely on `one-var` rule
    'no-new-require': 2,
    'no-path-concat': 2,
    'no-process-env': 0,
    'no-process-exit': 0,
    'no-restricted-modules': 0,
    'no-sync': 0,

    // stylistic issues
    'array-bracket-spacing': 2,
    'block-spacing': 2,
    'brace-style': [2, '1tbs', {allowSingleLine: true}],
    'camelcase': [2, {properties: 'never'}],
    'comma-dangle': [2, 'always-multiline'],
    'comma-spacing': 2,
    'comma-style': [2, 'last'],
    'computed-property-spacing': 2,
    'consistent-this': 0,
    'eol-last': 2,
    'func-names': [2, 'never'],
    'func-style': [2, 'declaration', {allowArrowFunctions: true}],
    'id-blacklist': 0,
    'id-length': 0,
    'id-match': 0,
    'indent': [2, 2, {SwitchCase: 1}],
    'jsx-quotes': 0,
    'key-spacing': 2,
    'keyword-spacing': 2,
    'linebreak-style': 2,
    'lines-around-comment': 0,
    'max-depth': 1,
    'max-len': 0,
    'max-lines': 1,
    'max-nested-callbacks': [1, 4],
    'max-params': [1, 5],
    'max-statements': 0,
    'max-statements-per-line': 1,
    'multiline-ternary': 0,
    'new-cap': 2,
    'new-parens': 2,
    'newline-after-var': 2,
    'newline-before-return': 2,
    'newline-per-chained-call': 2,
    'no-array-constructor': 2,
    'no-bitwise': 0,
    'no-continue': 2,
    'no-inline-comments': 0,
    'no-lonely-if': 2,
    'no-mixed-operators': [2, {allowSamePrecedence: true}],
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, {max: 1, maxBOF: 0}],
    'no-negated-condition': 2,
    // IMO, there is no better alternatives
    // http://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js
    'no-nested-ternary': 0,
    'no-new-object': 2,
    'no-plusplus': 0,
    // use for-of with Object.keys() instead of for-in
    // https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
    'no-restricted-syntax': [2, 'WithStatement', 'ForInStatement'],
    'no-spaced-func': 2,
    'no-tabs': 2,
    'no-ternary': 0,
    'no-trailing-spaces': [2, {skipBlankLines: true}],
    'no-underscore-dangle': [2, {allowAfterThis: true, allowAfterSuper: true}],
    'no-unneeded-ternary': [2, {defaultAssignment: false}],
    'no-whitespace-before-property': 2,
    // TODO: ENABLE ?
    // issue: https://github.com/eslint/eslint/issues/6488
    // 'object-curly-newline': [2, {multiline: true, minProperties: 4}],
    'object-curly-spacing': 2,
    'object-property-newline': [2, {allowMultiplePropertiesPerLine: true}],
    'one-var': [2, 'never'],
    'one-var-declaration-per-line': 2, // rely on `one-var` rule
    'operator-assignment': [2, 'always'],
    'operator-linebreak': 2,
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'as-needed'],
    'quotes': [2, 'single'],
    'require-jsdoc': 0,
    'semi': 2,
    'semi-spacing': 2,
    'sort-vars': 0,
    'space-before-blocks': 2,
    'space-before-function-paren': [2, {anonymous: 'always', named: 'never'}],
    'space-in-parens': 2,
    'space-infix-ops': 2,
    'space-unary-ops': 2,
    'spaced-comment': [2, 'always', {block: {balanced: true}}],
    'unicode-bom': 2,
    'wrap-regex': 0,

    // ecmascript 6 rules
    'arrow-body-style': [2, 'as-needed'],
    'arrow-parens': 2,
    'arrow-spacing': 2,
    'constructor-super': 2,
    'generator-star-spacing': 2,
    'no-class-assign': 2,
    'no-confusing-arrow': 0,
    'no-const-assign': 2,
    'no-dupe-class-members': 2,
    'no-duplicate-imports': [2, {includeExports: true}],
    'no-new-symbol': 2,
    'no-restricted-imports': 0,
    'no-this-before-super': 2,
    'no-useless-computed-key': 2,
    'no-useless-constructor': 2,
    'no-useless-rename': 2,
    'no-var': 2,
    'object-shorthand': 2,
    'prefer-arrow-callback': 2,
    'prefer-const': 2,
    'prefer-reflect': 2,
    'prefer-rest-params': 2,
    'prefer-spread': 2,
    'prefer-template': 2,
    'require-yield': 2,
    'rest-spread-spacing': 2,
    'sort-imports': 0,
    'template-curly-spacing': 2,
    'yield-star-spacing': 2,
  },
};
<|endoftext|>


<commit_before>function generalAttack(attacker, receiver){
	if(attacker.attack > receiver.defense){
		receiver.health = receiver.health - (attacker.attack - receiver.defense);
	}
	else {
		 receiver.health -= 2;
	}
}
var damageTaken = 0;
function wolvesAttack() {
var wolf = new Character();
		wolf.health = 30;
		wolf.attack = 5;
		wolf.defense = 5;

	while(wolf.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 20){
			window.setInterval(function(){print_to_path(hero.health)}, 1000);
			damageTaken = hero.health;
			generalAttack(wolf, hero);
			if(chance % 2 == 0){
				print_to_path("The wolf ran up to you and bit you for " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("The wolf clawed you for " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(wolf.health);
			generalAttack(hero, wolf);
			print_to_path("hero has attacked");
			print_to_path(wolf.health);
		}
		update_status();
	}
}

function banditsAttack() {
var bandit = new Character();
		bandit.health = 40;
		bandit.attack = 10;
		bandit.defense = 5;
	while(bandit.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 30){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(bandit, hero);
			if(chance % 2 == 0){
				print_to_path("A clan of bandits knock you on the ground kicking you for " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("A bandit snuck up from behind you and stabbed you dealing " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(bandit.health);
			generalAttack(hero, bandit);
			print_to_path("hero has attacked");
			print_to_path(bandit.health);
		}
		update_status();
	}
}
function trollsAttack() {
var troll = new Character();
		troll.health = 50;
		troll.attack = 25;
		troll.defense = 15;
	while(troll.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 35){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(troll, hero);
			if(chance % 2 == 0){
				print_to_path("Threw a small axe at you, hitting your chest dealing " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("The Troll smashed you with his club for " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(troll.health);
			generalAttack(hero, troll);
			print_to_path("hero has attacked");
			print_to_path(troll.health);
		}
		update_status();
	}
}

function golemsAttack() {
var golem = new Character();
		golem.health = 60;
		golem.attack = 10;
		golem.defense = 50;
	while(golem.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 20){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(golem, hero);
			if(chance % 2 == 0){
				print_to_path("Flails its arms smashing you into the ground. You took " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("Stomps its foot on the ground causing rocks to fall on you from the nearby mountain. You took " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(golem.health);
			generalAttack(hero, golem);
			print_to_path("hero has attacked");
			print_to_path(golem.health);
		}
		update_status();
	}
}

function dragonAttack() {
// atk 30
var dragon = new Character();
		dragon.health = 60;
		dragon.attack = 30;
		dragon.defense = 30;
	while(dragon.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 20){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(dragon, hero);
			if(chance % 2 == 0){
				print_to_path("Breaths green flames at you which inflicted a burn on you. You took " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("Swipes its tail along the floor flinging you into the wall. You took " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(dragon.health);
			generalAttack(hero, dragon);
			print_to_path("hero has attacked");
			print_to_path(dragon.health);
		}
		update_status();
	}
}

function blackSquirrelAttacks() {

}
<commit_msg>adding stats<commit_after>function generalAttack(attacker, receiver){
	if(attacker.attack > receiver.defense){
		receiver.health = receiver.health - (attacker.attack - receiver.defense);
	}
	else {
		 receiver.health -= 2;
	}
}
var damageTaken = 0;
var totalDamageDealt = 0;
var totalDamageTaken = 0;
var totalKills = 0;
var totalTurns = 0;
function wolvesAttack() {
var wolf = new Character();
		wolf.health = 30;
		wolf.attack = 5;
		wolf.defense = 5;

	while(wolf.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 20){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(wolf, hero);
			if(chance % 2 == 0){
				print_to_path("The wolf ran up to you and bit you for " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("The wolf clawed you for " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(wolf.health);
			generalAttack(hero, wolf);
			print_to_path("hero has attacked");
			print_to_path(wolf.health);
		}
		update_status();
		totalKills += 1;
	}
}

function banditsAttack() {
var bandit = new Character();
		bandit.health = 40;
		bandit.attack = 10;
		bandit.defense = 5;
	while(bandit.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 30){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(bandit, hero);
			if(chance % 2 == 0){
				print_to_path("A clan of bandits knock you on the ground kicking you for " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("A bandit snuck up from behind you and stabbed you dealing " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(bandit.health);
			generalAttack(hero, bandit);
			print_to_path("hero has attacked");
			print_to_path(bandit.health);
		}
		update_status();
		totalKills += 1;
	}
}
function trollsAttack() {
var troll = new Character();
		troll.health = 50;
		troll.attack = 25;
		troll.defense = 15;
	while(troll.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 35){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(troll, hero);
			if(chance % 2 == 0){
				print_to_path("Threw a small axe at you, hitting your chest dealing " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("The Troll smashed you with his club for " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(troll.health);
			generalAttack(hero, troll);
			print_to_path("hero has attacked");
			print_to_path(troll.health);
		}
		update_status();
		totalKills += 1;
	}
}

function golemsAttack() {
var golem = new Character();
		golem.health = 60;
		golem.attack = 10;
		golem.defense = 50;
	while(golem.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 20){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(golem, hero);
			if(chance % 2 == 0){
				print_to_path("Flails its arms smashing you into the ground. You took " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("Stomps its foot on the ground causing rocks to fall on you from the nearby mountain. You took " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(golem.health);
			generalAttack(hero, golem);
			print_to_path("hero has attacked");
			print_to_path(golem.health);
		}
		update_status();
		totalKills += 1;
	}
}

function dragonAttack() {
// atk 30
var dragon = new Character();
		dragon.health = 60;
		dragon.attack = 30;
		dragon.defense = 30;
	while(dragon.health > 0 && hero.health > 0)
	{
		var chance = Math.floor((Math.random() * 100) + 1);
		if(chance < 20){
			print_to_path(hero.health);
			damageTaken = hero.health;
			generalAttack(dragon, hero);
			if(chance % 2 == 0){
				print_to_path("Breaths green flames at you which inflicted a burn on you. You took " + (damageTaken - hero.health) + " Damage");
			}else{
				print_to_path("Swipes its tail along the floor flinging you into the wall. You took " + (damageTaken - hero.health) + " Damage");
			}
		}
		else {
			print_to_path(dragon.health);
			generalAttack(hero, dragon);
			print_to_path("hero has attacked");
			print_to_path(dragon.health);
		}
		update_status();
		totalKills += 1;
	}
}

function blackSquirrelAttacks() {

}

function Statistics()
<|endoftext|>


<commit_before>// stolen from: https://medium.com/developers-writing/building-a-desktop-application-with-electron-204203eeb658

'use strict';

var nconf = null; // later
var app = null; //
var fs = require('fs');
var isRenderer = require('is-electron-renderer');

var confdefaults = require('./blink1control2-config-defaults.json');
// var log = require('./logger');

// make sure we only use 'nconf' from non-renderer process
// because nconf uses yargs which makes webpack choke
if( isRenderer ) {
    var remote = require('electron').remote;
    nconf = remote.require('nconf');
    app = remote.app;
}
else {
    nconf = require('nconf');
    app = require('electron').app;
}

var conf_dir = app.getPath('userData');
var conf_file = conf_dir + '/blink1control2-config.json';
console.log("Blink1Control2: config file:"+conf_file);

// if no conf file, put in a default one
if( ! fs.existsSync(conf_file) ) {
    if( !fs.existsSync(conf_dir) ) {
        console.log("Blink1Control2: no config dir, creating it");
        fs.mkdirSync( conf_dir ); // for Windows
    }
    console.log("Blink1Control2: config: no conf file at "+conf_file+", writing defaults");
    fs.writeFileSync( conf_file, JSON.stringify(confdefaults,null, 2) );
}
nconf.file({file: conf_file});

var Config = {
    // start: function() {
    //     var logconfig = this.readSettings('logger');
    //     // log.setConfig( logconfig );
    // },
    saveSettings: function(settingKey, settingValue) {
        // console.log("saving key:",settingKey);
        nconf.set(settingKey, settingValue);
        nconf.save();
    },
    readSettings: function(settingKey) {
        nconf.load();
        return nconf.get(settingKey);
    },
    getFilepath: function() {
        return conf_file;
        // return nconf.stores.file.file;  //FIXME: seems weird
    }
    // getUserDataHome: function() {
    //     var userDataHome = app.getPath('userData');
    //     return userDataHome;
    // }
};

module.exports = Config;
<commit_msg>config file saving performance improvements, mostly on Preferences pane because configuration.js is dumb<commit_after>// stolen from: https://medium.com/developers-writing/building-a-desktop-application-with-electron-204203eeb658

'use strict';

var nconf = null; // later
var app = null; //
var fs = require('fs');
var isRenderer = require('is-electron-renderer');

var confdefaults = require('./blink1control2-config-defaults.json');
// var log = require('./logger');

// make sure we only use 'nconf' from non-renderer process
// because nconf uses yargs which makes webpack choke
if( isRenderer ) {
    var remote = require('electron').remote;
    nconf = remote.require('nconf');
    app = remote.app;
}
else {
    nconf = require('nconf');
    app = require('electron').app;
}

var conf_dir = app.getPath('userData');
var conf_file = conf_dir + '/blink1control2-config.json';
console.log("Blink1Control2: config file:"+conf_file);

// if no conf file, put in a default one
if( ! fs.existsSync(conf_file) ) {
    if( !fs.existsSync(conf_dir) ) {
        console.log("Blink1Control2: no config dir, creating it");
        fs.mkdirSync( conf_dir ); // for Windows
    }
    console.log("Blink1Control2: config: no conf file at "+conf_file+", writing defaults");
    fs.writeFileSync( conf_file, JSON.stringify(confdefaults,null, 2) );
}
nconf.file({file: conf_file});

var Config = {
  saveTimer:null,
    // start: function() {
    //     var logconfig = this.readSettings('logger');
    //     // log.setConfig( logconfig );
    // },
    saveSettings: function(settingKey, settingValue) {
        // console.log("saving key:",settingKey);
        nconf.set(settingKey, settingValue);
        //nconf.save();
        this.queueSave();
    },
    readSettings: function(settingKey) {
        nconf.load();
        return nconf.get(settingKey);
    },
    getFilepath: function() {
        return conf_file;
        // return nconf.stores.file.file;  //FIXME: seems weird
    },
    queueSave: function() {
      var self = this;
      if( !self.saveTimer ) {
        // console.log("queueSave: starting timer");
        self.saveTimer = setTimeout( function() {
          nconf.save();
          self.saveTimer = null;
          // console.log("queueSave: saved!");
        }, 1000 );
      }
      else { // do nothing, wait for timer to expire to save us
        // console.log("queueSave: timer already started")
      }
    }
    // getUserDataHome: function() {
    //     var userDataHome = app.getPath('userData');
    //     return userDataHome;
    // }
};

module.exports = Config;
<|endoftext|>


<commit_before>'use strict'
import React, {Component} from 'react'
import {Navigator, View, Text, TouchableOpacity} from 'react-native'
import {Provider, connect} from 'react-redux'
const ReactRedux = require('react-redux')
const store = require ('../store')
const SplashPage = require('../view/splashpage')
const Lobby = require('../view/lobby')
const ProjectOverview = require('../view/projectoverview')

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {store: store}
    store.subscribe(()=>{
      this.setState({store: store.getState()})
    })
  }

  render() {
    return(
    <Provider store={store}>
      <Navigator //NOTE: copy pasted
        initialRoute={{id: 'SplashPage'}}
        renderScene={this.renderScene.bind(this)}
        configureScene={(route) => {
          if (route.sceneConfig) {
            console.log(route.sceneConfig)
            return route.sceneConfig;
          }
          return Navigator.SceneConfigs.FloatFromRight;
        }} />
    </Provider>
    )
  }

  renderScene(route,navigator) {
    let routeId = route.id
    switch(routeId) {
      case 'SplashPage':
        return (<SplashPage navigator={navigator}/>)
      case 'Lobby':
        return (<Lobby navigator={navigator}/>)
      case 'ProjectOverview':
        return (<ProjectOverview navigator={navigator} projID={route.projID}/>)
      default:
        return this.noRoute(route, navigator)
    }
  }

  noRoute(route, navigator) {
    return (
      <View style={{flex: 1, alignItems: 'stretch', justifyContent: 'center'}}>
        <TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
            onPress={() => navigator.pop()}>
          <Text style={{color: 'red', fontWeight: 'bold'}}>the route {route.id} does not exist</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
module.exports = App
<commit_msg>firebase change listener which updates redux-state<commit_after>'use strict'
import React, {Component} from 'react'
import {Navigator, View, Text, TouchableOpacity} from 'react-native'
import {Provider, connect} from 'react-redux'
const ReactRedux = require('react-redux')
const store = require ('../store')
const actions = require('../actions')
const SplashPage = require('../view/splashpage')
const Lobby = require('../view/lobby')
const ProjectOverview = require('../view/projectoverview')
const firebase = require('../reusables/firebase')

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {store: store}
    store.subscribe(()=>{
      this.setState({store: store.getState()})
    })
  }

  componentWillMount() {
    firebase.listenToProjects(()=>store.dispatch(actions.updateProjects()))
  }

  render() {
    return(
    <Provider store={store}>
      <Navigator //NOTE: copy pasted
        initialRoute={{id: 'SplashPage'}}
        renderScene={this.renderScene.bind(this)}
        configureScene={(route) => {
          if (route.sceneConfig) {
            console.log(route.sceneConfig)
            return route.sceneConfig;
          }
          return Navigator.SceneConfigs.FloatFromRight;
        }} />
    </Provider>
    )
  }

  renderScene(route,navigator) {
    let routeId = route.id
    switch(routeId) {
      case 'SplashPage':
        return (<SplashPage navigator={navigator}/>)
      case 'Lobby':
        return (<Lobby navigator={navigator}/>)
      case 'ProjectOverview':
        return (<ProjectOverview navigator={navigator} projID={route.projID}/>)
      default:
        return this.noRoute(route, navigator)
    }
  }

  noRoute(route, navigator) {
    return (
      <View style={{flex: 1, alignItems: 'stretch', justifyContent: 'center'}}>
        <TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
            onPress={() => navigator.pop()}>
          <Text style={{color: 'red', fontWeight: 'bold'}}>the route {route.id} does not exist</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
module.exports = App
<|endoftext|>