<commit_before>define(['itemObjectModel'], function(itemObjectModel) {

  'use strict';

  function open(item) {
    return item.getBytes().then(function(bytes) {
      if (String.fromCharCode.apply(null, bytes.subarray(0, 4)) !== 'RIFX'
        || String.fromCharCode.apply(null, bytes.subarray(8, 12)) !== 'MV93') {
        return Promise.reject('not a MV93 RIFX file');
      }
      var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      if (bytes.length < dv.getUint32(4, false) + 8) {
        return Promise.reject('bad length');
      }
      item.notifyPopulating(new Promise(function(resolve, reject) {
        for (var pos = 12; pos < bytes.length; ) {
          var chunkName = String.fromCharCode.apply(null, bytes.subarray(pos, pos+4));
          var chunkItem = itemObjectModel.createItem(chunkName);
          var chunkLen = dv.getUint32(pos + 4);
          if (chunkLen !== 0) {
            chunkItem.byteSource = item.byteSource.slice(pos + 8, pos + 8 + dv.getUint32(pos + 4));
          }
          switch (chunkName) {
            case 'mmap':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, MMapView.itemPopulator);
              break;
            case 'KEY*':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, KeyStarView.itemPopulator);
              break;
            case 'VWCF':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, VWCFView.itemPopulator);
              break;
            case 'CAS*':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, uint32ArrayItemPopulator);
              break;
          }
          item.addItem(chunkItem);
          pos += 8 + chunkLen + chunkLen % 2;
        }
        resolve(item);
      }));

    });
  }

  function uint32ArrayItemPopulator() {
    var item = this;
    item.notifyPopulating(item.getBytes().then(function(bytes) {
      var array = new Array(bytes.length / 4);
      var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      for (var i = 0; i < array.length; i++) {
        array[i] = dv.getUint32(i * 4, false);
      }
      item.setDataObject(array);
    }));
  }

  function MMapView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  MMapView.itemPopulator = function() {
    var self = this;
    this.notifyPopulating(this.getBytes().then(function(bytes) {
      var mmap = new MMapView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      self.setDataObject(mmap);
    }));
  };
  MMapView.prototype = {
    toJSON: function() {
      return {
        unknown_0x00: this.unknown_0x00,
        unknown_0x04: this.unknown_0x04,
        entries: this.entries,
        unknown_0x0C: this.unknown_0x0C,
        unknown_0x10: this.unknown_0x10,
      };
    },
  };
  Object.defineProperties(MMapView.prototype, {
    unknown_0x00: {
      get: function() {
        return this.dataView.getUint32(0, false);
      },
    },
    unknown_0x04: {
      get: function() {
        return this.dataView.getUint32(4, false);
      },
    },
    entryCount: {
      get: function() {
        return this.dataView.getUint32(8, false);
      },
    },
    unknown_0x0C: {
      get: function() {
        return this.dataView.getUint32(12, false);
      },
    },
    unknown_0x10: {
      get: function() {
        return this.dataView.getUint32(16, false);
      },
    },
    entries: {
      get: function() {
        var entries = new Array(this.entryCount);
        var buffer = this.dataView.buffer, byteOffset = this.dataView.byteOffset;
        for (var i = 0; i < entries.length; i++) {
          entries[i] = new MMapRecordView(
            buffer,
            byteOffset + (i + 1) * MMapRecordView.byteLength,
            MMapRecordView.byteLength);
        }
        return entries;
      },
    },
  });

  function MMapRecordView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
      bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)},
    });
  }
  MMapRecordView.prototype = {
    toJSON: function() {
      if (this.isUnused) return null;
      return {
        unknown1: this.unknown1,
        chunkName: this.chunkName,
        chunkLength: this.chunkLength,
        chunkOffset: this.chunkOffset,
        unknown2: this.unknown2,
      };
    },
  };
  Object.defineProperties(MMapRecordView.prototype, {
    unknown1: {
      get: function() {
        return this.dataView.getUint32(0, false);
      },
    },
    chunkName: {
      get: function() {
        return String.fromCharCode.apply(null, this.bytes.subarray(4, 8));
      },
    },
    isUnused: {
      get: function() {
        switch (this.chunkName) {
          case 'free': case 'junk': return true;
          default: return false;
        }
      },
    },
    chunkLength: {
      get: function() {
        return this.dataView.getUint32(8, false);
      },
    },
    chunkOffset: {
      get: function() {
        return this.dataView.getUint32(12, false);
      },
    },
    unknown2: {
      get: function() {
        return this.dataView.getUint32(16, false);
      },
    },
  });
  MMapRecordView.byteLength = 20;

  function KeyStarView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  KeyStarView.itemPopulator = function() {
    var self = this;
    this.notifyPopulating(this.getBytes().then(function(bytes) {
      self.setDataObject(new KeyStarView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
    }));
  };
  KeyStarView.prototype = {
    toJSON: function() {
      return {
        unknown_0x00: this.unknown_0x00,
        unknown_0x02: this.unknown_0x02,
        unknown_0x04: this.unknown_0x04,
        entries: this.entries,
      };
    },
  };
  Object.defineProperties(KeyStarView.prototype, {
    unknown_0x00: {
      get: function() {
        return this.dataView.getUint16(0, false);
      },
    },
    unknown_0x02: {
      get: function() {
        return this.dataView.getUint16(2, false);
      },
    },
    unknown_0x04: {
      get: function() {
        return this.dataView.getUint32(4, false);
      },
    },
    entryCount: {
      get: function() {
        return this.dataView.getUint32(8, false);
      },
    },
    entries: {
      get: function() {
        var entries = new Array(this.entryCount);
        var buffer = this.dataView.buffer, byteOffset = this.dataView.byteOffset;
        for (var i = 0; i < entries.length; i++) {
          entries[i] = new KeyStarRecordView(
            buffer,
            byteOffset + (i + 1) * KeyStarRecordView.byteLength,
            KeyStarRecordView.byteLength);
        }
        return entries;
      },
    },
  });

  function KeyStarRecordView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
      bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)},
    });
  }
  KeyStarRecordView.prototype = {
    toJSON: function() {
      return {
        parentNumber: this.parentNumber,
        childNumber: this.childNumber,
        childName: this.childName,
      };
    },
  };
  Object.defineProperties(KeyStarRecordView.prototype, {
    childNumber: {
      get: function() {
        return this.dataView.getUint32(0, false);
      },
    },
    parentNumber: {
      get: function() {
        return this.dataView.getUint32(4, false);
      },
    },
    childName: {
      get: function() {
        return String.fromCharCode.apply(null, this.bytes.subarray(8, 12));
      },
    },
  });
  KeyStarRecordView.byteLength = 12;

  function VWCFView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  VWCFView.prototype = {
    toJSON: function() {
      return {
        width: this.width,
        height: this.height,
        frameDuration: this.frameDuration,
        stageColor: this.stageColor,
        defaultPalette: this.defaultPalette,
      };
    },
  };
  VWCFView.itemPopulator = function() {
    var item = this;
    item.notifyPopulating(item.getBytes().then(function(bytes) {
      item.setDataObject(new VWCFView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
    }));
  };
  Object.defineProperties(VWCFView.prototype, {
    frameDuration: {
      get: function() {
        return 1000/this.dataView.getUint8(0x37);
      },
    },
    height: {
      get: function() {
        return this.dataView.getUint16(0x8, false);
      },
    },
    width: {
      get: function() {
        return this.dataView.getUint16(0xA, false);
      },
    },
    stageColor: {
      get: function() {
        return this.dataView.getUint8(0x1B);
      },
    },
    defaultPalette: {
      get: function() {
				return this.dataView.getInt16(0x46, false);
      },
    },
  });

  return open;

});
<commit_msg>Support CASt chunk<commit_after>define(['itemObjectModel', 'mac/roman'], function(itemObjectModel, macintoshRoman) {

  'use strict';

  function open(item) {
    return item.getBytes().then(function(bytes) {
      if (String.fromCharCode.apply(null, bytes.subarray(0, 4)) !== 'RIFX'
        || String.fromCharCode.apply(null, bytes.subarray(8, 12)) !== 'MV93') {
        return Promise.reject('not a MV93 RIFX file');
      }
      var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      if (bytes.length < dv.getUint32(4, false) + 8) {
        return Promise.reject('bad length');
      }
      item.notifyPopulating(new Promise(function(resolve, reject) {
        for (var pos = 12; pos < bytes.length; ) {
          var chunkName = String.fromCharCode.apply(null, bytes.subarray(pos, pos+4));
          var chunkItem = itemObjectModel.createItem(chunkName);
          var chunkLen = dv.getUint32(pos + 4);
          if (chunkLen !== 0) {
            chunkItem.byteSource = item.byteSource.slice(pos + 8, pos + 8 + dv.getUint32(pos + 4));
          }
          switch (chunkName) {
            case 'mmap':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, MMapView.itemPopulator);
              break;
            case 'KEY*':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, KeyStarView.itemPopulator);
              break;
            case 'VWCF':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, VWCFView.itemPopulator);
              break;
            case 'CAS*':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, uint32ArrayItemPopulator);
              break;
            case 'CASt':
              chunkItem.startAddingItems();
              chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, CastView.itemPopulator);
              break;
          }
          item.addItem(chunkItem);
          pos += 8 + chunkLen + chunkLen % 2;
        }
        resolve(item);
      }));

    });
  }

  function uint32ArrayItemPopulator() {
    var item = this;
    item.notifyPopulating(item.getBytes().then(function(bytes) {
      var array = new Array(bytes.length / 4);
      var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      for (var i = 0; i < array.length; i++) {
        array[i] = dv.getUint32(i * 4, false);
      }
      item.setDataObject(array);
    }));
  }

  function MMapView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  MMapView.itemPopulator = function() {
    var self = this;
    this.notifyPopulating(this.getBytes().then(function(bytes) {
      var mmap = new MMapView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      self.setDataObject(mmap);
    }));
  };
  MMapView.prototype = {
    toJSON: function() {
      return {
        unknown_0x00: this.unknown_0x00,
        unknown_0x04: this.unknown_0x04,
        entries: this.entries,
        unknown_0x0C: this.unknown_0x0C,
        unknown_0x10: this.unknown_0x10,
      };
    },
  };
  Object.defineProperties(MMapView.prototype, {
    unknown_0x00: {
      get: function() {
        return this.dataView.getUint32(0, false);
      },
    },
    unknown_0x04: {
      get: function() {
        return this.dataView.getUint32(4, false);
      },
    },
    entryCount: {
      get: function() {
        return this.dataView.getUint32(8, false);
      },
    },
    unknown_0x0C: {
      get: function() {
        return this.dataView.getUint32(12, false);
      },
    },
    unknown_0x10: {
      get: function() {
        return this.dataView.getUint32(16, false);
      },
    },
    entries: {
      get: function() {
        var entries = new Array(this.entryCount);
        var buffer = this.dataView.buffer, byteOffset = this.dataView.byteOffset;
        for (var i = 0; i < entries.length; i++) {
          entries[i] = new MMapRecordView(
            buffer,
            byteOffset + (i + 1) * MMapRecordView.byteLength,
            MMapRecordView.byteLength);
        }
        return entries;
      },
    },
  });

  function MMapRecordView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
      bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)},
    });
  }
  MMapRecordView.prototype = {
    toJSON: function() {
      if (this.isUnused) return null;
      return {
        unknown1: this.unknown1,
        chunkName: this.chunkName,
        chunkLength: this.chunkLength,
        chunkOffset: this.chunkOffset,
        unknown2: this.unknown2,
      };
    },
  };
  Object.defineProperties(MMapRecordView.prototype, {
    unknown1: {
      get: function() {
        return this.dataView.getUint32(0, false);
      },
    },
    chunkName: {
      get: function() {
        return String.fromCharCode.apply(null, this.bytes.subarray(4, 8));
      },
    },
    isUnused: {
      get: function() {
        switch (this.chunkName) {
          case 'free': case 'junk': return true;
          default: return false;
        }
      },
    },
    chunkLength: {
      get: function() {
        return this.dataView.getUint32(8, false);
      },
    },
    chunkOffset: {
      get: function() {
        return this.dataView.getUint32(12, false);
      },
    },
    unknown2: {
      get: function() {
        return this.dataView.getUint32(16, false);
      },
    },
  });
  MMapRecordView.byteLength = 20;

  function KeyStarView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  KeyStarView.itemPopulator = function() {
    var self = this;
    this.notifyPopulating(this.getBytes().then(function(bytes) {
      self.setDataObject(new KeyStarView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
    }));
  };
  KeyStarView.prototype = {
    toJSON: function() {
      return {
        unknown_0x00: this.unknown_0x00,
        unknown_0x02: this.unknown_0x02,
        unknown_0x04: this.unknown_0x04,
        entries: this.entries,
      };
    },
  };
  Object.defineProperties(KeyStarView.prototype, {
    unknown_0x00: {
      get: function() {
        return this.dataView.getUint16(0, false);
      },
    },
    unknown_0x02: {
      get: function() {
        return this.dataView.getUint16(2, false);
      },
    },
    unknown_0x04: {
      get: function() {
        return this.dataView.getUint32(4, false);
      },
    },
    entryCount: {
      get: function() {
        return this.dataView.getUint32(8, false);
      },
    },
    entries: {
      get: function() {
        var entries = new Array(this.entryCount);
        var buffer = this.dataView.buffer, byteOffset = this.dataView.byteOffset;
        for (var i = 0; i < entries.length; i++) {
          entries[i] = new KeyStarRecordView(
            buffer,
            byteOffset + (i + 1) * KeyStarRecordView.byteLength,
            KeyStarRecordView.byteLength);
        }
        return entries;
      },
    },
  });

  function KeyStarRecordView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
      bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)},
    });
  }
  KeyStarRecordView.prototype = {
    toJSON: function() {
      return {
        parentNumber: this.parentNumber,
        childNumber: this.childNumber,
        childName: this.childName,
      };
    },
  };
  Object.defineProperties(KeyStarRecordView.prototype, {
    childNumber: {
      get: function() {
        return this.dataView.getUint32(0, false);
      },
    },
    parentNumber: {
      get: function() {
        return this.dataView.getUint32(4, false);
      },
    },
    childName: {
      get: function() {
        return String.fromCharCode.apply(null, this.bytes.subarray(8, 12));
      },
    },
  });
  KeyStarRecordView.byteLength = 12;

  function VWCFView(buffer, byteOffset, byteLength) {
    Object.defineProperties(this, {
      dataView: {value:new DataView(buffer, byteOffset, byteLength)},
    });
  }
  VWCFView.prototype = {
    toJSON: function() {
      return {
        width: this.width,
        height: this.height,
        frameDuration: this.frameDuration,
        stageColor: this.stageColor,
        defaultPalette: this.defaultPalette,
      };
    },
  };
  VWCFView.itemPopulator = function() {
    var item = this;
    item.notifyPopulating(item.getBytes().then(function(bytes) {
      item.setDataObject(new VWCFView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
    }));
  };
  Object.defineProperties(VWCFView.prototype, {
    frameDuration: {
      get: function() {
        return 1000/this.dataView.getUint8(0x37);
      },
    },
    height: {
      get: function() {
        return this.dataView.getUint16(0x8, false);
      },
    },
    width: {
      get: function() {
        return this.dataView.getUint16(0xA, false);
      },
    },
    stageColor: {
      get: function() {
        return this.dataView.getUint8(0x1B);
      },
    },
    defaultPalette: {
      get: function() {
        return this.dataView.getInt16(0x46, false);
      },
    },
  });

  function CAStItemPopulator() {
    var item = this;
    item.notifyPopulating(item.getBytes().then(function(CASt) {
      var data1 = new DataView(
        CASt.buffer,
        CASt.byteOffset + 2 + 4,
        CASt.getUint16(0, false));
      var dataObject;
      if (data1.byteLength >= 12) {
        dataObject.rectTop = data1.getInt16(4, false);
        dataObject.rectLeft = data1.getInt16(6, false);
        dataObject.rectBottom = data1.getInt16(8, false);
        dataObject.rectRight = data1.getInt16(10, false);
        if (data1.byteLength >= 24) {
          dataObject.regPointY = data1.getInt16(20, false);
          dataObject.regPointX = data1.getInt16(22, false);
          if (data1.byteLength >= 26) {
            dataObject.bitsPerPixel = data1.getUint8(25);
            if (data1.byteLength >= 28) {
              dataObject.palette = data1.getUint16(26, false);
            }
          }
        }
      }
      var data2Len = CASt.getUint32(2, false);
      if (data2Len > 0) {
        var pos = 2 + 4 + data1.byteLength;
        var data2 = new DataView(CASt.buffer, CASt.byteOffset + pos, 20);
        if (data2.getUint32(0, false) !== 20) {
          return Promise.reject('CASt data chunk is not 20 bytes as expected');
        }
        pos += 20;
        var moreData = [];
        var moreDataCount = CASt.getUint16(pos, false);
        pos += 2;
        var moreDataBase = pos + (moreDataCount + 1) * 4;
        for (var i = 0; i < moreDataCount; i++) {
          var offset = CASt.getUint32(pos + i * 4, false);
          var length = CASt.getUint32(pos + (i + 1) * 4, false) - offset;
          if (length === 0) {
            moreData.push(null);
          }
          else {
            moreData.push(new Uint8Array(CASt.buffer, CASt.byteOffset + moreDataBase + offset, length));
          }
        }
        if (moreData[0]) {
          itemObject.scriptText = macintoshRoman(moreData[0], 0, moreData[0].byteLength);
        }
        if (moreData[1]) {
          itemObject.castName = macintoshRoman(moreData[1], 1, moreData[1][0]);
        }
        if (moreData[2]) {
          itemObject.folder = macintoshRoman(moreData[2], 1, moreData[2][0]);
        }
        if (moreData[3]) {
          itemObject.fileName = macintoshRoman(moreData[3], 1, moreData[3][0]);
        }
        if (moreData[4]) {
          itemObject.fileType = macintoshRoman(moreData[4], 0, 4);
        }
      }
      item.setDataObject(dataObject);
    }));
  }

  return open;

});
<|endoftext|>


