<commit_before>// CONSTANTS
var image_default = '/home/pi/losp/grey.png';
var splash = '/home/pi/losp/welcome.png';
var dockImg = '/home/pi/losp/reset.png';
// Beacon 1
var image10 = '/home/pi/losp/Ohm_1_A.jpg';
var image11 = '/home/pi/losp/Ohm_1_R.jpg';
var audio10 = '/home/pi/losp/a-draft.wav';
var audio11 = '/home/pi/losp/r-draft.wav';
// Beacon 2
var image20 = '/home/pi/losp/Ohm_2_B.jpg';
var image21 = '/home/pi/losp/Ohm_2_Q.jpg';
var audio20 = '/home/pi/losp/b-draft.wav';
var audio21 = '/home/pi/losp/q-draft.wav';
// Beacon 3
var image30 = '/home/pi/losp/Ohm_3_C.jpg';
var image31 = '/home/pi/losp/Ohm_3_P.jpg';
var audio30 = '/home/pi/losp/c-draft.wav';
var audio31 = '/home/pi/losp/p-draft.wav';
// Beacon 4
var image40 = '/home/pi/losp/Ohm_4_D.jpg';
var image41 = '/home/pi/losp/Ohm_4_O.jpg';
var audio40 = '/home/pi/losp/d-draft.wav';
var audio41 = '/home/pi/losp/o-draft.wav';
// Beacon 5
var image50 = '/home/pi/losp/Ohm_5_E.jpg';
var image51 = '/home/pi/losp/Ohm_5_N.jpg';
var audio50 = '/home/pi/losp/e-draft.wav';
var audio51 = '/home/pi/losp/n-draft.wav';
// Beacon 6
var image60 = '/home/pi/losp/Ohm_6_F.jpg';
var image61 = '/home/pi/losp/Ohm_6_M.jpg';
var audio60 = '/home/pi/losp/f-draft.wav';
var audio61 = '/home/pi/losp/m-draft.wav';
// Beacon 7
var image70 = '/home/pi/losp/Ohm_7_G.jpg';
var image71 = '/home/pi/losp/Ohm_7_L.jpg';
var audio70 = '/home/pi/losp/g-draft.wav';
var audio71 = '/home/pi/losp/l-draft.wav';
// Beacon 8
var image80 = '/home/pi/losp/Ohm_8_H.jpg';
var image81 = '/home/pi/losp/Ohm_8_J.jpg';
var audio80 = '/home/pi/losp/h-draft.wav';
var audio81 = '/home/pi/losp/j-draft.wav';
// Beacon 9
var image90 = '/home/pi/losp/Ohm_9_I.jpg';
var image91 = '/home/pi/losp/Ohm_9_K.jpg';
var audio90 = '/home/pi/losp/i-draft.wav';
var audio91 = '/home/pi/losp/k-draft.wav';

var rangeLimit = 3;
var playMax = 2;
var lastPlayed = '';
var checking = false;
var docked = false;
var timeLimit = 0;
var timer;

// Load beacon scanner package
var UriBeaconScanner = require('uri-beacon-scanner');
// load package to run child process
var childProcess = require('child_process');

startTimer = function() {
    timer = setTimeout(function() {
        docked = false;
        imgDisplay(splash);
    }, 5000);
};

resetTimer = function() {
    clearTimeout(timer);
    startTimer();
};

function imgDisplay(img) {
    picture = childProcess.exec('sudo fbi -T 2 -d /dev/fb1 -noverbose -a '
                                            + img, function(error, stdout, stderr) {
        if (error) {
            console.log(error.stack);
            console.log('Error code: '+error.code);
            console.log('Signal received: '+error.signal);
        }
        console.log('Child Process STDOUT: '+stdout);
        console.log('Child Process STDERR: '+stderr);
    });
    picture.on('exit', function(code) {
        console.log('Show exit code '+code);
        // UriBeaconScanner.startScanning();
    });
};

function reset(img) {
    if(!docked) {
        imgDisplay(img);
    };
    docked = true;
    lastPlayed = '';
    resetTimer();
    number1.startOver();
    number2.startOver();
    number3.startOver();
    number4.startOver();
    number5.startOver();
    number6.startOver();
    number7.startOver();
    number8.startOver();
    number9.startOver();
};

// Ranging function
function calc_range(rssi, tx_power) {
    var diff_db = tx_power - rssi;
    var ratio_linear = Math.pow(10, diff_db / 10);
    var r = Math.sqrt(ratio_linear);
    console.log('Range: ' +Math.round(r))
    return Math.round(r);
}

// Ranging function for Blesh beacons
function calc_range_alt(rssi, tx_power) {
    // Alternative calculation to test, likely very similar answer!
    // rssi1m needs to be found with testing
    // Based on; http://matts-soup.blogspot.co.uk/2013/12/finding-distance-from-rssi.html
    var rssi1m = -40;
    var pathLoss = 5.2; // free space
    if (rssi > 0) { rssi = 0 };
    var rawRange = Math.pow(10, (rssi - (tx_power + rssi1m)) / (-10*pathLoss));
    console.log('rangeAlt = ' +  Math.round(rawRange));
    return Math.round(rawRange);
}

// Step up 'listen' station
var station = function(name, audio1, image1, audio2, image2) {
    console.log('station creation');
    this.playCount = 0;
    this.lastPlayed  = 0;
    this.showImage = true;
    this.beacon = name;
    this.audio1 = audio1;
    this.image1 = image1;
    this.audio2 = audio2;
    this.image2 = image2;
    this.audio = this.audio1;
    this.image = this.image1;
};

// Test for if station is in range and hasn't just been played
station.prototype.playTest = function(txPower, rssi) {
    now = Math.floor(new Date()/1000);
    if (calc_range_alt(rssi, txPower) < rangeLimit
                && this.playCount < playMax
                && this.beacon != lastPlayed
                && now - this.lastPlayed > timeLimit) {
        if (this.playCount == 0) {
            console.log('Play beacon ' + this.beacon + ' ' + this.playCount)
            this.playCount = 1;
            this.image = this.image1;
            this.audio = this.audio1;
            lastPlayed = this.beacon;
        } else {
            console.log('Play beacon ' + this.beacon + ' ' + this.playCount)
            this.playCount = 2;
            this.image = this.image2;
            this.audio = this.audio2;
            lastPlayed = this.beacon;
        }
        this.lastPlayed = now;
        this.showImage = true;
        return true;
    } else {
        console.log('This beacon: ' + this.beacon + ' last played: ' + lastPlayed);
        console.log('playCount: ' + this.playCount)
        this.showImage = false;
        return false;
    }
}

// Show the image for this station
station.prototype.show = function() {
    if (this.showImage) {
        this.picture = childProcess.exec('sudo fbi -T 2 -d /dev/fb1 -noverbose -a '
                                            + this.image, function(error, stdout, stderr) {
            if (error) {
                console.log(error.stack);
                console.log('Error code: '+error.code);
                console.log('Signal received: '+error.signal);
            }
            console.log('Child Process STDOUT: '+stdout);
            console.log('Child Process STDERR: '+stderr);
        });

        this.picture.on('exit', function(code) {
            console.log('Show exit code '+code);
            // UriBeaconScanner.startScanning();
        });
    };
};

// Play the audio for this station
station.prototype.play = function(txPower, rssi) {
    if (this.playTest(txPower, rssi)) {
        UriBeaconScanner.stopScanning();
        console.log('Play tune...');
        this.sound = childProcess.exec('aplay ' +this.audio, function(error, stdout, stderr) {
            if (error) {
                console.log(error.stack);
                console.log('Error code: '+error.code);
                console.log('Signal received: '+error.signal);
            }
            console.log('Child Process STDOUT: '+stdout);
            console.log('Child Process STDERR: '+stderr);
        });

        this.sound.on('exit', function(code) {
            console.log('Child process exited with exit code '+code);
            console.log('Tune has finished');
            walking.show();
            UriBeaconScanner.startScanning(true);
        });
    };
};

station.prototype.startOver = function() {
    this.playCount = 0;
    this.lastPlayed  = 0;
    this.showImage = true;
};

// Create instances of the stations
walking = new station('walking', '', image_default, '', '');
number1 = new station('number1', audio10, image10, audio11, image11);
number2 = new station('number2', audio20, image20, audio21, image21);
number3 = new station('number3', audio30, image30, audio31, image31);
number4 = new station('number4', audio40, image40, audio41, image41);
number5 = new station('number5', audio50, image50, audio51, image51);
number6 = new station('number6', audio60, image60, audio61, image61);
number7 = new station('number7', audio70, image70, audio71, image71);
number8 = new station('number8', audio80, image80, audio81, image81);
number9 = new station('number9', audio90, image90, audio91, image91);

// Event handler for when beacon is discovered
UriBeaconScanner.on('discover', function(uriBeacon) {
    if (!checking && !docked) {
        checking = true;
        console.log();
        console.log('discovered UriBeacon:');
        console.log('  uri      = ' + uriBeacon.uri);
        console.log('  flags    = ' + uriBeacon.flags);
        console.log('  TX power = ' + uriBeacon.txPower);
        console.log('  RSSI     = ' + uriBeacon.rssi);
        if(uriBeacon.uri.search('number1') > 0) {
            number1.play(uriBeacon.txPower, uriBeacon.rssi);
            number1.show();
        } else if(uriBeacon.uri.search('number2') > 0) {
            number2.play(uriBeacon.txPower, uriBeacon.rssi);
            number2.show();
        } else if(uriBeacon.uri.search('number3') > 0) {
            number3.play(uriBeacon.txPower, uriBeacon.rssi);
            number3.show();
        } else if(uriBeacon.uri.search('number4') > 0) {
            number4.play(uriBeacon.txPower, uriBeacon.rssi);
            number4.show();
        } else if(uriBeacon.uri.search('number5') > 0) {
            number5.play(uriBeacon.txPower, uriBeacon.rssi);
            number5.show();
        } else if(uriBeacon.uri.search('number6') > 0) {
            number6.play(uriBeacon.txPower, uriBeacon.rssi);
            number6.show();
        } else if(uriBeacon.uri.search('number7') > 0) {
            number7.play(uriBeacon.txPower, uriBeacon.rssi);
            number7.show();
        } else if(uriBeacon.uri.search('number8') > 0) {
            number8.play(uriBeacon.txPower, uriBeacon.rssi);
            number8.show();
        } else if(uriBeacon.uri.search('number9') > 0) {
            number9.play(uriBeacon.txPower, uriBeacon.rssi);
            number9.show();
        }
        checking = false;
    }
    if(uriBeacon.uri.search('1972') > 0) {
        if(calc_range(uriBeacon.rssi, uriBeacon.txPower) < 3 ) {
            reset(dockImg)
        }

    }
});

