<commit_before>/*
    Need to develop a proper Single Page Application.
    until then this is what I can come up with.
    The minimalistic UI was developed by @nithinsanjey.
    I DONT KNOW TO DESIGN WEBPAGES .
    WEB DESIGNERS FEEL FREE TO CONTRIBUTE!!!
*/

//HACK: Harcoding journal name
let journalName = 'Test';

$('#info')[0].innerText  = new Date().toDateString();
let baseUrl = 'http://localhost:8080';

function saveJournalEntry(journalName, title, data){
    let payload = {
        data,
        title: title,
        createdDate: new Date().toISOString()
    }
    jQuery.post(`${baseUrl}/journal/${journalName}`, payload).done(function(result){
        alert("saved");
        console.log("saved: " + result)
    }).fail(function(err){
        alert("failed")
        console.error(err)
    })
}

$(document).keypress("s",function(e) {
    if(e.ctrlKey && e.shiftKey){
        let title = $('h1')[0].innerText
        let data = $('main')[0].innerHTML
        saveJournalEntry(journalName, title, data);
    }

  });

if(location.hash){
    let entryId = location.hash.slice(1);
    if(entryId)
        jQuery.get(`${baseUrl}/journal/${journalName}/${entryId}`).done(function(result){
            $('#info')[0].innerText  = new Date(result.timestamp).toDateString();
            $('main')[0].innerHTML = result.data;
            $('h1')[0].innerText = result.title;

            $('[contenteditable]').attr('contenteditable', false)

            $('#info')[0].innerText  = new Date(result.createdDate).toDateString();
        })
}<commit_msg>Default journalName<commit_after>/*
    Need to develop a proper Single Page Application.
    until then this is what I can come up with.
    The minimalistic UI was developed by @nithinsanjey.
    I DONT KNOW TO DESIGN WEBPAGES .
    WEB DESIGNERS FEEL FREE TO CONTRIBUTE!!!
*/

//HACK: Harcoding journal name
let journalName = 'Personal';

$('#info')[0].innerText  = new Date().toDateString();
let baseUrl = 'http://localhost:8080';

function saveJournalEntry(journalName, title, data){
    let payload = {
        data,
        title: title,
        createdDate: new Date().toISOString()
    }
    jQuery.post(`${baseUrl}/journal/${journalName}`, payload).done(function(result){
        alert("saved");
        console.log("saved: " + result)
    }).fail(function(err){
        alert("failed")
        console.error(err)
    })
}

$(document).keypress("s",function(e) {
    if(e.ctrlKey && e.shiftKey){
        let title = $('h1')[0].innerText
        let data = $('main')[0].innerHTML
        saveJournalEntry(journalName, title, data);
    }

  });

if(location.hash){
    let entryId = location.hash.slice(1);
    if(entryId)
        jQuery.get(`${baseUrl}/journal/${journalName}/${entryId}`).done(function(result){
            $('#info')[0].innerText  = new Date(result.timestamp).toDateString();
            $('main')[0].innerHTML = result.data;
            $('h1')[0].innerText = result.title;

            $('[contenteditable]').attr('contenteditable', false)

            $('#info')[0].innerText  = new Date(result.createdDate).toDateString();
        })
}<|endoftext|>


<commit_before>'use strict'

let sql = require('sql')
let Query = require('./query')

class Model {

  constructor (data) {
    this.constructor.defineProperties()
    this.errors = {}
    this.data = new Map()
    for (let key in data) this[key] = data[key]
  }

  get db () {
    return this.constructor.db
  }

  get table () {
    return this.constructor.table
  }

  get tableName () {
    return this.constructor.tableName
  }

  get colunns () {
    return this.constructor.columns
  }

  get relations () {
    return this.constructor.relations
  }

  get properties () {
    return this.constructor.properties
  }

  slice () {
    let result = {}
    for (let key of arguments) result[key] = this[key]
    return result
  }

  update (values) {
    for (let key in values) {
      this[key] = values[key]
      values[key] = this[key]
    }
    if (!this.valid) {
      let e = new Error('invalid')
      e.model = this
      throw e
    }
    let query = this.constructor.where({id: this.id})
    return query.update(this.slice.apply(this, Object.keys(values)))
  }

  destroy () {
    return this.constructor.where({id: this.id}).delete()
  }

  validate () {
  }

  get valid () {
    this.validate()
    return Object.keys(this.errors).length === 0
  }

  static get table () {
    if (!this._table) {
      this._table = sql.define({name: this.tableName, columns: this.columns})
    }
    return this._table
  }

  static get properties () {
    if (!this._properties) {
      this._properties = {}
      for (let column of this.table.columns) {
        this._properties[column.property] = column
      }
    }
    return this._properties
  }

  static get relations () {
    if (!this._relations) this._relations = {}
    return this._relations
  }

  static create (values) {
    let model = new this(values)
    if (!model.valid) {
      let e = new Error('invalid')
      e.model = model
      throw e
    }
    for (let key of Object.keys(values)) values[key] = model[key]
    return this.insert(values).then(function (values) {
      for (let key of Object.keys(values)) model[key] = values[key]
      return model
    })
  }

  static hasMany (name, options) {
    options.many = true
    this.relations[name] = options
  }

  static belongsTo (name, options) {
    options.many = false
    this.relations[name] = options
  }

  static defineProperties () {
    if (this._propsDefined) return
    this._propsDefined = true
    for (let column of this.table.columns) {
      if (Object.getOwnPropertyDescriptor(this.prototype, column.property)) {
        continue
      }
      Object.defineProperty(this.prototype, column.property, {
        get: function () {
          return this.data.get(column.property)
        },
        set: function (value) {
          this.data.set(column.property, value)
        }
      })
    }
  }

}

// Attach Query methods to Model
let queryMethods = [
  'all',
  'count',
  'find',
  'include',
  'insert',
  'join',
  'limit',
  'not',
  'offset',
  'order',
  'paginate',
  'select',
  'update',
  'where'
]

for (let method of queryMethods) {
  Model[method] = function () {
    let query = new Query(this)
    return query[method].apply(query, arguments)
  }
}

module.exports = Model
<commit_msg>Object.assign<commit_after>'use strict'

let sql = require('sql')
let Query = require('./query')

class Model {

  constructor (data) {
    this.constructor.defineProperties()
    this.errors = {}
    this.data = new Map()
    Object.assign(this, data)
  }

  get db () {
    return this.constructor.db
  }

  get table () {
    return this.constructor.table
  }

  get tableName () {
    return this.constructor.tableName
  }

  get colunns () {
    return this.constructor.columns
  }

  get relations () {
    return this.constructor.relations
  }

  get properties () {
    return this.constructor.properties
  }

  slice () {
    let result = {}
    for (let key of arguments) result[key] = this[key]
    return result
  }

  update (values) {
    for (let key in values) {
      this[key] = values[key]
      values[key] = this[key]
    }
    if (!this.valid) {
      let e = new Error('invalid')
      e.model = this
      throw e
    }
    let query = this.constructor.where({id: this.id})
    return query.update(this.slice.apply(this, Object.keys(values)))
  }

  destroy () {
    return this.constructor.where({id: this.id}).delete()
  }

  validate () {
  }

  get valid () {
    this.validate()
    return Object.keys(this.errors).length === 0
  }

  static get table () {
    if (!this._table) {
      this._table = sql.define({name: this.tableName, columns: this.columns})
    }
    return this._table
  }

  static get properties () {
    if (!this._properties) {
      this._properties = {}
      for (let column of this.table.columns) {
        this._properties[column.property] = column
      }
    }
    return this._properties
  }

  static get relations () {
    if (!this._relations) this._relations = {}
    return this._relations
  }

  static create (values) {
    let model = new this(values)
    if (!model.valid) {
      let e = new Error('invalid')
      e.model = model
      throw e
    }
    for (let key of Object.keys(values)) values[key] = model[key]
    return this.insert(values).then(function (values) {
      return Object.assign(model, values)
    })
  }

  static hasMany (name, options) {
    options.many = true
    this.relations[name] = options
  }

  static belongsTo (name, options) {
    options.many = false
    this.relations[name] = options
  }

  static defineProperties () {
    if (this._propsDefined) return
    this._propsDefined = true
    for (let column of this.table.columns) {
      if (Object.getOwnPropertyDescriptor(this.prototype, column.property)) {
        continue
      }
      Object.defineProperty(this.prototype, column.property, {
        get: function () {
          return this.data.get(column.property)
        },
        set: function (value) {
          this.data.set(column.property, value)
        }
      })
    }
  }

}

// Attach Query methods to Model
let queryMethods = [
  'all',
  'count',
  'find',
  'include',
  'insert',
  'join',
  'limit',
  'not',
  'offset',
  'order',
  'paginate',
  'select',
  'update',
  'where'
]

for (let method of queryMethods) {
  Model[method] = function () {
    let query = new Query(this)
    return query[method].apply(query, arguments)
  }
}

module.exports = Model
<|endoftext|>


<commit_before>"use strict";

if (typeof (JSIL) === "undefined")
  throw new Error("JSIL.Core is required");

JSIL.DeclareAssembly("JSIL.IO");