<commit_before>/* This software is licensed under a BSD license; see the LICENSE file for details. */

(function () {
var soundId = 0;

define_ibex_controller({
name: "FlashSentence",

jqueryWidget: {
    _init: function () {
        var self = this;
        self.cssPrefix = self.options._cssPrefix;

        var $loading;
        var doneLoading = false;
        if (typeof(self.options.s) != "string") {
            if (self.options.s.audio) {
                if (self.options.audioMessage) {
                    self.element.append($loading = $("<div>").addClass(self.cssPrefix + 'loading'));
                    setTimeout(function () {
                        if (! doneLoading)
                            $loading.text(conf_loadingMessage);
                    }, 250);
                }
                withSoundManager(completeInit);
            }
            else {
                self.sentenceDom = htmlCodeToDOM(self.options.s)
                completeInit();
            }
        }
        else {
            self.sentenceDom = $("<div>").text(self.options.s);
            completeInit();
        }

        function completeInit(sm) {
            if (sm) {
                if (self.options.audioMessage) {
                    if (typeof(self.options.audioMessage) != "string")
                        self.sentenceDom = htmlCodeToDOM(self.options.audioMessage);
                    else
                        self.sentenceDom = $("<div>").text(self.options.audioMessage);
                }
                var name = self.options.s.audio;
                var url = __server_py_script_name__ + '?resource=' + escape(name);
                self.sid = soundId++;
                sm.createSound('sound' + self.sid, url);

                if (self.options.audioTrigger == "click") {
                    self.sentenceDom.css('cursor', 'pointer');
                    self.sentenceDom.click(function () {
                        sm.play('sound' + self.sid);
                    });
                }
                else { // Immediate
                    sm.play('sound' + self.sid);
                }
            }

            self.finishedCallback = self.options._finishedCallback;
            self.utils = self.options._utils;

            self.timeout = dget(self.options, "timeout", 2000);

            self.sentenceDescType = dget(self.options, "sentenceDescType", "literal");
            assert(self.sentenceDescType == "md5" || self.sentenceDescType == "literal", "Bad value for 'sentenceDescType' option of FlashSentence controller.");
            if (self.sentenceDescType == "md5") {
                alert("'md5' value no longer supported for 'sentenceDescType' option of FlashSentence controller");
                throw "Bad option to FlashSentence";
            }
            else {
                self.sentenceMD5 = csv_url_encode(self.options.s.html ? self.options.s.html : (self.options.s.audio ? self.options.s.audio : (self.options.s+'')));
            }

            self.element.addClass(self.cssPrefix + "flashed-sentence");
            if (self.sentenceDom) {
                if ($loading) {
                    doneLoading = true;
                    $loading.replaceWith(self.sentenceDom)
                }
                else
                    self.element.append(self.sentenceDom);
            }

            if (self.timeout) {
                var t = this;
                self.utils.setTimeout(function() {
                    t.finishedCallback([[["Sentence (or sentence MD5)", t.sentenceMD5]]]);
                }, self.timeout);
            }
            else {
                // Give results without actually finishing.
                if (self.utils.setResults)
                    self.utils.setResults([[["Sentence (or sentence MD5)", self.sentenceMD5]]]);
            }
        }
    }
},

properties: {
    obligatory: ["s"],
    htmlDescription: function (opts) {
        return $(document.createElement("div")).text(opts.s)[0];
    }
}
});

})();
<commit_msg>Minor.<commit_after>/* This software is licensed under a BSD license; see the LICENSE file for details. */

