<commit_before>const _ = require('lodash');
const Promise = require("bluebird");
const fs = require('fs');
const net = require('net');
const os = require('os');
const solc = require('solc');
const path = require('path');
const crypto = require('crypto');
const Tx = require('ethereumjs-tx');
const chalk = require('chalk');
const read = require('read');
const Web3 = require('web3');
const util = require('util');
const ethUtil = require('ethereumjs-util');
const salt = '2';
var web3;
Promise.config({
  longStackTraces: false
});

function getWeb3() {
  if (web3) {
    return web3;
  }

  var argv = require('yargs').argv;
  if (argv.g) {
    web3 = new Web3(new Web3.providers.IpcProvider(argv.g, net));
  } else {
    var ip = '127.0.0.1', port = 8545;
    if (argv.r) {
      var ipPort = argv.r.split(':');
      ip = ipPort[0];
      if (ipPort.length>1) {
        port = parseInt(ipPort[1], 10);
      }
    }

    web3 = new Web3(new Web3.providers.HttpProvider(`http://${ip}:${port}`));
  }

  return web3;
}

function privateToAddress(privateKey) {
  var public = ethUtil.privateToPublic(new Buffer(privateKey, 'hex'));
  return '0x' + ethUtil.publicToAddress(public).toString('hex');
}

function getNonce(address) {
  if (_.isArray(address)) {
    return Promise.map(address, getNonce).then(function(res) {
      return _.zipObject(address, res);
    });
  }

  return new Promise(function(resolve, reject) {
    getWeb3().eth.getTransactionCount(address, function(error, nonce) {
      if (error) {
        reject(error);
      } else {
        resolve(nonce);
      }
    });
  });
};

function signWithNonce(privateKey, nonce, from, to, amount, data) {
  return new Promise(function(resolve, reject) {
    var rawTx = {
      value: getWeb3().fromDecimal(amount),
      to: to,
      data: data,
      from: from,
    };

    getWeb3().eth.getGasPrice(function(error, price) {
      if (error) {
        reject(error);
        return;
      }
      getWeb3().eth.estimateGas(rawTx, function(error, gasUsage) {
        if (error) {
          reject(error);
          return;
        }
        // var forceLimit = 4700000;
        // if (gasUsage>forceLimit) {
        //   console.log(chalk.red(`Needed gas is too high: ${gasUsage}`));
        //   process.exit();
        // }
        //
        gasUsage = Math.min(gasUsage * 2, 3000000);

        var tx = new Tx({
          nonce: (getWeb3().toHex(nonce)),
          to: rawTx.to,
          value: rawTx.value,
          from: from,
          gasPrice: getWeb3().toHex(price),
          gasLimit: getWeb3().toHex(gasUsage),
          data: data
        });
        var key = new Buffer(privateKey, 'hex')
        tx.sign(key);

        resolve('0x'+tx.serialize().toString('hex'));
      });
    });
  });
};

function signTx(privateKey, from, to, amount, data) {
  return getNonce(from).then(function(nonce) {
    return signWithNonce(privateKey, nonce, from, to, amount, data);
  });
};

function sendRaw(signed) {
  return new Promise(function(resolve, reject) {
    getWeb3().eth.sendRawTransaction(signed, function(error, res) {
      if (error) {
        reject(error);
      } else {
        resolve(res);
      }
    });
  });
};

function sendTx(from, to, amount, data) {
  var rawTx = {
    value: getWeb3().fromDecimal(amount),
    to: to,
    data: data,
    from: from,
  };

  return new Promise(function(resolve, reject) {
    getWeb3().eth.estimateGas(rawTx, function(error, gasUsage) {
      if (error) {
        reject(error);
        return;
      }

      // var forceLimit = 4700000;
      // if (gasUsage>forceLimit) {
      //   console.log(chalk.red(`Needed gas is too high: ${gasUsage}`));
      //   process.exit();
      // }

      rawTx.gas = Math.min(gasUsage * 2, 3000000);

      getWeb3().eth.sendTransaction(rawTx, function(error, res) {
        if (error) {
          reject(error);
        } else {
          resolve(res);
        }
      });
    });
  });
}

function callMethod(privateKey, toAddress, value, contract, methodName, args) {
  var fromAddress = privateKey ? privateToAddress(privateKey) : getWeb3().eth.accounts[0];
  var method = contract[methodName];
  var data = method.getData.apply(method, args);
  if (methodName=='new') {
    data = '0x'+data;
  }
  return new Promise(function(resolve, reject) {
    var txId;

    getWeb3().eth.filter('latest').watch(function(error, block) {
      if (error || !txId) {
        return;
      }

      getWeb3().eth.getTransactionReceipt(txId, function(err, info) {
        if (!info) {
          return;
        }
        writeDone();
        resolve(info);
      });
    });

    if (!privateKey) {
      return step('Broadcasting tx for '+methodName, sendTx(
        fromAddress,
        toAddress,
        value,
        data
      )).then(function(id) {
        txId = id;
        console.log('Transaction:');
        console.log(chalk.green(id));
        writeLabel('Waiting to be mined');
      });
    }

    return step('Broadcasting tx for '+methodName, signTx(
      privateKey,
      fromAddress,
      toAddress,
      value,
      data
    ).then(sendRaw)).then(function(id) {
      txId = id;
      console.log('Transaction:');
      console.log(chalk.green(id));
      writeLabel('Waiting to be mined');
    });
  });
};

function resolve(fileName) {
  var cwd = path.dirname(fileName)
  var name = path.basename(fileName);
  var processed = [];

  var _resolve = function(cwd, name) {
    var extractImports = function(content) {
      var imports = [];
      var lines = content.split(/\n/);
      lines.forEach(function(line, ii) {
        var m = line.replace(/\/\/.*$/, '').match(/import\s+["']([^"']+)["']/);
        if (m) {
          lines[ii] = `import "${m[1]}";`;
          imports.push(m[1]);
        }
      });
      var finalCode = lines.join('\n');

      return [finalCode, imports];
    };

    var res = {};
    var fullName = fs.realpathSync(cwd + '/' + name);
    if (processed.indexOf(fullName)!=-1) {
      return res;
    }
    processed.push(fullName);
    return readFile(fullName).then(function(content) {
      var contentImports = extractImports(content);
      res[fullName] = {content: contentImports[0], file:fullName};

      return Promise.all(contentImports[1].map(function(name) {
        var newCwd = fs.realpathSync(cwd+'/'+name).split('/').slice(0, -1).join('/');
        return _resolve(newCwd, name);
      }));
    }).then(function(items) {
      items.forEach(function(child) {
        _.extend(res, child);
      })
      return res;
    });
  }

  return _resolve(cwd, name);
};

function readFile(fileName) {
  return new Promise(function(resolve, reject) {
    fs.readFile(fileName, 'UTF-8', function(err, data) {
      if (err) {
        reject(err);
      }
      resolve(data);
    });
  })
};

function fileTime(fileName) {
  return new Promise(function(resolve, reject) {
    fs.stat(fileName, function(err, stat) {
      if (err) {
        reject(err);
      } else {
        resolve(stat.mtime.getTime());
      }
    });
  });
};

function valToPromise(val) {
  if (_.isFunction(val)) {
    return new Promise(function(resolve, reject) {
      resolve(val());
    });
  }

  return new Promise(function(resolve, reject) {
    resolve(val);
  });
};

function cache(key, val) {
  var dir = os.tmpdir();

  var exec = function(cachePath, val) {
    return valToPromise(val).then(function(val) {
      val = JSON.stringify(val);
      return new Promise(function(resolve, reject) {
        fs.writeFile(cachePath, val, function(err) {
          if (err) {
            reject(err);
            return;
          }
          fs.chmodSync(cachePath, '777');
          resolve(val);
        });
      });
    });
  };

  var hash = crypto.createHash('sha256');
  hash.update(salt + key);
  var cacheFile = hash.digest('hex');
  var cachePath = dir+"/"+cacheFile;

  if (arguments[2]===true) {
    return exec(cachePath, val).then(function(res) {
      return JSON.parse(res);
    })
  }

  return readFile(cachePath).catch(function(err) {
    return exec(cachePath, val);
  }).then(function(res) {
    try {
      return JSON.parse(res);
    } catch(e) {
      console.log(chalk.red(`Failed reading cache file for ${key}:`));
      return cache(key, val, true);
    }
  });
};

var getContract = function(fileName, incContract) {
  fileName = fs.realpathSync(fileName);

  var fileMaxTime = function(files) {
    return Promise.map(files, fileTime).then(function(times) {
      return Math.max.apply(Math, times);
    });
  };

  var build = function() {
    return resolve(fileName).then(function(res) {
      var contractName = fileName.split('/').pop().replace(/\.sol$/, '');
      var input = {};
      var files = [];
      _.each(res, function(item, name) {
        input[name.split('/').pop()] = item.content;
        files.push(item.file);
      });

      return fileMaxTime(files).then(function(maxTime) {
        var output = solc.compile({sources: input}, 1);
        if (output.errors) {
          throw new Error(output.errors.join('\n'));
        }
        var contract = output.contracts[`${fileName.split('/').pop()}:${contractName}`];
        var byteCode = contract.bytecode;
        var jsonAbi = contract.interface;
        var abi = JSON.parse(jsonAbi);

        return {
          files: files,
          name: contractName,
          time: maxTime,
          byteCode: byteCode,
          abi: abi
        };
      });
    })
  };

  return cache(fileName, build).then(function(res) {
    var decorate = function(res) {
      var props = ['name', 'byteCode', 'abi'];
      return _.extend(_.pick(res, props), {
        contract: (incContract===undefined || incContract) ? getWeb3().eth.contract(res.abi) : null
      });
    };

    return fileMaxTime(res.files).then(function(time) {
      if (time==res.time) {
        return decorate(res);
      }

      return build().then(function(res) {
        return cache(fileName, res, true).then(function() {
          return decorate(res);
        });
      });
    })
  });
};

function prepareArgs(inputs, args) {
  return inputs.map(function(param, index) {
    var v = args[index];
    if (v===undefined) {
      throw new Error("Missing arg: "+param.name);
    }

    if (/\[\]$/.test(param.type)) {
      if (_.isString(v)) {
        try {
          v = JSON.parse(v);
        } catch (err) {
          throw new Error("Failed parsing arg: "+param.name);
        }
      }
    }

    return {
      name: param.name,
      value: v
    };
  });
};