JSIL.ImplementExternals(
  "System.IO.File", false, {
    Exists: function (filename) {
      return JSIL.Host.doesFileExist(filename);
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.Path", false, {
    Combine: function () {
      return Array.prototype.slice.call(arguments).join("/");
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.FileStream", true, {
    _ctor$0: function () {
      System.IO.Stream.prototype._ctor.call(this);
    },
    _ctor$1: function (filename, mode) {
      System.IO.Stream.prototype._ctor.call(this);

      this._fileName = filename;
      this._buffer = JSIL.Host.getFile(filename);
      if (
        (typeof (this._buffer) === "undefined") ||
        (typeof (this._buffer.length) !== "number")
      )
        throw new System.Exception("Unable to get an array for the file '" + filename + "'");

      this._pos = 0;
    },
    Peek: function () {
      if ((this._pos < 0) || (this._pos >= this._buffer.length))
        return -1;

      return this._buffer[this._pos];
    },
    ReadByte: function () {
      if ((this._pos < 0) || (this._pos >= this._buffer.length))
        return -1;

      return this._buffer[this._pos++];
    },
    Close: function () {
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.BinaryReader", true, {
    _ctor$0: function (stream) {
      System.Object.prototype._ctor.call(this);

      if (typeof (stream) !== "object")
        throw new Error();

      this.m_stream = stream;
      this.m_encoding = System.Text.Encoding.ASCII;
    },
    _ctor$1: function (stream, encoding) {
      System.Object.prototype._ctor.call(this);

      if (typeof (stream) !== "object")
        throw new Error();

      this.m_stream = stream;
      this.m_encoding = encoding;
    },
    ReadBytes: function (count) {
      var result = new Array(count);
      for (var i = 0; i < count; i++) {
        var b = this.m_stream.ReadByte();
        if (b === -1)
          return result.slice(0, i - 1);

        result[i] = b;
      };

      return result;
    },
    ReadChars: function (count) {
      var result = new Array(count);
      for (var i = 0; i < count; i++) {
        var b = this.m_stream.ReadByte();
        if (b === -1)
          return result.slice(0, i - 1);

        result[i] = String.fromCharCode(b);
      };

      return result;
    },
    ReadInt32: function () {
      var value = this.ReadUInt32();
      if (value > System.Int32.MaxValue)
        return value - 4294967296;
      else
        return value;
    },
    ReadUInt32: function () {
      var low1 = this.m_stream.ReadByte();
      var low2 = this.m_stream.ReadByte();
      var low3 = this.m_stream.ReadByte();
      return low1 | (low2 << 8) | (low3 << 16) | (this.m_stream.ReadByte() << 24);
    },
    ReadInt16: function () {
      var value = this.ReadUInt16();
      if (value > System.Int16.MaxValue)
        return value - 65536;
      else
        return value;
    },
    ReadUInt16: function () {
      var low = this.m_stream.ReadByte();
      return low | (this.m_stream.ReadByte() << 8);
    },
    ReadSByte: function () {
      var byt = this.m_stream.ReadByte();
      if (byt > 127)
        return byt - 256;
      else
        return byt;
    },
    ReadSingle: function () {
      var bytes = this.ReadBytes(4);
      return this._decodeFloat(bytes, 23, 8);
    },
    ReadDouble: function () {
      var bytes = this.ReadBytes(8);
      return this._decodeFloat(bytes, 52, 11);
    },
    ReadByte: function () {
      return this.m_stream.ReadByte();
    },
    Close: function () {
    },
    // Derived from http://blog.vjeux.com/wp-content/uploads/2010/01/binaryReader.js
    _shl: function (a, b) {
      for (
        ++b; --b;
        a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ?
          a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1
      );

      return a;
    },
    _readBits: function (bytes, start, length) {
      var offsetLeft = (start + length) % 8;
      var offsetRight = start % 8;
      var curByte = bytes.length - (start >> 3) - 1;
      var lastByte = bytes.length + (-(start + length) >> 3);
      var diff = curByte - lastByte;

      var sum = (bytes[bytes.length - curByte - 1] >> offsetRight) &
        ((1 << (diff ? 8 - offsetRight : length)) - 1);

      if (diff && offsetLeft)
        sum += (bytes[bytes.length - lastByte++ - 1] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;

      while (diff)
        sum += this._shl(bytes[bytes.length - lastByte++ - 1], (diff-- << 3) - offsetRight);

      return sum;
    },
    _decodeFloat: function (bytes, precisionBits, exponentBits) {
      var length = precisionBits + exponentBits + 1;
      if ((length >> 3) > bytes.length)
        throw new Error("Buffer too small");

      var bias = Math.pow(2, exponentBits - 1) - 1;
      var signal = this._readBits(bytes, precisionBits + exponentBits, 1);
      var exponent = this._readBits(bytes, precisionBits, exponentBits);
      var significand = 0;
      var divisor = 2;
      var curByte = 0;
      do {
        var byteValue = bytes[++curByte - bytes.length - 1];
        var startBit = precisionBits % 8 || 8;
        var mask = 1 << startBit;
        while (mask >>= 1) {
          if (byteValue & mask) {
            significand += 1 / divisor;
          }
          divisor *= 2;
        }
      } while (precisionBits -= startBit);

      var result = exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
        : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
        : Math.pow(2, exponent - bias) * (1 + significand) : 0);

      return result;
    },
    IDisposable_Dispose: function () {
      this.m_stream = null;
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.StreamReader", true, {
    _ctor$7: function (filename) {
      this.stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
    },
    ReadLine: function () {
      var line = [];

      while (true) {
        var ch = this.stream.ReadByte();
        if (ch === -1) {
          if (line.length === 0)
            return null;
          else
            break;
        } else if (ch === 13) {
          var next = this.stream.Peek();
          if (next === 10)
            continue;
          else if (next === -1) {
            if (line.length === 0)
              return null;
            else
              break;
          } else
            break;
        } else if (ch === 10) {
          break;
        }

        line.push(ch);
      };

      return String.fromCharCode.apply(null, line);
    },
    IDisposable_Dispose: function () {
      this.stream = null;
    }
  }
);
<commit_msg>Fix incorrectly named Dispose externals in JSIL.IO that caused load failures by trying to replace an indirect interface getter<commit_after>"use strict";

if (typeof (JSIL) === "undefined")
  throw new Error("JSIL.Core is required");

JSIL.DeclareAssembly("JSIL.IO");

JSIL.ImplementExternals(
  "System.IO.File", false, {
    Exists: function (filename) {
      return JSIL.Host.doesFileExist(filename);
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.Path", false, {
    Combine: function () {
      return Array.prototype.slice.call(arguments).join("/");
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.FileStream", true, {
    _ctor$0: function () {
      System.IO.Stream.prototype._ctor.call(this);
    },
    _ctor$1: function (filename, mode) {
      System.IO.Stream.prototype._ctor.call(this);

      this._fileName = filename;
      this._buffer = JSIL.Host.getFile(filename);
      if (
        (typeof (this._buffer) === "undefined") ||
        (typeof (this._buffer.length) !== "number")
      )
        throw new System.Exception("Unable to get an array for the file '" + filename + "'");

      this._pos = 0;
    },
    Peek: function () {
      if ((this._pos < 0) || (this._pos >= this._buffer.length))
        return -1;

      return this._buffer[this._pos];
    },
    ReadByte: function () {
      if ((this._pos < 0) || (this._pos >= this._buffer.length))
        return -1;

      return this._buffer[this._pos++];
    },
    Close: function () {
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.BinaryReader", true, {
    _ctor$0: function (stream) {
      System.Object.prototype._ctor.call(this);

      if (typeof (stream) !== "object")
        throw new Error();

      this.m_stream = stream;
      this.m_encoding = System.Text.Encoding.ASCII;
    },
    _ctor$1: function (stream, encoding) {
      System.Object.prototype._ctor.call(this);

      if (typeof (stream) !== "object")
        throw new Error();

      this.m_stream = stream;
      this.m_encoding = encoding;
    },
    ReadBytes: function (count) {
      var result = new Array(count);
      for (var i = 0; i < count; i++) {
        var b = this.m_stream.ReadByte();
        if (b === -1)
          return result.slice(0, i - 1);

        result[i] = b;
      };

      return result;
    },
    ReadChars: function (count) {
      var result = new Array(count);
      for (var i = 0; i < count; i++) {
        var b = this.m_stream.ReadByte();
        if (b === -1)
          return result.slice(0, i - 1);

        result[i] = String.fromCharCode(b);
      };

      return result;
    },
    ReadInt32: function () {
      var value = this.ReadUInt32();
      if (value > System.Int32.MaxValue)
        return value - 4294967296;
      else
        return value;
    },
    ReadUInt32: function () {
      var low1 = this.m_stream.ReadByte();
      var low2 = this.m_stream.ReadByte();
      var low3 = this.m_stream.ReadByte();
      return low1 | (low2 << 8) | (low3 << 16) | (this.m_stream.ReadByte() << 24);
    },
    ReadInt16: function () {
      var value = this.ReadUInt16();
      if (value > System.Int16.MaxValue)
        return value - 65536;
      else
        return value;
    },
    ReadUInt16: function () {
      var low = this.m_stream.ReadByte();
      return low | (this.m_stream.ReadByte() << 8);
    },
    ReadSByte: function () {
      var byt = this.m_stream.ReadByte();
      if (byt > 127)
        return byt - 256;
      else
        return byt;
    },
    ReadSingle: function () {
      var bytes = this.ReadBytes(4);
      return this._decodeFloat(bytes, 23, 8);
    },
    ReadDouble: function () {
      var bytes = this.ReadBytes(8);
      return this._decodeFloat(bytes, 52, 11);
    },
    ReadByte: function () {
      return this.m_stream.ReadByte();
    },
    Close: function () {
    },
    // Derived from http://blog.vjeux.com/wp-content/uploads/2010/01/binaryReader.js
    _shl: function (a, b) {
      for (
        ++b; --b;
        a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ?
          a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1
      );

      return a;
    },
    _readBits: function (bytes, start, length) {
      var offsetLeft = (start + length) % 8;
      var offsetRight = start % 8;
      var curByte = bytes.length - (start >> 3) - 1;
      var lastByte = bytes.length + (-(start + length) >> 3);
      var diff = curByte - lastByte;

      var sum = (bytes[bytes.length - curByte - 1] >> offsetRight) &
        ((1 << (diff ? 8 - offsetRight : length)) - 1);

      if (diff && offsetLeft)
        sum += (bytes[bytes.length - lastByte++ - 1] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;

      while (diff)
        sum += this._shl(bytes[bytes.length - lastByte++ - 1], (diff-- << 3) - offsetRight);

      return sum;
    },
    _decodeFloat: function (bytes, precisionBits, exponentBits) {
      var length = precisionBits + exponentBits + 1;
      if ((length >> 3) > bytes.length)
        throw new Error("Buffer too small");

      var bias = Math.pow(2, exponentBits - 1) - 1;
      var signal = this._readBits(bytes, precisionBits + exponentBits, 1);
      var exponent = this._readBits(bytes, precisionBits, exponentBits);
      var significand = 0;
      var divisor = 2;
      var curByte = 0;
      do {
        var byteValue = bytes[++curByte - bytes.length - 1];
        var startBit = precisionBits % 8 || 8;
        var mask = 1 << startBit;
        while (mask >>= 1) {
          if (byteValue & mask) {
            significand += 1 / divisor;
          }
          divisor *= 2;
        }
      } while (precisionBits -= startBit);

      var result = exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
        : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
        : Math.pow(2, exponent - bias) * (1 + significand) : 0);

      return result;
    },
    Dispose: function () {
      this.m_stream = null;
    }
  }
);

JSIL.ImplementExternals(
  "System.IO.StreamReader", true, {
    _ctor$7: function (filename) {
      this.stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
    },
    ReadLine: function () {
      var line = [];

      while (true) {
        var ch = this.stream.ReadByte();
        if (ch === -1) {
          if (line.length === 0)
            return null;
          else
            break;
        } else if (ch === 13) {
          var next = this.stream.Peek();
          if (next === 10)
            continue;
          else if (next === -1) {
            if (line.length === 0)
              return null;
            else
              break;
          } else
            break;
        } else if (ch === 10) {
          break;
        }

        line.push(ch);
      };

      return String.fromCharCode.apply(null, line);
    },
    Dispose: function () {
      this.stream = null;
    }
  }
);
<|endoftext|>


<commit_before>import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage, formatDuration } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import SCHOOLS from 'common/MAGIC_SCHOOLS';

class EmpowerWards extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    spellUsable: SpellUsable,
  };

  hitsWithNoWards = 0;
  hitsWithWards = 0;
  hitsWithWardsOffCD = 0;

  on_toPlayer_damage(event) {
    // Physical
    if (event.ability.type === SCHOOLS.ids.PHYSICAL) {
      return;
    }
    if (this.combatants.selected.hasBuff(SPELLS.EMPOWER_WARDS.id, event.timestamp)) {
      this.hitsWithWards += 1;
    }else{
      this.hitsWithNoWards += 1;

      const isAvailable = this.spellUsable.isAvailable(SPELLS.EMPOWER_WARDS.id);
      if(isAvailable) {
        this.hitsWithWardsOffCD += 1;
      }
    }
  }

  statistic() {
    const EMPOWER_WARDS_UPTIME = this.combatants.selected.getBuffUptime(SPELLS.EMPOWER_WARDS.id);
    const EMPOWER_WARDS_UPTIME_PERCENTAGE = EMPOWER_WARDS_UPTIME / this.owner.fightDuration;
    const HITS_WITH_WARDS_PERCENTAGE = this.hitsWithWards / (this.hitsWithWards + this.hitsWithNoWards);
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.EMPOWER_WARDS.id} />}
        value={`${formatPercentage(HITS_WITH_WARDS_PERCENTAGE)}%`}
        label="Hits Mitigated By Empower Wards"
        tooltip={`Empower Wards usage breakdown:

You were hit ${this.hitsWithWards} times with your Empower Wards buff.

You were hit ${this.hitsWithNoWards} times without your Empower Wards buff.

You were hit ${this.hitsWithWardsOffCD} times with Empower Wards  avalible for use but not used.

              Empower Wards uptime: ${formatPercentage(EMPOWER_WARDS_UPTIME_PERCENTAGE)}%

              Empower Wards duration: ${formatDuration(EMPOWER_WARDS_UPTIME / 1000)}.`}
      />
    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(8);
}

export default EmpowerWards;
<commit_msg>Changes made per PR recommendations<commit_after>import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage, formatDuration } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import SCHOOLS from 'common/MAGIC_SCHOOLS';

class EmpowerWards extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    spellUsable: SpellUsable,
  };

  hitsWithNoWards = 0;
  hitsWithWards = 0;
  hitsWithWardsOffCD = 0;

  on_toPlayer_damage(event) {
    // Physical
    if (event.ability.type === SCHOOLS.ids.PHYSICAL) {
      return;
    }
    if (this.combatants.selected.hasBuff(SPELLS.EMPOWER_WARDS.id, event.timestamp)) {
      this.hitsWithWards += 1;
    }else{
      this.hitsWithNoWards += 1;

      const isAvailable = this.spellUsable.isAvailable(SPELLS.EMPOWER_WARDS.id);
      if(isAvailable) {
        this.hitsWithWardsOffCD += 1;
      }
    }
  }

  statistic() {
    const empoweWardsUptime = this.combatants.selected.getBuffUptime(SPELLS.EMPOWER_WARDS.id);
    const empowerWardsUptimePercentage = empoweWardsUptime / this.owner.fightDuration;
    const hitsWithWardsPercentage = this.hitsWithWards / (this.hitsWithWards + this.hitsWithNoWards);
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.EMPOWER_WARDS.id} />}
        value={`${formatPercentage(hitsWithWardsPercentage)}%`}
        label="Hits mitigated by Empower Wards"
        tooltip={`Empower Wards usage breakdown:

You were hit ${this.hitsWithWards} times with your Empower Wards buff.

You were hit ${this.hitsWithNoWards} times without your Empower Wards buff.

You were hit ${this.hitsWithWardsOffCD} times with Empower Wards  avalible for use but not used.

              Empower Wards total uptime: ${formatPercentage(empowerWardsUptimePercentage)}% / (${formatDuration(empoweWardsUptime / 1000)})`}
      />
    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(8);
}