imgDisplay(splash);
resetTimer();
// Start scanning for beacons (duplicates allowed)
UriBeaconScanner.startScanning(true);
<commit_msg>Post rehearsal update<commit_after>// CONSTANTS
var image_default = '/home/pi/losp/grey.png';
var splash = '/home/pi/losp/welcome.png';
var dockImg = '/home/pi/losp/reset.png';
// Beacon 1
var image10 = '/home/pi/losp/Revised_Ohm_1_A.jpg';
var image11 = '/home/pi/losp/Revised_Ohm_1_R.jpg';
var audio10 = '/home/pi/losp/a-draft.wav';
var audio11 = '/home/pi/losp/r-draft.wav';
// Beacon 2
var image20 = '/home/pi/losp/Revised_Ohm_2_B.jpg';
var image21 = '/home/pi/losp/Revised_Ohm_2_Q.jpg';
var audio20 = '/home/pi/losp/b-draft.wav';
var audio21 = '/home/pi/losp/q-draft.wav';
// Beacon 3
var image30 = '/home/pi/losp/Revised_Ohm_3_C.jpg';
var image31 = '/home/pi/losp/Revised_Ohm_3_P.jpg';
var audio30 = '/home/pi/losp/c-draft.wav';
var audio31 = '/home/pi/losp/p-draft.wav';
// Beacon 4
var image40 = '/home/pi/losp/Revised_Ohm_4_D.jpg';
var image41 = '/home/pi/losp/Revised_Ohm_4_O.jpg';
var audio40 = '/home/pi/losp/d-draft.wav';
var audio41 = '/home/pi/losp/o-draft.wav';
// Beacon 5
var image50 = '/home/pi/losp/Revised_Ohm_5_E.jpg';
var image51 = '/home/pi/losp/Revised_Ohm_5_J.jpg';
var audio50 = '/home/pi/losp/e-draft.wav';
var audio51 = '/home/pi/losp/n-draft.wav';
// Beacon 6
var image60 = '/home/pi/losp/Revised_Ohm_6_F.jpg';
var image61 = '/home/pi/losp/Revised_Ohm_6_K.jpg';
var audio60 = '/home/pi/losp/f-draft.wav';
var audio61 = '/home/pi/losp/m-draft.wav';
// Beacon 7
var image70 = '/home/pi/losp/Revised_Ohm_7_G.jpg';
var image71 = '/home/pi/losp/Revised_Ohm_7_L.jpg';
var audio70 = '/home/pi/losp/g-draft.wav';
var audio71 = '/home/pi/losp/l-draft.wav';
// Beacon 8
var image80 = '/home/pi/losp/Revised_Ohm_8_H.jpg';
var image81 = '/home/pi/losp/Revised_Ohm_8_M.jpg';
var audio80 = '/home/pi/losp/h-draft.wav';
var audio81 = '/home/pi/losp/j-draft.wav';
// Beacon 9
var image90 = '/home/pi/losp/Reivsed_Ohm_9_I.jpg';
var image91 = '/home/pi/losp/Reivsed_Ohm_9_N.jpg';
var audio90 = '/home/pi/losp/i-draft.wav';
var audio91 = '/home/pi/losp/k-draft.wav';

var rangeLimit = 2.5;
var playMax = 99;
var lastPlayed = '';
var checking = false;
var docked = false;
var timeLimit = 0;
var timer;

// Load beacon scanner package
var UriBeaconScanner = require('uri-beacon-scanner');
// load package to run child process
var childProcess = require('child_process');

startTimer = function() {
    timer = setTimeout(function() {
        docked = false;
        imgDisplay(splash);
    }, 5000);
};

resetTimer = function() {
    clearTimeout(timer);
    startTimer();
};

function imgDisplay(img) {
    picture = childProcess.exec('sudo fbi -T 2 -d /dev/fb1 -noverbose -a '
                                            + img, function(error, stdout, stderr) {
        if (error) {
            console.log(error.stack);
            console.log('Error code: '+error.code);
            console.log('Signal received: '+error.signal);
        }
        console.log('Child Process STDOUT: '+stdout);
        console.log('Child Process STDERR: '+stderr);
    });
    picture.on('exit', function(code) {
        console.log('Show exit code '+code);
        // UriBeaconScanner.startScanning();
    });
};

function reset(img) {
    if(!docked) {
        imgDisplay(img);
    };
    docked = true;
    lastPlayed = '';
    resetTimer();
    number1.startOver();
    number2.startOver();
    number3.startOver();
    number4.startOver();
    number5.startOver();
    number6.startOver();
    number7.startOver();
    number8.startOver();
    number9.startOver();
};

function round2(rawValue) {
    return Math.round(rawValue * 100)/100
}

// Ranging function
function calc_range(rssi, tx_power) {
    var diff_db = tx_power - rssi;
    var ratio_linear = Math.pow(10, diff_db / 10);
    var r = Math.sqrt(ratio_linear);
    console.log('Range: ' +Math.round(r))
    return Math.round(r);
}

// Ranging function for Blesh beacons
function calc_range_alt(rssi, tx_power) {
    // Alternative calculation to test, likely very similar answer!
    // rssi1m needs to be found with testing
    // Based on; http://matts-soup.blogspot.co.uk/2013/12/finding-distance-from-rssi.html
    var rssi1m = -40;
    var pathLoss = 5.2; // free space
    if (rssi > 0) { rssi = 0 };
    var rawRange = Math.pow(10, (rssi - (tx_power + rssi1m)) / (-10*pathLoss));
    console.log('rangeAlt = ' +  round2(rawRange));
    return round2(rawRange);
}

// Step up 'listen' station
var station = function(name, audio1, image1, audio2, image2) {
    console.log('station creation');
    this.playCount = 0;
    this.lastPlayed  = 0;
    this.showImage = true;
    this.beacon = name;
    this.audio1 = audio1;
    this.image1 = image1;
    this.audio2 = audio2;
    this.image2 = image2;
    this.audio = this.audio1;
    this.image = this.image1;
};

// Test for if station is in range and hasn't just been played
station.prototype.playTest = function(txPower, rssi) {
    now = Math.floor(new Date()/1000);
    if (calc_range_alt(rssi, txPower) < rangeLimit
                && this.playCount < playMax
                && this.beacon != lastPlayed
                && now - this.lastPlayed > timeLimit) {
        if (this.playCount % 2 === 0) {
            console.log('Play beacon ' + this.beacon + ' ' + this.playCount)
            this.playCount++;
            this.image = this.image1;
            this.audio = this.audio1;
            lastPlayed = this.beacon;
        } else {
            console.log('Play beacon ' + this.beacon + ' ' + this.playCount)
            this.playCount++;
            this.image = this.image2;
            this.audio = this.audio2;
            lastPlayed = this.beacon;
        }
        this.lastPlayed = now;
        this.showImage = true;
        return true;
    } else {
        console.log('This beacon: ' + this.beacon + ' last played: ' + lastPlayed);
        console.log('playCount: ' + this.playCount)
        this.showImage = false;
        return false;
    }
}

// Show the image for this station
station.prototype.show = function() {
    if (this.showImage) {
        this.picture = childProcess.exec('sudo fbi -T 2 -d /dev/fb1 -noverbose -a '
                                            + this.image, function(error, stdout, stderr) {
            if (error) {
                console.log(error.stack);
                console.log('Error code: '+error.code);
                console.log('Signal received: '+error.signal);
            }
            console.log('Child Process STDOUT: '+stdout);
            console.log('Child Process STDERR: '+stderr);
        });

        this.picture.on('exit', function(code) {
            console.log('Show exit code '+code);
            // UriBeaconScanner.startScanning();
        });
    };
};

// Play the audio for this station
station.prototype.play = function(txPower, rssi) {
    if (this.playTest(txPower, rssi)) {
        UriBeaconScanner.stopScanning();
        console.log('Play tune...');
        this.sound = childProcess.exec('aplay ' +this.audio, function(error, stdout, stderr) {
            if (error) {
                console.log(error.stack);
                console.log('Error code: '+error.code);
                console.log('Signal received: '+error.signal);
            }
            console.log('Child Process STDOUT: '+stdout);
            console.log('Child Process STDERR: '+stderr);
        });

        this.sound.on('exit', function(code) {
            console.log('Child process exited with exit code '+code);
            console.log('Tune has finished');
            walking.show();
            UriBeaconScanner.startScanning(true);
        });
    };
};

station.prototype.startOver = function() {
    this.playCount = 0;
    this.lastPlayed  = 0;
    this.showImage = true;
};

// Create instances of the stations
walking = new station('walking', '', image_default, '', '');
number1 = new station('number1', audio10, image10, audio11, image11);
number2 = new station('number2', audio20, image20, audio21, image21);
number3 = new station('number3', audio30, image30, audio31, image31);
number4 = new station('number4', audio40, image40, audio41, image41);
number5 = new station('number5', audio50, image50, audio51, image51);
number6 = new station('number6', audio60, image60, audio61, image61);
number7 = new station('number7', audio70, image70, audio71, image71);
number8 = new station('number8', audio80, image80, audio81, image81);
number9 = new station('number9', audio90, image90, audio91, image91);