var writeLabel = function(label) {
  process.stdout.write(label+' ... ');
};

var writeDone = function() {
  console.log(chalk.green('done'));
};

var writeFailed = function() {
  console.log(chalk.red('failed'));
};

var step = function(label, cb) {
  writeLabel(label);
  return valToPromise(cb).then(function(res) {
    writeDone();
    return res;
  }).catch(function(err) {
    writeFailed();
    throw err;
  });
};

var confirm = function(question) {
  console.log(question);
  return new Promise(function(resolve, reject) {
    read({ prompt: chalk.blue("[yes]/no: ") }, function(er, answer) {
      if (answer=='yes' || answer=='y') {
        resolve();
      } else {
        reject('canceled');
      }
    });
  });
};

var printException = function(err) {
  if (_.isString(err)) {
    console.log(chalk.red('Failed: '+err));
  } else {
    process.stdout.write(chalk.styles.red.open);
    console.log(err.stack);
    process.stdout.write(chalk.styles.red.close);
  }
};

function watchTxs(txToWatch, afterMined) {
  return new Promise(function(resolve, reject) {
    var blockFilter = getWeb3().eth.filter('latest');
    blockFilter.watch(function(error, block) {
      if (error) {
        return;
      }

      var checkTx = function(txId) {
        getWeb3().eth.getTransactionReceipt(txId, function(err, info) {
          if (!info) {
            return;
          }

          if (afterMined[txId]) {
            afterMined[txId](info);
            _.remove(txToWatch, function(id) { return id==txId; });

            if (txToWatch.length==0) {
              blockFilter.stopWatching();
              resolve();
            }
          }
        });
      };

      _.each(txToWatch, checkTx);
    });
  });
}

var exports = module.exports = {
  getContract: getContract,
  prepareArgs: prepareArgs,
  step: step,
  confirm: confirm,
  callMethod: callMethod,
  printException: printException,
  readFile: readFile,
  getNonce: getNonce,
  signWithNonce: signWithNonce,
  signTx: signTx,
  privateToAddress: privateToAddress,
  sendRaw: sendRaw,
  watchTxs: watchTxs,
  writeLabel: writeLabel,
  writeDone: writeDone,
  toWei : function(...args) {
    return getWeb3().toWei(...args);
  },
  read: function(options) {
    return new Promise(function(resolve, reject) {
      read(options, function(err, ret) {
        if (err) {
          reject(err);
        } else {
          resolve(ret);
        }
      })
    });
  },
  getBalance: function(addr) {
    return new Promise(function(resolve, reject) {
      getWeb3().eth.getBalance(addr, function(err, res) {
        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      });
    });
  }
};
<commit_msg>Fix relative imports<commit_after>const _ = require('lodash');
const Promise = require("bluebird");
const fs = require('fs');
const net = require('net');
const os = require('os');
const solc = require('solc');
const path = require('path');
const crypto = require('crypto');
const Tx = require('ethereumjs-tx');
const chalk = require('chalk');
const read = require('read');
const Web3 = require('web3');
const util = require('util');
const ethUtil = require('ethereumjs-util');
const salt = '2';
var web3;
Promise.config({
  longStackTraces: false
});

function getWeb3() {
  if (web3) {
    return web3;
  }

  var argv = require('yargs').argv;
  if (argv.g) {
    web3 = new Web3(new Web3.providers.IpcProvider(argv.g, net));
  } else {
    var ip = '127.0.0.1', port = 8545;
    if (argv.r) {
      var ipPort = argv.r.split(':');
      ip = ipPort[0];
      if (ipPort.length>1) {
        port = parseInt(ipPort[1], 10);
      }
    }

    web3 = new Web3(new Web3.providers.HttpProvider(`http://${ip}:${port}`));
  }

  return web3;
}

function privateToAddress(privateKey) {
  var public = ethUtil.privateToPublic(new Buffer(privateKey, 'hex'));
  return '0x' + ethUtil.publicToAddress(public).toString('hex');
}

function getNonce(address) {
  if (_.isArray(address)) {
    return Promise.map(address, getNonce).then(function(res) {
      return _.zipObject(address, res);
    });
  }

  return new Promise(function(resolve, reject) {
    getWeb3().eth.getTransactionCount(address, function(error, nonce) {
      if (error) {
        reject(error);
      } else {
        resolve(nonce);
      }
    });
  });
};

function signWithNonce(privateKey, nonce, from, to, amount, data) {
  return new Promise(function(resolve, reject) {
    var rawTx = {
      value: getWeb3().fromDecimal(amount),
      to: to,
      data: data,
      from: from,
    };

    getWeb3().eth.getGasPrice(function(error, price) {
      if (error) {
        reject(error);
        return;
      }
      getWeb3().eth.estimateGas(rawTx, function(error, gasUsage) {
        if (error) {
          reject(error);
          return;
        }
        // var forceLimit = 4700000;
        // if (gasUsage>forceLimit) {
        //   console.log(chalk.red(`Needed gas is too high: ${gasUsage}`));
        //   process.exit();
        // }
        //
        gasUsage = Math.min(gasUsage * 2, 3000000);

        var tx = new Tx({
          nonce: (getWeb3().toHex(nonce)),
          to: rawTx.to,
          value: rawTx.value,
          from: from,
          gasPrice: getWeb3().toHex(price),
          gasLimit: getWeb3().toHex(gasUsage),
          data: data
        });
        var key = new Buffer(privateKey, 'hex')
        tx.sign(key);

        resolve('0x'+tx.serialize().toString('hex'));
      });
    });
  });
};

function signTx(privateKey, from, to, amount, data) {
  return getNonce(from).then(function(nonce) {
    return signWithNonce(privateKey, nonce, from, to, amount, data);
  });
};

function sendRaw(signed) {
  return new Promise(function(resolve, reject) {
    getWeb3().eth.sendRawTransaction(signed, function(error, res) {
      if (error) {
        reject(error);
      } else {
        resolve(res);
      }
    });
  });
};

function sendTx(from, to, amount, data) {
  var rawTx = {
    value: getWeb3().fromDecimal(amount),
    to: to,
    data: data,
    from: from,
  };

  return new Promise(function(resolve, reject) {
    getWeb3().eth.estimateGas(rawTx, function(error, gasUsage) {
      if (error) {
        reject(error);
        return;
      }

      // var forceLimit = 4700000;
      // if (gasUsage>forceLimit) {
      //   console.log(chalk.red(`Needed gas is too high: ${gasUsage}`));
      //   process.exit();
      // }

      rawTx.gas = Math.min(gasUsage * 2, 3000000);

      getWeb3().eth.sendTransaction(rawTx, function(error, res) {
        if (error) {
          reject(error);
        } else {
          resolve(res);
        }
      });
    });
  });
}

function callMethod(privateKey, toAddress, value, contract, methodName, args) {
  var fromAddress = privateKey ? privateToAddress(privateKey) : getWeb3().eth.accounts[0];
  var method = contract[methodName];
  var data = method.getData.apply(method, args);
  if (methodName=='new') {
    data = '0x'+data;
  }
  return new Promise(function(resolve, reject) {
    var txId;

    getWeb3().eth.filter('latest').watch(function(error, block) {
      if (error || !txId) {
        return;
      }

      getWeb3().eth.getTransactionReceipt(txId, function(err, info) {
        if (!info) {
          return;
        }
        writeDone();
        resolve(info);
      });
    });

    if (!privateKey) {
      return step('Broadcasting tx for '+methodName, sendTx(
        fromAddress,
        toAddress,
        value,
        data
      )).then(function(id) {
        txId = id;
        console.log('Transaction:');
        console.log(chalk.green(id));
        writeLabel('Waiting to be mined');
      });
    }

    return step('Broadcasting tx for '+methodName, signTx(
      privateKey,
      fromAddress,
      toAddress,
      value,
      data
    ).then(sendRaw)).then(function(id) {
      txId = id;
      console.log('Transaction:');
      console.log(chalk.green(id));
      writeLabel('Waiting to be mined');
    });
  });
};

function resolve(fileName) {
  var cwd = path.dirname(fileName)
  var name = path.basename(fileName);
  var processed = [];

  var _resolve = function(cwd, name) {
    var extractImports = function(content) {
      var imports = [];
      var lines = content.split(/\n/);
      lines.forEach(function(line, ii) {
        var m = line.replace(/\/\/.*$/, '').match(/import\s+["']([^"']+)["']/);
        if (m) {

          lines[ii] = `import "${m[1].split('/').pop()}";`;
          imports.push(m[1]);
        }
      });
      var finalCode = lines.join('\n');

      return [finalCode, imports];
    };

    var res = {};
    var fullName = fs.realpathSync(cwd + '/' + name);
    if (processed.indexOf(fullName)!=-1) {
      return res;
    }
    processed.push(fullName);
    return readFile(fullName).then(function(content) {
      var contentImports = extractImports(content);
      res[fullName] = {content: contentImports[0], file:fullName};

      return Promise.all(contentImports[1].map(function(name) {
        var newCwd = fs.realpathSync(cwd+'/'+name).split('/').slice(0, -1).join('/');
        return _resolve(newCwd, name);
      }));
    }).then(function(items) {
      items.forEach(function(child) {
        _.extend(res, child);
      })
      return res;
    });
  }

  return _resolve(cwd, name);
};

function readFile(fileName) {
  return new Promise(function(resolve, reject) {
    fs.readFile(fileName, 'UTF-8', function(err, data) {
      if (err) {
        reject(err);
      }
      resolve(data);
    });
  })
};

function fileTime(fileName) {
  return new Promise(function(resolve, reject) {
    fs.stat(fileName, function(err, stat) {
      if (err) {
        reject(err);
      } else {
        resolve(stat.mtime.getTime());
      }
    });
  });
};

function valToPromise(val) {
  if (_.isFunction(val)) {
    return new Promise(function(resolve, reject) {
      resolve(val());
    });
  }

  return new Promise(function(resolve, reject) {
    resolve(val);
  });
};