export default EmpowerWards;
<|endoftext|>


<commit_before>import Swiper from 'swiper';

function togglePopup() {
    const block = $('.photo-tape');

    block.find('.photo-tape__item').off('hover');
    block.off('click');

    if (!!('ontouchstart' in window)) {
        block.on('click', '.photo-tape__link', function(e) {
            console.log('click');
            e.preventDefault();

            const popup = $(this).siblings('.model-info-popup');

            popup.parents('.photo-tape').find('.model-info-popup').fadeOut();

            if (popup.is(':visible')) {
                popup.fadeOut();
            } else {
                popup.fadeIn();
            }
        });
    } else {
        block.find('.photo-tape__item').hover(
            function() {
                $(this).find('.model-info-popup').fadeIn();
            },
            function() {
                $(this).find('.model-info-popup').fadeOut();
            }
        );
    }
}

export default function photoTape() {
    const block = $('.photo-tape .swiper-container');

    if (!block.length) {
        return;
    }

    new Swiper(block, {
        slidesPerView: 'auto',
        freeMode: true
    });

    togglePopup();
}
<commit_msg>fix photo-tape<commit_after>import Swiper from 'swiper';

function togglePopup() {
    const block = $('.photo-tape');

    block.find('.photo-tape__item').off('hover');
    block.off('click');

    let timer = null;

    if (!!('ontouchstart' in window)) {
        block.on('click', '.photo-tape__link', function(e) {
            console.log('click');
            e.preventDefault();

            const popup = $(this).siblings('.model-info-popup');

            popup.parents('.photo-tape').find('.model-info-popup').fadeOut();

            if (popup.is(':visible')) {
                popup.fadeOut();
            } else {
                popup.fadeIn();
            }
        });
    } else {
        block.find('.photo-tape__item').hover(
            function() {
                const item = $(this).find('.model-info-popup');
                timer = setTimeout(() => {
                    item.fadeIn();
                }, 200);
            },
            function() {
                clearTimeout(timer);
                $(this).find('.model-info-popup').fadeOut();
            }
        );
    }
}

export default function photoTape() {
    const block = $('.photo-tape .swiper-container');

    if (!block.length) {
        return;
    }

    new Swiper(block, {
        slidesPerView: 'auto',
        freeMode: true
    });

    togglePopup();
}
<|endoftext|>