// Event handler for when beacon is discovered
UriBeaconScanner.on('discover', function(uriBeacon) {
    if (!checking && !docked) {
        checking = true;
        console.log();
        console.log('discovered UriBeacon:');
        console.log('  uri      = ' + uriBeacon.uri);
        console.log('  flags    = ' + uriBeacon.flags);
        console.log('  TX power = ' + uriBeacon.txPower);
        console.log('  RSSI     = ' + uriBeacon.rssi);
        if(uriBeacon.uri.search('number1') > 0) {
            number1.play(uriBeacon.txPower, uriBeacon.rssi);
            number1.show();
        } else if(uriBeacon.uri.search('number2') > 0) {
            number2.play(uriBeacon.txPower, uriBeacon.rssi);
            number2.show();
        } else if(uriBeacon.uri.search('number3') > 0) {
            number3.play(uriBeacon.txPower, uriBeacon.rssi);
            number3.show();
        } else if(uriBeacon.uri.search('number4') > 0) {
            number4.play(uriBeacon.txPower, uriBeacon.rssi);
            number4.show();
        } else if(uriBeacon.uri.search('number5') > 0) {
            number5.play(uriBeacon.txPower, uriBeacon.rssi);
            number5.show();
        } else if(uriBeacon.uri.search('number6') > 0) {
            number6.play(uriBeacon.txPower, uriBeacon.rssi);
            number6.show();
        } else if(uriBeacon.uri.search('number7') > 0) {
            number7.play(uriBeacon.txPower, uriBeacon.rssi);
            number7.show();
        } else if(uriBeacon.uri.search('number8') > 0) {
            number8.play(uriBeacon.txPower, uriBeacon.rssi);
            number8.show();
        } else if(uriBeacon.uri.search('number9') > 0) {
            number9.play(uriBeacon.txPower, uriBeacon.rssi);
            number9.show();
        }
        checking = false;
    }
    if(uriBeacon.uri.search('1972') > 0) {
        if(calc_range(uriBeacon.rssi, uriBeacon.txPower) < 3 ) {
            reset(dockImg)
        }

    }
});

imgDisplay(splash);
resetTimer();
// Start scanning for beacons (duplicates allowed)
UriBeaconScanner.startScanning(true);
<|endoftext|>


<commit_before>'use strict';
/*
 * Build javascript passthrough modules for highlight.js languages
*/
const path = require('path');
const fs = require('fs');
const camel = require('to-camel-case');

fs.readdir(path.join(__dirname, '../node_modules/highlight.js/lib/languages'), (err, files) => {
  files.forEach(createLanguagePassthroughModule);

  const availableLanguageNames = files.map(file => file.split('.js')[0]);
  const languagesLi = availableLanguageNames.map(name => `\n* ${camel(name)}`);
  const languageMD = `## Available \`language\` props ${languagesLi.join('')}`;
  fs.writeFile(path.join(__dirname, '../AVAILABLE_LANGUAGES.MD'), languageMD);

  const defaultExports = availableLanguageNames.map(name => `export { default as ${camel(name)} } from './${name}';\n`);
  fs.writeFile(path.join(__dirname, '../src/languages/index.js'), defaultExports.join(''));
});

function createLanguagePassthroughModule(file) {
  const fileWithoutJS = file.split('.js')[0];
  const fileCamel = camel(fileWithoutJS)
  const lines = [
    `import ${fileCamel} from "highlight.js/lib/languages/${fileWithoutJS}"`,
    `export default ${fileCamel}`,
    ''
  ]

  fs.writeFile(path.join(__dirname, `../src/languages/${file}`), lines.join(";\n"));
}
<commit_msg>codacy checks<commit_after>'use strict';
/*
 * Build javascript passthrough modules for highlight.js languages
*/
const path = require('path');
const fs = require('fs');
const camel = require('to-camel-case');

function createLanguagePassthroughModule(file) {
  const fileWithoutJS = file.split('.js')[0];
  const fileCamel = camel(fileWithoutJS);
  const lines = [
    `import ${fileCamel} from "highlight.js/lib/languages/${fileWithoutJS}"`,
    `export default ${fileCamel}`,
    ''
  ];

  fs.writeFile(path.join(__dirname, `../src/languages/${file}`), lines.join(';\n'));
}

fs.readdir(path.join(__dirname, '../node_modules/highlight.js/lib/languages'), (err, files) => {
  if (err) {
    process.exit(1);
  }

  files.forEach(createLanguagePassthroughModule);

  const availableLanguageNames = files.map((file) => file.split('.js')[0]);
  const languagesLi = availableLanguageNames.map((name) => `\n* ${camel(name)}`);
  const languageMD = `## Available \`language\` props ${languagesLi.join('')}`;
  fs.writeFile(path.join(__dirname, '../AVAILABLE_LANGUAGES.MD'), languageMD);

  const defaultExports = availableLanguageNames.map((name) => `export { default as ${camel(name)} } from './${name}';\n`);
  fs.writeFile(path.join(__dirname, '../src/languages/index.js'), defaultExports.join(''));
});
<|endoftext|>


<commit_before>/**
 * Copyright...
 */
#target "InDesign";