function cache(key, val) {
  var dir = os.tmpdir();

  var exec = function(cachePath, val) {
    return valToPromise(val).then(function(val) {
      val = JSON.stringify(val);
      return new Promise(function(resolve, reject) {
        fs.writeFile(cachePath, val, function(err) {
          if (err) {
            reject(err);
            return;
          }
          fs.chmodSync(cachePath, '777');
          resolve(val);
        });
      });
    });
  };

  var hash = crypto.createHash('sha256');
  hash.update(salt + key);
  var cacheFile = hash.digest('hex');
  var cachePath = dir+"/"+cacheFile;

  if (arguments[2]===true) {
    return exec(cachePath, val).then(function(res) {
      return JSON.parse(res);
    })
  }

  return readFile(cachePath).catch(function(err) {
    return exec(cachePath, val);
  }).then(function(res) {
    try {
      return JSON.parse(res);
    } catch(e) {
      console.log(chalk.red(`Failed reading cache file for ${key}:`));
      return cache(key, val, true);
    }
  });
};

var getContract = function(fileName, incContract) {
  fileName = fs.realpathSync(fileName);

  var fileMaxTime = function(files) {
    return Promise.map(files, fileTime).then(function(times) {
      return Math.max.apply(Math, times);
    });
  };

  var build = function() {
    return resolve(fileName).then(function(res) {
      var contractName = fileName.split('/').pop().replace(/\.sol$/, '');
      var input = {};
      var files = [];
      _.each(res, function(item, name) {
        input[name.split('/').pop()] = item.content;
        files.push(item.file);
      });

      return fileMaxTime(files).then(function(maxTime) {
        var output = solc.compile({sources: input}, 1);
        if (output.errors) {
          throw new Error(output.errors.join('\n'));
        }
        var contract = output.contracts[`${fileName.split('/').pop()}:${contractName}`];
        var byteCode = contract.bytecode;
        var jsonAbi = contract.interface;
        var abi = JSON.parse(jsonAbi);

        return {
          files: files,
          name: contractName,
          time: maxTime,
          byteCode: byteCode,
          abi: abi
        };
      });
    })
  };

  return cache(fileName, build).then(function(res) {
    var decorate = function(res) {
      var props = ['name', 'byteCode', 'abi'];
      return _.extend(_.pick(res, props), {
        contract: (incContract===undefined || incContract) ? getWeb3().eth.contract(res.abi) : null
      });
    };

    return fileMaxTime(res.files).then(function(time) {
      if (time==res.time) {
        return decorate(res);
      }

      return build().then(function(res) {
        return cache(fileName, res, true).then(function() {
          return decorate(res);
        });
      });
    })
  });
};

function prepareArgs(inputs, args) {
  return inputs.map(function(param, index) {
    var v = args[index];
    if (v===undefined) {
      throw new Error("Missing arg: "+param.name);
    }

    if (/\[\]$/.test(param.type)) {
      if (_.isString(v)) {
        try {
          v = JSON.parse(v);
        } catch (err) {
          throw new Error("Failed parsing arg: "+param.name);
        }
      }
    }

    return {
      name: param.name,
      value: v
    };
  });
};

var writeLabel = function(label) {
  process.stdout.write(label+' ... ');
};

var writeDone = function() {
  console.log(chalk.green('done'));
};

var writeFailed = function() {
  console.log(chalk.red('failed'));
};

var step = function(label, cb) {
  writeLabel(label);
  return valToPromise(cb).then(function(res) {
    writeDone();
    return res;
  }).catch(function(err) {
    writeFailed();
    throw err;
  });
};

var confirm = function(question) {
  console.log(question);
  return new Promise(function(resolve, reject) {
    read({ prompt: chalk.blue("[yes]/no: ") }, function(er, answer) {
      if (answer=='yes' || answer=='y') {
        resolve();
      } else {
        reject('canceled');
      }
    });
  });
};

var printException = function(err) {
  if (_.isString(err)) {
    console.log(chalk.red('Failed: '+err));
  } else {
    process.stdout.write(chalk.styles.red.open);
    console.log(err.stack);
    process.stdout.write(chalk.styles.red.close);
  }
};

function watchTxs(txToWatch, afterMined) {
  return new Promise(function(resolve, reject) {
    var blockFilter = getWeb3().eth.filter('latest');
    blockFilter.watch(function(error, block) {
      if (error) {
        return;
      }

      var checkTx = function(txId) {
        getWeb3().eth.getTransactionReceipt(txId, function(err, info) {
          if (!info) {
            return;
          }

          if (afterMined[txId]) {
            afterMined[txId](info);
            _.remove(txToWatch, function(id) { return id==txId; });

            if (txToWatch.length==0) {
              blockFilter.stopWatching();
              resolve();
            }
          }
        });
      };

      _.each(txToWatch, checkTx);
    });
  });
}