<commit_before>(function(root){
    /**
     * @module WordCount
     */

    /**
     * @title WordCount.js
     * @author Robert Bost <bostrt at gmail dot com>
     * @copyright © 2013 Robert Bost
     * @license MIT
     * WordCount.js is a client-side JS library that counts bytes, words, lines
     * chars, and calculates the longest line of a file. This library utilized
     * the HTML5 File API.
     *
     * > # Callbacks
     * Callbacks are passed into each of WordCount's
     * functions. Each callback should accept 3 parameters, (1) the value that the
     * function is calculating or finding, (2) the File object that was uploaded,
     * (3) and the ID selector of the file input element.
     * `callback(value, file, inputSelector)`
     */
    var WordCount = function() {
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of the bytes in the uploaded file is calculated
     * and then callback is called.
     * @param {String} inputSelector - The selector for a file input element.
     * @param {Function} callback - Called when a file has been completely uploaded and bytes have been calculated.
     * @returns {undefined}
     */
    WordCount.bytes = function(inputSelector, callback){
        addFileChangeListener(inputSelector, function(file) {
            callback(file.size, file, inputSelector);
        });
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the longest line in the file is located and the callback
     * is called.
     *
     * @param {String} inputSelector - The selector for a file input element.
     * @param {Function} callback - Called when a file has been completely uploaded and the longest line has been found.
     * @returns {undefined}
     */
    WordCount.longest = function(inputSelector, callback) {
        addFileChangeListener(inputSelector, function(file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                if (e.target.readyState === 2) {
                    var text = e.target.result;
                    callback(WordCount.longestInText(text) ,file, inputSelector);
                }
            };

            reader.readAsText(file);
        });
    };

    /*
     * Finds longest line in given text.
     */
    WordCount.longestInText = function(text) {
        if (text == null) {
            return null;
        }

        var split = text.split(/\n/g);
        if (split != null) {
            if (split.length > 1) {
                var longest = split[0];
                for (var i = 1; i < split.length; i++) {
                    if (longest.length < split[i].length) {
                        longest = split[i];
                    }
                }
                return longest;
            } else {
                return split[0];
            }
        } else {
            // return the only line...
            return text;
        }

    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of words in the file is calculated and the
     * callback is called. A word is a non-zero-length sequence of characters
     * delimited by white space.
     * @param {String} inputSelector - The selector for a file input element.
     * @param {Function} callback - Called after a file is available and the number of words have been calculated.
     * @returns {undefined}
     */
    WordCount.words = function(inputSelector, callback) {
        addFileChangeListener(inputSelector, function(file) {
           var reader = new FileReader() ;
           reader.onload = function(e) {
             if (e.target.readyState === 2) {
                 var text = e.target.result;
                 callback(WordCount.wordsInText(text), file, inputSelector);
             }
           };

           reader.readAsText(file);
        });
    };

    /*
     * Find number of words in given text.
     */
    WordCount.wordsInText = function(text) {
        if (text == null) {
            // There is no text.
            return 0;
        }

        text = text.trim(); // Clear ends.
        var split = text.split(/\s+/g);
        if (split.length === 1) {
            if (split[0].trim() === '') {
                // There is no text.
                return 0;
            } else {
                // There can be only one.
                return 1;
            }
        } else {
            return split.length;
        }
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of chars in the file are calculated and the
     * callback is called.
     * @param {String} inputSelector - The selector for a file input element.
     * @param {Function} callback - Called after a file is available and the number of chars in that file have been calculated.
     * @returns {undefined}
     */
    WordCount.chars = function(inputSelector, callback) {
        addFileChangeListener(inputSelector, function(file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                if (e.target.readyState === 2) {
                    var text = e.target.result;
                    var charsLength = WordCount.charsInText(text);
                    callback(charsLength, file, inputSelector);
                }
            };

            reader.readAsText(file);
        });
    };

    /*
     * Find number of chars in given text.
     */
    WordCount.charsInText = function(text) {
        if (text == null) {
            return 0;
        }

        return text.split(/./g).length;
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of lines in the file are calculated and the
     * callback is called.
     * @param {String} inputSelector - The selector for a file input element.
     * @param {Function} callback - Called after a file is available and the number of lines in that file have been calculated.
     * @returns {undefined}
     */
    WordCount.lines = function(inputSelector, callback) {
        addFileChangeListener(inputSelector, function(file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                if (e.target.readyState === 2) {
                    // upload is complete.
                    if (e.loaded > 0) {
                        // File has contents
                        var string = e.target.result;
                        callback(WordCount.linesInText(string), file, inputSelector);
                    }
                }
            };
            reader.readAsBinaryString(file);
        });
    };

    /*
     * Find number of lines in given text.
     */
    WordCount.linesInText = function(text) {
        if (text == null) {
            return 0;
        }
        var matching = text.match(/\n/g);
        if (matching != null) {
            return matching.length;
        } else {
            // File has content but no newlines...must be a single line!
            return 1;
        }
    };

    /*
     * Schedules a "change" event listener on a file input element.
     * When the "change" event is fired, the callback is called for each
     * file that was supplied.
     */
    function addFileChangeListener(inputSelector, callback) {
        var input = document.getElementById(inputSelector);
        input.addEventListener("change", function(event) {
            var files = event.target.files;
            if (files != undefined) {
                for (var i = 0; i < files.length; i++) {
                    callback(files[i]);
                }
            }
        });
    };

    // Export the wc.js class to the world!
    if (typeof define !== 'undefined' && define.amd) {
        define(WordCount);
    } else if (typeof exports === 'object') {
        module.exports = WordCount;
    } else {
        root.WordCount = WordCount;
    }
})(this);
<commit_msg>Updated param name.<commit_after>(function(root){
    /**
     * @module WordCount
     */

    /**
     * @title WordCount.js
     * @author Robert Bost <bostrt at gmail dot com>
     * @copyright © 2013 Robert Bost
     * @license MIT
     * WordCount.js is a client-side JS library that counts bytes, words, lines
     * chars, and calculates the longest line of a file. This library utilized
     * the HTML5 File API.
     *
     * > # Callbacks
     * Callbacks are passed into each of WordCount's
     * functions. Each callback should accept 3 parameters, (1) the value that the
     * function is calculating or finding, (2) the File object that was uploaded,
     * (3) and the ID selector of the file input element.
     * `callback(value, file, selector)`
     */
    var WordCount = function() {
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of the bytes in the uploaded file is calculated
     * and then callback is called.
     * @param {String} selector - The ID selector for a file input element.
     * @param {Function} callback - Called when a file has been completely uploaded and bytes have been calculated.
     * @returns {undefined}
     */
    WordCount.bytes = function(selector, callback){
        addFileChangeListener(selector, function(file) {
            callback(file.size, file, selector);
        });
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the longest line in the file is located and the callback
     * is called.
     *
     * @param {String} selector - The ID selector for a file input element.
     * @param {Function} callback - Called when a file has been completely uploaded and the longest line has been found.
     * @returns {undefined}
     */
    WordCount.longest = function(selector, callback) {
        addFileChangeListener(selector, function(file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                if (e.target.readyState === 2) {
                    var text = e.target.result;
                    callback(WordCount.longestInText(text) ,file, selector);
                }
            };

            reader.readAsText(file);
        });
    };

    /*
     * Finds longest line in given text.
     */
    WordCount.longestInText = function(text) {
        if (text == null) {
            return null;
        }

        var split = text.split(/\n/g);
        if (split != null) {
            if (split.length > 1) {
                var longest = split[0];
                for (var i = 1; i < split.length; i++) {
                    if (longest.length < split[i].length) {
                        longest = split[i];
                    }
                }
                return longest;
            } else {
                return split[0];
            }
        } else {
            // return the only line...
            return text;
        }

    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of words in the file is calculated and the
     * callback is called. A word is a non-zero-length sequence of characters
     * delimited by white space.
     * @param {String} selector - The ID selector for a file input element.
     * @param {Function} callback - Called after a file is available and the number of words have been calculated.
     * @returns {undefined}
     */
    WordCount.words = function(selector, callback) {
        addFileChangeListener(selector, function(file) {
           var reader = new FileReader() ;
           reader.onload = function(e) {
             if (e.target.readyState === 2) {
                 var text = e.target.result;
                 callback(WordCount.wordsInText(text), file, selector);
             }
           };

           reader.readAsText(file);
        });
    };

    /*
     * Find number of words in given text.
     */
    WordCount.wordsInText = function(text) {
        if (text == null) {
            // There is no text.
            return 0;
        }

        text = text.trim(); // Clear ends.
        var split = text.split(/\s+/g);
        if (split.length === 1) {
            if (split[0].trim() === '') {
                // There is no text.
                return 0;
            } else {
                // There can be only one.
                return 1;
            }
        } else {
            return split.length;
        }
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of chars in the file are calculated and the
     * callback is called.
     * @param {String} selector - The ID selector for a file input element.
     * @param {Function} callback - Called after a file is available and the number of chars in that file have been calculated.
     * @returns {undefined}
     */
    WordCount.chars = function(selector, callback) {
        addFileChangeListener(selector, function(file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                if (e.target.readyState === 2) {
                    var text = e.target.result;
                    var charsLength = WordCount.charsInText(text);
                    callback(charsLength, file, selector);
                }
            };

            reader.readAsText(file);
        });
    };

    /*
     * Find number of chars in given text.
     */
    WordCount.charsInText = function(text) {
        if (text == null) {
            return 0;
        }

        return text.split(/./g).length;
    };

    /**
     * When a file is uploaded using the file input element with the given input
     * selector then the number of lines in the file are calculated and the
     * callback is called.
     * @param {String} selector - The ID selector for a file input element.
     * @param {Function} callback - Called after a file is available and the number of lines in that file have been calculated.
     * @returns {undefined}
     */
    WordCount.lines = function(selector, callback) {
        addFileChangeListener(selector, function(file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                if (e.target.readyState === 2) {
                    // upload is complete.
                    if (e.loaded > 0) {
                        // File has contents
                        var string = e.target.result;
                        callback(WordCount.linesInText(string), file, selector);
                    }
                }
            };
            reader.readAsBinaryString(file);
        });
    };

    /*
     * Find number of lines in given text.
     */
    WordCount.linesInText = function(text) {
        if (text == null) {
            return 0;
        }
        var matching = text.match(/\n/g);
        if (matching != null) {
            return matching.length;
        } else {
            // File has content but no newlines...must be a single line!
            return 1;
        }
    };

    /*
     * Schedules a "change" event listener on a file input element.
     * When the "change" event is fired, the callback is called for each
     * file that was supplied.
     */
    function addFileChangeListener(selector, callback) {
        var input = document.getElementById(selector);
        input.addEventListener("change", function(event) {
            var files = event.target.files;
            if (files != undefined) {
                for (var i = 0; i < files.length; i++) {
                    callback(files[i]);
                }
            }
        });
    };

    // Export the wc.js class to the world!
    if (typeof define !== 'undefined' && define.amd) {
        define(WordCount);
    } else if (typeof exports === 'object') {
        module.exports = WordCount;
    } else {
        root.WordCount = WordCount;
    }
})(this);
<|endoftext|>


<commit_before>const cheerio = require('cheerio');
const axios = require('axios');
const gtranslate = require('google-translate-api');
const convertUnits = require('convert-units');
const mathjs = require('mathjs');

const scv = require('./modules/scv.js');
const cconvert = require('./modules/cconvert');

const config = require('./config.json');

const commandDesc = require('./data/commands.json');
const cyrillicMap = require('./data/cyrillic.json');
const NUMBERS = require('./data/numbers.json');

const UNITSPACE = '\u202F';
const ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

const DISCORD_CHAR_LIMIT = 2000;
const MY_CHAR_LIMIT = 10000;

const removeWhitespace = (str) => {
    return str.replace(/ /g, '');
};

const safeSendMsg = (channel, text, surround = '') => {
    let localCharLim = DISCORD_CHAR_LIMIT - 2 * surround.length;

    if (text.length > MY_CHAR_LIMIT) {
        return false;
    } else if (text.length < localCharLim) {
        channel.send(surround + text + surround);
        return true;
    } else {
        let textTemp = text;

        for (let i = 0; i <= textTemp.length % localCharLim; i++) {
            channel.send(surround + textTemp.slice(0, localCharLim) + surround);

            textTemp = textTemp.slice(localCharLim);
        }
        return true;
    }
};

/**
 * Rounds a float to a specified number of digits.
 *
 * @param n The number to round.
 * @param digits The number of digits (not decimal places) to round to.
 * @returns {number} The rounded value.
 */
const roundTo = (n, digits) => {
    if (digits === undefined) {
        digits = 0;
    }

    let multiplicator = Math.pow(10, digits);
    n = parseFloat((n * multiplicator).toFixed(11));
    let test = (Math.round(n) / multiplicator);
    return +(test.toFixed(digits));
};

const numberWithCommas = (x) => {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const slayerAuraChance = (tier) => {
    let auraToTier = {
        "none": 1.0,
        "dedicated": 1.03,
        "greater": 1.05,
        "master": 1.07,
        "supreme": 1.1,
        "legendary": 1.15
    }, multiplier;

    if (tier > 5 || tier < 0 || (typeof tier !== 'number' && auraToTier[tier] === 'undefined')) {
        return false;
    }

    let index = typeof tier === 'string' ? tier : Object.keys(auraToTier)[tier];

    multiplier = auraToTier[index];
    return 1 / (2 - multiplier); // expected value of geometric distribution
};

const randomInRange = (min, max) => {
    return Math.floor(Math.random() * (max + 1 - min)) + min;
};

const youtubeIDToLink = (id) => {
    return 'https://www.youtube.com/watch?v=' + id;
};

let mathVariables = {};
mathConstants = {
    pi: Math.PI,
    e: Math.E
};

commands = {
    help: (msg) => {
        let outText = 'Available commands:\n\n',
            commandsArray = [],
            cmdNames = Object.keys(commandDesc);

        for (let i in cmdNames) {
            let commandName = cmdNames[i],
                commandEntry = '',
                aliasesArray = commandDesc[commandName].aliases;

            commandEntry += commandName;

            if (Array.isArray(aliasesArray)) {
                commandEntry += ' (' + aliasesArray.join(', ') + ')';
            }

            commandsArray.push(commandEntry);
        }

        outText += commandsArray.join(', ');
        return outText;
    },
    import_fn: (msg, text) => {
        if (text === 'this') {
            return exports.cmd.pasta(msg, 'pyzen');
        }
    },
    ping: (msg) => {
        console.log(Date.now(), msg.createdTimestamp);
        let pingTime = (Date.now() - msg.createdTimestamp);
        msg.channel.send('Pong! ' + pingTime + 'ms');
    },
    roll: (msg, sides, dice = 1) => {
        let rolls = [];

        for (let i = 0; i < dice; i++) {
            rolls.push(randomInRange(1, sides));
        }

        let data = {
            variance: mathjs.var,
            std: mathjs.std,
            mean: mathjs.mean,
            median: mathjs.median,
            mode: mathjs.mode,
            max: mathjs.max,
            min: mathjs.min,
            sum: mathjs.sum
        };

        let rollsString = rolls.join(' '),
            dataString = Object.keys(data).map(key => {
                let func = val => {
                    return roundTo(data[key](val), 3);
                };

                return `${key}: ${func(rolls)}`;
            }).join(', ');

        return `${rollsString};\n\n${dataString}`;
    },
    pasta: (msg, pastaName) => {
        let pastaData = require("./data/pastas.json");
        if (pastaName !== 'list') {
            pastaText = pastaData[pastaName];

            msg.channel.send(pastaText);
        } else {
            return Object.keys(pastaData).slice(0);
        }
    },
    priceCheck: (msg, item, amount = 1) => {
        const baseUrl = 'http://runescape.wikia.com/wiki/Exchange:';

        axios.get(baseUrl + item).then(response => {
            let $ = cheerio.load(response.data),
                price = parseInt($('#GEPrice').text().replace(/,/g, '')),
                totalPrice = numberWithCommas(price * amount);

            msg.channel.send(item + ' x ' + amount + ': ' + totalPrice + 'gp');
        }).catch((error) => {
            console.log(error);
        });

        return false;
    },
    slayer: (msg, monster, amount = 1, aura = 0) => {
        const baseUrl = 'http://runescape.wikia.com/wiki/';

        let auraMultiplier = slayerAuraChance(aura),
            expectedAmount;

        if (!auraMultiplier) {
            msg.channel.send('**Invalid aura tier **' + aura);
            return;
        }

        expectedAmount = parseInt(amount * auraMultiplier);

        // get the monster id
        axios.get(baseUrl + monster).then((response) => {
            const processXpText = (text) => {
                return Math.floor(parseFloat(text.replace(/,/g, '')) * expectedAmount);
            };

            let $ = cheerio.load(response.data),
                monsterName = $('.page-header__title').text(),
                xpCombat = processXpText($('.mob-cb-xp').text()),
                xpHp = processXpText($('.mob-hp-xp').text()),
                xpSlayer = processXpText($('.mob-slay-xp').text());

            msg.channel.send(monsterName + ' x ' + expectedAmount + ': ' + xpSlayer
                + ' slayer xp, ' + xpCombat + ' combat xp and ' + xpHp + ' hp xp.');
        }).catch((error) => {
            console.log(error);
        });
    },
    wikipedia: (msg, article, lang = 'en') => {
        let baseUrl = 'https://' + lang + '.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=',
            baseLinkUrl = 'https://' + lang + '.wikipedia.org/wiki/';

        axios.get(baseUrl + article).then((response) => {
            if (response.data.query.search.length !== 0) {
                let firstResult = response.data.query.search[0],
                    firstResultTitle = firstResult.title.replace(/ /g, '_');

                msg.channel.send('Wikipedia link: ' + baseLinkUrl + firstResultTitle);
            } else {
                msg.channel.send('No search results found for "' + article + '"');
            }
        }).catch((error) => {
            console.log(error);
            if (error.code === 'ENOTFOUND') {
                msg.channel.send('**Invalid language code** "' + lang + '"');
            }
        });
    },
    translate: (msg, langFrom, langInto, ...text) => {
        let textJoined = text.join(' ');

        gtranslate(textJoined, {from: langFrom, to: langInto}).then((res) => {
            let out = '';

            if (res.from.text.autoCorrected || res.from.text.didYouMean) {
                out += '**Autocorrected** "' + textJoined + '" **to** "' + res.from.text.value + '"\n\n';
            }

            out += res.text;

            msg.channel.send(out);
        }).catch(err => {
            console.error(err);
            msg.channel.send('**' + err.message + '**');
        });
    },
    onerm: (msg, weight, reps) => {
        // using Epley formula:
        let max = Math.floor(weight * (1 + reps / 30));

        msg.channel.send('Estimated one rep max: ' + max);
    },
    convert: (msg, number, unitsFrom, unitsTo, dp = 2) => {
        let converted;
        try {
            converted = roundTo(convertUnits(number).from(unitsFrom).to(unitsTo), dp);
            msg.channel.send('**' + number + UNITSPACE + unitsFrom + '** is **' + converted + UNITSPACE + unitsTo + '**');
        } catch (e) {
            msg.channel.send('**Error**: ' + e.message);
        }
    },
    b: (msg) => {
        msg.channel.send(':b:');
    },
    youtube: (msg, query) => {
        let baseYoutubeUrl = 'https://www.googleapis.com/youtube/v3/search';

        axios.get(baseYoutubeUrl, {
            params: {
                key: config.googleAPIKey,
                part: 'snippet',
                order: 'viewCount',
                type: 'video',
                q: query
            }
        }).then((response) => {
            let items = response.data.items,
                firstResult = items[0],
                firstVideoID;

            try {
                firstVideoID = firstResult.id.videoId;
            } catch (e) {
                return `**No results found for** "${query}"`;
            }

            msg.channel.send(youtubeIDToLink(firstVideoID));
        }).catch((response) => {
            console.log(response);
        });
    },
    prettify: (msg, text) => {
        let prettifiedText = (text + '').split(' ').map((word) => {
            return word.split('').map((char) => {
                if (ALPHABET.indexOf(char) !== -1) {
                    return ':regional_indicator_' + char.toLowerCase() + ':';
                } else if (typeof NUMBERS[char] !== 'undefined') {
                    return ':' + NUMBERS[char] + ':';
                } else {
                    return char;
                }
            }).join('');
        }).join('  ');

        msg.channel.send(prettifiedText);
    },
    cyrillify: (msg, text) => {
        let cyrillifiedText = text.split('').map((elem) => {
            let mappedChar = cyrillicMap[elem];
            if (typeof mappedChar === 'undefined') {
                return elem;
            } else {
                return mappedChar;
            }
        }).join('');

        msg.channel.send(cyrillifiedText);
    },
    setPrefix: (msg, value) => {
        let channelID = msg.channel.id;

        console.log('setting for ' + channelID);
        return new Promise((resolve, reject) => {
            scv.set(channelID, 'prefix', value).then((value) => {
                msg.channel.send("**Prefix set to**: " + value);
                console.log(`prefix set to ${value}`);
                resolve();
            }).catch((err) => {
                msg.channel.send("Failed to set prefix value.");
                reject(err);
            });
        });
    },
    eval: (msg, expression) => {
        let channelID = msg.channel.id,
            context = mathVariables[channelID + ''];

        if (typeof context === 'undefined') {
            context = {};
        }

        try {
            let result = mathjs.eval(expression, context);
            msg.channel.send(`Expression value: ${result}`);
        } catch (e) {
            msg.channel.send('Bad expression. Make sure all variables are defined!');
        }
    },
    setvar: (msg, varname, varvalue) => {
        if (Object.keys(mathConstants).indexOf(varname) !== -1) {
            msg.channel.send(`**Unable to set as variable name** ${varname} **is reserved.**`);
        } else {
            let varvalueParsed,
                channelID = msg.channel.id,
                channelMathVariables = mathVariables[channelID + ''];

            if (typeof channelMathVariables === 'undefined') {
                mathVariables[channelID + ''] = {};
                channelMathVariables = mathVariables[channelID + ''];
            }

            let context = Object.assign({}, channelMathVariables, mathConstants);

            // parse expression if we need to
            if (typeof varvalue === 'number') {
                varvalueParsed = varvalue;
            } else {
                varvalueParsed = mathjs.eval(varvalue, context);
            }

            if (typeof channelMathVariables[varname] === 'undefined') {
                msg.channel.send(`**Variable** ${varname} **created and set to** ${varvalueParsed}`);
            } else {
                msg.channel.send(`**Variable** ${varname} **changed from** ${mathVariables[varname]} **to** ${varvalueParsed}`);
            }

            channelMathVariables[varname] = varvalueParsed;
        }
    },
    setvars: (msg, varnames, varvalues) => {
        const varnamesArray = removeWhitespace(varnames).split(','),
            varvaluesArray = removeWhitespace(varvalues).split(',');

        varnamesArray.forEach((elem, index) => {
            let value = varvaluesArray[index];
            if (Object.keys(mathConstants).indexOf(elem) !== -1) {
                // do nothing since we don't want to overwrite global constants
            } else {
                let valueParsed,
                    channelID = msg.channel.id,
                    channelMathVariables = mathVariables[channelID + ''];

                if (typeof channelMathVariables === 'undefined') {
                    mathVariables[channelID + ''] = {};
                    channelMathVariables = mathVariables[channelID + ''];
                }

                let context = Object.assign({}, channelMathVariables, mathConstants);

                // parse expression if we need to
                if (typeof value === 'number') {
                    valueParsed = value;
                } else {
                    valueParsed = mathjs.eval(value, context);
                }

                channelMathVariables[elem] = valueParsed;
            }
        });
    },
    ree: (msg, i) => {
        safeSendMsg(msg.channel, `R${Array(i + 1).join('E')}`);
    }

};

module.exports = commands;

module.exports.safeSendMsg = safeSendMsg;
module.exports.MY_CHAR_LIMIT = MY_CHAR_LIMIT;<commit_msg>this should be sufficient i think<commit_after>const cheerio = require('cheerio');
const axios = require('axios');
const gtranslate = require('google-translate-api');
const convertUnits = require('convert-units');
const mathjs = require('mathjs');

const scv = require('./modules/scv.js');
const cconvert = require('./modules/cconvert');

const config = require('./config.json');

const commandDesc = require('./data/commands.json');
const cyrillicMap = require('./data/cyrillic.json');
const NUMBERS = require('./data/numbers.json');

const UNITSPACE = '\u202F';
const ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

const DISCORD_CHAR_LIMIT = 2000;
const MY_CHAR_LIMIT = 10000;

const removeWhitespace = (str) => {
    return str.replace(/ /g, '');
};

const safeSendMsg = (channel, text, surround = '') => {
    let localCharLim = DISCORD_CHAR_LIMIT - 2 * surround.length;

    if (text.length > MY_CHAR_LIMIT) {
        return false;
    } else if (text.length < localCharLim) {
        channel.send(surround + text + surround);
        return true;
    } else {
        let textTemp = text;

        for (let i = 0; i <= textTemp.length % localCharLim; i++) {
            channel.send(surround + textTemp.slice(0, localCharLim) + surround);

            textTemp = textTemp.slice(localCharLim);
        }
        return true;
    }
};

/**
 * Rounds a float to a specified number of digits.
 *
 * @param n The number to round.
 * @param digits The number of digits (not decimal places) to round to.
 * @returns {number} The rounded value.
 */
const roundTo = (n, digits) => {
    if (digits === undefined) {
        digits = 0;
    }

    let multiplicator = Math.pow(10, digits);
    n = parseFloat((n * multiplicator).toFixed(11));
    let test = (Math.round(n) / multiplicator);
    return +(test.toFixed(digits));
};

const numberWithCommas = (x) => {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const slayerAuraChance = (tier) => {
    let auraToTier = {
        "none": 1.0,
        "dedicated": 1.03,
        "greater": 1.05,
        "master": 1.07,
        "supreme": 1.1,
        "legendary": 1.15
    }, multiplier;

    if (tier > 5 || tier < 0 || (typeof tier !== 'number' && auraToTier[tier] === 'undefined')) {
        return false;
    }

    let index = typeof tier === 'string' ? tier : Object.keys(auraToTier)[tier];

    multiplier = auraToTier[index];
    return 1 / (2 - multiplier); // expected value of geometric distribution
};

const randomInRange = (min, max) => {
    return Math.floor(Math.random() * (max + 1 - min)) + min;
};

const youtubeIDToLink = (id) => {
    return 'https://www.youtube.com/watch?v=' + id;
};

let mathVariables = {};
mathConstants = {
    pi: Math.PI,
    e: Math.E
};

commands = {
    help: (msg) => {
        let outText = 'Available commands:\n\n',
            commandsArray = [],
            cmdNames = Object.keys(commandDesc);

        for (let i in cmdNames) {
            let commandName = cmdNames[i],
                commandEntry = '',
                aliasesArray = commandDesc[commandName].aliases;

            commandEntry += commandName;

            if (Array.isArray(aliasesArray)) {
                commandEntry += ' (' + aliasesArray.join(', ') + ')';
            }

            commandsArray.push(commandEntry);
        }

        outText += commandsArray.join(', ');
        return outText;
    },
    import_fn: (msg, text) => {
        if (text === 'this') {
            return exports.cmd.pasta(msg, 'pyzen');
        }
    },
    ping: (msg) => {
        console.log(Date.now(), msg.createdTimestamp);
        let pingTime = (Date.now() - msg.createdTimestamp);
        msg.channel.send('Pong! ' + pingTime + 'ms');
    },
    roll: (msg, sides, dice = 1) => {
        let rolls = [];

        for (let i = 0; i < dice; i++) {
            rolls.push(randomInRange(1, sides));
        }

        let data = {
            variance: mathjs.var,
            std: mathjs.std,
            mean: mathjs.mean,
            median: mathjs.median,
            mode: mathjs.mode,
            max: mathjs.max,
            min: mathjs.min,
            sum: mathjs.sum
        };

        let rollsString = rolls.join(' '),
            dataString = Object.keys(data).map(key => {
                let func = val => {
                    if (key === 'mode') {
                        return `[${data[key](val)}]`;
                    }
                    return roundTo(data[key](val), 3);
                };

                return `${key}: ${func(rolls)}`;
            }).join(', ');

        return `${rollsString};\n\n${dataString}`;
    },
    pasta: (msg, pastaName) => {
        let pastaData = require("./data/pastas.json");
        if (pastaName !== 'list') {
            pastaText = pastaData[pastaName];

            msg.channel.send(pastaText);
        } else {
            return Object.keys(pastaData).slice(0);
        }
    },
    priceCheck: (msg, item, amount = 1) => {
        const baseUrl = 'http://runescape.wikia.com/wiki/Exchange:';

        axios.get(baseUrl + item).then(response => {
            let $ = cheerio.load(response.data),
                price = parseInt($('#GEPrice').text().replace(/,/g, '')),
                totalPrice = numberWithCommas(price * amount);

            msg.channel.send(item + ' x ' + amount + ': ' + totalPrice + 'gp');
        }).catch((error) => {
            console.log(error);
        });

        return false;
    },
    slayer: (msg, monster, amount = 1, aura = 0) => {
        const baseUrl = 'http://runescape.wikia.com/wiki/';

        let auraMultiplier = slayerAuraChance(aura),
            expectedAmount;

        if (!auraMultiplier) {
            msg.channel.send('**Invalid aura tier **' + aura);
            return;
        }

        expectedAmount = parseInt(amount * auraMultiplier);

        // get the monster id
        axios.get(baseUrl + monster).then((response) => {
            const processXpText = (text) => {
                return Math.floor(parseFloat(text.replace(/,/g, '')) * expectedAmount);
            };

            let $ = cheerio.load(response.data),
                monsterName = $('.page-header__title').text(),
                xpCombat = processXpText($('.mob-cb-xp').text()),
                xpHp = processXpText($('.mob-hp-xp').text()),
                xpSlayer = processXpText($('.mob-slay-xp').text());

            msg.channel.send(monsterName + ' x ' + expectedAmount + ': ' + xpSlayer
                + ' slayer xp, ' + xpCombat + ' combat xp and ' + xpHp + ' hp xp.');
        }).catch((error) => {
            console.log(error);
        });
    },
    wikipedia: (msg, article, lang = 'en') => {
        let baseUrl = 'https://' + lang + '.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=',
            baseLinkUrl = 'https://' + lang + '.wikipedia.org/wiki/';

        axios.get(baseUrl + article).then((response) => {
            if (response.data.query.search.length !== 0) {
                let firstResult = response.data.query.search[0],
                    firstResultTitle = firstResult.title.replace(/ /g, '_');

                msg.channel.send('Wikipedia link: ' + baseLinkUrl + firstResultTitle);
            } else {
                msg.channel.send('No search results found for "' + article + '"');
            }
        }).catch((error) => {
            console.log(error);
            if (error.code === 'ENOTFOUND') {
                msg.channel.send('**Invalid language code** "' + lang + '"');
            }
        });
    },
    translate: (msg, langFrom, langInto, ...text) => {
        let textJoined = text.join(' ');

        gtranslate(textJoined, {from: langFrom, to: langInto}).then((res) => {
            let out = '';

            if (res.from.text.autoCorrected || res.from.text.didYouMean) {
                out += '**Autocorrected** "' + textJoined + '" **to** "' + res.from.text.value + '"\n\n';
            }

            out += res.text;

            msg.channel.send(out);
        }).catch(err => {
            console.error(err);
            msg.channel.send('**' + err.message + '**');
        });
    },
    onerm: (msg, weight, reps) => {
        // using Epley formula:
        let max = Math.floor(weight * (1 + reps / 30));

        msg.channel.send('Estimated one rep max: ' + max);
    },
    convert: (msg, number, unitsFrom, unitsTo, dp = 2) => {
        let converted;
        try {
            converted = roundTo(convertUnits(number).from(unitsFrom).to(unitsTo), dp);
            msg.channel.send('**' + number + UNITSPACE + unitsFrom + '** is **' + converted + UNITSPACE + unitsTo + '**');
        } catch (e) {
            msg.channel.send('**Error**: ' + e.message);
        }
    },
    b: (msg) => {
        msg.channel.send(':b:');
    },
    youtube: (msg, query) => {
        let baseYoutubeUrl = 'https://www.googleapis.com/youtube/v3/search';

        axios.get(baseYoutubeUrl, {
            params: {
                key: config.googleAPIKey,
                part: 'snippet',
                order: 'viewCount',
                type: 'video',
                q: query
            }
        }).then((response) => {
            let items = response.data.items,
                firstResult = items[0],
                firstVideoID;

            try {
                firstVideoID = firstResult.id.videoId;
            } catch (e) {
                return `**No results found for** "${query}"`;
            }

            msg.channel.send(youtubeIDToLink(firstVideoID));
        }).catch((response) => {
            console.log(response);
        });
    },
    prettify: (msg, text) => {
        let prettifiedText = (text + '').split(' ').map((word) => {
            return word.split('').map((char) => {
                if (ALPHABET.indexOf(char) !== -1) {
                    return ':regional_indicator_' + char.toLowerCase() + ':';
                } else if (typeof NUMBERS[char] !== 'undefined') {
                    return ':' + NUMBERS[char] + ':';
                } else {
                    return char;
                }
            }).join('');
        }).join('  ');

        msg.channel.send(prettifiedText);
    },
    cyrillify: (msg, text) => {
        let cyrillifiedText = text.split('').map((elem) => {
            let mappedChar = cyrillicMap[elem];
            if (typeof mappedChar === 'undefined') {
                return elem;
            } else {
                return mappedChar;
            }
        }).join('');

        msg.channel.send(cyrillifiedText);
    },
    setPrefix: (msg, value) => {
        let channelID = msg.channel.id;

        console.log('setting for ' + channelID);
        return new Promise((resolve, reject) => {
            scv.set(channelID, 'prefix', value).then((value) => {
                msg.channel.send("**Prefix set to**: " + value);
                console.log(`prefix set to ${value}`);
                resolve();
            }).catch((err) => {
                msg.channel.send("Failed to set prefix value.");
                reject(err);
            });
        });
    },
    eval: (msg, expression) => {
        let channelID = msg.channel.id,
            context = mathVariables[channelID + ''];

        if (typeof context === 'undefined') {
            context = {};
        }

        try {
            let result = mathjs.eval(expression, context);
            msg.channel.send(`Expression value: ${result}`);
        } catch (e) {
            msg.channel.send('Bad expression. Make sure all variables are defined!');
        }
    },
    setvar: (msg, varname, varvalue) => {
        if (Object.keys(mathConstants).indexOf(varname) !== -1) {
            msg.channel.send(`**Unable to set as variable name** ${varname} **is reserved.**`);
        } else {
            let varvalueParsed,
                channelID = msg.channel.id,
                channelMathVariables = mathVariables[channelID + ''];

            if (typeof channelMathVariables === 'undefined') {
                mathVariables[channelID + ''] = {};
                channelMathVariables = mathVariables[channelID + ''];
            }

            let context = Object.assign({}, channelMathVariables, mathConstants);

            // parse expression if we need to
            if (typeof varvalue === 'number') {
                varvalueParsed = varvalue;
            } else {
                varvalueParsed = mathjs.eval(varvalue, context);
            }

            if (typeof channelMathVariables[varname] === 'undefined') {
                msg.channel.send(`**Variable** ${varname} **created and set to** ${varvalueParsed}`);
            } else {
                msg.channel.send(`**Variable** ${varname} **changed from** ${mathVariables[varname]} **to** ${varvalueParsed}`);
            }

            channelMathVariables[varname] = varvalueParsed;
        }
    },
    setvars: (msg, varnames, varvalues) => {
        const varnamesArray = removeWhitespace(varnames).split(','),
            varvaluesArray = removeWhitespace(varvalues).split(',');

        varnamesArray.forEach((elem, index) => {
            let value = varvaluesArray[index];
            if (Object.keys(mathConstants).indexOf(elem) !== -1) {
                // do nothing since we don't want to overwrite global constants
            } else {
                let valueParsed,
                    channelID = msg.channel.id,
                    channelMathVariables = mathVariables[channelID + ''];

                if (typeof channelMathVariables === 'undefined') {
                    mathVariables[channelID + ''] = {};
                    channelMathVariables = mathVariables[channelID + ''];
                }

                let context = Object.assign({}, channelMathVariables, mathConstants);

                // parse expression if we need to
                if (typeof value === 'number') {
                    valueParsed = value;
                } else {
                    valueParsed = mathjs.eval(value, context);
                }

                channelMathVariables[elem] = valueParsed;
            }
        });
    },
    ree: (msg, i) => {
        safeSendMsg(msg.channel, `R${Array(i + 1).join('E')}`);
    }

};

module.exports = commands;

module.exports.safeSendMsg = safeSendMsg;
module.exports.MY_CHAR_LIMIT = MY_CHAR_LIMIT;
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form.handlers");

frappe.ui.form.get_event_handler_list = function(doctype, fieldname) {
	if(!frappe.ui.form.handlers[doctype]) {
		frappe.ui.form.handlers[doctype] = {};
	}
	if(!frappe.ui.form.handlers[doctype][fieldname]) {
		frappe.ui.form.handlers[doctype][fieldname] = [];
	}
	return frappe.ui.form.handlers[doctype][fieldname];
}

frappe.ui.form.on = frappe.ui.form.on_change = function(doctype, fieldname, handler) {
	var add_handler = function(fieldname, handler) {
		var handler_list = frappe.ui.form.get_event_handler_list(doctype, fieldname);
		handler_list.push(handler);

		// add last handler to events so it can be called as
		// frm.events.handler(frm)
		if(cur_frm && cur_frm.doctype===doctype) {
			cur_frm.events[fieldname] = handler;
		}
	}

	if (!handler && $.isPlainObject(fieldname)) {
		// a dict of handlers {fieldname: handler, ...}
		for (var key in fieldname) {
			var fn = fieldname[key];
			if (typeof fn === "function") {
				add_handler(key, fn);
			}
		}
	} else {
		add_handler(fieldname, handler);
	}
}

// remove standard event handlers
frappe.ui.form.off = function(doctype, fieldname, handler) {
	var handler_list = frappe.ui.form.get_event_handler_list(doctype, fieldname);
	if(handler_list.length) {
		frappe.ui.form.handlers[doctype][fieldname] = [];
	}

	if(cur_frm && cur_frm.doctype===doctype && cur_frm.events[fieldname]) {
		delete cur_frm.events[fieldname];
	}

	if(cur_frm && cur_frm.cscript && cur_frm.cscript[fieldname]) {
		delete cur_frm.cscript[fieldname];
	}
}

frappe.ui.form.trigger = function(doctype, fieldname) {
	cur_frm.script_manager.trigger(fieldname, doctype);
}

frappe.ui.form.ScriptManager = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
	},
	make: function(ControllerClass) {
		this.frm.cscript = $.extend(this.frm.cscript,
			new ControllerClass({frm: this.frm}));
	},
	trigger: function(event_name, doctype, name) {
		// trigger all the form level events that
		// are bound to this event_name
		let me = this;
		doctype = doctype || this.frm.doctype;
		name = name || this.frm.docname;

		let tasks = [];
		let handlers = this.get_handlers(event_name, doctype);

		// helper for child table
		this.frm.selected_doc = frappe.get_doc(doctype, name);

		let runner = (_function, is_old_style) => {
			let _promise = null;
			if(is_old_style) {
				// old style arguments (doc, cdt, cdn)
				_promise = me.frm.cscript[_function](me.frm.doc, doctype, name);
			} else {
				// new style (frm, doctype, name)
				_promise = _function(me.frm, doctype, name);
			}

			// if the trigger returns a promise, return it,
			// or use the default promise frappe.after_ajax
			if (_promise && _promise.then) {
				return _promise;
			} else {
				return frappe.after_server_call();
			}
		};

		// make list of functions to be run serially
		handlers.new_style.forEach((_function) => {
			if(event_name==='setup') {
				// setup must be called immediately
				runner(_function, false);
			} else {
				tasks.push(() => runner(_function, false));
			}
		});

		handlers.old_style.forEach((_function) => {
			if(event_name==='setup') {
				// setup must be called immediately
				runner(_function, true);
			} else {
				tasks.push(() => runner(_function, true));
			}
		});

		// run them serially
		return frappe.run_serially(tasks);
	},
	has_handlers: function(event_name, doctype) {
		let handlers = this.get_handlers(event_name, doctype);
		return handlers && (handlers.old_style.length || handlers.new_style.length);
	},
	get_handlers: function(event_name, doctype) {
		// returns list of all functions to be called (old style and new style)
		let me = this;
		let handlers = {
			old_style: [],
			new_style: []
		};
		if(frappe.ui.form.handlers[doctype] && frappe.ui.form.handlers[doctype][event_name]) {
			$.each(frappe.ui.form.handlers[doctype][event_name], function(i, fn) {
				handlers.new_style.push(fn);
			});
		}
		if(this.frm.cscript[event_name]) {
			handlers.old_style.push(event_name);
		}
		if(this.frm.cscript["custom_" + event_name]) {
			handlers.old_style.push("custom_" + event_name);
		}
		return handlers;
	},
	setup: function() {
		var doctype = this.frm.meta;
		var me = this;

		// js
		var cs = doctype.__js;
		if(cs) {
			var tmp = eval(cs);
		}

		if(doctype.__custom_js) {
			try {
				eval(doctype.__custom_js);
			} catch(e) {
				frappe.msgprint({
					title: __('Error in Custom Script'),
					indicator: 'orange',
					message: '
' + e.stack  + '
'
				});
			}
		}

		function setup_add_fetch(df) {
			if((['Data', 'Read Only', 'Text', 'Small Text', 'Currency',
				'Text Editor', 'Code', 'Link', 'Float', 'Int'].includes(df.fieldtype) || df.read_only==1)
				&& df.fetch_from && df.fetch_from.indexOf(".")!=-1) {
				var parts = df.fetch_from.split(".");
				me.frm.add_fetch(parts[0], parts[1], df.fieldname);
			}
		}

		// setup add fetch
		$.each(this.frm.fields, function(i, field) {
			setup_add_fetch(field.df);
			if(field.df.fieldtype==="Table") {
				$.each(frappe.meta.get_docfields(field.df.options, me.frm.docname), function(i, df) {
					setup_add_fetch(df);
				});
			}
		});

		// css
		doctype.__css && frappe.dom.set_style(doctype.__css);

		this.trigger('setup');
	},
	log_error: function(caller, e) {
		frappe.show_alert("Error in Client Script.");
		console.group && console.group();
		console.log("----- error in client script -----");
		console.log("method: " + caller);
		console.log(e);
		console.log("error message: " + e.message);
		console.trace && console.trace();
		console.log("----- end of error message -----");
		console.group && console.groupEnd();
	},
	copy_from_first_row: function(parentfield, current_row, fieldnames) {
		var data = this.frm.doc[parentfield];
		if(data.length===1 || data[0]===current_row) return;

		if(typeof fieldnames==='string') {
			fieldnames = [fieldnames];
		}

		$.each(fieldnames, function(i, fieldname) {
			frappe.model.set_value(current_row.doctype, current_row.name, fieldname,
				data[0][fieldname]);
		});
	}
});
<commit_msg>Fetch from for dates<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form.handlers");

frappe.ui.form.get_event_handler_list = function(doctype, fieldname) {
	if(!frappe.ui.form.handlers[doctype]) {
		frappe.ui.form.handlers[doctype] = {};
	}
	if(!frappe.ui.form.handlers[doctype][fieldname]) {
		frappe.ui.form.handlers[doctype][fieldname] = [];
	}
	return frappe.ui.form.handlers[doctype][fieldname];
}

frappe.ui.form.on = frappe.ui.form.on_change = function(doctype, fieldname, handler) {
	var add_handler = function(fieldname, handler) {
		var handler_list = frappe.ui.form.get_event_handler_list(doctype, fieldname);
		handler_list.push(handler);

		// add last handler to events so it can be called as
		// frm.events.handler(frm)
		if(cur_frm && cur_frm.doctype===doctype) {
			cur_frm.events[fieldname] = handler;
		}
	}

	if (!handler && $.isPlainObject(fieldname)) {
		// a dict of handlers {fieldname: handler, ...}
		for (var key in fieldname) {
			var fn = fieldname[key];
			if (typeof fn === "function") {
				add_handler(key, fn);
			}
		}
	} else {
		add_handler(fieldname, handler);
	}
}

// remove standard event handlers
frappe.ui.form.off = function(doctype, fieldname, handler) {
	var handler_list = frappe.ui.form.get_event_handler_list(doctype, fieldname);
	if(handler_list.length) {
		frappe.ui.form.handlers[doctype][fieldname] = [];
	}

	if(cur_frm && cur_frm.doctype===doctype && cur_frm.events[fieldname]) {
		delete cur_frm.events[fieldname];
	}

	if(cur_frm && cur_frm.cscript && cur_frm.cscript[fieldname]) {
		delete cur_frm.cscript[fieldname];
	}
}

frappe.ui.form.trigger = function(doctype, fieldname) {
	cur_frm.script_manager.trigger(fieldname, doctype);
}

frappe.ui.form.ScriptManager = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
	},
	make: function(ControllerClass) {
		this.frm.cscript = $.extend(this.frm.cscript,
			new ControllerClass({frm: this.frm}));
	},
	trigger: function(event_name, doctype, name) {
		// trigger all the form level events that
		// are bound to this event_name
		let me = this;
		doctype = doctype || this.frm.doctype;
		name = name || this.frm.docname;

		let tasks = [];
		let handlers = this.get_handlers(event_name, doctype);

		// helper for child table
		this.frm.selected_doc = frappe.get_doc(doctype, name);

		let runner = (_function, is_old_style) => {
			let _promise = null;
			if(is_old_style) {
				// old style arguments (doc, cdt, cdn)
				_promise = me.frm.cscript[_function](me.frm.doc, doctype, name);
			} else {
				// new style (frm, doctype, name)
				_promise = _function(me.frm, doctype, name);
			}

			// if the trigger returns a promise, return it,
			// or use the default promise frappe.after_ajax
			if (_promise && _promise.then) {
				return _promise;
			} else {
				return frappe.after_server_call();
			}
		};

		// make list of functions to be run serially
		handlers.new_style.forEach((_function) => {
			if(event_name==='setup') {
				// setup must be called immediately
				runner(_function, false);
			} else {
				tasks.push(() => runner(_function, false));
			}
		});

		handlers.old_style.forEach((_function) => {
			if(event_name==='setup') {
				// setup must be called immediately
				runner(_function, true);
			} else {
				tasks.push(() => runner(_function, true));
			}
		});

		// run them serially
		return frappe.run_serially(tasks);
	},
	has_handlers: function(event_name, doctype) {
		let handlers = this.get_handlers(event_name, doctype);
		return handlers && (handlers.old_style.length || handlers.new_style.length);
	},
	get_handlers: function(event_name, doctype) {
		// returns list of all functions to be called (old style and new style)
		let me = this;
		let handlers = {
			old_style: [],
			new_style: []
		};
		if(frappe.ui.form.handlers[doctype] && frappe.ui.form.handlers[doctype][event_name]) {
			$.each(frappe.ui.form.handlers[doctype][event_name], function(i, fn) {
				handlers.new_style.push(fn);
			});
		}
		if(this.frm.cscript[event_name]) {
			handlers.old_style.push(event_name);
		}
		if(this.frm.cscript["custom_" + event_name]) {
			handlers.old_style.push("custom_" + event_name);
		}
		return handlers;
	},
	setup: function() {
		var doctype = this.frm.meta;
		var me = this;

		// js
		var cs = doctype.__js;
		if(cs) {
			var tmp = eval(cs);
		}

		if(doctype.__custom_js) {
			try {
				eval(doctype.__custom_js);
			} catch(e) {
				frappe.msgprint({
					title: __('Error in Custom Script'),
					indicator: 'orange',
					message: '
' + e.stack  + '
'
				});
			}
		}

		function setup_add_fetch(df) {
			if((['Data', 'Read Only', 'Text', 'Small Text', 'Currency',
				'Text Editor', 'Code', 'Link', 'Float', 'Int', 'Date'].includes(df.fieldtype) || df.read_only==1)
				&& df.fetch_from && df.fetch_from.indexOf(".")!=-1) {
				var parts = df.fetch_from.split(".");
				me.frm.add_fetch(parts[0], parts[1], df.fieldname);
			}
		}

		// setup add fetch
		$.each(this.frm.fields, function(i, field) {
			setup_add_fetch(field.df);
			if(field.df.fieldtype==="Table") {
				$.each(frappe.meta.get_docfields(field.df.options, me.frm.docname), function(i, df) {
					setup_add_fetch(df);
				});
			}
		});

		// css
		doctype.__css && frappe.dom.set_style(doctype.__css);

		this.trigger('setup');
	},
	log_error: function(caller, e) {
		frappe.show_alert("Error in Client Script.");
		console.group && console.group();
		console.log("----- error in client script -----");
		console.log("method: " + caller);
		console.log(e);
		console.log("error message: " + e.message);
		console.trace && console.trace();
		console.log("----- end of error message -----");
		console.group && console.groupEnd();
	},
	copy_from_first_row: function(parentfield, current_row, fieldnames) {
		var data = this.frm.doc[parentfield];
		if(data.length===1 || data[0]===current_row) return;

		if(typeof fieldnames==='string') {
			fieldnames = [fieldnames];
		}

		$.each(fieldnames, function(i, fieldname) {
			frappe.model.set_value(current_row.doctype, current_row.name, fieldname,
				data[0][fieldname]);
		});
	}
});
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var mediaObjects = {};