(function () {
var soundId = 0;

define_ibex_controller({
name: "FlashSentence",

jqueryWidget: {
    _init: function () {
        var self = this;
        self.cssPrefix = self.options._cssPrefix;

        var $loading;
        var doneLoading = false;
        if (typeof(self.options.s) != "string") {
            if (self.options.s.audio) {
                if (self.options.audioMessage) {
                    self.element.append($loading = $("<div>").addClass(self.cssPrefix + 'loading'));
                    setTimeout(function () {
                        if (! doneLoading)
                            $loading.text(conf_loadingMessage);
                    }, 250);
                }
                withSoundManager(completeInit);
            }
            else {
                self.sentenceDom = htmlCodeToDOM(self.options.s)
                completeInit();
            }
        }
        else {
            self.sentenceDom = $("<div>").text(self.options.s);
            completeInit();
        }

        function completeInit(sm) {
            if (sm) {
                if (self.options.audioMessage) {
                    if (typeof(self.options.audioMessage) != "string") {
                        alert("HH");
                        self.sentenceDom = htmlCodeToDOM(self.options.audioMessage);
                    }
                    else {
                        alert("YY");
                        self.sentenceDom = $("<div>").text(self.options.audioMessage);
                    }
                    alert(self.sentenceDom);
                }
                var name = self.options.s.audio;
                var url = __server_py_script_name__ + '?resource=' + escape(name);
                self.sid = soundId++;
                sm.createSound('sound' + self.sid, url);

                if (self.options.audioTrigger == "click") {
                    self.sentenceDom.css('cursor', 'pointer');
                    self.sentenceDom.click(function () {
                        sm.play('sound' + self.sid);
                    });
                }
                else { // Immediate
                    sm.play('sound' + self.sid);
                }
            }

            self.finishedCallback = self.options._finishedCallback;
            self.utils = self.options._utils;

            self.timeout = dget(self.options, "timeout", 2000);

            self.sentenceDescType = dget(self.options, "sentenceDescType", "literal");
            assert(self.sentenceDescType == "md5" || self.sentenceDescType == "literal", "Bad value for 'sentenceDescType' option of FlashSentence controller.");
            if (self.sentenceDescType == "md5") {
                alert("'md5' value no longer supported for 'sentenceDescType' option of FlashSentence controller");
                throw "Bad option to FlashSentence";
            }
            else {
                self.sentenceMD5 = csv_url_encode(self.options.s.html ? self.options.s.html : (self.options.s.audio ? self.options.s.audio : (self.options.s+'')));
            }

            self.element.addClass(self.cssPrefix + "flashed-sentence");
            if (self.sentenceDom) {
                if ($loading) {
                    doneLoading = true;
                    $loading.replaceWith(self.sentenceDom)
                }
                else
                    self.element.append(self.sentenceDom);
            }

            if (self.timeout) {
                var t = this;
                self.utils.setTimeout(function() {
                    t.finishedCallback([[["Sentence (or sentence MD5)", t.sentenceMD5]]]);
                }, self.timeout);
            }
            else {
                // Give results without actually finishing.
                if (self.utils.setResults)
                    self.utils.setResults([[["Sentence (or sentence MD5)", self.sentenceMD5]]]);
            }
        }
    }
},

properties: {
    obligatory: ["s"],
    htmlDescription: function (opts) {
        return $(document.createElement("div")).text(opts.s)[0];
    }
}
});

})();
<|endoftext|>


<commit_before>import 'source-map-support/register'

import chalk from 'chalk'
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
import cluster from 'cluster'

import ServiceLocator from '+/ServiceLocator'
import EventBus from './bus'

import createMiddlewares from './middlewares'
import createLogger from './logger'
import createSecurity from './security'
import createNotifications from './notifications'
import createHearMiddleware from './hear'
import createDatabase from './database'
import createLicensing from './licensing'
import createAbout from './about'
import createModules from './modules'
import createUMM from './umm'
import createConversations from './conversations'
import stats from './stats'
import packageJson from '../package.json'
import createEmails from '+/emails'
import createMediator from '+/mediator'

import createServer from './server'

import { getBotpressVersion } from './util'

import {
  isDeveloping,
  print
} from './util'

const RESTART_EXIT_CODE = 107

const getDataLocation = (dataDir, projectLocation) => (
  dataDir && path.isAbsolute(dataDir)
    ? path.resolve(dataDir)
    : path.resolve(projectLocation, dataDir || 'data')
)

const mkdirIfNeeded = (path, logger) => {
  if (!fs.existsSync(path)) {
    logger.info(`Creating data directory: ${path}`)

    try {
      fs.mkdirSync(path)
    } catch (err) {
      logger.error(`[FATAL] Error creating directory: ${err.message}`)
      process.exit(1)
    }
  }
}

/**
 * Global context botpress
*/
class botpress {
  /**
   * Create botpress
   *
   * @param {string} obj.botfile - the config path
   */
  constructor({ botfile }) {
    this.version = getBotpressVersion()
    /**
     * The project location, which is the folder where botfile.js located
     */
    this.projectLocation = path.dirname(botfile)

    /**
     * The botfile config object
     */
    this.botfile = eval('require')(botfile)

    this.stats = stats(this.botfile)

    this.interval = null
  }

  /**
   * Start the bot instance
   *
   * It will do the following initiation steps:
   *
   * 1. setup logger
   * 2. resolve paths (dataLocation)
   * 3. inject security functions
   * 4. load modules
   */
  _start() {

    this.stats.track('bot', 'started')

    if (!this.interval) {
      this.inverval = setInterval(() => {
        this.stats.track('bot', 'running')
      }, 30 * 1000)
    }

    // change the current working directory to botpress's installation path
    // the bot's location is kept in this.projectLocation
    process.chdir(path.join(__dirname, '../'))

    const { projectLocation, botfile } = this

    const isFirstRun = fs.existsSync(path.join(projectLocation, '.welcome'))
    const dataLocation = getDataLocation(botfile.dataDir, projectLocation)
    const modulesConfigDir = getDataLocation(botfile.modulesConfigDir, projectLocation)
    const dbLocation = path.join(dataLocation, 'db.sqlite')
    const version = packageJson.version

    const logger = createLogger(dataLocation, botfile.log)
    mkdirIfNeeded(dataLocation, logger)
    mkdirIfNeeded(modulesConfigDir, logger)

    logger.info(`Starting botpress version ${version}`)

    const db = createDatabase({
      sqlite: { location: dbLocation },
      postgres: botfile.postgres
    })

    const security = createSecurity({
      dataLocation,
      securityConfig: botfile.login,
      db
    })

    const modules = createModules(logger, projectLocation, dataLocation, db.kvs)

    const moduleDefinitions = modules._scan()

    const events = new EventBus()
    const notifications = createNotifications(dataLocation, botfile.notification, moduleDefinitions, events, logger)
    const about = createAbout(projectLocation)
    const licensing = createLicensing({ logger, projectLocation, version, db, botfile })
    const middlewares = createMiddlewares(this, dataLocation, projectLocation, logger)
    const { hear, middleware: hearMiddleware } = createHearMiddleware()
    const emails = createEmails({ emailConfig: botfile.emails })
    const mediator = createMediator(this)
    const convo = createConversations({ logger, middleware: middlewares })
    const umm = createUMM({ logger })

    middlewares.register(hearMiddleware)

    _.assign(this, {
      dataLocation,
      isFirstRun,
      version,
      logger,
      security, // login, authenticate, getSecret
      events,
      notifications,    // load, save, send
      about,
      middlewares,
      hear,
      licensing,
      modules,
      db,
      emails,
      mediator,
      convo,
      umm
    })

    ServiceLocator.init({ bp: this })

    const loadedModules = modules._load(moduleDefinitions, this)

    this.stats.track('bot', 'modules', 'loaded', loadedModules.length)

    _.assign(this, {
      _loadedModules: loadedModules
    })

    mediator.install()

    const server = createServer(this)
    server.start()
    .then(() => {
      events.emit('ready')
      for (let mod of _.values(loadedModules)) {
        mod.handlers.ready && mod.handlers.ready(this, mod.configuration)
      }

      const { port } = botfile
      logger.info(chalk.green.bold('Bot launched. Visit: http://localhost:' + port))
    })

    const projectEntry = eval('require')(projectLocation)
    if (typeof(projectEntry) === 'function') {
      projectEntry.call(projectEntry, this)
    } else {
      logger.error('[FATAL] The bot entry point must be a function that takes an instance of bp')
      process.exit(1)
    }

    process.on('uncaughtException', err => {
      logger.error('[FATAL] An unhandled exception occured in your bot', err)
      if (isDeveloping) {
        logger.error(err.stack)
      }

      this.stats.trackException(err.message)
      process.exit(1)
    })

    process.on('unhandledRejection', (reason, p) => {
      logger.error('Unhandled Rejection in Promise: ', p, 'Reason:', reason)

      this.stats.trackException(reason)
      if (isDeveloping && reason && reason.stack) {
        logger.error(reason.stack)
      }
    })
  }

  start() {
    if (cluster.isMaster) {
      cluster.fork()

      cluster.on('exit', (worker, code /* , signal */) => {
        if (code === RESTART_EXIT_CODE) {
          cluster.fork()

          this.stats.track('bot', 'restarted')
          print('info', '*** restarted worker process ***')
        } else {
          process.exit(code)
        }
      })
    }

    if (cluster.isWorker) {
      this._start()
    }
  }

  restart(interval = 0) {
    setTimeout(() => {
      process.exit(RESTART_EXIT_CODE)
    }, interval)
  }
}

module.exports = botpress
<commit_msg>Commented out UMM<commit_after>import 'source-map-support/register'

import chalk from 'chalk'
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
import cluster from 'cluster'

import ServiceLocator from '+/ServiceLocator'
import EventBus from './bus'

import createMiddlewares from './middlewares'
import createLogger from './logger'
import createSecurity from './security'
import createNotifications from './notifications'
import createHearMiddleware from './hear'
import createDatabase from './database'
import createLicensing from './licensing'
import createAbout from './about'
import createModules from './modules'
import createUMM from './umm'
import createConversations from './conversations'
import stats from './stats'
import packageJson from '../package.json'
import createEmails from '+/emails'
import createMediator from '+/mediator'

import createServer from './server'

import { getBotpressVersion } from './util'

import {
  isDeveloping,
  print
} from './util'

const RESTART_EXIT_CODE = 107

const getDataLocation = (dataDir, projectLocation) => (
  dataDir && path.isAbsolute(dataDir)
    ? path.resolve(dataDir)
    : path.resolve(projectLocation, dataDir || 'data')
)