(function(glob, app) {
  var pub = {};

  // ----------------------------------------
  // constants
  pub.VERSION = "0.1";
  pub.CMYK = "CMYK";
  pub.RGB = "RGB";
  pub.PT = "pt";
  pub.PX = "px";
  pub.CM = "cm";
  pub.MM = "mm";
  var ERROR_PREFIX = "### Basil Error -> ",
    WARNING_PREFIX = "### Basil Warning -> ";

  // ----------------------------------------
  // public vars
  pub.width = null;
  pub.height = null;

  // ----------------------------------------
  // private vars
  var currDoc = null,
    currSpread = null,
    currPage = null,
    currLayer = null,
    currUnits = null,
    currColorMode = null,
    currFillColor = null,
    currStrokeColor = null,
    currStrokeTint = null,
    currFillTint = null,
    currStrokeWeight = null;

  // ----------------------------------------
  // global functions

  if (!glob.forEach) {
    glob.forEach = function(collection, cb) {
      for (var i = 0, len = collection.length; i < len; i++) {
        cb(collection[i]);
      }
    };
  }

  // ----------------------------------------
  // Environment

  /**
   * Sets or possibly creates the current document and returns it.
   * If the param doc is not given the current document gets set to the active document
   * in the application. If no document at all is open, a new document gets created.
   * @param  {Document} [doc] The document to set the current document to.
   * @return {Document} The current document instance.
   */
  pub.doc = function(doc) {
    if (doc instanceof Document) {
      currDoc = doc;
      addCurrDocCloseEventListener();
    }
    return currentDoc();
  };

  /**
   * Returns the current page and possibly sets it.
   * @param  {Page|Number} [page] The page or page index to set the current page to.
   * @return {Page} The current page instance.
   */
  pub.page = function(page) {
    if (page instanceof Page) {
      currPage = page;
    } else if (typeof page === 'number') {
      var tempPage = currentDoc().pages[page];
      try {
        tempPage.id;
      } catch (e) {
        error('Page ' + page + ' does not exist.');
      }
      currPage = tempPage;
    }
    return currentPage();
  };

  /**
   * Returns the current spread and possibly sets it.
   * @param  {Spread|Number} [spread] The spread or spread index to set the current spread to.
   * @return {Spread} The current spread instance.
   */
  pub.spread = function(spread) {
    if (spread instanceof Spread) {
      currSpread = spread;
    } else if (typeof spread === 'number') {
      var tempSpread = currentDoc().spreads[spread];
      try {
        tempSpread.id;
      } catch (e) {
        error('Spread ' + spread + ' does not exist.');
      }
      currSpread = tempSpread;
    }
    return currentSpread();
  };

  /**
   * Returns the current layer and possibly sets it.
   * @param  {Layer|String} [layer] The layer or layer name to set the current layer to.
   * @return {Layer} The current page instance.
   */
  pub.layer = function(layer) {
    if (layer instanceof Layer) {
      currLayer = layer;
    } else if (typeof layer === 'string') {
      var layers = currentDoc().layers;
      currLayer = layers.item(layer);
      if (!currLayer.isValid) {
        currLayer = layers.add({name: layer});
      }
    }
    return currentLayer();
  };

  /**
   * Sets the units of the document (like right clicking the rulers).
   * @param  {Constant} supported: PT, PX, CM or MM
   * @return {Constant} current unit setting
   */
  pub.units = function (units) {
    if (!units) return currUnits;

    if (units === pub.CM ||
        units === pub.MM ||
        units === pub.PT ||
        units === pub.PX ) {
      var unitType = null;
      if      (units === pub.CM) unitType = MeasurementUnits.centimeters;
      else if (units === pub.MM) unitType = MeasurementUnits.millimeters;
      else if (units === pub.PT) unitType = MeasurementUnits.points;
      else if (units === pub.PX) unitType = MeasurementUnits.pixels;
      var doc = currentDoc();
      with (doc.viewPreferences){
        //* MeasurementUnits.agates
        //* MeasurementUnits.picas
        //* MeasurementUnits.points
        //* MeasurementUnits.inches
        //* MeasurementUnits.inchesDecimal
        //* MeasurementUnits.millimeters
        //* MeasurementUnits.centimeters
        //* MeasurementUnits.ciceros
        horizontalMeasurementUnits = unitType;
        verticalMeasurementUnits = unitType;
      }
      currUnits = units;
    } else {
      error("Not supported unit");
    }
    return currUnits;
  }

  // ----------------------------------------
  // Shape
  /**
   * Draws a rectangle to the page.
   * @param  {Number} Position X
   * @param  {Number} Position Y
   * @param  {Number} Width
   * @param  {Number} Height
   * @return {Rectangle}   new Rectangle
   */
  pub.rect = function(x, y, w, h){
    var rectBounds = [];
    rectBounds[0] = y;
    rectBounds[1] = x;
    rectBounds[2] = (y+h);
    rectBounds[3] = (x+w);
    var newRect = currentPage().rectangles.add( currentLayer() );
    with(newRect) {
      geometricBounds = rectBounds;
      strokeWeight = currStrokeWeight;
      strokeTint = currStrokeTint;
      fillColor = currFillColor;
      fillTint = currFillTint;
      strokeColor = currStrokeColor;
    }
    return newRect;
  };

  // ----------------------------------------
  // Color
  /**
   * Sets the color mode of basil, supported: CMYK or RGB.
   * @param  {Object} new color mode (optional)
   * @return {Object} current color mode
   */
  pub.colorMode = function(colorMode) {
    if (!colorMode) return currLayer;

    if (colorMode === pub.CMYK || colorMode === pub.RGB) {
      currColorMode = colorMode;
    } else {
      error("Not supported color mode");
    }
    return currColorMode;
  };

  // ----------------------------------------
  // Typography
  // FIXME, set color + tint is missing
  pub.text = function(txt, x, y, w, h) {
    var textFrame = currentPage().textFrames.add( currentLayer() );
    textFrame.geometricBounds = [y, x, (y+h), (x+w)];
    textFrame.contents = txt;
    return textFrame;
  };

  // ----------------------------------------
  // Math
  var currentRandom = Math.random;
  pub.random = function() {
    if (arguments.length === 0) return currentRandom();
    if (arguments.length === 1) return currentRandom() * arguments[0];
    var aMin = arguments[0],
      aMax = arguments[1];
    return currentRandom() * (aMax - aMin) + aMin
  };

  function Marsaglia(i1, i2) {
    var z = i1 || 362436069,
      w = i2 || 521288629;
    var nextInt = function() {
      z = 36969 * (z & 65535) + (z >>> 16) & 4294967295;
      w = 18E3 * (w & 65535) + (w >>> 16) & 4294967295;
      return ((z & 65535) << 16 | w & 65535) & 4294967295
    };
    this.nextDouble = function() {
      var i = nextInt() / 4294967296;
      return i < 0 ? 1 + i : i
    };
    this.nextInt = nextInt
  }
  Marsaglia.createRandomized = function() {
    var now = new Date;
    return new Marsaglia(now / 6E4 & 4294967295, now & 4294967295)
  };

  pub.randomSeed = function(seed) {
    currentRandom = (new Marsaglia(seed)).nextDouble
  };

  pub.Random = function(seed) {
    var haveNextNextGaussian = false,
      nextNextGaussian, random;
    this.nextGaussian = function() {
      if (haveNextNextGaussian) {
        haveNextNextGaussian = false;
        return nextNextGaussian
      }
      var v1, v2, s;
      do {
        v1 = 2 * random() - 1;
        v2 = 2 * random() - 1;
        s = v1 * v1 + v2 * v2
      } while (s >= 1 || s === 0);
      var multiplier = Math.sqrt(-2 * Math.log(s) / s);
      nextNextGaussian = v2 * multiplier;
      haveNextNextGaussian = true;
      return v1 * multiplier
    };
    random = seed === undef ? Math.random : (new Marsaglia(seed)).nextDouble
  };

  pub.map = function(value, istart, istop, ostart, ostop) {
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
  };

  pub.constrain = function(aNumber, aMin, aMax) {
    return aNumber > aMax ? aMax : aNumber < aMin ? aMin : aNumber;
  };

  // ----------------------------------------
  // Input

  pub.findByLabel = function(label) {
    var result = [];
    var doc = currentDoc();
    for (var i = 0, len = doc.pageItems.length; i < len; i++) {
      var pageItem = doc.pageItems[i];
      if (pageItem.label === label) {
        result.push(pageItem);
      }
    }
    return result;
  };

  // ----------------------------------------
  // Output

  pub.println = function(msg) {
    $.writeln(msg);
  };

  pub.print = function(msg) {
    $.write(msg);
  };

  // ----------------------------------------
  // all private from here

  var init = function() {
    glob.b = pub;

    pub.units(pub.PT);

    // -- init internal state vars --
    currColorMode = pub.CMYK;
    currFillColor = currentDoc().swatches.item("Black"),
    currStrokeColor = currentDoc().swatches.item("Black");
    currStrokeWeight = 1;
    currStrokeTint = 100;
    currFillTint = 100;

    // -- init public vars --
    var pageSize = currentPageSize();
    pub.width = pageSize.width;
    pub.height = pageSize.height;

    welcome();
    runUserScript();
  };

  var runUserScript = function() {
    app.doScript(function() {
      if (typeof glob.setup === 'function') {
        glob.setup();
      }
      if (typeof glob.draw === 'function') {
        glob.draw();
      }
    }, ScriptLanguage.javascript, undefined, UndoModes.entireScript);
  };

  var welcome = function() {
    $.writeln("basil.js "
        + pub.VERSION
        + " "
        + "infos, feedback @ http://basiljs.ch");
  };

  var currentDoc = function() {
    if (!currDoc) {
      try {
        currDoc = app.activeDocument;
      } catch(e) {
        currDoc = app.documents.add();
      }
      addCurrDocCloseEventListener();
    }
    return currDoc;
  };

  var addCurrDocCloseEventListener = function(doc) {
    currDoc.addEventListener(Event.BEFORE_CLOSE, function() {
      currDoc = null;
      currSpread = null;
      currPage = null;
      currLayer = null;
    });
  }

  var currentLayer = function() {
    if (!currLayer) {
      currentDoc();
      currLayer = app.activeDocument.activeLayer;
    }
    return currLayer;
  };

  var currentSpread = function() {
    if (!currSpread) {
      currentDoc();
      currSpread = app.activeWindow.activeSpread;
    }
    return currSpread;
  };

  var currentPage = function() {
    if (!currPage) {
      currentDoc();
      currPage = app.activeWindow.activePage;
    }
    return currPage;
  };

  var currentPageSize = function () {
    var pageBounds = currentPage().bounds; // [y1, x1, y2, x2]
    var w = pageBounds[3] - pageBounds[1];
    var h = pageBounds[2] - pageBounds[0];
    return {width: w, height: h};
  };

  var error = function(msg) {
    $.writeln(ERROR_PREFIX + msg);
    throw msg;
  };

  var warning = function(msg) {
    $.writeln(WARNING_PREFIX + msg);
  };

  init();

})(this, app);

<commit_msg>removed utf8 bom<commit_after>/**
 * Copyright...
 */
#target "InDesign";