/**
 * This class provides access to the device media, interfaces to both sound and video
 *
 * @constructor
 * @param src                   The file name or url to play
 * @param successCallback       The callback to be called when the file is done playing or recording.
 *                                  successCallback()
 * @param errorCallback         The callback to be called if there is an error.
 *                                  errorCallback(int errorCode) - OPTIONAL
 * @param statusCallback        The callback to be called when media status has changed.
 *                                  statusCallback(int statusCode) - OPTIONAL
 */
var Media = function(src, successCallback, errorCallback, statusCallback) {
    argscheck.checkArgs('SFFF', 'Media', arguments);
    this.id = utils.createUUID();
    mediaObjects[this.id] = this;
    this.src = src;
    this.successCallback = successCallback;
    this.errorCallback = errorCallback;
    this.statusCallback = statusCallback;
    this._duration = -1;
    this._position = -1;
    exec(null, this.errorCallback, "Media", "create", [this.id, this.src]);
};

// Media messages
Media.MEDIA_STATE = 1;
Media.MEDIA_DURATION = 2;
Media.MEDIA_POSITION = 3;
Media.MEDIA_ERROR = 9;

// Media states
Media.MEDIA_NONE = 0;
Media.MEDIA_STARTING = 1;
Media.MEDIA_RUNNING = 2;
Media.MEDIA_PAUSED = 3;
Media.MEDIA_STOPPED = 4;
Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];