const mkdirIfNeeded = (path, logger) => {
  if (!fs.existsSync(path)) {
    logger.info(`Creating data directory: ${path}`)

    try {
      fs.mkdirSync(path)
    } catch (err) {
      logger.error(`[FATAL] Error creating directory: ${err.message}`)
      process.exit(1)
    }
  }
}

/**
 * Global context botpress
*/
class botpress {
  /**
   * Create botpress
   *
   * @param {string} obj.botfile - the config path
   */
  constructor({ botfile }) {
    this.version = getBotpressVersion()
    /**
     * The project location, which is the folder where botfile.js located
     */
    this.projectLocation = path.dirname(botfile)

    /**
     * The botfile config object
     */
    this.botfile = eval('require')(botfile)

    this.stats = stats(this.botfile)

    this.interval = null
  }

  /**
   * Start the bot instance
   *
   * It will do the following initiation steps:
   *
   * 1. setup logger
   * 2. resolve paths (dataLocation)
   * 3. inject security functions
   * 4. load modules
   */
  _start() {

    this.stats.track('bot', 'started')

    if (!this.interval) {
      this.inverval = setInterval(() => {
        this.stats.track('bot', 'running')
      }, 30 * 1000)
    }

    // change the current working directory to botpress's installation path
    // the bot's location is kept in this.projectLocation
    process.chdir(path.join(__dirname, '../'))

    const { projectLocation, botfile } = this

    const isFirstRun = fs.existsSync(path.join(projectLocation, '.welcome'))
    const dataLocation = getDataLocation(botfile.dataDir, projectLocation)
    const modulesConfigDir = getDataLocation(botfile.modulesConfigDir, projectLocation)
    const dbLocation = path.join(dataLocation, 'db.sqlite')
    const version = packageJson.version

    const logger = createLogger(dataLocation, botfile.log)
    mkdirIfNeeded(dataLocation, logger)
    mkdirIfNeeded(modulesConfigDir, logger)

    logger.info(`Starting botpress version ${version}`)

    const db = createDatabase({
      sqlite: { location: dbLocation },
      postgres: botfile.postgres
    })

    const security = createSecurity({
      dataLocation,
      securityConfig: botfile.login,
      db
    })

    const modules = createModules(logger, projectLocation, dataLocation, db.kvs)

    const moduleDefinitions = modules._scan()

    const events = new EventBus()
    const notifications = createNotifications(dataLocation, botfile.notification, moduleDefinitions, events, logger)
    const about = createAbout(projectLocation)
    const licensing = createLicensing({ logger, projectLocation, version, db, botfile })
    const middlewares = createMiddlewares(this, dataLocation, projectLocation, logger)
    const { hear, middleware: hearMiddleware } = createHearMiddleware()
    const emails = createEmails({ emailConfig: botfile.emails })
    const mediator = createMediator(this)
    const convo = createConversations({ logger, middleware: middlewares })
    //const umm = createUMM({ logger })

    middlewares.register(hearMiddleware)

    _.assign(this, {
      dataLocation,
      isFirstRun,
      version,
      logger,
      security, // login, authenticate, getSecret
      events,
      notifications,    // load, save, send
      about,
      middlewares,
      hear,
      licensing,
      modules,
      db,
      emails,
      mediator,
      convo
      //umm
    })

    ServiceLocator.init({ bp: this })

    const loadedModules = modules._load(moduleDefinitions, this)

    this.stats.track('bot', 'modules', 'loaded', loadedModules.length)

    _.assign(this, {
      _loadedModules: loadedModules
    })

    mediator.install()

    const server = createServer(this)
    server.start()
    .then(() => {
      events.emit('ready')
      for (let mod of _.values(loadedModules)) {
        mod.handlers.ready && mod.handlers.ready(this, mod.configuration)
      }

      const { port } = botfile
      logger.info(chalk.green.bold('Bot launched. Visit: http://localhost:' + port))
    })

    const projectEntry = eval('require')(projectLocation)
    if (typeof(projectEntry) === 'function') {
      projectEntry.call(projectEntry, this)
    } else {
      logger.error('[FATAL] The bot entry point must be a function that takes an instance of bp')
      process.exit(1)
    }

    process.on('uncaughtException', err => {
      logger.error('[FATAL] An unhandled exception occured in your bot', err)
      if (isDeveloping) {
        logger.error(err.stack)
      }

      this.stats.trackException(err.message)
      process.exit(1)
    })

    process.on('unhandledRejection', (reason, p) => {
      logger.error('Unhandled Rejection in Promise: ', p, 'Reason:', reason)

      this.stats.trackException(reason)
      if (isDeveloping && reason && reason.stack) {
        logger.error(reason.stack)
      }
    })
  }

  start() {
    if (cluster.isMaster) {
      cluster.fork()

      cluster.on('exit', (worker, code /* , signal */) => {
        if (code === RESTART_EXIT_CODE) {
          cluster.fork()

          this.stats.track('bot', 'restarted')
          print('info', '*** restarted worker process ***')
        } else {
          process.exit(code)
        }
      })
    }

    if (cluster.isWorker) {
      this._start()
    }
  }

  restart(interval = 0) {
    setTimeout(() => {
      process.exit(RESTART_EXIT_CODE)
    }, interval)
  }
}

module.exports = botpress
<|endoftext|>


<commit_before>'use strict';

/**
 * User service. Wraps fetch to/from server and local storage to deal
 * with information about the user/player.
 *
 * @ngdoc service
 * @name playerApp.user
 * @description
 * # user
 * Factory in the playerApp.
 */
angular.module('playerApp')
  .factory('user',
  [          '$log','$state','API','$http',
    function ($log,  $state,  API,  $http) {

    var user = {};

    user.profile = {};

    user.rules = {}
    user.rules.nameRule = "At least 3 characters, no spaces.";
    user.rules.namePattern = /^\w{3,}$/;
    user.rules.colorRule = "At least 3 characters, no spaces.";
    user.rules.colorPattern = /^\w{3,}$/;

    user.load = function(id,name) {

      $log.debug('quering token %o',localStorage.token);

	  //we're using the id from the token introspect as our player db id.
	  user.profile.id = id;

      // Load the user's information from the DB and/or session
      // Load needs to come from the Auth token
      var playerURL = API.PROFILE_URL + user.profile.id;
      var parameters = {};
      var q;

      // Fetch data about the user
      $log.debug('fetch data from %o', playerURL);
      q = $http({
          method : 'GET',
          url : playerURL,
          cache : false,
          params : parameters
      }).then(function(response) {
          $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);

          var tmp = angular.fromJson(response.data);
          user.profile.name = tmp.name;
          user.profile.favoriteColor = tmp.favoriteColor;

          return true;
      }, function(response) {
        $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);

        // go to the sad room.. (Can't find the player information)
        // or back to the login/registration screen? or..
        user.profile.name = name;
        return false;
      });

      return q;
    };

    user.save = function() {
      $log.debug("Saving user data: %o", user.profile);
      // SAVE GOES HERE -- save needs to test for ID uniqueness.. so only go on to
      // the next room if all data could validate properly.

      //save is a request to create,

      var playerURL = API.PROFILE_URL;

      var q = $http({
        method : 'POST',
        url : playerURL,
        cache : false,
        data : user.profile
      }).then(function(response) {
        $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);
        $state.go('play.room');

      }, function(response) {
        $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);

        // go to the sad room.. (Can't find the player information)
        // or back to the login/registration screen? or..
      });

    };

    return user;
  }]);<commit_msg>Convert usernames with spaces from fb/twttr into _ names<commit_after>'use strict';

/**
 * User service. Wraps fetch to/from server and local storage to deal
 * with information about the user/player.
 *
 * @ngdoc service
 * @name playerApp.user
 * @description
 * # user
 * Factory in the playerApp.
 */
angular.module('playerApp')
  .factory('user',
  [          '$log','$state','API','$http',
    function ($log,  $state,  API,  $http) {

    var user = {};

    user.profile = {};

    user.rules = {}
    user.rules.nameRule = "At least 3 characters, no spaces.";
    user.rules.namePattern = /^\w{3,}$/;
    user.rules.colorRule = "At least 3 characters, no spaces.";
    user.rules.colorPattern = /^\w{3,}$/;

    user.load = function(id,name) {

      $log.debug('quering token %o',localStorage.token);

	  //we're using the id from the token introspect as our player db id.
	  user.profile.id = id;

      // Load the user's information from the DB and/or session
      // Load needs to come from the Auth token
      var playerURL = API.PROFILE_URL + user.profile.id;
      var parameters = {};
      var q;

      // Fetch data about the user
      $log.debug('fetch data from %o', playerURL);
      q = $http({
          method : 'GET',
          url : playerURL,
          cache : false,
          params : parameters
      }).then(function(response) {
          $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);

          var tmp = angular.fromJson(response.data);
          user.profile.name = tmp.name;
          user.profile.favoriteColor = tmp.favoriteColor;

          return true;
      }, function(response) {
        $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);

        // go to the sad room.. (Can't find the player information)
        // or back to the login/registration screen? or..
        user.profile.name = name.replace(/ /g , '_');
        return false;
      });

      return q;
    };

    user.save = function() {
      $log.debug("Saving user data: %o", user.profile);
      // SAVE GOES HERE -- save needs to test for ID uniqueness.. so only go on to
      // the next room if all data could validate properly.

      //save is a request to create,

      var playerURL = API.PROFILE_URL;

      var q = $http({
        method : 'POST',
        url : playerURL,
        cache : false,
        data : user.profile
      }).then(function(response) {
        $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);
        $state.go('play.room');

      }, function(response) {
        $log.debug(response.status + ' ' + response.statusText + ' ' + playerURL);

        // go to the sad room.. (Can't find the player information)
        // or back to the login/registration screen? or..
      });

    };

    return user;
  }]);<|endoftext|>


<commit_before>angular.module("app").factory('AuthenticationService', function($http) {
  // these routes are configured in config/server.js
  return {
    login: function(credentials) {
      return $http.post('/login', credentials);
    },
    logout: function() {
      return $http.post('/logout');
    }
  };
});
<commit_msg>[balrog-ui] Update authentication_service.js<commit_after>angular.module("app").factory('AuthenticationService', function($http) {
  // these routes map to stubbed API endpoints in config/server.js
  return {
    login: function(credentials) {
      return $http.post('/login', credentials);
    },
    logout: function() {
      return $http.post('/logout');
    }
  };
});
<|endoftext|>


<commit_before>angular.module('orderCloud')
    .factory('ocAuthNet', AuthorizeNet)
;