(function(glob, app) {
  var pub = {};

  // ----------------------------------------
  // constants
  pub.VERSION = "0.1";
  pub.CMYK = "CMYK";
  pub.RGB = "RGB";
  pub.PT = "pt";
  pub.PX = "px";
  pub.CM = "cm";
  pub.MM = "mm";
  var ERROR_PREFIX = "### Basil Error -> ",
    WARNING_PREFIX = "### Basil Warning -> ";

  // ----------------------------------------
  // public vars
  pub.width = null;
  pub.height = null;

  // ----------------------------------------
  // private vars
  var currDoc = null,
    currSpread = null,
    currPage = null,
    currLayer = null,
    currUnits = null,
    currColorMode = null,
    currFillColor = null,
    currStrokeColor = null,
    currStrokeTint = null,
    currFillTint = null,
    currStrokeWeight = null;

  // ----------------------------------------
  // global functions

  if (!glob.forEach) {
    glob.forEach = function(collection, cb) {
      for (var i = 0, len = collection.length; i < len; i++) {
        cb(collection[i]);
      }
    };
  }

  // ----------------------------------------
  // Environment

  /**
   * Sets or possibly creates the current document and returns it.
   * If the param doc is not given the current document gets set to the active document
   * in the application. If no document at all is open, a new document gets created.
   * @param  {Document} [doc] The document to set the current document to.
   * @return {Document} The current document instance.
   */
  pub.doc = function(doc) {
    if (doc instanceof Document) {
      currDoc = doc;
      addCurrDocCloseEventListener();
    }
    return currentDoc();
  };

  /**
   * Returns the current page and possibly sets it.
   * @param  {Page|Number} [page] The page or page index to set the current page to.
   * @return {Page} The current page instance.
   */
  pub.page = function(page) {
    if (page instanceof Page) {
      currPage = page;
    } else if (typeof page === 'number') {
      var tempPage = currentDoc().pages[page];
      try {
        tempPage.id;
      } catch (e) {
        error('Page ' + page + ' does not exist.');
      }
      currPage = tempPage;
    }
    return currentPage();
  };

  /**
   * Returns the current spread and possibly sets it.
   * @param  {Spread|Number} [spread] The spread or spread index to set the current spread to.
   * @return {Spread} The current spread instance.
   */
  pub.spread = function(spread) {
    if (spread instanceof Spread) {
      currSpread = spread;
    } else if (typeof spread === 'number') {
      var tempSpread = currentDoc().spreads[spread];
      try {
        tempSpread.id;
      } catch (e) {
        error('Spread ' + spread + ' does not exist.');
      }
      currSpread = tempSpread;
    }
    return currentSpread();
  };

  /**
   * Returns the current layer and possibly sets it.
   * @param  {Layer|String} [layer] The layer or layer name to set the current layer to.
   * @return {Layer} The current page instance.
   */
  pub.layer = function(layer) {
    if (layer instanceof Layer) {
      currLayer = layer;
    } else if (typeof layer === 'string') {
      var layers = currentDoc().layers;
      currLayer = layers.item(layer);
      if (!currLayer.isValid) {
        currLayer = layers.add({name: layer});
      }
    }
    return currentLayer();
  };

  /**
   * Sets the units of the document (like right clicking the rulers).
   * @param  {Constant} supported: PT, PX, CM or MM
   * @return {Constant} current unit setting
   */
  pub.units = function (units) {
    if (!units) return currUnits;

    if (units === pub.CM ||
        units === pub.MM ||
        units === pub.PT ||
        units === pub.PX ) {
      var unitType = null;
      if      (units === pub.CM) unitType = MeasurementUnits.centimeters;
      else if (units === pub.MM) unitType = MeasurementUnits.millimeters;
      else if (units === pub.PT) unitType = MeasurementUnits.points;
      else if (units === pub.PX) unitType = MeasurementUnits.pixels;
      var doc = currentDoc();
      with (doc.viewPreferences){
        //* MeasurementUnits.agates
        //* MeasurementUnits.picas
        //* MeasurementUnits.points
        //* MeasurementUnits.inches
        //* MeasurementUnits.inchesDecimal
        //* MeasurementUnits.millimeters
        //* MeasurementUnits.centimeters
        //* MeasurementUnits.ciceros
        horizontalMeasurementUnits = unitType;
        verticalMeasurementUnits = unitType;
      }
      currUnits = units;
    } else {
      error("Not supported unit");
    }
    return currUnits;
  }

  // ----------------------------------------
  // Shape
  /**
   * Draws a rectangle to the page.
   * @param  {Number} Position X
   * @param  {Number} Position Y
   * @param  {Number} Width
   * @param  {Number} Height
   * @return {Rectangle}   new Rectangle
   */
  pub.rect = function(x, y, w, h){
    var rectBounds = [];
    rectBounds[0] = y;
    rectBounds[1] = x;
    rectBounds[2] = (y+h);
    rectBounds[3] = (x+w);
    var newRect = currentPage().rectangles.add( currentLayer() );
    with(newRect) {
      geometricBounds = rectBounds;
      strokeWeight = currStrokeWeight;
      strokeTint = currStrokeTint;
      fillColor = currFillColor;
      fillTint = currFillTint;
      strokeColor = currStrokeColor;
    }
    return newRect;
  };

  // ----------------------------------------
  // Color
  /**
   * Sets the color mode of basil, supported: CMYK or RGB.
   * @param  {Object} new color mode (optional)
   * @return {Object} current color mode
   */
  pub.colorMode = function(colorMode) {
    if (!colorMode) return currLayer;

    if (colorMode === pub.CMYK || colorMode === pub.RGB) {
      currColorMode = colorMode;
    } else {
      error("Not supported color mode");
    }
    return currColorMode;
  };

  // ----------------------------------------
  // Typography
  // FIXME, set color + tint is missing
  pub.text = function(txt, x, y, w, h) {
    var textFrame = currentPage().textFrames.add( currentLayer() );
    textFrame.geometricBounds = [y, x, (y+h), (x+w)];
    textFrame.contents = txt;
    return textFrame;
  };

  // ----------------------------------------
  // Math
  var currentRandom = Math.random;
  pub.random = function() {
    if (arguments.length === 0) return currentRandom();
    if (arguments.length === 1) return currentRandom() * arguments[0];
    var aMin = arguments[0],
      aMax = arguments[1];
    return currentRandom() * (aMax - aMin) + aMin
  };

  function Marsaglia(i1, i2) {
    var z = i1 || 362436069,
      w = i2 || 521288629;
    var nextInt = function() {
      z = 36969 * (z & 65535) + (z >>> 16) & 4294967295;
      w = 18E3 * (w & 65535) + (w >>> 16) & 4294967295;
      return ((z & 65535) << 16 | w & 65535) & 4294967295
    };
    this.nextDouble = function() {
      var i = nextInt() / 4294967296;
      return i < 0 ? 1 + i : i
    };
    this.nextInt = nextInt
  }
  Marsaglia.createRandomized = function() {
    var now = new Date;
    return new Marsaglia(now / 6E4 & 4294967295, now & 4294967295)
  };

  pub.randomSeed = function(seed) {
    currentRandom = (new Marsaglia(seed)).nextDouble
  };

  pub.Random = function(seed) {
    var haveNextNextGaussian = false,
      nextNextGaussian, random;
    this.nextGaussian = function() {
      if (haveNextNextGaussian) {
        haveNextNextGaussian = false;
        return nextNextGaussian
      }
      var v1, v2, s;
      do {
        v1 = 2 * random() - 1;
        v2 = 2 * random() - 1;
        s = v1 * v1 + v2 * v2
      } while (s >= 1 || s === 0);
      var multiplier = Math.sqrt(-2 * Math.log(s) / s);
      nextNextGaussian = v2 * multiplier;
      haveNextNextGaussian = true;
      return v1 * multiplier
    };
    random = seed === undef ? Math.random : (new Marsaglia(seed)).nextDouble
  };

  pub.map = function(value, istart, istop, ostart, ostop) {
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
  };

  pub.constrain = function(aNumber, aMin, aMax) {
    return aNumber > aMax ? aMax : aNumber < aMin ? aMin : aNumber;
  };

  // ----------------------------------------
  // Input

  pub.findByLabel = function(label) {
    var result = [];
    var doc = currentDoc();
    for (var i = 0, len = doc.pageItems.length; i < len; i++) {
      var pageItem = doc.pageItems[i];
      if (pageItem.label === label) {
        result.push(pageItem);
      }
    }

    return result;
  };

  // ----------------------------------------
  // Output

  pub.println = function(msg) {
    $.writeln(msg);
  };

  pub.print = function(msg) {
    $.write(msg);
  };

  // ----------------------------------------
  // all private from here

  var init = function() {
    glob.b = pub;

    pub.units(pub.PT);

    // -- init internal state vars --
    currColorMode = pub.CMYK;
    currFillColor = currentDoc().swatches.item("Black"),
    currStrokeColor = currentDoc().swatches.item("Black");
    currStrokeWeight = 1;
    currStrokeTint = 100;
    currFillTint = 100;

    // -- init public vars --
    var pageSize = currentPageSize();
    pub.width = pageSize.width;
    pub.height = pageSize.height;

    welcome();
    runUserScript();
  };

  var runUserScript = function() {
    app.doScript(function() {
      if (typeof glob.setup === 'function') {
        glob.setup();
      }
      if (typeof glob.draw === 'function') {
        glob.draw();
      }
    }, ScriptLanguage.javascript, undefined, UndoModes.entireScript);
  };

  var welcome = function() {
    $.writeln("basil.js "
        + pub.VERSION
        + " "
        + "infos, feedback @ http://basiljs.ch");
  };

  var currentDoc = function() {
    if (!currDoc) {
      try {
        currDoc = app.activeDocument;
      } catch(e) {
        currDoc = app.documents.add();
      }
      addCurrDocCloseEventListener();
    }
    return currDoc;
  };

  var addCurrDocCloseEventListener = function(doc) {
    currDoc.addEventListener(Event.BEFORE_CLOSE, function() {
      currDoc = null;
      currSpread = null;
      currPage = null;
      currLayer = null;
    });
  }

  var currentLayer = function() {
    if (!currLayer) {
      currentDoc();
      currLayer = app.activeDocument.activeLayer;
    }
    return currLayer;
  };

  var currentSpread = function() {
    if (!currSpread) {
      currentDoc();
      currSpread = app.activeWindow.activeSpread;
    }
    return currSpread;
  };

  var currentPage = function() {
    if (!currPage) {
      currentDoc();
      currPage = app.activeWindow.activePage;
    }
    return currPage;
  };

  var currentPageSize = function () {
    var pageBounds = currentPage().bounds; // [y1, x1, y2, x2]
    var w = pageBounds[3] - pageBounds[1];
    var h = pageBounds[2] - pageBounds[0];
    return {width: w, height: h};
  };

  var error = function(msg) {
    $.writeln(ERROR_PREFIX + msg);
    throw msg;
  };

  var warning = function(msg) {
    $.writeln(WARNING_PREFIX + msg);
  };

  init();

})(this, app);<|endoftext|>


<commit_before>var path = require("path")
  , assert = require("assert")
  , fs = require("graceful-fs")
  , http = require("http")
  , log = require("npmlog")
  , semver = require("semver")
  , readJson = require("read-package-json")
  , url = require("url")
  , npm = require("../npm.js")
  , registry = npm.registry
  , deprCheck = require("../utils/depr-check.js")
  , inflight = require("inflight")
  , addRemoteTarball = require("./add-remote-tarball.js")
  , cachedPackageRoot = require("./cached-package-root.js")
  , mapToRegistry = require("../utils/map-to-registry.js")

module.exports = addNamed

function addNamed (name, version, data, cb_) {
  assert(typeof name === "string", "must have module name")
  assert(typeof cb_ === "function", "must have callback")

  var key = name + "@" + version
  log.verbose("addNamed", key)

  function cb (er, data) {
    if (data && !data._fromGithub) data._from = key
    cb_(er, data)
  }

  cb_ = inflight("addName:" + key, cb_)
  if (!cb_) return log.verbose("addNamed", key, "already in flight; waiting")
  log.verbose("addNamed", key, "not in flight; adding")

  log.silly("addNamed", "semver.valid", semver.valid(version))
  log.silly("addNamed", "semver.validRange", semver.validRange(version))
  var fn = ( semver.valid(version, true) ? addNameVersion
           : semver.validRange(version, true) ? addNameRange
           : addNameTag
           )
  fn(name, version, data, cb)
}

function addNameTag (name, tag, data, cb) {
  log.info("addNameTag", [name, tag])
  var explicit = true
  if (!tag) {
    explicit = false
    tag = npm.config.get("tag")
  }

  mapToRegistry(name, npm.config, function (er, uri) {
    if (er) return cb(er)

    registry.get(uri, null, next)
  })

  function next (er, data, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    engineFilter(data)
    if (data["dist-tags"] && data["dist-tags"][tag]
        && data.versions[data["dist-tags"][tag]]) {
      var ver = data["dist-tags"][tag]
      return addNamed(name, ver, data.versions[ver], cb)
    }
    if (!explicit && Object.keys(data.versions).length) {
      return addNamed(name, "*", data, cb)
    }

    er = installTargetsError(tag, data)
    return cb(er)
  }
}

function engineFilter (data) {
  var npmv = npm.version
    , nodev = npm.config.get("node-version")
    , strict = npm.config.get("engine-strict")

  if (!nodev || npm.config.get("force")) return data

  Object.keys(data.versions || {}).forEach(function (v) {
    var eng = data.versions[v].engines
    if (!eng) return
    if (!strict && !data.versions[v].engineStrict) return
    if (eng.node && !semver.satisfies(nodev, eng.node, true)
        || eng.npm && !semver.satisfies(npmv, eng.npm, true)) {
      delete data.versions[v]
    }
  })
}