// "static" function to return existing objs.
Media.get = function(id) {
    return mediaObjects[id];
};

/**
 * Start or resume playing audio file.
 */
Media.prototype.play = function(options) {
    exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]);
};

/**
 * Stop playing audio file.
 */
Media.prototype.stop = function() {
    var me = this;
    exec(function() {
        me._position = 0;
    }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]);
};

/**
 * Seek or jump to a new time in the track..
 */
Media.prototype.seekTo = function(milliseconds) {
    var me = this;
    exec(function(p) {
        me._position = p;
    }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]);
};

/**
 * Pause playing audio file.
 */
Media.prototype.pause = function() {
    exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]);
};

/**
 * Get duration of an audio file.
 * The duration is only set for audio that is playing, paused or stopped.
 *
 * @return      duration or -1 if not known.
 */
Media.prototype.getDuration = function() {
    return this._duration;
};

/**
 * Get position of audio.
 */
Media.prototype.getCurrentPosition = function(success, fail) {
    var me = this;
    exec(function(p) {
        me._position = p;
        success(p);
    }, fail, "Media", "getCurrentPositionAudio", [this.id]);
};

/**
 * Start recording audio file.
 */
Media.prototype.startRecord = function() {
    exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]);
};

/**
 * Stop recording audio file.
 */