var exports = module.exports = {
  getContract: getContract,
  prepareArgs: prepareArgs,
  step: step,
  confirm: confirm,
  callMethod: callMethod,
  printException: printException,
  readFile: readFile,
  getNonce: getNonce,
  signWithNonce: signWithNonce,
  signTx: signTx,
  privateToAddress: privateToAddress,
  sendRaw: sendRaw,
  watchTxs: watchTxs,
  writeLabel: writeLabel,
  writeDone: writeDone,
  toWei : function(...args) {
    return getWeb3().toWei(...args);
  },
  read: function(options) {
    return new Promise(function(resolve, reject) {
      read(options, function(err, ret) {
        if (err) {
          reject(err);
        } else {
          resolve(ret);
        }
      })
    });
  },
  getBalance: function(addr) {
    return new Promise(function(resolve, reject) {
      getWeb3().eth.getBalance(addr, function(err, res) {
        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      });
    });
  }
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var gulpsync = require('gulp-sync')(gulp);
var plumber = require('gulp-plumber');
var less = require('gulp-less');
var cssmin = require('gulp-cssmin');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var pjson = require('./package.json');
var rimraf = require('gulp-rimraf');
var replace = require('gulp-replace');
var concat = require('gulp-concat-util');
var header = require('gulp-header');
var babel = require('gulp-babel');
var fs = require('fs');

// =========================================================================
// Clean tasks
// =========================================================================
var clearFolder = function (src) {
    return gulp.src(src)
        .pipe(rimraf()).on('error', gutil.log);
};

gulp.task('clean-css-dist', function () {
    return clearFolder('./dist/css/*.*');
});
gulp.task('clean-js-dist', function () {
    return clearFolder('./dist/js/*.*');
});
gulp.task('clean-snippets-examples', function () {
    return clearFolder('./examples/snippets');
});

// =========================================================================
// Components tasks
// =========================================================================
var buildComponents = function (typeType) {
    return gulp.src(['./src/' + typeType + '/keditor-component-*.' + typeType])
        .pipe(plumber())
        .pipe(concat('keditor-components.' + typeType + ''))
        .pipe(gulp.dest('./dist/' + typeType + '/'))
};

gulp.task('build-css-components', function () {
    return buildComponents('css');
});
gulp.task('build-js-components', function () {
    return buildComponents('js');
});

// =========================================================================
// Copy tasks
// =========================================================================
gulp.task('copy-css', function () {
    return gulp.src(['./src/css/keditor.css', './src/css/keditor-bootstrap-form.css'])
        .pipe(gulp.dest('./dist/css/'));
});
gulp.task('copy-js', function () {
    return gulp.src('./src/js/keditor.js')
        .pipe(replace('@{version}', pjson.version))
        .pipe(gulp.dest('./dist/js/'));
});
gulp.task('copy-snippets-src-examples', function () {
    return gulp.src('./src/snippets/**/*')
        .pipe(gulp.dest('./examples/snippets'));
});

// =========================================================================
// Minify tasks
// =========================================================================
gulp.task('min-css', function () {
    return gulp.src('./dist/css/*.css')
        .pipe(sourcemaps.init())
        .pipe(cssmin({
            specialComments: 1,
            advanced: false
        }))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./dist/css/'))
});

gulp.task('min-js', function () {
    return gulp.src(['./dist/js/*.js'])
        .pipe(sourcemaps.init())
        .pipe(uglify({
            preserveComments: /(?:^!|@(?:license|preserve|cc_on))/
        }))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/js/')).on('error', gutil.log);
});

// =========================================================================
// Header tasks
// =========================================================================
var prependHeader = function (fileType) {
    return gulp.src(['./dist/' + fileType + '/*.' + fileType])
        .pipe(header(fs.readFileSync('./header.txt', 'utf8'), { pkg: pjson }))
        .pipe(gulp.dest('./dist/' + fileType));
};

gulp.task('prepend-header-css', function () {
    return prependHeader('css')
});
gulp.task('prepend-header-js', function () {
    return prependHeader('js')
});

// =========================================================================
// Examples tasks
// =========================================================================
gulp.task('build-snippets-examples', gulpsync.sync(['clean-snippets-examples', 'copy-snippets-src-examples']));

// =========================================================================
// Build CSS
// =========================================================================
gulp.task('build-css', function () {
    return gulp.src(['./src/less/*.less', '!./src/less/_*.less'])
        .pipe(plumber())
        .pipe(less())
        .pipe(gulp.dest('./src/css/')).on('error', gutil.log);
});

// =========================================================================
// Build JS
// =========================================================================
gulp.task('build-js-dev', function () {
    return gulp.src(['./src/js/*.js'])
        .pipe(babel({
            presets: ['env'],
            plugins: [
                'transform-class-properties'
            ]
        }))
        .pipe(gulp.dest('./src/js-dev/')).on('error', gutil.log);
});

// =========================================================================
// Watch
// =========================================================================
gulp.task('watch', function () {
    gulp.watch(['./src/less/*.less'], ['build-css']);
    gulp.watch(['./src/js/*.js'], ['build-js-dev']);
});

// =========================================================================
// Main tasks
// =========================================================================
gulp.task('build-css-dist', gulpsync.sync(['build-css', 'clean-css-dist', 'copy-css', 'build-css-components', 'min-css', 'prepend-header-css']));
gulp.task('build-js-dist', gulpsync.sync(['clean-js-dist', 'copy-js', 'build-js-components', 'min-js', 'prepend-header-js']));

gulp.task('build', ['build-css-dist', 'build-js-dist', 'build-snippets-examples']);

gulp.task('dev', ['build-css', 'build-js-dev', 'watch']);

// Gulp Default
gulp.task('default', ['build', 'dev']);
<commit_msg>Update<commit_after>var gulp = require('gulp');
var gulpsync = require('gulp-sync')(gulp);
var plumber = require('gulp-plumber');
var less = require('gulp-less');
var cssmin = require('gulp-cssmin');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var pjson = require('./package.json');
var rimraf = require('gulp-rimraf');
var replace = require('gulp-replace');
var concat = require('gulp-concat-util');
var header = require('gulp-header');
var babel = require('gulp-babel');
var fs = require('fs');

// =========================================================================
// Clean tasks
// =========================================================================
var clearFolder = function (src) {
    return gulp.src(src)
        .pipe(rimraf()).on('error', gutil.log);
};

gulp.task('clean-css-dist', function () {
    return clearFolder('./dist/css/*.*');
});
gulp.task('clean-js-dist', function () {
    return clearFolder('./dist/js/*.*');
});
gulp.task('clean-snippets-examples', function () {
    return clearFolder('./examples/snippets');
});

// =========================================================================
// Components tasks
// =========================================================================
var buildComponents = function (typeType) {
    return gulp.src(['./src/' + typeType + '/keditor-component-*.' + typeType])
        .pipe(plumber())
        .pipe(concat('keditor-components.' + typeType + ''))
        .pipe(gulp.dest('./dist/' + typeType + '/'))
};

gulp.task('build-css-components', function () {
    return buildComponents('css');
});
gulp.task('build-js-components', function () {
    return buildComponents('js');
});

// =========================================================================
// Copy tasks
// =========================================================================
gulp.task('copy-css', function () {
    return gulp.src(['./src/css/keditor.css', './src/css/keditor-bootstrap-form.css'])
        .pipe(gulp.dest('./dist/css/'));
});
gulp.task('copy-js', function () {
    return gulp.src('./src/js/keditor.js')
        .pipe(replace('@{version}', pjson.version))
        .pipe(gulp.dest('./dist/js/'));
});
gulp.task('copy-snippets-src-examples', function () {
    return gulp.src('./src/snippets/**/*')
        .pipe(gulp.dest('./examples/snippets'));
});

// =========================================================================
// Minify tasks
// =========================================================================
gulp.task('min-css', function () {
    return gulp.src('./dist/css/*.css')
        .pipe(sourcemaps.init())
        .pipe(cssmin({
            specialComments: 1,
            advanced: false
        }))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./dist/css/'))
});

gulp.task('min-js', function () {
    return gulp.src(['./dist/js/*.js'])
        .pipe(sourcemaps.init())
        .pipe(uglify({
            preserveComments: /(?:^!|@(?:license|preserve|cc_on))/
        }))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/js/')).on('error', gutil.log);
});

// =========================================================================
// Header tasks
// =========================================================================
var prependHeader = function (fileType) {
    return gulp.src(['./dist/' + fileType + '/*.' + fileType])
        .pipe(header(fs.readFileSync('./header.txt', 'utf8'), { pkg: pjson }))
        .pipe(gulp.dest('./dist/' + fileType));
};

gulp.task('prepend-header-css', function () {
    return prependHeader('css')
});
gulp.task('prepend-header-js', function () {
    return prependHeader('js')
});

// =========================================================================
// Examples tasks
// =========================================================================
gulp.task('build-snippets-examples', gulpsync.sync(['clean-snippets-examples', 'copy-snippets-src-examples']));

// =========================================================================
// Build CSS
// =========================================================================
gulp.task('build-css', function () {
    return gulp.src(['./src/less/*.less', '!./src/less/_*.less'])
        .pipe(plumber())
        .pipe(less())
        .pipe(gulp.dest('./src/css/')).on('error', gutil.log);
});

// =========================================================================
// Build JS
// =========================================================================
gulp.task('build-js', function () {
    return gulp.src(['./src/js/*.js'])
        .pipe(babel({
            presets: ['env'],
            plugins: [
                'transform-class-properties'
            ]
        }))
        .pipe(gulp.dest('./src/js-dev/')).on('error', gutil.log);
});

// =========================================================================
// Watch
// =========================================================================
gulp.task('watch', function () {
    gulp.watch(['./src/less/*.less'], ['build-css']);
    gulp.watch(['./src/js/*.js'], ['build-js']);
});

// =========================================================================
// Main tasks
// =========================================================================
gulp.task('build-css-dist', gulpsync.sync(['clean-css-dist', 'build-css', 'copy-css', 'build-css-components', 'min-css', 'prepend-header-css']));
gulp.task('build-js-dist', gulpsync.sync(['clean-js-dist', 'build-js', 'copy-js', 'build-js-components', 'min-js', 'prepend-header-js']));

gulp.task('build', ['build-css-dist', 'build-js-dist', 'build-snippets-examples']);

gulp.task('dev', ['build-css', 'build-js', 'watch']);

<|endoftext|>


<commit_before>var colors = require('colors');
var express = require('express');
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var util = require('util');

console.log();
console.log("  ____            _    _                          ");
console.log(" |  _ \\  ___  ___| | _| |    __ _ _ __ ___  _ __  ");
console.log(" | | | |/ _ \\/ __| |/ / |   / _` | '_ ` _ \\| '_ \\ ");
console.log(" | |_| |  __/\\__ \\   <| |__| (_| | | | | | | |_) |");
console.log(" |____/ \\___||___/_|\\_\\_____\\__,_|_| |_| |_| .__/ ");
console.log("                                           |_|    ");
console.log("                                                  ");
console.log("--------------------------------------------------");
console.log(" Author: Brian Wigginton - brianwiggintongmail.com");
console.log("--------------------------------------------------");
console.log();

var app;

var device = "/dev/tty.usbmodem1421";
var baudrate = 9600;

var serialPort = new SerialPort(device, {
	baudrate: baudrate,
	parser: serialport.parsers.readline("\n")
})

serialPort.on("open", function() {
	setTimeout(connected, 1000);
});

var r = 255, g = 255, b = 255;

function connected() {
	console.log('Opened '.green + device.yellow + ' @ ' + baudrate.toString().blue + ' bps'.blue);
	console.log();

	startServer();

	serialPort.on('data', function(data) {
		console.info('∞ '.magenta + data);
	});
	setInterval(pulse, 50);
}

function startServer() {
	app = express();
	app.get('/', function(req, res) {
		res.send('<input type="color">');
	});
	app.listen(3000);
}

function colorize() {
	serialPort.write(r + ',' + g + ',' + b + '\n');
}

pulseInhale = false;

function pulse() {
	if(pulseInhale) {
		r+=5;
		g+=5;
		b+=5;
		if(r >= 255) pulseInhale = false;
	} else {
		r-=5;
		g-=5;
		b-=5;
		if(r <= 50) pulseInhale = true;
	}

	serialPort.write(r + ',' + g + ',' + b + '\n');
}

<commit_msg>removing express for now, as it will be developed in another branch<commit_after>var colors = require('colors');
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var util = require('util');

console.log();
console.log("  ____            _    _                          ");
console.log(" |  _ \\  ___  ___| | _| |    __ _ _ __ ___  _ __  ");
console.log(" | | | |/ _ \\/ __| |/ / |   / _` | '_ ` _ \\| '_ \\ ");
console.log(" | |_| |  __/\\__ \\   <| |__| (_| | | | | | | |_) |");
console.log(" |____/ \\___||___/_|\\_\\_____\\__,_|_| |_| |_| .__/ ");
console.log("                                           |_|    ");
console.log("                                                  ");
console.log("--------------------------------------------------");
console.log(" Author: Brian Wigginton - brianwiggintongmail.com");
console.log("--------------------------------------------------");
console.log();

// TODO: make this dynamic, if there's only one option use it, otherwise
// prompt for the user to choose a device
var device = "/dev/tty.usbmodem1421";
var baudrate = 9600;

var serialPort = new SerialPort(device, {
	baudrate: baudrate,
	parser: serialport.parsers.readline("\n")
});

serialPort.on("open", function() {
	setTimeout(connected, 1000);
});

var r = 255, g = 255, b = 255;

function connected() {
	console.log('Opened '.green + device.yellow + ' @ ' + baudrate.toString().blue + ' bps'.blue);
	console.log();

	serialPort.on('data', function(data) {
		console.info('∞ '.magenta + data);
	});
	setInterval(pulse, 50);
}

function colorize() {
	serialPort.write(r + ',' + g + ',' + b + '\n');
}

pulseInhale = false;

function pulse() {
	if(pulseInhale) {
		r+=5;
		g+=5;
		b+=5;
		if(r >= 255) pulseInhale = false;
	} else {
		r-=5;
		g-=5;
		b-=5;
		if(r <= 50) pulseInhale = true;
	}

	serialPort.write(r + ',' + g + ',' + b + '\n');
}

<|endoftext|>


<commit_before>function setup() {

}

var mic, recorder, soundFile;

var state = 0; // mousePress will increment from Record, to Stop, to Play

function setup() {
  createCanvas(400,400);
  background(200);
  fill(0);
  text('Enable mic and click the mouse to begin recording', 20, 20);

  // create an audio in
  mic = new p5.AudioIn();

  // users must manually enable their browser microphone for recording to work properly!
  mic.start();

  // create a sound recorder
  recorder = new p5.SoundRecorder();

  // connect the mic to the recorder
  recorder.setInput(mic);

  // create an empty sound file that we will use to playback the recording
  soundFile = new p5.SoundFile();
}

function mousePressed() {
  // use the '.enabled' boolean to make sure user enabled the mic (otherwise we'd record silence)
  if (state === 0 && mic.enabled) {

    // Tell recorder to record to a p5.SoundFile which we will use for playback
    recorder.record(soundFile);

    background(255,0,0);
    text('Recording now! Click to stop.', 20, 20);
    state++;
  }

  else if (state === 1) {
    recorder.stop(); // stop recorder, and send the result to soundFile

    background(0,255,0);
    text('Recording stopped. Click to play & save', 20, 20);
    state++;
  }

  else if (state === 2) {
    soundFile.play(); // play the result!
    saveSound(soundFile, 'js/mySound.wav'); // save file
    state++;
  }
}
<commit_msg>Update sketch.js<commit_after>function setup() {

}

var mic, recorder, soundFile;

var state = 0; // mousePress will increment from Record, to Stop, to Play

function setup() {
  createCanvas(400,400);
//    background(200);
//   fill(0);
  text('Enable mic and click the mouse to begin recording', 20, 20);

  // create an audio in
  mic = new p5.AudioIn();

  // users must manually enable their browser microphone for recording to work properly!
  mic.start();

  // create a sound recorder
  recorder = new p5.SoundRecorder();

  // connect the mic to the recorder
  recorder.setInput(mic);

  // create an empty sound file that we will use to playback the recording
  soundFile = new p5.SoundFile();
}

function draw() {
  background(200);

  // Get the overall volume (between 0 and 1.0)
  var vol = mic.getLevel();
  fill(127);
  stroke(0);

  // Draw an ellipse with height based on volume
  var h = map(vol, 0, 1, height, 0);
  ellipse(width/2, h - 25, 50, 50);
}

function mousePressed() {
  // use the '.enabled' boolean to make sure user enabled the mic (otherwise we'd record silence)
  if (state === 0 && mic.enabled) {

    // Tell recorder to record to a p5.SoundFile which we will use for playback
    recorder.record(soundFile);

    background(255,0,0);
    text('Recording now! Click to stop.', 20, 20);
    state++;
  }

  else if (state === 1) {
    recorder.stop(); // stop recorder, and send the result to soundFile

    background(0,255,0);
    text('Recording stopped. Click to play & save', 20, 20);
    state++;
  }

  else if (state === 2) {
    soundFile.play(); // play the result!
    saveSound(soundFile, 'js/mySound.wav'); // save file
    state++;
  }
}
<|endoftext|>


<commit_before>import path from 'path';
import {
  jsf, pick, tryTest, getTests,
} from './helpers';

const { only, all } = getTests(__dirname);

const seeds = [];

function seed() {
  const value = Math.random();
  seeds.push(value);
  return value;
}

(only.length ? only : all).forEach(suite => {
  const normalizedFilename = path.normalize(suite.file);
  const relativeFilename = normalizedFilename.replace(`${process.cwd()}${path.sep}`, '');

  describe(`${suite.description} (${relativeFilename})`, () => {
    suite.tests.forEach(test => {
      if (!process.env.CI && test.online) return;
      if (process.argv.includes('--skip')) {
        if (!test.skip) return;
        delete test.skip;
      }

      if (test.skip) {
        it.skip(test.description);
        return;
      }

      it(test.description, () => {
        jsf.option(jsf.option.getDefaults());

        if (test.set) {
          jsf.option(test.set);
        }

        jsf.option({
          random: () => ((test.seed && (Array.isArray(test.seed) ? test.seed.shift() : test.seed)) || seed()),
        });

        if (test.require) {
          test.require = Array.isArray(test.require) ? test.require : [test.require];

          test.require.map(toRequire => {
            return require(`./${toRequire}`).register(jsf);
          });
        }

        const schema = typeof test.schema === 'string'
          ? pick(suite, test.schema)
          : test.schema;

        const refs = (test.refs || []).map(ref => {
          return typeof ref === 'string'
            ? pick(suite, ref)
            : ref;
        });

        // support for "exhaustive" testing, increase or set in .json spec
        // for detecting more bugs quickly by executing the same test N-times
        const max = test.repeat || (process.CI ? 250 : 1);

        let nth = max;

        const tasks = [];

        if (test.throwsSometimes) {
          test.throwCount = 0;
        }

        while (nth) {
          if (!test.skip) {
            tasks.push(tryTest(max - nth + 1, max, test, refs, schema));
          }

          nth -= 1;
        }

        return Promise.all(tasks).catch(e => {
          if (test.online) {
            console.log('---> failed due connectivity issues?');
            console.log(e.message);
            return;
          }

          // FIXME: find a way to debug this
          console.log('---> Used seeds:', seeds.slice(-10).join(', ') || test.seed);
          throw e;
        }).then(() => {
          if (test.throwsSometimes && !(test.throwCount > 0)) {
            throw new Error('Expected some tests to throw');
          }
        });
      }).timeout(suite.timeout || test.timeout || (process.CI ? 30000 : 10000));
    });
  });
});
<commit_msg>chore: increase repeat value on CI<commit_after>import path from 'path';
import {
  jsf, pick, tryTest, getTests,
} from './helpers';

const { only, all } = getTests(__dirname);

const seeds = [];

function seed() {
  const value = Math.random();
  seeds.push(value);
  return value;
}

(only.length ? only : all).forEach(suite => {
  const normalizedFilename = path.normalize(suite.file);
  const relativeFilename = normalizedFilename.replace(`${process.cwd()}${path.sep}`, '');

  describe(`${suite.description} (${relativeFilename})`, () => {
    suite.tests.forEach(test => {
      if (!process.env.CI && test.online) return;
      if (process.argv.includes('--skip')) {
        if (!test.skip) return;
        delete test.skip;
      }

      if (test.skip) {
        it.skip(test.description);
        return;
      }

      it(test.description, () => {
        jsf.option(jsf.option.getDefaults());

        if (test.set) {
          jsf.option(test.set);
        }

        jsf.option({
          random: () => ((test.seed && (Array.isArray(test.seed) ? test.seed.shift() : test.seed)) || seed()),
        });

        if (test.require) {
          test.require = Array.isArray(test.require) ? test.require : [test.require];

          test.require.map(toRequire => {
            return require(`./${toRequire}`).register(jsf);
          });
        }

        const schema = typeof test.schema === 'string'
          ? pick(suite, test.schema)
          : test.schema;

        const refs = (test.refs || []).map(ref => {
          return typeof ref === 'string'
            ? pick(suite, ref)
            : ref;
        });

        // support for "exhaustive" testing, increase or set in .json spec
        // for detecting more bugs quickly by executing the same test N-times
        const max = process.CI ? 250 : (test.repeat || 1);

        let nth = max;

        const tasks = [];

        if (test.throwsSometimes) {
          test.throwCount = 0;
        }

        while (nth) {
          if (!test.skip) {
            tasks.push(tryTest(max - nth + 1, max, test, refs, schema));
          }

          nth -= 1;
        }

        return Promise.all(tasks).catch(e => {
          if (test.online) {
            console.log('---> failed due connectivity issues?');
            console.log(e.message);
            return;
          }

          // FIXME: find a way to debug this
          console.log('---> Used seeds:', seeds.slice(-10).join(', ') || test.seed);
          throw e;
        }).then(() => {
          if (test.throwsSometimes && !(test.throwCount > 0)) {
            throw new Error('Expected some tests to throw');
          }
        });
      }).timeout(suite.timeout || test.timeout || (process.CI ? 30000 : 10000));
    });
  });
});
<|endoftext|>


<commit_before>jQuery.Controller.extend('ApiPlayground.Controllers.MainController',
/* @Static */
{
	onDocument : true
},
/* @Prototype */
{
	"{window} load" : function() {
	    var _this = this;

	    SMART.ready(function() {
		$(window).resize(function() {
			h = $(window).height();
			$("#type-nav").css("min-height", h+"px");
		});
		$(window).resize();

		_this.calls = {};
		_this.payload_box = $("#payload");
		_this.response_box = $("#response");
        _this.response_tabs = $("#response_tabs");
        _this.response_tabs.tabs();
		window.jash = new Jash(_this.response_box.get(0));
		window.jash.main();

		_this.payload_box.hide();
		_this.response_box.hide();
        _this.response_tabs.hide();
		ApiType.interpolations.record_id = SMART.record.id;
		ApiType.addInterpolationValue("record_id", SMART.record.id);
		ApiType.find_all_types_and_calls();

	    });

    },

    'ontology_parsed subscribe': function(topic, element) {
		$("#type-nav").html(this.view('groups', {groups: ApiCallGroup.get_top_groups()}));
		$("#wrap").css({marginLeft: $("#type-nav").width()});
    },

    ".type click": function(el, ev ){
		var g = el.closest(".type").model();
		this.selected_top_group = g;
		g.element = el;

		$("#type-heading").html(this.view('calls', {group: g}));
		this.payload_box.hide();
		this.response_box.hide();
        this.response_tabs.hide();
		$("#interpolation-fields").html("");
		g.group_type.fetchParameters();

    },

    "BUTTON.call click": function(el, ev)
    {

    	var c = el.closest(".call").model();
		this.selected_call = c;
		var method = c.method;

		if ($.inArray(method, ApiCall.payload_methods) !== -1)
		{
		    if (c.example !== undefined)
			this.payload_box.val(c.example);
		    else
			this.payload_box.val(this.selected_top_group.group_type.example);
		    this.payload_box.show();
		} else  {
			this.payload_box.val("");
			this.payload_box.hide();
		}

		this.response_box.hide();
        this.response_tabs.hide()

		$("#interpolation-fields").html(this.view('interpolations', {type: this.selected_top_group.group_type,
																	 call: this.selected_call}));
		$("#interpolation-fields INPUT").each(function() {
			$i = $(this);
			var field_name = $i.attr("field_name");

			var compfunc = function(request, response) {
				try {
				//console.log("looking up " + field_name + ": " + ApiType.interpolations.lists[field_name].join(", "));
				response(ApiType.interpolations.lists[field_name]);
				} catch(err) {response([]);}
			};

			$i.autocomplete(
				{source: compfunc,
				 minLength: 0,
				 delay: 0,
				 close: function() {$(this).data("close_handled", false);}})
				.focus(function () {
				 		var close_handled = $(this).data("close_handled");
						if (close_handled) {
						   $(this).keydown();
						}
				 		$(this).data("close_handled", true);
				}).data("close_handled", true);
			try  {$i.val(ApiType.interpolations.lists[field_name][0]);} catch(err){}

		});

   },

    "BUTTON.cancel-call click": function(el, ev) {
    	this.selected_top_group.element.click();

    },

    "BUTTON.complete-call click": function(el, ev) {
    	$(".cancel-call").attr("DISABLED", "true");
		$(".complete-call").attr("DISABLED", "true");

    	$("#interpolation-fields INPUT").each(function() {
			$i = $(this);
			var field_name = $i.attr("field_name");
    		ApiType.interpolations[field_name] = $i.val();
    		$i.attr("DISABLED", "true");
    	});

    	this.selected_call.callAPI( this.payload_box.val(),
    								this.callback(this.receivedResult))
    },

    receivedResult: function(res) {

        if (res.contentType === "application/rdf+xml") {
            r = SMART.process_rdf(res.contentType, res.body);

            res.ntriples = "";
            r.where('?s ?p ?o')
                .each(function(){
                    res.ntriples += this.s.toString() + " " + this.p.toString() + " " + this.o.toString() + " .\n";
                });

            $("#tab_rdf pre").text(res.body);
            $("#tab_ntriples pre").text(res.ntriples);

            var o = SMART.break_json_cycles(res.objects.of_type);
            $("#tab_jsonld pre").text(JSON.stringify(o, null, "  "));

            // Arbitrary limit on the code pretification (it's not very efficient and
            // hoses the browser up for large chunks of code)
            if (res.body.length <= 4096) {
                // Reset the pretty print processed flag
                $('pre.prettyprint').removeClass('prettyprinted');

                // Now prettify
                prettyPrint();
            }

            this.response_tabs.show()

            window.response = r;
            window.jash.clear();
            window.jash.output.value = window.jash.defaultText;
            window.jash.output.value += "\n";
            window.jash.output.value += "Triples in RDF graph returned: " + response.where('?s ?p ?o.').length+"\n\n";
            window.jash.output.value += "To explore the graph, try:\n";
            window.jash.output.value += "  > response.source_xml\n";
            window.jash.output.value += "  > response.where('?s ?p ?o.').length\n";
            window.jash.output.value += "  > response.where('?s ?p ?o.')[0].s \n";
                this.response_box.show();
            window.jash.print("\nTo explore type or paste commands in the textbox below, then press Enter.");
            window.jash.input.focus();
                $(".cancel-call").removeAttr("DISABLED");
                $(".complete-call").removeAttr("DISABLED");
                $("#interpolation-fields INPUT").each(function() {
                    $i = $(this);
                    $i.removeAttr("DISABLED");
                });
        } else {
            window.jash.clear();
            window.jash.output.value = res.body;
            window.jash.output.value += "\n\n------------\n";
            window.jash.output.value += window.jash.defaultText;
            window.jash.output.value += "\n";
            this.response_box.show();
        }

    	this.selected_top_group.group_type.fetchParameters();
    }

});
<commit_msg>Update the examples in the interactive tab of API Verifier<commit_after>jQuery.Controller.extend('ApiPlayground.Controllers.MainController',
/* @Static */
{
	onDocument : true
},
/* @Prototype */
{
	"{window} load" : function() {
	    var _this = this;

	    SMART.ready(function() {
		$(window).resize(function() {
			h = $(window).height();
			$("#type-nav").css("min-height", h+"px");
		});
		$(window).resize();

		_this.calls = {};
		_this.payload_box = $("#payload");
		_this.response_box = $("#response");
        _this.response_tabs = $("#response_tabs");
        _this.response_tabs.tabs();
		window.jash = new Jash(_this.response_box.get(0));
		window.jash.main();

		_this.payload_box.hide();
		_this.response_box.hide();
        _this.response_tabs.hide();
		ApiType.interpolations.record_id = SMART.record.id;
		ApiType.addInterpolationValue("record_id", SMART.record.id);
		ApiType.find_all_types_and_calls();

	    });

    },

    'ontology_parsed subscribe': function(topic, element) {
		$("#type-nav").html(this.view('groups', {groups: ApiCallGroup.get_top_groups()}));
		$("#wrap").css({marginLeft: $("#type-nav").width()});
    },

    ".type click": function(el, ev ){
		var g = el.closest(".type").model();
		this.selected_top_group = g;
		g.element = el;

		$("#type-heading").html(this.view('calls', {group: g}));
		this.payload_box.hide();
		this.response_box.hide();
        this.response_tabs.hide();
		$("#interpolation-fields").html("");
		g.group_type.fetchParameters();

    },

    "BUTTON.call click": function(el, ev)
    {

    	var c = el.closest(".call").model();
		this.selected_call = c;
		var method = c.method;

		if ($.inArray(method, ApiCall.payload_methods) !== -1)
		{
		    if (c.example !== undefined)
			this.payload_box.val(c.example);
		    else
			this.payload_box.val(this.selected_top_group.group_type.example);
		    this.payload_box.show();
		} else  {
			this.payload_box.val("");
			this.payload_box.hide();
		}

		this.response_box.hide();
        this.response_tabs.hide()

		$("#interpolation-fields").html(this.view('interpolations', {type: this.selected_top_group.group_type,
																	 call: this.selected_call}));
		$("#interpolation-fields INPUT").each(function() {
			$i = $(this);
			var field_name = $i.attr("field_name");

			var compfunc = function(request, response) {
				try {
				//console.log("looking up " + field_name + ": " + ApiType.interpolations.lists[field_name].join(", "));
				response(ApiType.interpolations.lists[field_name]);
				} catch(err) {response([]);}
			};

			$i.autocomplete(
				{source: compfunc,
				 minLength: 0,
				 delay: 0,
				 close: function() {$(this).data("close_handled", false);}})
				.focus(function () {
				 		var close_handled = $(this).data("close_handled");
						if (close_handled) {
						   $(this).keydown();
						}
				 		$(this).data("close_handled", true);
				}).data("close_handled", true);
			try  {$i.val(ApiType.interpolations.lists[field_name][0]);} catch(err){}

		});

   },

    "BUTTON.cancel-call click": function(el, ev) {
    	this.selected_top_group.element.click();

    },

    "BUTTON.complete-call click": function(el, ev) {
    	$(".cancel-call").attr("DISABLED", "true");
		$(".complete-call").attr("DISABLED", "true");

    	$("#interpolation-fields INPUT").each(function() {
			$i = $(this);
			var field_name = $i.attr("field_name");
    		ApiType.interpolations[field_name] = $i.val();
    		$i.attr("DISABLED", "true");
    	});

    	this.selected_call.callAPI( this.payload_box.val(),
    								this.callback(this.receivedResult))
    },

    receivedResult: function(res) {

        if (res.contentType === "application/rdf+xml") {

            res.ntriples = "";
            res.graph.where('?s ?p ?o')
                .each(function(){
                    res.ntriples += this.s.toString() + " " + this.p.toString() + " " + this.o.toString() + " .\n";
                });

            $("#tab_rdf pre").text(res.body);
            $("#tab_ntriples pre").text(res.ntriples);

            var o = SMART.break_json_cycles(res.objects.of_type);
            $("#tab_jsonld pre").text(JSON.stringify(o, null, "  "));

            // Arbitrary limit on the code pretification (it's not very efficient and
            // hoses the browser up for large chunks of code)
            if (res.body.length <= 4096) {
                // Reset the pretty print processed flag
                $('pre.prettyprint').removeClass('prettyprinted');

                // Now prettify
                prettyPrint();
            }

            this.response_tabs.show()

            window.response = res;
            window.jash.clear();
            window.jash.output.value = window.jash.defaultText;
            window.jash.output.value += "\n";
            window.jash.output.value += "Triples in RDF graph returned: " + response.graph.where('?s ?p ?o.').length+"\n\n";
            window.jash.output.value += "To explore the graph, try:\n";
            window.jash.output.value += "  > response.body\n";
            window.jash.output.value += "  > response.graph.where('?s ?p ?o.').length\n";
            window.jash.output.value += "  > response.graph.where('?s ?p ?o.')[0].s\n";
            window.jash.output.value += "  > JSON.stringify(response.objects,null,'  ')\n";
                this.response_box.show();
            window.jash.print("\nTo explore type or paste commands in the textbox below, then press Enter.");
            window.jash.input.focus();
                $(".cancel-call").removeAttr("DISABLED");
                $(".complete-call").removeAttr("DISABLED");
                $("#interpolation-fields INPUT").each(function() {
                    $i = $(this);
                    $i.removeAttr("DISABLED");
                });
        } else {
            window.jash.clear();
            window.jash.output.value = res.body;
            window.jash.output.value += "\n\n------------\n";
            window.jash.output.value += window.jash.defaultText;
            window.jash.output.value += "\n";
            this.response_box.show();
        }

    	this.selected_top_group.group_type.fetchParameters();
    }

});
<|endoftext|>


<commit_before>'use strict';

var Promise = require('bluebird');
const oadaLib = require('../../libs/oada-lib-arangodb');
const kf = require('kafka-node');
const pointer = require('json-pointer');
const hash = require('object-hash');
const debug = require('debug')('write-handler');
const error = require('debug')('write-handler:error');
const info = require('debug')('write-handler:info');

var config = require('./config');

var client = new kf.Client(config.get('kafka:broker'), 'http-handler');
var offset = Promise.promisifyAll(new kf.Offset(client));
var producer = Promise.promisifyAll(new kf.Producer(client, {
    partitionerType: 0 //kf.Producer.PARTITIONER_TYPES.keyed
}));
var consumer = new kf.ConsumerGroup({
    host: config.get('kafka:broker'),
    groupId: 'write-handlers',
    fromOffset: 'latest'
}, [config.get('kafka:topics:writeRequest')]);

producer = producer
    .onAsync('ready')
    .return(producer);

consumer.on('message', handleMsg);

function handleMsg(msg) {
    // TODO: Check scope/permission?
    var req = JSON.parse(msg.value);
    req.source = req.source || '';
    var id = req['resource_id'];

    // Get body and check permission in parallel
    var body = Promise.try(function getBody() {
        return req.body || oadaLib.putBodies.getPutBody(req.bodyid);
    });
    var permitted = Promise.try(function checkPermissions() {
        if (req.source === 'rev-graph-update') {
            // no need to check permission for rev graph updates
            return;
        }

        if (id) { // Only run checks if resource exists
            // TODO: Support sharing (i.e., not just owner has permission)
            var start = new Date().getTime();
            info(`Checking permissions of "${id}".`);
            return oadaLib.resources.getResource(id, '_meta/_owner')
                .then(function checkOwner(owner) {
                  var end = new Date().getTime();
                  info(`Got owner of "${id}" from arango. +${end-start}ms`);
                    if (owner !== req['user_id']) {
                        return Promise.reject(new Error('permission'));
                    }
                });
        }
    });

    var start = new Date().getTime();
    info(`PUTing to "${req['path_leftover']}" in "${id}"`);
    var upsert = Promise.join(body, permitted, function doUpsert(body) {
        var path = req['path_leftover'].replace(/\/*$/, '');
        var obj = {};
        var ts = Date.now();
        // TODO: Sanitize keys?

        // Create new resource
        if (!id) {
            let parts = pointer.parse(path);

            id = 'resources/' + parts[1];
            path = pointer.compile(parts.slice(2));

            // Initialize resource stuff
            obj = {
                '_type': req['content_type'],
                '_meta': {
                    '_id': id + '/_meta',
                    '_type': req['content_type'],
                    '_owner': req['user_id'],
                    'stats': {
                        'createdBy': req['user_id'],
                        'created': ts
                    },
                }
            };
        }
        // Create object to recursively merge into the resource
        if (path) {
            pointer.set(obj, path, body);
        } else {
            obj = Object.assign(body, obj);
        }

        // Update meta
        var meta = {
            'modifiedBy': req['user_id'],
            'modified': ts
        };
        obj['_meta'] = Object.assign(obj['_meta'] || {}, meta);

        // Precompute new rev
        var rev = msg.offset + '-' + hash(obj, {algorithm: 'md5'});
        obj['_rev'] = rev;
        pointer.set(obj, '/_meta/_rev', rev);

        // Compute new change
        var change = {
            '_id': id + '/_meta/_changes',
            '_rev': rev,
            [rev]: {
                'merge': Object.assign({}, obj),
                'userId': req['user_id'],
                'authorizationID': req['authorizationid']
            },
        };
        obj['_meta'] = Object.assign({'_changes': change}, obj['_meta']);

        // Update rev of meta?
        obj['_meta']['_rev'] = rev;

        return oadaLib.resources.putResource(id, obj).return(rev);
    }).then(function respond(rev) {
        var end = new Date().getTime();
        info(`Finished PUTing to "${req['path_leftover']}". + ${end-start}ms`);
        return producer.call('sendAsync', [{
            topic: config.get('kafka:topics:httpResponse'),
            partition: req['resp_partition'],
            messages: JSON.stringify({
                'msgtype': 'write-response',
                'code': 'success',
                'resource_id': id,
                '_rev': rev,
                'user_id': req['user_id'],
                'authorizationid': req['authorizationid'],
                'connection_id': req['connection_id'],
            })
        }]);
    }).catch(function respondErr(err) {
        error(err);
        return producer.call('sendAsync', [{
            topic: config.get('kafka:topics:httpResponse'),
            partition: req['resp_partition'],
            messages: JSON.stringify({
                'msgtype': 'write-response',
                'code': err.message || 'error',
                'user_id': req['user_id'],
                'authorizationid': req['authorizationid'],
                'connection_id': req['connection_id'],
            })
        }]);
    });

    var cleanup = body.then(() => {
        // Remove putBody, if there was one
        return req.bodyid && oadaLib.putBodies.removePutBody(req.bodyid);
    });
    return Promise.join(upsert, cleanup);
}
<commit_msg>Make objects instead of arrays on numeric key<commit_after>'use strict';

var Promise = require('bluebird');
const oadaLib = require('../../libs/oada-lib-arangodb');
const kf = require('kafka-node');
const pointer = require('json-pointer');
const hash = require('object-hash');
const debug = require('debug')('write-handler');
const error = require('debug')('write-handler:error');
const info = require('debug')('write-handler:info');

var config = require('./config');

var client = new kf.Client(config.get('kafka:broker'), 'http-handler');
var offset = Promise.promisifyAll(new kf.Offset(client));
var producer = Promise.promisifyAll(new kf.Producer(client, {
    partitionerType: 0 //kf.Producer.PARTITIONER_TYPES.keyed
}));
var consumer = new kf.ConsumerGroup({
    host: config.get('kafka:broker'),
    groupId: 'write-handlers',
    fromOffset: 'latest'
}, [config.get('kafka:topics:writeRequest')]);

producer = producer
    .onAsync('ready')
    .return(producer);

consumer.on('message', handleMsg);

function handleMsg(msg) {
    // TODO: Check scope/permission?
    var req = JSON.parse(msg.value);
    req.source = req.source || '';
    var id = req['resource_id'];

    // Get body and check permission in parallel
    var body = Promise.try(function getBody() {
        return req.body || oadaLib.putBodies.getPutBody(req.bodyid);
    });
    var permitted = Promise.try(function checkPermissions() {
        if (req.source === 'rev-graph-update') {
            // no need to check permission for rev graph updates
            return;
        }

        if (id) { // Only run checks if resource exists
            // TODO: Support sharing (i.e., not just owner has permission)
            var start = new Date().getTime();
            info(`Checking permissions of "${id}".`);
            return oadaLib.resources.getResource(id, '_meta/_owner')
                .then(function checkOwner(owner) {
                  var end = new Date().getTime();
                  info(`Got owner of "${id}" from arango. +${end-start}ms`);
                    if (owner !== req['user_id']) {
                        return Promise.reject(new Error('permission'));
                    }
                });
        }
    });

    var start = new Date().getTime();
    info(`PUTing to "${req['path_leftover']}" in "${id}"`);
    var upsert = Promise.join(body, permitted, function doUpsert(body) {
        var path = pointer.parse(req['path_leftover'].replace(/\/*$/, ''));
        var obj = {};
        var ts = Date.now();
        // TODO: Sanitize keys?

        // Create new resource
        if (!id) {
            id = 'resources/' + parts[1];
            path = path.slice(2);

            // Initialize resource stuff
            obj = {
                '_type': req['content_type'],
                '_meta': {
                    '_id': id + '/_meta',
                    '_type': req['content_type'],
                    '_owner': req['user_id'],
                    'stats': {
                        'createdBy': req['user_id'],
                        'created': ts
                    },
                }
            };
        }
        // Create object to recursively merge into the resource
        if (path.length > 0) {
            let o = obj;

            let endk = path.pop();
            path.forEach(k => {
                if (!(k in o)) {
                    // TODO: Support arrays better?
                    o[k] = {}
                }
                o = o[k];
            });

            o[endk] = body;
        } else {
            obj = Object.assign(body, obj);
        }

        // Update meta
        var meta = {
            'modifiedBy': req['user_id'],
            'modified': ts
        };
        obj['_meta'] = Object.assign(obj['_meta'] || {}, meta);

        // Precompute new rev
        var rev = msg.offset + '-' + hash(obj, {algorithm: 'md5'});
        obj['_rev'] = rev;
        pointer.set(obj, '/_meta/_rev', rev);

        // Compute new change
        var change = {
            '_id': id + '/_meta/_changes',
            '_rev': rev,
            [rev]: {
                'merge': Object.assign({}, obj),
                'userId': req['user_id'],
                'authorizationID': req['authorizationid']
            },
        };
        obj['_meta'] = Object.assign({'_changes': change}, obj['_meta']);

        // Update rev of meta?
        obj['_meta']['_rev'] = rev;

        return oadaLib.resources.putResource(id, obj).return(rev);
    }).then(function respond(rev) {
        var end = new Date().getTime();
        info(`Finished PUTing to "${req['path_leftover']}". + ${end-start}ms`);
        return producer.call('sendAsync', [{
            topic: config.get('kafka:topics:httpResponse'),
            partition: req['resp_partition'],
            messages: JSON.stringify({
                'msgtype': 'write-response',
                'code': 'success',
                'resource_id': id,
                '_rev': rev,
                'user_id': req['user_id'],
                'authorizationid': req['authorizationid'],
                'connection_id': req['connection_id'],
            })
        }]);
    }).catch(function respondErr(err) {
        error(err);
        return producer.call('sendAsync', [{
            topic: config.get('kafka:topics:httpResponse'),
            partition: req['resp_partition'],
            messages: JSON.stringify({
                'msgtype': 'write-response',
                'code': err.message || 'error',
                'user_id': req['user_id'],
                'authorizationid': req['authorizationid'],
                'connection_id': req['connection_id'],
            })
        }]);
    });

    var cleanup = body.then(() => {
        // Remove putBody, if there was one
        return req.bodyid && oadaLib.putBodies.removePutBody(req.bodyid);
    });
    return Promise.join(upsert, cleanup);
}
<|endoftext|>


<commit_before>'use strict'

const url = require('url')
const parse = require('./parse')
const flatten = require('./flatten')

async function analyze(location, options) {
  options = {
    etag: null,
    lastCheckedAt: null,
    userAgent: 'plunger/1.0',
    fetchTimeout: 10000,
    inlineTypes: [
      'xml',
      'html',
      'txt',
      'json'
    ],
    digestAlgorithm: 'sha384',
    extractArchives: true,

    ...options
  }

  const u = url.parse(location)

  const token = {
    inputType: u.protocol ? 'url' : 'path',
    location
  }

  await parse(token, options)

  return token
}

function extractFiles(token, options) {
  options = {
    keepUnknownTypes: true,
    types: [
      {
        extensions: ['gpkg'],
        type: 'geopackage',
        format: 'mixed'
      },
      {
        extensions: ['shp'],
        type: 'shapefile',
        format: 'vector',
        related: ['shx', 'dbf', 'prj', 'sbn', 'sbx', 'fbn', 'fbx', 'ain', 'aih', 'shp.xml', 'atx', 'qix', 'cpg', 'qpj']
      },
      {
        extensions: ['mif'],
        type: 'mif',
        format: 'vector',
        related: ['mid']
      },
      {
        extensions: ['tab'],
        type: 'tab',
        format: 'vector',
        related: ['dat', 'map', 'id', 'ind']
      },
      {
        extensions: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'rtf', 'txt'],
        type: 'document'
      },
      {
        extensions: ['csv', 'tsv', 'dbf'],
        type: 'table'
      },
      {
        extensions: ['ecw', 'tiff', 'jp2'],
        type: 'image',
        format: 'raster'
      }
    ],

    ...options
  }

  return flatten(token, options)
}

module.exports = {analyze, extractFiles}
<commit_msg>Add cpg to dbf associated files<commit_after>'use strict'

const url = require('url')
const parse = require('./parse')
const flatten = require('./flatten')

async function analyze(location, options) {
  options = {
    etag: null,
    lastCheckedAt: null,
    userAgent: 'plunger/1.0',
    fetchTimeout: 10000,
    inlineTypes: [
      'xml',
      'html',
      'txt',
      'json'
    ],
    digestAlgorithm: 'sha384',
    extractArchives: true,

    ...options
  }

  const u = url.parse(location)

  const token = {
    inputType: u.protocol ? 'url' : 'path',
    location
  }

  await parse(token, options)

  return token
}

function extractFiles(token, options) {
  options = {
    keepUnknownTypes: true,
    types: [
      {
        extensions: ['gpkg'],
        type: 'geopackage',
        format: 'mixed'
      },
      {
        extensions: ['shp'],
        type: 'shapefile',
        format: 'vector',
        related: ['shx', 'dbf', 'prj', 'sbn', 'sbx', 'fbn', 'fbx', 'ain', 'aih', 'shp.xml', 'atx', 'qix', 'cpg', 'qpj']
      },
      {
        extensions: ['dbf'],
        type: 'table',
        related: ['cpg']
      },
      {
        extensions: ['mif'],
        type: 'mif',
        format: 'vector',
        related: ['mid']
      },
      {
        extensions: ['tab'],
        type: 'tab',
        format: 'vector',
        related: ['dat', 'map', 'id', 'ind']
      },
      {
        extensions: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'rtf', 'txt'],
        type: 'document'
      },
      {
        extensions: ['csv', 'tsv'],
        type: 'table'
      },
      {
        extensions: ['ecw', 'tiff', 'jp2'],
        type: 'image',
        format: 'raster'
      }
    ],

    ...options
  }

  return flatten(token, options)
}

module.exports = {analyze, extractFiles}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Google Reader Compacter
// @namespace   http://aj.garcialagar.es/gmscripts
// @description To compact the new Google Reader Interface
// @version     1.0.2
// @include     http://www.google.*/reader/*
// @include     https://www.google.*/reader/*
// ==/UserScript==

// @author      Antonio J. García Lagar <aj@garcialagar.es>
// @copyright   Copyright (c) 2011, Antonio J. García Lagar <aj@garcialagar.es>
// @license     http://www.opensource.org/licenses/BSD-3-Clause
// @homepage    https://github.com/ajgarlag/google-reader-compacter

var styleText='';

styleText += ' #sections-header {height: 40px}';
styleText += ' #logo-section {height: 28px}';
styleText += ' #viewer-header {height: 40px}';
styleText += ' #lhn-add-subscription-section {height: 40px}';
styleText += ' #viewer-view-options, #mark-all-as-read-split-button, #viewer-top-controls .goog-button {margin-right: 0.2em}';
styleText += ' #nav {width: 245px}';
styleText += ' #chrome {margin-left: 245px}';
styleText += ' #top-bar {height: 5px}';
styleText += ' #logo, .loaded #search {display: none}';
styleText += ' #top-bar:hover {height: 45px}';
styleText += ' #top-bar:hover #logo, .loaded #top-bar:hover #search {display: block}';
styleText += ' #search {padding: 8px 0}';
styleText += ' #scrollable-sections-top-shadow, #scrollable-sections-bottom-shadow {width: 245px}';
styleText += ' #entries {padding-right: 0}';
styleText += ' #entries.list .entry .collapsed {padding: 0}';
styleText += ' #entries.list .collapsed .entry-icons {top: 0}';
styleText += ' #entries.list .collapsed .entry-main .entry-source-title {top: 0}';
styleText += ' #entries.list .collapsed .entry-secondary {top: 0}';

// Minimize the recommendations section
if (document.getElementById('lhn-recommendations').className.indexOf('section-minimized') == -1) {
    document.getElementById('lhn-recommendations').className += ' section-minimized';
}

// Write down the style
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
var rules = document.createTextNode(styleText);

style.type = 'text/css';

if (style.styleSheet) {
    style.styleSheet.cssText = rules.nodeValue;
} else {
    style.appendChild(rules);
}

head.appendChild(style);
<commit_msg>New version 1.1.0<commit_after>// ==UserScript==
// @name        Google Reader Compacter
// @namespace   http://aj.garcialagar.es/gmscripts
// @description To compact the new Google Reader Interface
// @version     1.1.0
// @include     http://www.google.*/reader/*
// @include     https://www.google.*/reader/*
// ==/UserScript==

// @author      Antonio J. García Lagar <aj@garcialagar.es>
// @copyright   Copyright (c) 2011, Antonio J. García Lagar <aj@garcialagar.es>
// @license     http://www.opensource.org/licenses/BSD-3-Clause
// @homepage    https://github.com/ajgarlag/google-reader-compacter

var styleText='';

styleText += ' #sections-header {height: 40px}';
styleText += ' #logo-section {height: 28px}';
styleText += ' #viewer-header {height: 40px}';
styleText += ' #lhn-add-subscription-section {height: 40px}';
styleText += ' #viewer-view-options, #mark-all-as-read-split-button, #viewer-top-controls .goog-button {margin-right: 0.2em}';
styleText += ' #nav {width: 245px}';
styleText += ' #chrome {margin-left: 245px}';
styleText += ' #top-bar {height: 5px}';
styleText += ' #logo, .loaded #search {display: none}';
styleText += ' #top-bar:hover {height: 45px}';
styleText += ' #top-bar:hover #logo, .loaded #top-bar:hover #search {display: block}';
styleText += ' #search {padding: 8px 0}';
styleText += ' #scrollable-sections-top-shadow, #scrollable-sections-bottom-shadow {width: 245px}';
styleText += ' #entries {padding-right: 0}';
styleText += ' #entries.list .entry .collapsed {padding: 0}';
styleText += ' #entries.list .collapsed .entry-icons {top: 0}';
styleText += ' #entries.list .collapsed .entry-main .entry-source-title {top: 0}';
styleText += ' #entries.list .collapsed .entry-secondary {top: 0}';

// Minimize the recommendations section
if (document.getElementById('lhn-recommendations').className.indexOf('section-minimized') == -1) {
    document.getElementById('lhn-recommendations').className += ' section-minimized';
}

// Write down the style
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
var rules = document.createTextNode(styleText);

style.type = 'text/css';

if (style.styleSheet) {
    style.styleSheet.cssText = rules.nodeValue;
} else {
    style.appendChild(rules);
}

head.appendChild(style);
<|endoftext|>


<commit_before>import $ from 'jquery'
import sanitizeHtml from 'sanitize-html'
import * as sanitizeOpts from './sanitizeOpts'

export const equationImageSelector =
    'img[src^="/math.svg?latex="]:not(img[src="/math.svg?latex="]), img[src^="data:image/svg+xml"]'
const screenshotImageSelector = 'img[src^="/screenshot/"], img[src^="data:image/png"]'

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

export function sanitize(html) {
    return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts)
}
export function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

export function isKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey && keyOrKeyCode(e, key))
}

export function isCtrlKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))
}

function keyOrKeyCode(e, val) {
    return typeof val === 'string' ? e.key === val : e.keyCode === val
}
function preventIfTrue(e, val) {
    if (val) e.preventDefault()
    return val
}

export function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    const scrollPos = $(window).scrollTop()
    $mathEditor.hide()
    const text = $answerElement.get(0).innerText
    $mathEditor.show()
    $(window).scrollTop(scrollPos)

    const html = sanitize($answerElement.html())

    const answerConsideredEmpty =
        text.trim().length +
            $answerElement.find(equationImageSelector).length +
            $answerElement.find(screenshotImageSelector).length ===
        0

    return {
        answerHTML: answerConsideredEmpty ? '' : html,
        answerText: text,
        imageCount: existingScreenshotCount($(`<div>${html}</div>`))
    }
}

export function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    range.setStartAfter(img)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

export function existingScreenshotCount($editor) {
    const imageCount = $editor.find('img').length
    const emptyImageCount = $editor.find('img[src=""]').length
    const equationCount = $editor.find(equationImageSelector).length
    return imageCount - equationCount - emptyImageCount
}

export function scrollIntoView($element) {
    const $window = $(window)
    const windowHeight = $window.height() - 40
    const scroll = windowHeight + $window.scrollTop()
    const pos = $element.offset().top + $element.height()
    if (scroll < pos) {
        $window.scrollTop(pos - windowHeight)
    }
}
<commit_msg>Simplify and fix logic for counting screenshots<commit_after>import $ from 'jquery'
import sanitizeHtml from 'sanitize-html'
import * as sanitizeOpts from './sanitizeOpts'

const emptyEquationSelector = 'img[src="/math.svg?latex="]'
export const equationImageSelector = `img[src^="/math.svg?latex="]:not(${emptyEquationSelector}), img[src^="data:image/svg+xml"]`
const screenshotImageSelector = 'img[src^="/screenshot/"], img[src^="data:image/png"]'

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

export function sanitize(html) {
    return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts)
}
export function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

export function isKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey && keyOrKeyCode(e, key))
}

export function isCtrlKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))
}

function keyOrKeyCode(e, val) {
    return typeof val === 'string' ? e.key === val : e.keyCode === val
}
function preventIfTrue(e, val) {
    if (val) e.preventDefault()
    return val
}

export function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    const scrollPos = $(window).scrollTop()
    $mathEditor.hide()
    const text = $answerElement.get(0).innerText
    $mathEditor.show()
    $(window).scrollTop(scrollPos)

    const html = sanitize($answerElement.html())

    const answerConsideredEmpty =
        text.trim().length +
            $answerElement.find(equationImageSelector).length +
            $answerElement.find(screenshotImageSelector).length ===
        0

    return {
        answerHTML: answerConsideredEmpty ? '' : html,
        answerText: text,
        imageCount: existingScreenshotCount($(`<div>${html}</div>`))
    }
}

export function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    range.setStartAfter(img)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

export function existingScreenshotCount($editor) {
    return $editor.find(screenshotImageSelector).length
}

export function scrollIntoView($element) {
    const $window = $(window)
    const windowHeight = $window.height() - 40
    const scroll = windowHeight + $window.scrollTop()
    const pos = $element.offset().top + $element.height()
    if (scroll < pos) {
        $window.scrollTop(pos - windowHeight)
    }
}
<|endoftext|>