function addNameVersion (name, v, data, cb) {
  var ver = semver.valid(v, true)
  if (!ver) return cb(new Error("Invalid version: "+v))

  var response

  if (data) {
    response = null
    return next()
  }

  mapToRegistry(name, npm.config, function (er, uri) {
    if (er) return cb(er)

    registry.get(uri, null, setData)
  })

  function setData (er, d, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    data = d && d.versions[ver]
    if (!data) {
      er = new Error("version not found: "+name+"@"+ver)
      er.package = name
      er.statusCode = 404
      return cb(er)
    }
    response = resp
    next()
  }

  function next () {
    deprCheck(data)
    var dist = data.dist

    if (!dist) return cb(new Error("No dist in "+data._id+" package"))

    if (!dist.tarball) return cb(new Error(
      "No dist.tarball in " + data._id + " package"))

    if ((response && response.statusCode !== 304) || npm.config.get("force")) {
      return fetchit()
    }

    // we got cached data, so let's see if we have a tarball.
    var pkgroot = cachedPackageRoot({name : name, version : ver})
    var pkgtgz = path.join(pkgroot, "package.tgz")
    var pkgjson = path.join(pkgroot, "package", "package.json")
    fs.stat(pkgtgz, function (er) {
      if (!er) {
        readJson(pkgjson, function (er, data) {
          if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er)

          if (data) {
            if (!data.name) return cb(new Error("No name provided"))
            if (!data.version) return cb(new Error("No version provided"))

            // check the SHA of the package we have, to ensure it wasn't installed
            // from somewhere other than the registry (eg, a fork)
            if (data._shasum && dist.shasum && data._shasum !== dist.shasum) {
              return fetchit()
            }
          }

          if (er) return fetchit()
            else return cb(null, data)
        })
      } else return fetchit()
    })

    function fetchit () {
      if (!npm.config.get("registry")) {
        return cb(new Error("Cannot fetch: "+dist.tarball))
      }

      // Use the same protocol as the registry.  https registry --> https
      // tarballs, but only if they're the same hostname, or else detached
      // tarballs may not work.
      var tb = url.parse(dist.tarball)
      var rp = url.parse(npm.config.get("registry"))
      if (tb.hostname === rp.hostname
          && tb.protocol !== rp.protocol) {
        tb.protocol = url.parse(npm.config.get("registry")).protocol
        delete tb.href
      }
      tb = url.format(tb)

      // Only add non-shasum'ed packages if --forced. Only ancient things
      // would lack this for good reasons nowadays.
      if (!dist.shasum && !npm.config.get("force")) {
        return cb(new Error("package lacks shasum: " + data._id))
      }
      return addRemoteTarball(tb, data, dist.shasum, cb)
    }
  }
}

function addNameRange (name, range, data, cb) {
  range = semver.validRange(range, true)
  if (range === null) return cb(new Error(
    "Invalid version range: " + range
  ))

  log.silly("addNameRange", {name:name, range:range, hasData:!!data})

  if (data) return next()

  mapToRegistry(name, npm.config, function (er, uri) {
    if (er) return cb(er)

    registry.get(uri, null, setData)
  })

  function setData (er, d, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    data = d
    next()
  }

  function next () {
    log.silly( "addNameRange", "number 2"
             , {name:name, range:range, hasData:!!data})
    engineFilter(data)

    log.silly("addNameRange", "versions"
             , [data.name, Object.keys(data.versions || {})])

    // if the tagged version satisfies, then use that.
    var tagged = data["dist-tags"][npm.config.get("tag")]
    if (tagged
        && data.versions[tagged]
        && semver.satisfies(tagged, range, true)) {
      return addNamed(name, tagged, data.versions[tagged], cb)
    }

    // find the max satisfying version.
    var versions = Object.keys(data.versions || {})
    var ms = semver.maxSatisfying(versions, range, true)
    if (!ms) {
      return cb(installTargetsError(range, data))
    }

    // if we don't have a registry connection, try to see if
    // there's a cached copy that will be ok.
    addNamed(name, ms, data.versions[ms], cb)
  }
}

function installTargetsError (requested, data) {
  var targets = Object.keys(data["dist-tags"]).filter(function (f) {
    return (data.versions || {}).hasOwnProperty(f)
  }).concat(Object.keys(data.versions || {}))

  requested = data.name + (requested ? "@'" + requested + "'" : "")

  targets = targets.length
          ? "Valid install targets:\n" + JSON.stringify(targets) + "\n"
          : "No valid targets found.\n"
          + "Perhaps not compatible with your version of node?"

  var er = new Error( "No compatible version found: "
                  + requested + "\n" + targets)
  er.code = "ETARGET"
  return er
}

function errorResponse (name, response) {
  var er
  if (response.statusCode >= 400) {
    er = new Error(http.STATUS_CODES[response.statusCode])
    er.statusCode = response.statusCode
    er.code = "E" + er.statusCode
    er.pkgid = name
  }
  return er
}
<commit_msg>inflight by URL rather than package spec<commit_after>var path = require("path")
  , assert = require("assert")
  , fs = require("graceful-fs")
  , http = require("http")
  , log = require("npmlog")
  , semver = require("semver")
  , readJson = require("read-package-json")
  , url = require("url")
  , npm = require("../npm.js")
  , registry = npm.registry
  , deprCheck = require("../utils/depr-check.js")
  , inflight = require("inflight")
  , addRemoteTarball = require("./add-remote-tarball.js")
  , cachedPackageRoot = require("./cached-package-root.js")
  , mapToRegistry = require("../utils/map-to-registry.js")

module.exports = addNamed

function getOnceFromRegistry (name, from, next, done) {
  mapToRegistry(name, npm.config, function (er, uri) {
    if (er) return done(er)

    var key = "registry:" + uri
    next = inflight(key, next)
    if (!next) return log.verbose(from, key, "already in flight; waiting")
    else log.verbose(from, key, "not in flight; fetching")

    registry.get(uri, null, next)
  })
}

function addNamed (name, version, data, cb_) {
  assert(typeof name === "string", "must have module name")
  assert(typeof cb_ === "function", "must have callback")

  var key = name + "@" + version
  log.verbose("addNamed", key)

  function cb (er, data) {
    if (data && !data._fromGithub) data._from = key
    cb_(er, data)
  }

  log.silly("addNamed", "semver.valid", semver.valid(version))
  log.silly("addNamed", "semver.validRange", semver.validRange(version))
  var fn = ( semver.valid(version, true) ? addNameVersion
           : semver.validRange(version, true) ? addNameRange
           : addNameTag
           )
  fn(name, version, data, cb)
}

function addNameTag (name, tag, data, cb) {
  log.info("addNameTag", [name, tag])
  var explicit = true
  if (!tag) {
    explicit = false
    tag = npm.config.get("tag")
  }

  getOnceFromRegistry(name, "addNameTag", next, cb)

  function next (er, data, json, resp) {
    if (!er) er = errorResponse(name, resp)
    if (er) return cb(er)

    log.silly("addNameTag", "next cb for", name, "with tag", tag)

    engineFilter(data)
    if (data["dist-tags"] && data["dist-tags"][tag]
        && data.versions[data["dist-tags"][tag]]) {
      var ver = data["dist-tags"][tag]
      return addNamed(name, ver, data.versions[ver], cb)
    }
    if (!explicit && Object.keys(data.versions).length) {
      return addNamed(name, "*", data, cb)
    }

    er = installTargetsError(tag, data)
    return cb(er)
  }
}

function engineFilter (data) {
  var npmv = npm.version
    , nodev = npm.config.get("node-version")
    , strict = npm.config.get("engine-strict")

  if (!nodev || npm.config.get("force")) return data

  Object.keys(data.versions || {}).forEach(function (v) {
    var eng = data.versions[v].engines
    if (!eng) return
    if (!strict && !data.versions[v].engineStrict) return
    if (eng.node && !semver.satisfies(nodev, eng.node, true)
        || eng.npm && !semver.satisfies(npmv, eng.npm, true)) {
      delete data.versions[v]
    }
  })
}

function addNameVersion (name, v, data, cb) {
  var ver = semver.valid(v, true)
  if (!ver) return cb(new Error("Invalid version: "+v))

  var response

  if (data) {
    response = null
    return next()
  }

  getOnceFromRegistry(name, "addNameVersion", setData, cb)

  function setData (er, d, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    data = d && d.versions[ver]
    if (!data) {
      er = new Error("version not found: "+name+"@"+ver)
      er.package = name
      er.statusCode = 404
      return cb(er)
    }
    response = resp
    next()
  }

  function next () {
    deprCheck(data)
    var dist = data.dist

    if (!dist) return cb(new Error("No dist in "+data._id+" package"))

    if (!dist.tarball) return cb(new Error(
      "No dist.tarball in " + data._id + " package"))

    if ((response && response.statusCode !== 304) || npm.config.get("force")) {
      return fetchit()
    }

    // we got cached data, so let's see if we have a tarball.
    var pkgroot = cachedPackageRoot({name : name, version : ver})
    var pkgtgz = path.join(pkgroot, "package.tgz")
    var pkgjson = path.join(pkgroot, "package", "package.json")
    fs.stat(pkgtgz, function (er) {
      if (!er) {
        readJson(pkgjson, function (er, data) {
          if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er)

          if (data) {
            if (!data.name) return cb(new Error("No name provided"))
            if (!data.version) return cb(new Error("No version provided"))

            // check the SHA of the package we have, to ensure it wasn't installed
            // from somewhere other than the registry (eg, a fork)
            if (data._shasum && dist.shasum && data._shasum !== dist.shasum) {
              return fetchit()
            }
          }

          if (er) return fetchit()
            else return cb(null, data)
        })
      } else return fetchit()
    })

    function fetchit () {
      if (!npm.config.get("registry")) {
        return cb(new Error("Cannot fetch: "+dist.tarball))
      }

      // Use the same protocol as the registry.  https registry --> https
      // tarballs, but only if they're the same hostname, or else detached
      // tarballs may not work.
      var tb = url.parse(dist.tarball)
      var rp = url.parse(npm.config.get("registry"))
      if (tb.hostname === rp.hostname
          && tb.protocol !== rp.protocol) {
        tb.protocol = url.parse(npm.config.get("registry")).protocol
        delete tb.href
      }
      tb = url.format(tb)

      // Only add non-shasum'ed packages if --forced. Only ancient things
      // would lack this for good reasons nowadays.
      if (!dist.shasum && !npm.config.get("force")) {
        return cb(new Error("package lacks shasum: " + data._id))
      }
      return addRemoteTarball(tb, data, dist.shasum, cb)
    }
  }
}