Media.prototype.stopRecord = function() {
    exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]);
};

/**
 * Release the resources.
 */
Media.prototype.release = function() {
    exec(null, this.errorCallback, "Media", "release", [this.id]);
};

/**
 * Adjust the volume.
 */
Media.prototype.setVolume = function(volume) {
    if (device.platform == 'iOS'){
        exec(null, null, "Media", "setVolume", [this.id, volume]);
    } else {
        console.warn('media.setRate method is currently not supported for', device.platform, 'platform.')
    }
};

/**
 * Adjust the playback rate.
 */
Media.prototype.setRate = function(rate) {
    exec(null, null, "Media", "setRate", [this.id, rate]);
};

/**
 * Audio has status update.
 * PRIVATE
 *
 * @param id            The media object id (string)
 * @param msgType       The 'type' of update this is
 * @param value         Use of value is determined by the msgType
 */
Media.onStatus = function(id, msgType, value) {

    var media = mediaObjects[id];

    if(media) {
        switch(msgType) {
            case Media.MEDIA_STATE :
                media.statusCallback && media.statusCallback(value);
                if(value == Media.MEDIA_STOPPED) {
                    media.successCallback && media.successCallback();
                }
                break;
            case Media.MEDIA_DURATION :
                media._duration = value;
                break;
            case Media.MEDIA_ERROR :
                media.errorCallback && media.errorCallback(value);
                break;
            case Media.MEDIA_POSITION :
                media._position = Number(value);
                break;
            default :
                console.error && console.error("Unhandled Media.onStatus :: " + msgType);
                break;
        }
    }
    else {
         console.error && console.error("Received Media.onStatus callback for unknown media :: " + id);
    }

};