function AuthorizeNet( $q, $resource, OrderCloudSDK, apiurl, ocCreditCardUtility) {
    return {
        'CreateCreditCard': _createCreateCard,
        'UpdateCreditCard': _updateCreditCard,
        'DeleteCreditCard' : _deleteCreditCard,
        'MakeAuthnetCall' : _makeApiCall

    };

    function _createCreateCard(creditCard, buyerID) {
        var ExpirationDate = ocCreditCardUtility.ExpirationDateFormat(creditCard.ExpirationMonth, creditCard.ExpirationYear);
        return _makeApiCall('POST', {
            'buyerID' : buyerID,
            'TransactionType' : 'createCreditCard',
            'CardDetails' : {
                'CardholderName' : creditCard.CardholderName,
                'CardType' : creditCard.CardType,
                'CardNumber' : creditCard.CardNumber,
                'ExpirationDate' : ExpirationDate,
                'CardCode' : creditCard.CardCode
            }
        });
    }

    function _updateCreditCard(creditCard, buyerID) {
        var ExpirationDate = ocCreditCardUtility.ExpirationDateFormat(creditCard.ExpirationMonth, creditCard.ExpirationYear);
        return _makeApiCall('POST', {
            'buyerID' : buyerID,
            'TransactionType' : 'updateCreditCard',
            'CardDetails' : {
                'CreditCardID' : creditCard.ID,
                'CardholderName' : creditCard.CardholderName,
                'CardType' : creditCard.CardType,
                'CardNumber' : 'XXXX'+ creditCard.PartialAccountNumber,
                'ExpirationDate' : ExpirationDate
            }
        });

    }
    function _deleteCreditCard(creditCard, buyerID) {
        return _makeApiCall('POST', {
            'buyerID': buyerID,
            'TransactionType': 'deleteCreditCard',
            'CardDetails': {
                'CreditCardID': creditCard.ID
            }
        });
    }

    function _makeApiCall(method, requestBody) {
        var apiUrl = apiurl +'/v1/integrationproxy/authorizenettest';
        var d = $q.defer();
        $resource(apiUrl, null, {
            callApi: {
                method: method,
                headers: {
                    'Authorization': 'Bearer ' + OrderCloudSDK.GetToken()
                }
            }
        }).callApi(requestBody).$promise
            .then(function(data) {
                d.resolve(data);
            })
            .catch(function(ex) {
                d.reject(ex);
            });
        return d.promise;
    }
}<commit_msg>feat: add authorize and capture call to ocAuth service<commit_after>angular.module('orderCloud')
    .factory('ocAuthNet', AuthorizeNet)
;

function AuthorizeNet( $q, $resource, OrderCloudSDK, apiurl, ocCreditCardUtility) {
    return {
        'CreateCreditCard': _createCreateCard,
        'UpdateCreditCard': _updateCreditCard,
        'DeleteCreditCard' : _deleteCreditCard,
        'AuthCaptureTransaction': _authCaptureTransaction,
        'MakeAuthnetCall' : _makeApiCall

    };

    function _createCreateCard(creditCard, buyerID) {
        var ExpirationDate = ocCreditCardUtility.ExpirationDateFormat(creditCard.ExpirationMonth, creditCard.ExpirationYear);
        return _makeApiCall('POST', {
            'buyerID' : buyerID,
            'TransactionType' : 'createCreditCard',
            'CardDetails' : {
                'CardholderName' : creditCard.CardholderName,
                'CardType' : creditCard.CardType,
                'CardNumber' : creditCard.CardNumber,
                'ExpirationDate' : ExpirationDate,
                'CardCode' : creditCard.CardCode
            }
        });
    }

    function _updateCreditCard(creditCard, buyerID) {
        var ExpirationDate = ocCreditCardUtility.ExpirationDateFormat(creditCard.ExpirationMonth, creditCard.ExpirationYear);
        return _makeApiCall('POST', {
            'buyerID' : buyerID,
            'TransactionType' : 'updateCreditCard',
            'CardDetails' : {
                'CreditCardID' : creditCard.ID,
                'CardholderName' : creditCard.CardholderName,
                'CardType' : creditCard.CardType,
                'CardNumber' : 'XXXX'+ creditCard.PartialAccountNumber,
                'ExpirationDate' : ExpirationDate
            }
        });

    }

    function _deleteCreditCard(creditCard, buyerID) {
        return _makeApiCall('POST', {
            'buyerID': buyerID,
            'TransactionType': 'deleteCreditCard',
            'CardDetails': {
                'CreditCardID': creditCard.ID
            }
        });
    }

        function _authCaptureTransaction(order, payment) {
        return _makeApiCall('POST', {
            'BuyerID': order.FromCompanyID,
            'OrderID': order.ID,
            'OrderDirection': 'outgoing',
            'Amount': payment.Amount,
            'TransactionType': 'authCaptureTransaction',
            'CardDetails': {
                'PaymentID': payment.ID,
                'CreditCardID': payment.CreditCardID
            }
        });
    }

    function _makeApiCall(method, requestBody) {
        var apiUrl = apiurl +'/v1/integrationproxy/authorizenettest';
        var d = $q.defer();
        $resource(apiUrl, null, {
            callApi: {
                method: method,
                headers: {
                    'Authorization': 'Bearer ' + OrderCloudSDK.GetToken()
                }
            }
        }).callApi(requestBody).$promise
            .then(function(data) {
                d.resolve(data);
            })
            .catch(function(ex) {
                d.reject(ex);
            });
        return d.promise;
    }
}<|endoftext|>


<commit_before>/**
 * The router module.
 *
 * Router handles app routing and URL parameters and updates Presenter.
 *
 * @return singleton instance of Router class (extends Backbone.Router).
 */
define([
  'underscore',
  'backbone',
  'amplify',
  'map/utils',
  'map/services/PlaceService'
], function(_, Backbone, amplify, utils, PlaceService) {

  'use strict';

  var Router = Backbone.Router.extend({

    // temporary, we will do it with env variables
    _cacheVersion: 9,

    routes: {
      'map(/:zoom)(/:lat)(/:lng)(/:iso)(/:maptype)(/:baselayers)(/:sublayers)(/)': 'map',
      'embed/map(/:zoom)(/:lat)(/:lng)(/:iso)(/:maptype)(/:baselayers)(/:sublayers)(/)': 'embed'
    },

    /**
     * Boot file:
     *
     * @param  {[type]} boot [description]
     */
    initialize: function(mainView) {
      this.bind('all', this._checkForCacheBust());
      this.name = null;
      this.mainView = mainView;
      this.placeService = new PlaceService(this);
    },

    map: function() {
      this.name = 'map';
      this.mainView.setMapMode();
      this.initMap.apply(this, arguments);
    },

    embed: function() {
      this.name = 'embed/map';
      this.initMap.apply(this, arguments);
    },

    initMap: function(zoom, lat, lng, iso, maptype, baselayers, sublayers, subscribe) {
      var params = _.extend({
        zoom: zoom,
        lat: lat,
        lng: lng,
        iso: iso,
        maptype: maptype,
        baselayers: baselayers,
        sublayers: sublayers,
        subscribe_alerts: subscribe
      }, _.parseUrl());
      this.placeService.initPlace(this.name, params);
    },

    /**
     * If the URL contains the cache parameter (e.g., cache=bust), clear all
     * cached values in the browser (e.g., from memory, local storage,
     * session).
     */
    _checkForCacheBust: function() {
      var params = _.parseUrl();
      var localCacheVersion = _.toNumber(
        localStorage.getItem('CACHE_VERSION'));

      if (_.has(params, 'cache') || localCacheVersion !== this._cacheVersion) {
        console.log('...');
        _.each(amplify.store(), function(value, key) {
          amplify.store(key, null);
        });

        localStorage.setItem('CACHE_VERSION', this._cacheVersion);
      }
    },

    navigateTo: function(route, options) {
      this.navigate(route, options);
    }

  });

  return Router;

});
<commit_msg>Cache version ++<commit_after>/**
 * The router module.
 *
 * Router handles app routing and URL parameters and updates Presenter.
 *
 * @return singleton instance of Router class (extends Backbone.Router).
 */
define([
  'underscore',
  'backbone',
  'amplify',
  'map/utils',
  'map/services/PlaceService'
], function(_, Backbone, amplify, utils, PlaceService) {

  'use strict';

  var Router = Backbone.Router.extend({

    // temporary, we will do it with env variables
    _cacheVersion: 10,

    routes: {
      'map(/:zoom)(/:lat)(/:lng)(/:iso)(/:maptype)(/:baselayers)(/:sublayers)(/)': 'map',
      'embed/map(/:zoom)(/:lat)(/:lng)(/:iso)(/:maptype)(/:baselayers)(/:sublayers)(/)': 'embed'
    },

    /**
     * Boot file:
     *
     * @param  {[type]} boot [description]
     */
    initialize: function(mainView) {
      this.bind('all', this._checkForCacheBust());
      this.name = null;
      this.mainView = mainView;
      this.placeService = new PlaceService(this);
    },

    map: function() {
      this.name = 'map';
      this.mainView.setMapMode();
      this.initMap.apply(this, arguments);
    },

    embed: function() {
      this.name = 'embed/map';
      this.initMap.apply(this, arguments);
    },

    initMap: function(zoom, lat, lng, iso, maptype, baselayers, sublayers, subscribe) {
      var params = _.extend({
        zoom: zoom,
        lat: lat,
        lng: lng,
        iso: iso,
        maptype: maptype,
        baselayers: baselayers,
        sublayers: sublayers,
        subscribe_alerts: subscribe
      }, _.parseUrl());
      this.placeService.initPlace(this.name, params);
    },

    /**
     * If the URL contains the cache parameter (e.g., cache=bust), clear all
     * cached values in the browser (e.g., from memory, local storage,
     * session).
     */
    _checkForCacheBust: function() {
      var params = _.parseUrl();
      var localCacheVersion = _.toNumber(
        localStorage.getItem('CACHE_VERSION'));

      if (_.has(params, 'cache') || localCacheVersion !== this._cacheVersion) {
        console.log('...');
        _.each(amplify.store(), function(value, key) {
          amplify.store(key, null);
        });

        localStorage.setItem('CACHE_VERSION', this._cacheVersion);
      }
    },

    navigateTo: function(route, options) {
      this.navigate(route, options);
    }

  });

  return Router;

});
<|endoftext|>


<commit_before>export {
  default
} from 'https://www.lactame.com//lib/molecular-formula/0.17.5/molecular-formula.js';
<commit_msg>update molecular-formula to 0.17.6<commit_after>export {
  default
} from 'https://www.lactame.com//lib/molecular-formula/0.17.6/molecular-formula.js';
<|endoftext|>


<commit_before>/* eslint-disable object-curly-newline */
require('dotenv').config()