function addNameRange (name, range, data, cb) {
  range = semver.validRange(range, true)
  if (range === null) return cb(new Error(
    "Invalid version range: " + range
  ))

  log.silly("addNameRange", {name:name, range:range, hasData:!!data})

  if (data) return next()

  getOnceFromRegistry(name, "addNameRange", setData, cb)

  function setData (er, d, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    data = d
    next()
  }

  function next () {
    log.silly( "addNameRange", "number 2"
             , {name:name, range:range, hasData:!!data})
    engineFilter(data)

    log.silly("addNameRange", "versions"
             , [data.name, Object.keys(data.versions || {})])

    // if the tagged version satisfies, then use that.
    var tagged = data["dist-tags"][npm.config.get("tag")]
    if (tagged
        && data.versions[tagged]
        && semver.satisfies(tagged, range, true)) {
      return addNamed(name, tagged, data.versions[tagged], cb)
    }

    // find the max satisfying version.
    var versions = Object.keys(data.versions || {})
    var ms = semver.maxSatisfying(versions, range, true)
    if (!ms) {
      return cb(installTargetsError(range, data))
    }

    // if we don't have a registry connection, try to see if
    // there's a cached copy that will be ok.
    addNamed(name, ms, data.versions[ms], cb)
  }
}

function installTargetsError (requested, data) {
  var targets = Object.keys(data["dist-tags"]).filter(function (f) {
    return (data.versions || {}).hasOwnProperty(f)
  }).concat(Object.keys(data.versions || {}))

  requested = data.name + (requested ? "@'" + requested + "'" : "")

  targets = targets.length
          ? "Valid install targets:\n" + JSON.stringify(targets) + "\n"
          : "No valid targets found.\n"
          + "Perhaps not compatible with your version of node?"

  var er = new Error( "No compatible version found: "
                  + requested + "\n" + targets)
  er.code = "ETARGET"
  return er
}

function errorResponse (name, response) {
  var er
  if (response.statusCode >= 400) {
    er = new Error(http.STATUS_CODES[response.statusCode])
    er.statusCode = response.statusCode
    er.code = "E" + er.statusCode
    er.pkgid = name
  }
  return er
}
<|endoftext|>


<commit_before>//hi

$( document ).ready( function () {
    $("#content").text("loading");
    f = populate_flights();
    $("#content").text("");
    for (i = 0; i < f.length; i++) {
        $("#content").append("
"+f[i].location+"
");
    }
});

function populate_flights() {
    //gets all the flight data from a variable and displays them x at a time
    //in a json, which can be loaded into an array that can then be changed,
    //depending on stuff.
    return [{location: 'Edinburgh', friends: ["james","hamish"]},
           {location: 'London',     friends: ["charles","bob"]}];
}
<commit_msg>add formatting function to allow faster/easier editing of output<commit_after>//hi

$( document ).ready( function () {
    $("#content").text("loading");
    fs = populate_flights();
    $("#content").text("");
    for (i = 0; i < fs.length; i++) {
        $("#content").append(format_flight(fs[i]));
    }
});

function populate_flights() {
    //gets all the flight data from a variable and displays them x at a time
    //in a json, which can be loaded into an array that can then be changed,
    //depending on stuff.
    return [{location: 'Edinburgh', friends: ["james","hamish"]},
           {location: 'London',     friends: ["charles","bob"]}];
}
function format_flight(f) {
    var r = "

"+f.location+"
";
    r += "
";
    for (j = 0; j < f.friends.length; j++) {
        r += "
"+f.friends[j]+"
";
    }
    r += "
";
    r += "
";
    return r;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Progress } from 'reactstrap';
import { RaisedButton, Paper } from 'material-ui'
import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import Chip from 'material-ui/Chip';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import BetJson from 'build/contracts/Bet.json';
import getWeb3 from 'utils/getWeb3';
import betFields from './betFields';

class Bet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isExpanded : false,
      amountToBet : 0,
      ...betFields,
      web3: null, // TODO: REMOVE WEB3, DO STATIC
    }
  }

  setExpectedGain = (event, newValue) => {
    console.log(newValue);
    this.setState({amountToBet : parseInt(newValue, 10)});
  }

  ExpectedGain = (betTeam) => {
    var expectedIncome = this.state.amountToBet;
    var winnerPool;
    var loserPool;
    if (betTeam.betOn === '0') {
      loserPool = this.state.team_1_bet_sum - 0.02*this.state.team_1_bet_sum;
      winnerPool = expectedIncome + this.state.team_0_bet_sum;
    }
    else {
      loserPool = this.state.team_0_bet_sum - 0.02*this.state.team_0_bet_sum;
      winnerPool = expectedIncome + this.state.team_1_bet_sum;
    }

    expectedIncome +=  (expectedIncome/winnerPool)*loserPool;
    if (this.state.amountToBet === 0 || isNaN(this.state.amountToBet))
      return null;
    else
      return
Expected gain: {parseFloat(expectedIncome).toFixed(2)}

  }

  ExpandedBet = (props) => {
    if (this.state.isExpanded) {
      if (props.team === '0')
        return
          <TextField type='number'
            style={{width: '100px'}}
            name="jobNumber"
            hintText='Amount'
            floatingLabelText='In ether'
            onChange={this.setExpectedGain}/>
          <RaisedButton primary={true}>BET</RaisedButton>

          <this.ExpectedGain betOn={props.team}/>

      else
        return
          <TextField type='number'
            style={{width: '100px'}}
            name="jobNumber"
            hintText='Amount'
            floatingLabelText='In ether'
            onChange={this.setExpectedGain}/>
          <RaisedButton secondary={true}>BET</RaisedButton>
          <this.ExpectedGain betOn={props.team}/>

    }
    else
      return null;
  }

  onExpand = (expanded) => {
      console.log(this.props.address, this.state.isExpanded);
      this.setState({isExpanded: !this.state.isExpanded});
    }

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.

    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      });

      // Instantiate contract once web3 provided.
      this.instantiateContract();
    })
    .catch((err) => {
      console.log('Error finding web3', err);
    });
  }
        // <CardText className='bet'>
        //   <CardText className='team0'>
        //     {teams[0]}
        //     <Divider />
        //     Ξ{this.state.team_0_bet_sum}
        //     <this.ExpandedBet team='0'/>
        //   </CardText>
        //   <CardText className='team1'>
        //     {teams[1]}
        //     <Divider />
        //     Ξ{this.state.team_1_bet_sum}
        //     <this.ExpandedBet team='1'/>
        //   </CardText>
        // </CardText>
        // <CardText style={{'text-align': 'center'}}>
        //   { getState(this.state.bet_state) }
        // </CardText>
        // <ProgressBar />

  instantiateContract() {
    var self = this;
    var objs = {};
    function setAttributes(attributeNames, contractInstance) {
      var promises = Object.keys(attributeNames).map(async (attr) => {
        if (attr in betFields
            && attr !== 'bets_to_team_0' // Cannot get mapping keys, no prob: get from events
            && attr !== 'bets_to_team_1') { // idem

          var res = await betContractInstance[attr]();
          if (typeof res === 'object') // Handle BigNumber
            res = res.toNumber();
          else
            res = res.toString();
          objs[attr] = res;
          // self.setState(obj);
        }
      });
      Promise.all(promises).then(res => {
        self.setState(objs);
      })
    }

    const contract = require('truffle-contract');
    const betContract = contract(BetJson);
    betContract.setProvider(this.state.web3.currentProvider);

    // Declaring this for later so we can chain functions on SimpleStorage.
    var betContractInstance = betContract.at(this.props.address);
    setAttributes(this.state, betContractInstance);

    var betEvents = betContractInstance.new_bet({fromBlock: 0, toBlock: 'latest'});
    betEvents.watch((error, response) => {
      console.log('Bet:', response.args);
      if (response.args.for_team === false)
        this.setState({ team_0_bet_sum : this.state.team_0_bet_sum + response.args.amount.toNumber() });
      else
        this.setState({ team_1_bet_sum : this.state.team_1_bet_sum + response.args.amount.toNumber() });
    });
  }

  render() {
    var teams = this.state.title.split('x');

    var getState = (state) => {
      if (state === 0)
        return `Open bet`;
      else if (state === 1)
        return `${teams[0]} won`;
      else if (state === 2)
        return `${teams[1]} won`;
      else if (state === 3)
        return 'Draw';
      else if (state === 4)
        return 'Undecided';
    }
    var total = this.state.team_0_bet_sum + this.state.team_1_bet_sum;
    var percentage0 = (this.state.team_0_bet_sum / total)*100;
    var percentage1 = (this.state.team_1_bet_sum / total)*100;
    isNaN(percentage0) ? percentage0 = 0 : percentage0 = parseFloat(percentage0).toFixed(2);
    isNaN(percentage1) ? percentage1 = 0 : percentage1 = parseFloat(percentage1).toFixed(2);

    var ProgressBar = () => {
      if (percentage0 !== 0 && percentage1 !== 0)
        return <Progress multi className='progressBar'>
          <Progress bar color="danger" value={percentage0}>{percentage0}%</Progress>
          <Progress bar color="success" value={percentage1}>{percentage1}%</Progress>
          </Progress>;
      else
        return null;
    }

    return (
      <Card
        onExpandChange={this.onExpand}
        expanded={this.state.isExpanded}
      >
      <CardHeader
        actAsExpander={true}
        showExpandableButton={true}
      />

        <CardText>

            {this.state.category}

            Ξ{this.state.team_0_bet_sum}

            {teams[0]} vs {teams[1]}

            Ξ{this.state.team_1_bet_sum}

            { getState(this.state.bet_state) }

        </CardText>
        <CardText>

            <this.ExpandedBet team='0'/>

            <this.ExpandedBet team='1'/>

        </CardText>
        <ProgressBar />

      </Card>
    );
  }
}

export default Bet;
<commit_msg>Row layout in progress using Grid<commit_after>import React, { Component } from 'react';
import { Progress } from 'reactstrap';
import { RaisedButton, Paper } from 'material-ui'
import {Card, CardTitle, CardActions, CardHeader, CardText} from 'material-ui/Card';
import {GridList, GridTile} from 'material-ui/GridList';
import Chip from 'material-ui/Chip';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import BetJson from 'build/contracts/Bet.json';
import getWeb3 from 'utils/getWeb3';
import betFields from './betFields';