module.exports = Media;
<commit_msg>Add iOS platform check in Media.prototype.setRate fix<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var mediaObjects = {};

/**
 * This class provides access to the device media, interfaces to both sound and video
 *
 * @constructor
 * @param src                   The file name or url to play
 * @param successCallback       The callback to be called when the file is done playing or recording.
 *                                  successCallback()
 * @param errorCallback         The callback to be called if there is an error.
 *                                  errorCallback(int errorCode) - OPTIONAL
 * @param statusCallback        The callback to be called when media status has changed.
 *                                  statusCallback(int statusCode) - OPTIONAL
 */
var Media = function(src, successCallback, errorCallback, statusCallback) {
    argscheck.checkArgs('SFFF', 'Media', arguments);
    this.id = utils.createUUID();
    mediaObjects[this.id] = this;
    this.src = src;
    this.successCallback = successCallback;
    this.errorCallback = errorCallback;
    this.statusCallback = statusCallback;
    this._duration = -1;
    this._position = -1;
    exec(null, this.errorCallback, "Media", "create", [this.id, this.src]);
};

// Media messages
Media.MEDIA_STATE = 1;
Media.MEDIA_DURATION = 2;
Media.MEDIA_POSITION = 3;
Media.MEDIA_ERROR = 9;

// Media states
Media.MEDIA_NONE = 0;
Media.MEDIA_STARTING = 1;
Media.MEDIA_RUNNING = 2;
Media.MEDIA_PAUSED = 3;
Media.MEDIA_STOPPED = 4;
Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];

// "static" function to return existing objs.
Media.get = function(id) {
    return mediaObjects[id];
};

/**
 * Start or resume playing audio file.
 */
Media.prototype.play = function(options) {
    exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]);
};

/**
 * Stop playing audio file.
 */
Media.prototype.stop = function() {
    var me = this;
    exec(function() {
        me._position = 0;
    }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]);
};

/**
 * Seek or jump to a new time in the track..
 */
Media.prototype.seekTo = function(milliseconds) {
    var me = this;
    exec(function(p) {
        me._position = p;
    }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]);
};

/**
 * Pause playing audio file.
 */
Media.prototype.pause = function() {
    exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]);
};

/**
 * Get duration of an audio file.
 * The duration is only set for audio that is playing, paused or stopped.
 *
 * @return      duration or -1 if not known.
 */
Media.prototype.getDuration = function() {
    return this._duration;
};

/**
 * Get position of audio.
 */
Media.prototype.getCurrentPosition = function(success, fail) {
    var me = this;
    exec(function(p) {
        me._position = p;
        success(p);
    }, fail, "Media", "getCurrentPositionAudio", [this.id]);
};

/**
 * Start recording audio file.
 */
Media.prototype.startRecord = function() {
    exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]);
};

/**
 * Stop recording audio file.
 */
Media.prototype.stopRecord = function() {
    exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]);
};

/**
 * Release the resources.
 */
Media.prototype.release = function() {
    exec(null, this.errorCallback, "Media", "release", [this.id]);
};

/**
 * Adjust the volume.
 */
Media.prototype.setVolume = function(volume) {
    exec(null, null, "Media", "setVolume", [this.id, volume]);
};

/**
 * Adjust the playback rate.
 */
Media.prototype.setRate = function(rate) {
    if (cordova.platformId === 'ios'){
        exec(null, null, "Media", "setRate", [this.id, rate]);
    } else {
        console.warn('media.setRate method is currently not supported for', cordova.platformId, 'platform.')
    }
};

/**
 * Audio has status update.
 * PRIVATE
 *
 * @param id            The media object id (string)
 * @param msgType       The 'type' of update this is
 * @param value         Use of value is determined by the msgType
 */
Media.onStatus = function(id, msgType, value) {

    var media = mediaObjects[id];

    if(media) {
        switch(msgType) {
            case Media.MEDIA_STATE :
                media.statusCallback && media.statusCallback(value);
                if(value == Media.MEDIA_STOPPED) {
                    media.successCallback && media.successCallback();
                }
                break;
            case Media.MEDIA_DURATION :
                media._duration = value;
                break;
            case Media.MEDIA_ERROR :
                media.errorCallback && media.errorCallback(value);
                break;
            case Media.MEDIA_POSITION :
                media._position = Number(value);
                break;
            default :
                console.error && console.error("Unhandled Media.onStatus :: " + msgType);
                break;
        }
    }
    else {
         console.error && console.error("Received Media.onStatus callback for unknown media :: " + id);
    }

};

module.exports = Media;
<|endoftext|>