const headEn = {
  htmlAttrs: {
    lang: 'en',
  },
  title: 'Recontact.Me - Travelling Blog',
  meta: [
    { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    {
      hid: 'description',
      name: 'description',
      content: 'Articles of the world trip of Pierre and Benoît - South America, Oceania, Asia, Europa, Central America',
    },
    { name: 'theme-color', content: '#FFFFFF' },
    { name: 'msapplication-TileColor', content: '#DA532C' },
  ],
  link: [
    { rel: 'canonical', href: 'https://www.recontact.me' },
    { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' },
    { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' },
    { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png' },
    { rel: 'manifest', href: '/manifest.json' },
    { rel: 'mask-icon', href: '/safari-pinned-tab.svg', color: '#000000' },
  ],
}

const headFr = {
  htmlAttrs: {
    lang: 'fr',
  },
  title: 'Recontact.Me - Blog de Voyage',
  meta: [
    { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    {
      hid: 'description',
      name: 'description',
      content: 'Articles du tour du monde de Pierre et Benoît - Amérique du Sud, Océanie, Asie, Europe, Amérique centrale',
    },
    { name: 'theme-color', content: '#FFFFFF' },
    { name: 'msapplication-TileColor', content: '#DA532C' },
  ],
  link: [
    { rel: 'canonical', href: 'https://fr.recontact.me' },
    { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' },
    { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' },
    { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png' },
    { rel: 'manifest', href: '/manifest.json' },
    { rel: 'mask-icon', href: '/safari-pinned-tab.svg', color: '#000000' },
  ],
}

const articleRoutes = [...Array(92).keys()]
  .map((val, index) => `/articles/${index + 1}`)

module.exports = {
  target: 'static',
  css: [
    '~/assets/fonts/font.css',
    '~/assets/css/styles.css',
  ],
  env: { NUXT_ENV_API_URL: process.env.NUXT_ENV_API_URL || 'https://recontact.herokuapp.com' },
  head: process.env.NUXT_ENV_LANGUAGE === 'en' ? headEn : headFr, // Headers of the page
  loading: { color: '#3B8070' }, // Customize the progress bar color
  router: {},
  plugins: [
    '~/plugins/i18n.js',
    '~/plugins/lazyload.js',
    // '~/plugins/modal.js',
    // '~/plugins/notification.js',
  ],
  generate: {
    routes: [
      '/',
      '/admin',
      ...articleRoutes,
    ],
  },
  modules: [
    '@nuxtjs/dotenv',
    '@nuxtjs/pwa',
  ],
  build: {
    postcss: {
      plugins: {
        // I disabled all plugins by default, not necessary for now
        // Disable a plugin by passing false as value
        // 'postcss-url': false,
        // 'postcss-nested': {},
        // 'postcss-responsive-type': {},
        // 'postcss-hexrgba': {}
      },
      preset: {
        autoprefixer: {
          grid: true,
        },
      },
    },
  },
}

<commit_msg>feat(mapbox): add css<commit_after>/* eslint-disable object-curly-newline */
require('dotenv').config()

const headEn = {
  htmlAttrs: {
    lang: 'en',
  },
  title: 'Recontact.Me - Travelling Blog',
  meta: [
    { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    {
      hid: 'description',
      name: 'description',
      content: 'Articles of the world trip of Pierre and Benoît - South America, Oceania, Asia, Europa, Central America',
    },
    { name: 'theme-color', content: '#FFFFFF' },
    { name: 'msapplication-TileColor', content: '#DA532C' },
  ],
  link: [
    { rel: 'canonical', href: 'https://www.recontact.me' },
    { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' },
    { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' },
    { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png' },
    { rel: 'manifest', href: '/manifest.json' },
    { rel: 'mask-icon', href: '/safari-pinned-tab.svg', color: '#000000' },
    {
      rel: 'stylesheet',
      href: 'https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css',
    },
  ],
}

const headFr = {
  htmlAttrs: {
    lang: 'fr',
  },
  title: 'Recontact.Me - Blog de Voyage',
  meta: [
    { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    {
      hid: 'description',
      name: 'description',
      content: 'Articles du tour du monde de Pierre et Benoît - Amérique du Sud, Océanie, Asie, Europe, Amérique centrale',
    },
    { name: 'theme-color', content: '#FFFFFF' },
    { name: 'msapplication-TileColor', content: '#DA532C' },
  ],
  link: [
    { rel: 'canonical', href: 'https://fr.recontact.me' },
    { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' },
    { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' },
    { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png' },
    { rel: 'manifest', href: '/manifest.json' },
    { rel: 'mask-icon', href: '/safari-pinned-tab.svg', color: '#000000' },
    {
      rel: 'stylesheet',
      href: 'https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css',
    },
  ],
}

const articleRoutes = [...Array(92).keys()]
  .map((val, index) => `/articles/${index + 1}`)

module.exports = {
  target: 'static',
  css: [
    '~/assets/fonts/font.css',
    '~/assets/css/styles.css',
  ],
  env: { NUXT_ENV_API_URL: process.env.NUXT_ENV_API_URL || 'https://recontact.herokuapp.com' },
  head: process.env.NUXT_ENV_LANGUAGE === 'en' ? headEn : headFr, // Headers of the page
  loading: { color: '#3B8070' }, // Customize the progress bar color
  router: {},
  plugins: [
    '~/plugins/i18n.js',
    '~/plugins/lazyload.js',
    // '~/plugins/modal.js',
    // '~/plugins/notification.js',
  ],
  generate: {
    routes: [
      '/',
      '/admin',
      ...articleRoutes,
    ],
  },
  modules: [
    '@nuxtjs/dotenv',
    '@nuxtjs/pwa',
  ],
  build: {
    postcss: {
      plugins: {
        // I disabled all plugins by default, not necessary for now
        // Disable a plugin by passing false as value
        // 'postcss-url': false,
        // 'postcss-nested': {},
        // 'postcss-responsive-type': {},
        // 'postcss-hexrgba': {}
      },
      preset: {
        autoprefixer: {
          grid: true,
        },
      },
    },
  },
}

<|endoftext|>


<commit_before>
// [START app]
'use strict';

// [START setup]

var express = require('express');

var app = express();
var google = require('googleapis');

app.enable('trust proxy');

var Datastore = require('@google-cloud/datastore');

const projectId = "doolinhomeiot";
const datasetId = "OfficeData";
const tableId = "iotdata";

// Instantiate a datastore client
var datastore = Datastore();

var PubSub = require('@google-cloud/pubsub');

//Instantiate a pubsub client
var pubsub = PubSub();

var PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;

var topic = pubsub.topic(process.env.PUBSUB_TOPIC);

var subscription = pubsub.subscription(process.env.PUBSUB_SUBSCRIPTION_NAME);

// [END setup]

function storeEvent(message) {
    var key = datastore.key('officedata');
    key.identifier = "id"

    var obj = {
        messageid: message.id,
        deviceid: message.attributes.device_id,
        ////event: message.attributes.event,
        published: message.attributes.published_at,
        data: message.data
    }
    datastore.save(
        {
            key: key,
            data: obj
        }, function (err) {
            if (err) {
                console.log('There was an error storing the event', err);
            }
            console.log('stored in datastore', obj);
            console.log('Begin BIGQUERY:');
            var messagedata = message.data;
            //var content = {"nameid": "1658", "messagedata": " message.data "};
        insertRowsAsStream(datasetId,tableId,projectId,messagedata , message.attributes.published_at, message.attributes.device_id)
        }
    );

}

function insertRowsAsStream (datasetId, tableId, projectId, messagedata, publishedat, deviceid) {
     var content = {"nameid": "1658", "messagedata": " messagedata "};
    // [START bigquery_insert_stream]
    // Imports the Google Cloud client library
    const BigQuery = require('@google-cloud/bigquery');

    // Instantiates a client
    const bigquery = BigQuery({
        projectId: projectId
    });

    // Inserts data into a table
    bigquery
        .dataset(datasetId)
        .table(tableId)
        .insert(content)
        .then((insertErrors) => {
        console.log('Inserted:');

})
.catch((err) => {
        console.error('ERROR:', err);
});
    // [END bigquery_insert_stream]
}

subscription.on('message', function (message) {
    console.log('event received', message);
    // Called every time a message is received.
    // message.id = ID used to acknowledge its receival.
    // message.data = Contents of the message.
    // message.attributes = Attributes of the message.
    storeEvent(message);
    message.ack();
});

// [START listen]
var server = app.listen(process.env.PORT || 8080, function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
<commit_msg>Update app.js<commit_after>
// [START app]
'use strict';

// [START setup]

var express = require('express');

var app = express();
var google = require('googleapis');

app.enable('trust proxy');

var Datastore = require('@google-cloud/datastore');

const projectId = "doolinhomeiot";
const datasetId = "OfficeData";
const tableId = "iotdata";

// Instantiate a datastore client
var datastore = Datastore();

var PubSub = require('@google-cloud/pubsub');

//Instantiate a pubsub client
var pubsub = PubSub();

var PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;

var topic = pubsub.topic(process.env.PUBSUB_TOPIC);

var subscription = pubsub.subscription(process.env.PUBSUB_SUBSCRIPTION_NAME);

// [END setup]

function storeEvent(message) {
    var key = datastore.key('officedata');
    key.identifier = "id"

    var obj = {
        messageid: message.id,
        deviceid: message.attributes.device_id,
        ////event: message.attributes.event,
        published: message.attributes.published_at,
        data: message.data
    }
    datastore.save(
        {
            key: key,
            data: obj
        }, function (err) {
            if (err) {
                console.log('There was an error storing the event', err);
            }
            console.log('stored in datastore', obj);
            console.log('Begin BIGQUERY:');
            var messagedata = obj.data;
            //var content = {"nameid": "1658", "messagedata": " message.data "};
            insertRowsAsStream(datasetId,tableId,projectId,messagedata , message.attributes.published_at, message.attributes.device_id)
        }
    );

}

function insertRowsAsStream (datasetId, tableId, projectId, messagedata, publishedat, deviceid) {

    var builder = "deviceid:" + deviceid;
    builder =  builder + ", messagedata:" + messagedata;
    var content = "{" + builder + "}"; //deviceid": "1658", "messagedata": " + messagedata + "};
    console.log(content);
    // [START bigquery_insert_stream]
    // Imports the Google Cloud client library
    const BigQuery = require('@google-cloud/bigquery');

    // Instantiates a client
    const bigquery = BigQuery({
        projectId: projectId
    });

    // Inserts data into a table
    bigquery
        .dataset(datasetId)
        .table(tableId)
        .insert(content)
        .then((insertErrors) => {
        console.log('Inserted:');

})
.catch((err) => {
        console.error('ERROR:', err);
});
    // [END bigquery_insert_stream]
}

subscription.on('message', function (message) {
    console.log('event received', message);
    // Called every time a message is received.
    // message.id = ID used to acknowledge its receival.
    // message.data = Contents of the message.
    // message.attributes = Attributes of the message.
    storeEvent(message);
    message.ack();
});

// [START listen]
var server = app.listen(process.env.PORT || 8080, function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
<|endoftext|>


<commit_before>//本網頁讀取完成後 執行
$(document).ready(initFind);

function initFind(){
    initCurrencySelect()
    var keyword = tour.QueryString().keyword;
    //js取值
    // alert("keyword:"+keyword);
    //server取值
    // alert("strKeywordFromHome:"+strKeywordFromHome);

    //將值填入googlemap
    $('#pac-input').val(keyword);
    //將值填入place欄位
    $('#placeID').val(keyword);
    var $toggleCollapse = $('.toggleCollapse');
    $('#moreInfo').on('show.bs.collapse',function(){
       $toggleCollapse.html(' less');
    }).on('hide.bs.collapse',function(){
       $toggleCollapse.html(' more');
    });
    //不傳入sort條件
    search('');

};

//hmoe頁面傳值至find頁面 googleMap呈現
function initMap(sendLat,sendLng) {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: Number(tour.QueryString().lat),
            lng: Number(tour.QueryString().lng)
        },
        zoom: 13
    });
    var input = /** @type {!HTMLInputElement} */ (
        document.getElementById('placeID'));

    var types = document.getElementById('type-selector');
    //map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    //map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
        map: map,
        // anchorPoint: new google.maps.Point(0, -29)
        position:map.center
    });

    autocomplete.addListener('place_changed', function() {
        infowindow.close();
        marker.setVisible(false);
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert("Autocomplete's returned place contains no geometry");
            return;
        }

        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17); // Why 17? Because it looks good.
        }
        marker.setIcon( /** @type {google.maps.Icon} */ ({
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }

        infowindow.setContent('
' + place.name + '
' + address);
        //infowindow.open(map, marker);
    });
}

//home頁面到find頁面 or 按下search鍵 會執行的動作 可傳入排序條件
function search( condition){

//主搜尋
    //地點
    var place         = $("#placeID").val();
    //預算下限
    var budgetDown    = $("#budgetDownID").val();
    //預算上限
    var budgetUp      = $("#budgetUpID").val();
    //時間起迄
    var startFrom     =$("#startFrom").val();
    var to            =$("#to").val();
//摺疊搜尋
    //旅遊時間長短
    var duration      =$('input:checkbox:checked[name="duration"]').map(function() { return $(this).val(); }).get();
    //人數
    var passenger =$("#passenger").val();
    //類型
    var style         =$('input:checkbox:checked[name="style"]').map(function() { return $(this).val(); }).get();
    //旅遊時間點開始
    var tourStarts    =$('#tourStarts :selected').text();
    //旅遊時間點結束
    var tourEnds      =$('#tourEnds :selected').text();
    //導覽語言
    var guideLanguage =$('input:checkbox:checked[name="guideLanguage"]').map(function() { return $(this).val(); }).get();
    //可立即參與
    var availability  =$('input:checkbox:checked[name="availability"]').map(function() { return $(this).val(); }).get();
    //萬用搜尋
    var attrations    =$("#attrations").val();

    var strFilterQueryUrl = "/trip/filter?1=1";
    //place
    if (place != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&keyword=" + place;
    };
    //budgetDown
    if (budgetDown != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&min_budget=" + budgetDown;
    };
    //budgetUp
    if (budgetUp != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&max_budget=" + budgetUp;
    };
    //startFrom db無資料
    if (startFrom != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_from=" + startFrom;
    };
    //to db無資料
    if (to != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_to=" + to;
    };

    //duration
    if (duration != ""){
        for(var i=0;duration.length>i;i++){
            if(duration[i]=="1"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=0&max_duration=1";
            }
            if(duration[i]=="2"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=1&max_duration=2";
            }
            if(duration[i]=="3"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=2&max_duration=3";
            }
            if(duration[i]=="4"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=3&max_duration=6";
            }
            if(duration[i]=="5"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=12&max_duration=24";
            }
            if(duration[i]=="5"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=24&max_duration=1000";
            }
        }
    };
    //passenger 目前沒有
    if (passenger != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&keyword=" + passengerDown;
    };
    //style 目前db無資料 js需修改
    if (style != ""){
        for(var i=0;duration.length>i;i++){
            if(style[i]=="Cultural"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Food"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Fashion"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Wild"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Sports"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Eco"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
        }
    };
    //tourStarts 程式尚未實作
    if (tourStarts != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_from=" + tourStarts;
    };
    //tourEnds  程式尚未實作
    if (tourEnds != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_to=" + tourEnds;
    };
    //guideLanguage
    if (guideLanguage != ""){
        for(var i=0;guideLanguage.length>i;i++){
            if(guideLanguage[i]=="English"){
                strFilterQueryUrl = strFilterQueryUrl + "&guide_language=English";
            }
            if(guideLanguage[i]=="Chinese"){
                strFilterQueryUrl = strFilterQueryUrl + "&guide_language=中文";
            }
        }
    };
    //availability db 無資料
    if (availability != ""){
        for(var i=0;availability.length>i;i++){
            if(availability[i]=="instantConfirmation"){
                strFilterQueryUrl = strFilterQueryUrl + "&option=" + option[i];
            }
            if(availability[i]=="onRequest"){
                strFilterQueryUrl = strFilterQueryUrl + "&option=" + option[i];
            }
        }
    };
    //attrations
    if (attrations != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&keyword=" + attrations;
    };

    //排序條件
    if(condition !=""){
        if(condition=='intUsdCost'){
            //預算
            if($("#sortByBudgetID").val() =="Budget ↓"){
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=" +condition;
                $("#sortByBudgetID").val("Budget ↑");
            }else{
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=-" +condition;
                $("#sortByBudgetID").val("Budget ↓");
            }
        }
        if(condition=='intDurationHour'){
            //tour長短
            if($("#sortByDurationHourID").val() =="Duration ↓"){
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=" +condition;
                $("#sortByDurationHourID").val("Duration ↑");
            }else{
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=-" +condition;
                $("#sortByDurationHourID").val("Duration ↓");
            }
        }
        if(condition=='intReviewStar'){
            //評分高低
            if($("#sortByReviewStarID").val() =="ReviewStar ↓"){
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=" +condition;
                $("#sortByReviewStarID").val("ReviewStar ↑");
            }else{
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=-" +condition;
                $("#sortByReviewStarID").val("Star ↓");
            }
        }
    }

    //alert(" 254:strFilterQueryUrl:"+strFilterQueryUrl);
    $.getJSON(strFilterQueryUrl, function(jsonResp){
        //console.log(jsonResp);
        $("div.findResultDiv ul.lstTripData").html("");
        if(jsonResp.length>0){

            if($("body").find(".sortedBy").length!=1){
                var sortedByHtml=[
                 "
",
                    "<input class=\"btn btn-info\" id=\"sortByBudgetID\"       type=\"button\" onclick='search(\"intUsdCost\")'      value=\"Budget ↓\">    ",
                    "<input class=\"btn btn-info\" id=\"sortByDurationHourID\" type=\"button\" onclick='search(\"intDurationHour\")' value=\"Duration ↓\">  ",
                    "<input class=\"btn btn-info\" id=\"sortByReviewStarID\"   type=\"button\" onclick='search(\"intReviewStar\")'   value=\"Star ↓\">",
                 "
",
                ]
                $(".findResultDiv").prepend(sortedByHtml);
            }
        }

        for (i = 0; i < jsonResp.length; i++) {
            var dicTripData = jsonResp[i];
            var strTripDataHtml = getTripDataHtml(dicTripData["strTitle"], dicTripData["intUserCurrencyCost"], dicTripData["strIntroduction"], dicTripData["strLocation"], dicTripData["intDurationHour"], dicTripData["strOriginUrl"], dicTripData["strImageUrl"], dicTripData["intReviewStar"], dicTripData["intReviewVisitor"] );
            $("div.findResultDiv ul.lstTripData").append(strTripDataHtml);
        };
    });
};

//組出單組查詢結果出來的html字串
function getTripDataHtml(strTitle, intUserCurrencyCost, strIntroduction, strLocation, intDurationHour, strOriginUrl, strImageUrl, intReviewStar, intReviewVisitor ){
    var reviewStar;
    if(intReviewStar==0){
        reviewStar=' ';
    }
    if(intReviewStar==1){
        reviewStar='★';
    }
    if(intReviewStar==2){
        reviewStar='★★';
    }
    if(intReviewStar==3){
        reviewStar='★★★';
    }
    if(intReviewStar==4){
        reviewStar='★★★★';
    }
    if(intReviewStar==5){
        reviewStar='★★★★★';
    }

    var strUserCurrency = $("#moneySelect").val();

    var strTripDataHtml = [
    "
",
        "
",
            "
",
                "",
            "
",
            "
",
            "
",
                "
"+strTitle+"
",
                ""+strIntroduction+"
",
                " Duration:"+intDurationHour+"
",
                "Star:"+reviewStar+"
",
                " review:"+intReviewVisitor+"
",
                " read more
",
            "
",
            "
",
            "
",
                "",
                "",
                ""+intUserCurrencyCost+" "+strUserCurrency+"
",
            "
",
            "
",
                "",
            "
",
            "
",
    "
"
    ].join("");
    return strTripDataHtml;
};

//幣別功能
function initCurrencySelect(){
    //設定目前幣別
    var strUserCurrencyUrl = "/trip/userCurrency";
    $.getJSON(strUserCurrencyUrl, function(jsonResp){
        strUserCurrency = jsonResp["strUserCurrency"];
        $("#moneySelect").val(strUserCurrency);
        $("#moneySelect").selectpicker("refresh");
        console.log("init user currency selection: " + strUserCurrency);
    });
    //切換目前幣別
    $("#moneySelect").change(function(){
        var strSelectedCurrencyVal = $("#moneySelect").find(":selected").val();
        var strChangeUserCurrencyUrl = strUserCurrencyUrl + "?user_currency=" + strSelectedCurrencyVal;
        $.getJSON(strChangeUserCurrencyUrl, function(jsonResp){
            strUserCurrency = jsonResp["strUserCurrency"];
            console.log("switch user currency to: " + strUserCurrency);
        });
        //重新搜尋
        search("");
    });
};
<commit_msg>fix research after user currency changed<commit_after>//本網頁讀取完成後 執行
$(document).ready(initFind);

function initFind(){
    initCurrencySelect()
    var keyword = tour.QueryString().keyword;
    //js取值
    // alert("keyword:"+keyword);
    //server取值
    // alert("strKeywordFromHome:"+strKeywordFromHome);

    //將值填入googlemap
    $('#pac-input').val(keyword);
    //將值填入place欄位
    $('#placeID').val(keyword);
    var $toggleCollapse = $('.toggleCollapse');
    $('#moreInfo').on('show.bs.collapse',function(){
       $toggleCollapse.html(' less');
    }).on('hide.bs.collapse',function(){
       $toggleCollapse.html(' more');
    });
    //不傳入sort條件
    search('');

};

//hmoe頁面傳值至find頁面 googleMap呈現
function initMap(sendLat,sendLng) {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: Number(tour.QueryString().lat),
            lng: Number(tour.QueryString().lng)
        },
        zoom: 13
    });
    var input = /** @type {!HTMLInputElement} */ (
        document.getElementById('placeID'));

    var types = document.getElementById('type-selector');
    //map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    //map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
        map: map,
        // anchorPoint: new google.maps.Point(0, -29)
        position:map.center
    });

    autocomplete.addListener('place_changed', function() {
        infowindow.close();
        marker.setVisible(false);
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert("Autocomplete's returned place contains no geometry");
            return;
        }

        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17); // Why 17? Because it looks good.
        }
        marker.setIcon( /** @type {google.maps.Icon} */ ({
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }

        infowindow.setContent('
' + place.name + '
' + address);
        //infowindow.open(map, marker);
    });
}

//home頁面到find頁面 or 按下search鍵 會執行的動作 可傳入排序條件
function search( condition){

//主搜尋
    //地點
    var place         = $("#placeID").val();
    //預算下限
    var budgetDown    = $("#budgetDownID").val();
    //預算上限
    var budgetUp      = $("#budgetUpID").val();
    //時間起迄
    var startFrom     =$("#startFrom").val();
    var to            =$("#to").val();
//摺疊搜尋
    //旅遊時間長短
    var duration      =$('input:checkbox:checked[name="duration"]').map(function() { return $(this).val(); }).get();
    //人數
    var passenger =$("#passenger").val();
    //類型
    var style         =$('input:checkbox:checked[name="style"]').map(function() { return $(this).val(); }).get();
    //旅遊時間點開始
    var tourStarts    =$('#tourStarts :selected').text();
    //旅遊時間點結束
    var tourEnds      =$('#tourEnds :selected').text();
    //導覽語言
    var guideLanguage =$('input:checkbox:checked[name="guideLanguage"]').map(function() { return $(this).val(); }).get();
    //可立即參與
    var availability  =$('input:checkbox:checked[name="availability"]').map(function() { return $(this).val(); }).get();
    //萬用搜尋
    var attrations    =$("#attrations").val();

    var strFilterQueryUrl = "/trip/filter?1=1";
    //place
    if (place != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&keyword=" + place;
    };
    //budgetDown
    if (budgetDown != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&min_budget=" + budgetDown;
    };
    //budgetUp
    if (budgetUp != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&max_budget=" + budgetUp;
    };
    //startFrom db無資料
    if (startFrom != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_from=" + startFrom;
    };
    //to db無資料
    if (to != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_to=" + to;
    };

    //duration
    if (duration != ""){
        for(var i=0;duration.length>i;i++){
            if(duration[i]=="1"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=0&max_duration=1";
            }
            if(duration[i]=="2"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=1&max_duration=2";
            }
            if(duration[i]=="3"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=2&max_duration=3";
            }
            if(duration[i]=="4"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=3&max_duration=6";
            }
            if(duration[i]=="5"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=12&max_duration=24";
            }
            if(duration[i]=="5"){
                strFilterQueryUrl = strFilterQueryUrl + "&min_duration=24&max_duration=1000";
            }
        }
    };
    //passenger 目前沒有
    if (passenger != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&keyword=" + passengerDown;
    };
    //style 目前db無資料 js需修改
    if (style != ""){
        for(var i=0;duration.length>i;i++){
            if(style[i]=="Cultural"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Food"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Fashion"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Wild"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Sports"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
            if(style[i]=="Eco"){
                strFilterQueryUrl = strFilterQueryUrl + "&style=" + style;
            }
        }
    };
    //tourStarts 程式尚未實作
    if (tourStarts != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_from=" + tourStarts;
    };
    //tourEnds  程式尚未實作
    if (tourEnds != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&date_to=" + tourEnds;
    };
    //guideLanguage
    if (guideLanguage != ""){
        for(var i=0;guideLanguage.length>i;i++){
            if(guideLanguage[i]=="English"){
                strFilterQueryUrl = strFilterQueryUrl + "&guide_language=English";
            }
            if(guideLanguage[i]=="Chinese"){
                strFilterQueryUrl = strFilterQueryUrl + "&guide_language=中文";
            }
        }
    };
    //availability db 無資料
    if (availability != ""){
        for(var i=0;availability.length>i;i++){
            if(availability[i]=="instantConfirmation"){
                strFilterQueryUrl = strFilterQueryUrl + "&option=" + option[i];
            }
            if(availability[i]=="onRequest"){
                strFilterQueryUrl = strFilterQueryUrl + "&option=" + option[i];
            }
        }
    };
    //attrations
    if (attrations != ""){
        strFilterQueryUrl = strFilterQueryUrl + "&keyword=" + attrations;
    };

    //排序條件
    if(condition !=""){
        if(condition=='intUsdCost'){
            //預算
            if($("#sortByBudgetID").val() =="Budget ↓"){
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=" +condition;
                $("#sortByBudgetID").val("Budget ↑");
            }else{
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=-" +condition;
                $("#sortByBudgetID").val("Budget ↓");
            }
        }
        if(condition=='intDurationHour'){
            //tour長短
            if($("#sortByDurationHourID").val() =="Duration ↓"){
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=" +condition;
                $("#sortByDurationHourID").val("Duration ↑");
            }else{
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=-" +condition;
                $("#sortByDurationHourID").val("Duration ↓");
            }
        }
        if(condition=='intReviewStar'){
            //評分高低
            if($("#sortByReviewStarID").val() =="ReviewStar ↓"){
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=" +condition;
                $("#sortByReviewStarID").val("ReviewStar ↑");
            }else{
                strFilterQueryUrl = strFilterQueryUrl + "&order_by=-" +condition;
                $("#sortByReviewStarID").val("Star ↓");
            }
        }
    }

    //alert(" 254:strFilterQueryUrl:"+strFilterQueryUrl);
    $.getJSON(strFilterQueryUrl, function(jsonResp){
        //console.log(jsonResp);
        $("div.findResultDiv ul.lstTripData").html("");
        if(jsonResp.length>0){

            if($("body").find(".sortedBy").length!=1){
                var sortedByHtml=[
                 "
",
                    "<input class=\"btn btn-info\" id=\"sortByBudgetID\"       type=\"button\" onclick='search(\"intUsdCost\")'      value=\"Budget ↓\">    ",
                    "<input class=\"btn btn-info\" id=\"sortByDurationHourID\" type=\"button\" onclick='search(\"intDurationHour\")' value=\"Duration ↓\">  ",
                    "<input class=\"btn btn-info\" id=\"sortByReviewStarID\"   type=\"button\" onclick='search(\"intReviewStar\")'   value=\"Star ↓\">",
                 "
",
                ]
                $(".findResultDiv").prepend(sortedByHtml);
            }
        }

        for (i = 0; i < jsonResp.length; i++) {
            var dicTripData = jsonResp[i];
            var strTripDataHtml = getTripDataHtml(dicTripData["strTitle"], dicTripData["intUserCurrencyCost"], dicTripData["strIntroduction"], dicTripData["strLocation"], dicTripData["intDurationHour"], dicTripData["strOriginUrl"], dicTripData["strImageUrl"], dicTripData["intReviewStar"], dicTripData["intReviewVisitor"] );
            $("div.findResultDiv ul.lstTripData").append(strTripDataHtml);
        };
    });
};

//組出單組查詢結果出來的html字串
function getTripDataHtml(strTitle, intUserCurrencyCost, strIntroduction, strLocation, intDurationHour, strOriginUrl, strImageUrl, intReviewStar, intReviewVisitor ){
    var reviewStar;
    if(intReviewStar==0){
        reviewStar=' ';
    }
    if(intReviewStar==1){
        reviewStar='★';
    }
    if(intReviewStar==2){
        reviewStar='★★';
    }
    if(intReviewStar==3){
        reviewStar='★★★';
    }
    if(intReviewStar==4){
        reviewStar='★★★★';
    }
    if(intReviewStar==5){
        reviewStar='★★★★★';
    }

    var strUserCurrency = $("#moneySelect").val();

    var strTripDataHtml = [
    "
",
        "
",
            "
",
                "",
            "
",
            "
",
            "
",
                "
"+strTitle+"
",
                ""+strIntroduction+"
",
                " Duration:"+intDurationHour+"
",
                "Star:"+reviewStar+"
",
                " review:"+intReviewVisitor+"
",
                " read more
",
            "
",
            "
",
            "
",
                "",
                "",
                ""+intUserCurrencyCost+" "+strUserCurrency+"
",
            "
",
            "
",
                "",
            "
",
            "
",
    "
"
    ].join("");
    return strTripDataHtml;
};

//幣別功能
function initCurrencySelect(){
    //設定目前幣別
    var strUserCurrencyUrl = "/trip/userCurrency";
    $.getJSON(strUserCurrencyUrl, function(jsonResp){
        strUserCurrency = jsonResp["strUserCurrency"];
        $("#moneySelect").val(strUserCurrency);
        $("#moneySelect").selectpicker("refresh");
        console.log("init user currency selection: " + strUserCurrency);
    });
    //切換目前幣別
    $("#moneySelect").change(function(){
        var strSelectedCurrencyVal = $("#moneySelect").find(":selected").val();
        var strChangeUserCurrencyUrl = strUserCurrencyUrl + "?user_currency=" + strSelectedCurrencyVal;
        $.getJSON(strChangeUserCurrencyUrl, function(jsonResp){
            strUserCurrency = jsonResp["strUserCurrency"];
            console.log("switch user currency to: " + strUserCurrency);
            //重新搜尋
            console.log("research");
            search("");
        });
    });
};
<|endoftext|>


<commit_before>const {Lokka} = require('lokka')
const {Transport} = require('lokka-transport-http')

const client = new Lokka({
  transport: new Transport('https://api.graph.cool/simple/v1/__PROJECT_ID__')
})

const createEntry = async() => {
  // define a mutation with json and jsonList variables
  const mutation = `($json: Json, $jsonList: [Json!]) {
    createEntry(
      json: $json
      jsonList: $jsonList
    ) {
      id
      jsonList
    }
  }`

  // stringify an object for a single Json field
  const json = JSON.stringify({a: 2, message: "hello"})

  // stringify an array of objects for a [Json!] field
  const jsonList = JSON.stringify([{a: 2, message: "hello"}, {b: 3, message: "bye"}])

  // pass vars to mutation
  const vars = {
    json,
    jsonList
  }

  return await client.mutate(mutation, vars)
}

const main = async() => {
  const res = await createEntry()
  console.log('Created new entry:')
  console.log(res.createEntry)
  console.log('Done!')
}

main().catch((e) => console.error(e))
<commit_msg>Delete json-entries.js<commit_after><|endoftext|>