class Bet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isExpanded : false,
      amountToBet : 0,
      ...betFields,
      web3: null, // TODO: REMOVE WEB3, DO STATIC
    }
  }

  setBet0Value = (event, newValue) => {
    this.setState({amountToBet0 : parseInt(newValue, 10), amountToBet1: 0});
    this.setExpectedGain(newValue);
  }

  setBet1Value = (event, newValue) => {
    this.setState({amountToBet1 : parseInt(newValue, 10), amountToBet0: 0});
    this.setExpectedGain(newValue);
  }

  setExpectedGain = (newValue) => {
    console.log(newValue);
    this.setState({amountToBet : parseInt(newValue, 10)});
  }

  ExpectedGain = () => {
    var expectedIncome;
    var amount;
    var winnerPool;
    var loserPool;

    var betTeam = -1;
    if (this.state.amountToBet0 > 0) betTeam = 0;
    else if(this.state.amountToBet1 > 0) betTeam = 1;

    if (betTeam === -1)
      return <GridTile></GridTile>

    if (betTeam === 0) {
      amount = this.state.amountToBet0;
      expectedIncome = this.state.amountToBet0;
      loserPool = this.state.team_1_bet_sum - 0.02*this.state.team_1_bet_sum;
      winnerPool = expectedIncome + this.state.team_0_bet_sum;
    }
    else {
      amount = this.state.amountToBet1;
      expectedIncome = this.state.amountToBet1;
      loserPool = this.state.team_0_bet_sum - 0.02*this.state.team_0_bet_sum;
      winnerPool = expectedIncome + this.state.team_1_bet_sum;
    }

    expectedIncome +=  (expectedIncome/winnerPool)*loserPool;
    if (amount === 0 || isNaN(amount))
      return <GridTile></GridTile>
    else
      return <GridTile>Expected gain: {parseFloat(expectedIncome).toFixed(2)} </GridTile>
  }

  ExpandedBet = (props) => {
    if (this.state.isExpanded) {
      return <GridList cols={5} cellHeight={20}>
            <GridTile></GridTile>
            <GridTile>
              <TextField type='number'
                style={{width: '100px'}}
                name="jobNumber1"
                floatingLabelText="0 Eth"
                value={this.state.amountToBet0}
                onChange={this.setBet0Value}
              />
            </GridTile>
            <RaisedButton primary={true}>BET</RaisedButton>
            <GridTile>
              <TextField type='number'
                style={{width: '100px'}}
                name="jobNumber2"
                floatingLabelText="0 Eth"
                value={this.state.amountToBet1}
                onChange={this.setBet1Value}
            />
            </GridTile>
            <this.ExpectedGain/>
            </GridList>
    }
    else
      return <GridList cols={0} cellHeight={0}></GridList>
  }

  onExpand = (expanded) => {
      console.log(this.props.address, this.state.isExpanded);
      this.setState({isExpanded: !this.state.isExpanded});
    }

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.

    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      });

      // Instantiate contract once web3 provided.
      this.instantiateContract();
    })
    .catch((err) => {
      console.log('Error finding web3', err);
    });
  }

  instantiateContract() {
    var self = this;
    var objs = {};
    function setAttributes(attributeNames, contractInstance) {
      var promises = Object.keys(attributeNames).map(async (attr) => {
        if (attr in betFields
            && attr !== 'bets_to_team_0' // Cannot get mapping keys, no prob: get from events
            && attr !== 'bets_to_team_1') { // idem

          var res = await betContractInstance[attr]();
          if (typeof res === 'object') // Handle BigNumber
            res = res.toNumber();
          else
            res = res.toString();
          objs[attr] = res;
          // self.setState(obj);
        }
      });
      Promise.all(promises).then(res => {
        self.setState(objs);
      })
    }

    const contract = require('truffle-contract');
    const betContract = contract(BetJson);
    betContract.setProvider(this.state.web3.currentProvider);

    // Declaring this for later so we can chain functions on SimpleStorage.
    var betContractInstance = betContract.at(this.props.address);
    setAttributes(this.state, betContractInstance);

    var betEvents = betContractInstance.new_bet({fromBlock: 0, toBlock: 'latest'});
    betEvents.watch((error, response) => {
      console.log('Bet:', response.args);
      if (response.args.for_team === false)
        this.setState({ team_0_bet_sum : this.state.team_0_bet_sum + response.args.amount.toNumber() });
      else
        this.setState({ team_1_bet_sum : this.state.team_1_bet_sum + response.args.amount.toNumber() });
    });
  }

  render() {
    var teams = this.state.title.split('x');

    var getState = (state) => {
      if (state === 0)
        return `Open bet`;
      else if (state === 1)
        return `${teams[0]} won`;
      else if (state === 2)
        return `${teams[1]} won`;
      else if (state === 3)
        return 'Draw';
      else if (state === 4)
        return 'Undecided';
    }
    var total = this.state.team_0_bet_sum + this.state.team_1_bet_sum;
    var percentage0 = (this.state.team_0_bet_sum / total)*100;
    var percentage1 = (this.state.team_1_bet_sum / total)*100;
    isNaN(percentage0) ? percentage0 = 0 : percentage0 = parseFloat(percentage0).toFixed(2);
    isNaN(percentage1) ? percentage1 = 0 : percentage1 = parseFloat(percentage1).toFixed(2);

    var ProgressBar = () => {
      if (percentage0 !== 0 && percentage1 !== 0)
        return <Progress multi className='progressBar'>
          <Progress bar color="danger" value={percentage0}>{percentage0}%</Progress>
          <Progress bar color="success" value={percentage1}>{percentage1}%</Progress>
          </Progress>;
      else
        return null;
    }

    return (
      <Card
        onExpandChange={this.onExpand}
        expanded={this.state.isExpanded}
      >
      <CardTitle
        actAsExpander={true}
        showExpandableButton={true}
      />

      <CardText>

      <GridList cols={5} cellHeight={20}>
        <GridTile>{this.state.category}</GridTile>
        <GridTile>Ξ{this.state.team_0_bet_sum}</GridTile>
        <GridTile>{this.state.team_0} vs {this.state.team_1}</GridTile>
        <GridTile>Ξ{this.state.team_1_bet_sum}</GridTile>
        <GridTile>{ getState(this.state.bet_state) }</GridTile>
      </GridList>
      <this.ExpandedBet/>

      </CardText>
      <ProgressBar />

      </Card>
    );
  }
}

export default Bet;
<|endoftext|>


<commit_before>/** @jsx jsx */
import { Component } from 'react';
import { jsx } from '@emotion/core';
import { colors } from '@arch-ui/theme';
import Editor from './editor';
import { FieldContainer, FieldLabel, FieldInput } from '@arch-ui/fields';
import { inputStyles } from '@arch-ui/input';

class ErrorBoundary extends Component {
  state = {
    hasError: false,
  };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return Unable to render content;
    }

    return this.props.children;
  }
}

let ContentField = ({ field, value, onChange, autoFocus, errors }) => {
  const htmlID = `ks-content-editor-${field.path}`;

  return (
    <FieldContainer>
      <FieldLabel htmlFor={htmlID} field={field} errors={errors} />
      <FieldInput
        css={{ cursor: 'text', tabIndex: 0 }}
        onClick={() => {
          const elm = document.getElementById(htmlID).querySelector('[data-slate-editor]');
          if (elm) {
            elm.focus();
          }
        }}
      >
        <ErrorBoundary>
          {Object.values(field.getBlocks())
            .filter(({ Provider, options }) => Provider && options)
            .reduce(
              (children, { Provider, options }, index) => (
                // Using index within key is ok here as the blocks never change
                // across renders
                <Provider value={options} key={`${htmlID}-provider-${index}`}>
                  {children}
                </Provider>
              ),
              <Editor
                key={htmlID}
                blocks={field.getBlocks()}
                value={value}
                onChange={onChange}
                autoFocus={autoFocus}
                id={htmlID}
                css={{
                  ...inputStyles({ isMultiline: true }),
                  padding: '16px 32px',
                  minHeight: 200,
                  zIndex: 0,
                }}
              />
            )}
        </ErrorBoundary>
      </FieldInput>
    </FieldContainer>
  );
};

export default ContentField;
<commit_msg>minor change to content field UI - zindex was causing a bug (#2484)<commit_after>/** @jsx jsx */
import { Component } from 'react';
import { jsx } from '@emotion/core';
import { colors } from '@arch-ui/theme';
import Editor from './editor';
import { FieldContainer, FieldLabel, FieldInput } from '@arch-ui/fields';
import { inputStyles } from '@arch-ui/input';

class ErrorBoundary extends Component {
  state = {
    hasError: false,
  };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return Unable to render content;
    }

    return this.props.children;
  }
}

let ContentField = ({ field, value, onChange, autoFocus, errors }) => {
  const htmlID = `ks-content-editor-${field.path}`;

  return (
    <FieldContainer>
      <FieldLabel htmlFor={htmlID} field={field} errors={errors} />
      <FieldInput
        css={{ cursor: 'text', tabIndex: 0 }}
        onClick={() => {
          const elm = document.getElementById(htmlID).querySelector('[data-slate-editor]');
          if (elm) {
            elm.focus();
          }
        }}
      >
        <ErrorBoundary>
          {Object.values(field.getBlocks())
            .filter(({ Provider, options }) => Provider && options)
            .reduce(
              (children, { Provider, options }, index) => (
                // Using index within key is ok here as the blocks never change
                // across renders
                <Provider value={options} key={`${htmlID}-provider-${index}`}>
                  {children}
                </Provider>
              ),
              <Editor
                key={htmlID}
                blocks={field.getBlocks()}
                value={value}
                onChange={onChange}
                autoFocus={autoFocus}
                id={htmlID}
                css={{
                  ...inputStyles({ isMultiline: true }),
                  padding: '16px 32px',
                  minHeight: 200,
                }}
              />
            )}
        </ErrorBoundary>
      </FieldInput>
    </FieldContainer>
  );
};

export default ContentField;
<|endoftext|>