<commit_before>function PathDbMods() {
  console.log("PathDbMods()...");
  // put the auth jwt in cookie as token
  fetch("/jwt/token", {
    method: 'GET',
    credentials: 'include'
  }).then(x => x.json()).then(x => {
    console.log(x)
    if (x.hasOwnProperty('token') && x.token) {
      document.cookie = "token=" + x.token + ";"
    }
  })
  /**
  Gets a named cookie value
  * @param {string} key - the key to get from the cookie
  **/
  function getCookie(key) {
    var cookiestring = RegExp("" + key + "[^;]+").exec(document.cookie);
    return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./, "") : "");
  }
  console.warn("{PathDB mods enabled}")
  Store.prototype.default_findMark = Store.prototype.findMark
  Store.prototype.findMark = function(slide, name, specimen, study, footprint, source, x0, x1, y0, y1) {
    var suffix = "Mark/find"
    var url = this.base + suffix;
    var query = {}
    if (slide) {
      query.slide = slide
    }
    if (name) {
      query.name = name
    }
    if (specimen) {
      query.specimen = specimen
    }
    if (study) {
      query.study = study
    }
    if (footprint) {
      query.footprint = footprint
    }
    if (source) {
      query.source = source
    }
    if (x0) {
      query.x0 = x0;
    }
    if (x1) {
      query.x1 = x1;
    }
    if (y0) {
      query.y0 = y0;
    }
    if (y1) {
      query.y1 = y1;
    }
    return fetch(url + "?" + objToParamStr(query), {
      credentials: "same-origin",
      mode: "cors"
    }).then(this.errorHandler).then(x => this.filterBroken(x, "mark"))
  }
  Store.prototype.getMarkByIds = function(ids, slide, study, specimen, source, footprint, x0, x1, y0, y1) {
    if (!Array.isArray(ids) || !slide) {
      return {
        hasError: true,
        message: 'args are illegal'
      }
    }
    var suffix = "Mark/multi"
    var url = this.base + suffix;
    var query = {}
    var stringifiedIds = ids.map(id => `"${id}"`).join(',');
    query.name = `[${stringifiedIds}]`;
    query.slide = slide;
    if (study) {
      query.study = study;
    }
    if (specimen) {
      query.specimen = specimen;
    }
    if (source) {
      query.source = source;
    }
    if (footprint) {
      query.footprint = footprint;
    }
    if (x0) {
      query.x0 = x0;
    }
    if (x1) {
      query.x1 = x1;
    }
    if (y0) {
      query.y0 = y0;
    }
    if (y1) {
      query.y1 = y1;
    }
    return fetch(url + "?" + objToParamStr(query), {
      credentials: "same-origin",
      mode: "cors"
    }).then(this.errorHandler).then(x => this.filterBroken(x, "mark"))
  }
  Store.prototype.findMarkTypes = function(slide, name) {
    var suffix = "Mark/types"
    var url = this.base + suffix;
    var query = {}
    if(!slide) {
      console.error('Store.findMarkTypes needs slide ... ');
      return null;
    }
    // pathdb numeric->str coerce
    if ((parseInt(slide)==slide)||(parseFloat(slide)==slide)){
      query.slide = '"' + slide + '"'
    } else {
      query.slide = slide
    }

    if (name) {
      query.name = name
      suffix = "Mark/typesExec"
    }
    return fetch(url + "?" + objToParamStr(query), {
      credentials: "same-origin",
      mode: "cors"
    }).then(this.errorHandler)
  }
  Store.prototype.default_findSlide = Store.prototype.findSlide;
  Store.prototype.findSlide = function(slide, specimen, study, location) {
    var url = "/node/" + slide + "?_format=json"
    return fetch(url, {
      mode: "cors",
      headers: new Headers({
        'Authorization': 'Bearer ' + getCookie("token"),
      })
    }).then(function(response) {
      if (!response.ok) return {
        error: !response.ok,
        text: response.statusText,
        url: response.url
      };
      return response.json().then(x => [x]);
    })
  }
  Store.prototype.default_getSlide = Store.prototype.getSlide
  Store.prototype.getSlide = function(id) {
    var url = "/node/" + id + "?_format=json"
    return fetch(url, {
      mode: "cors",
      headers: new Headers({
        'Authorization': 'Bearer ' + getCookie("token"),
      })
    }).then(function(response) {
      if (!response.ok) return {
        error: !response.ok,
        text: response.statusText,
        url: response.url
      };
      return response.json().then(x => [x]);
    })
  }

  Store.prototype.default_findHeatmapType = Store.prototype.findHeatmapType;
  Store.prototype.findHeatmapType = function(slide, name) {
    var suffix = "Heatmap/types"
    var url = this.base + suffix;
    var query = {}
    query.slide = slide
    query.specimen = ""
    query.study = ""
    if(name) query.name = name;

    return fetch(url + "?" + objToParamStr(query), {
      credentials: "include",
      mode: "cors"
    }).then(this.errorHandler).then(x=>this.filterBroken(x, "heatmap"))

  };

  Store.prototype.default_findHeatmap = Store.prototype.findHeatmap;
  Store.prototype.findHeatmap = function(slide, name) {
    var suffix = "Heatmap/find"
    var url = this.base + suffix;
    var query = {}
    query.slide = slide
    query.specimen = ""
    query.study = ""
    if(name) query.name = name;

    return fetch(url + "?" + objToParamStr(query), {
      credentials: "include",
      mode: "cors"
    }).then(this.errorHandler).then(x=>this.filterBroken(x, "heatmap"))
  };
  Store.prototype.default_getHeatmap = Store.prototype.getHeatmap;
  Store.prototype.getHeatmap = function(slide, exec) {
    var suffix = "Heatmap/get"
    var url = this.base + suffix;
    var query = {}
    query.slide = slide
    query.specimen = ""
    query.study = ""
    if(exec) query.name = exec;

    return fetch(url + "?" + objToParamStr(query), {
      credentials: "include",
      mode: "cors"
    }).then(this.errorHandler).then(x=>this.filterBroken(x, "heatmap"))
  };

  StatesHelper.prototype.default_getCurrentStatesURL = StatesHelper.prototype.getCurrentStatesURL;
  getCurrentStatesURL = function(isImageCoordinate=false){
    let states = StatesHelper.getCurrentStates(isImageCoordinate);
    if(!states)return;
    console.log(states);
    states = StatesHelper.encodeStates(states);
    return `${location.origin}${location.pathname}?slideId=${$D.params.slideId}&states=${$D.params.states}&mode=${$D.params.mode}`
  };

  CaMic.prototype.default_loadImg = CaMic.prototype.loadImg
  CaMic.prototype.loadImg = function(func) {
    var urlParams = new URLSearchParams(window.location.search);
    var pathdb_id = urlParams.get('slideId');
    this.slideId = pathdb_id // default value
    this.slideName = pathdb_id
    this.study = ""
    this.specimen = ""
    this.subject_id = ""
    this.image_id = ""
    this.study_id = ""
    this.store.getSlide(pathdb_id).then(data => {
      data = data[0]
      console.log(data)
      // set mpp
      this.mpp = 1e9

      if (data.field_mpp_y && data.field_mpp_y.length >= 1) {
        this.mpp_y = data.field_mpp_y[0].value
        this.mpp = this.mpp_y
      }
      if (data.field_mpp_x && data.field_mpp_x.length >= 1) {
        this.mpp_x = data.field_mpp_x[0].value
        this.mpp = this.mpp_x
      }
      if (data.referencepixelphysicalvaluey && data.referencepixelphysicalvaluey.length >=1){
        this.mpp_y = data.referencepixelphysicalvaluey[0].value
        this.mpp = this.mpp_y
      }
      if (data.referencepixelphysicalvaluex && data.referencepixelphysicalvaluex.length >=1){
        this.mpp_x = data.referencepixelphysicalvaluex[0].value
        this.mpp = this.mpp_x
      }
      // identifier fields
      if(data.field_subject_id && data.field_subject_id.length >= 1){
        this.subject_id = data.field_subject_id[0].value
      }
      if(data.clinicaltrialsubjectid && data.clinicaltrialsubjectid.length >= 1){
        this.subject_id = data.clinicaltrialsubjectid[0].value
      }
      if(data.field_image_id && data.field_image_id.length >=1){
        this.image_id = data.field_image_id[0].value
      }
      if(data.imageid && data.imageid.length >=1){
        this.image_id = data.imageid[0].value
      }
      if(data.field_study_id && data.field_study_id.length >=1){
        this.study_id = data.field_study_id[0].value
      }
      if(data.studyid && data.studyid.length >=1){
        this.study_id = data.studyid[0].value
      }
      Store.prototype.pdb_hm_name = this.image_id

      if (data.field_iip_path && data.field_iip_path.length >= 1) {
        this.location = data.field_iip_path[0].value
        // MAKE URL FOR IIP
        this.url = "../../img/IIP/raw/?DeepZoom=" + this.location + ".dzi"
        this.viewer.open(this.url);
      } else {
        throw "No image location --could be token"
      }

      this.viewer.mpp = this.mpp;
      this.viewer.mpp_x = this.mpp_x;
      this.viewer.mpp_y = this.mpp_y;

      //set scalebar
      if (this.mpp && this.mpp != 1e9) this.createScalebar(this.mpp)
      var imagingHelper = new OpenSeadragonImaging.ImagingHelper({
        viewer: this.viewer
      });
      imagingHelper.setMaxZoom(1);
      // create item to pass to the callback function, previously x[0] (slide data)
      let x = {}
      x['_id'] = this.slideId
      x.name = this.slideName

      // identifier field
      x.subject_id = this.subject_id
      x.image_id = this.image_id
      x.study_id = this.study_id

      x.study = this.study
      x.specimen = this.specimen
      x.mpp = this.mpp;
      x.mpp_x = this.mpp_x;
      x.mpp_y = this.mpp_y;
      x.location = this.location;
      x.url = this.url;
      if (func && typeof func === 'function') {
        func.call(null, x);
      }
      Loading.text.textContent = `Loading Slide's Tiles...`;
      // we may want another init.js or our own callback
    }).catch(e => {
      console.error(e)
      Loading.text.textContent = "ERROR - PathDB Image Error (Try A Refresh)"
      //if(func && typeof func === 'function') func.call(null,{hasError:true,message:e});
    })

  }
}

PathDbMods()
console.warn("This Setup Is Intended For Pathdb")
<commit_msg>move pathdb conversion logic<commit_after>function PathDbMods() {
  console.log("PathDbMods()...");
  // put the auth jwt in cookie as token
  fetch("/jwt/token", {
    method: 'GET',
    credentials: 'include'
  }).then(x => x.json()).then(x => {
    console.log(x)
    if (x.hasOwnProperty('token') && x.token) {
      document.cookie = "token=" + x.token + ";"
    }
  })

  function convertPathDbSlide(data){
    let x={}
    x["_raw"] = data
    x.mpp = 1e9
    x.source="pathdb"
    let pathdbid = data.nid[0].value
    x["_id"] = {"$oid": pathdbid}
    x.location = data.field_iip_path[0].value
    if (data.field_mpp_y && data.field_mpp_y.length >= 1) {
      this.mpp_y = data.field_mpp_y[0].value
      this.mpp = this.mpp_y
    }
    if (data.field_mpp_x && data.field_mpp_x.length >= 1) {
      x.mpp_x = data.field_mpp_x[0].value
      x.mpp = this.mpp_x
    }
    if (data.referencepixelphysicalvaluey && data.referencepixelphysicalvaluey.length >=1){
      x.mpp_y = data.referencepixelphysicalvaluey[0].value
      x.mpp = this.mpp_y
    }
    if (data.referencepixelphysicalvaluex && data.referencepixelphysicalvaluex.length >=1){
      x.mpp_x = data.referencepixelphysicalvaluex[0].value
      x.mpp = this.mpp_x
    }
    if (data.field_iip_path && data.field_iip_path.length >= 1) {
      x.location = data.field_iip_path[0].value
      x.url = "../../img/IIP/raw/?DeepZoom=" + x.location + ".dzi"
    } else {
      throw "no iip path in pathdb data"
    }
    return x
  }

  /**
  Gets a named cookie value
  * @param {string} key - the key to get from the cookie
  **/
  function getCookie(key) {
    var cookiestring = RegExp("" + key + "[^;]+").exec(document.cookie);
    return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./, "") : "");
  }
  console.warn("{PathDB mods enabled}")
  Store.prototype.default_findSlide = Store.prototype.findSlide;
  Store.prototype.findSlide = function(slide, specimen, study, location) {
    var url = "/node/" + slide + "?_format=json"
    return fetch(url, {
      mode: "cors",
      headers: new Headers({
        'Authorization': 'Bearer ' + getCookie("token"),
      })
    }).then(function(response) {
      if (!response.ok) return {
        error: !response.ok,
        text: response.statusText,
        url: response.url
      };
      return response.json().then(convertPathDbSlide).then(x => [x]);
    })
  }
  Store.prototype.default_getSlide = Store.prototype.getSlide
  Store.prototype.getSlide = function(id) {
    var url = "/node/" + id + "?_format=json"
    return fetch(url, {
      mode: "cors",
      headers: new Headers({
        'Authorization': 'Bearer ' + getCookie("token"),
      })
    }).then(function(response) {
      if (!response.ok) return {
        error: !response.ok,
        text: response.statusText,
        url: response.url
      };
      return response.json().then(convertPathDbSlide).then(x => [x]);
    })
  }

  StatesHelper.prototype.default_getCurrentStatesURL = StatesHelper.prototype.getCurrentStatesURL;
  getCurrentStatesURL = function(isImageCoordinate=false){
    let states = StatesHelper.getCurrentStates(isImageCoordinate);
    if(!states)return;
    console.log(states);
    states = StatesHelper.encodeStates(states);
    return `${location.origin}${location.pathname}?slideId=${$D.params.slideId}&states=${$D.params.states}&mode=${$D.params.mode}`
  };

  CaMic.prototype.default_loadImg = CaMic.prototype.loadImg
  CaMic.prototype.loadImg = function(func) {
    var urlParams = new URLSearchParams(window.location.search);
    var pathdb_id = urlParams.get('slideId');
    this.slideId = pathdb_id // default value
    this.slideName = pathdb_id
    this.store.getSlide(pathdb_id).then(data => {
      data = data[0]
      console.log(data)
      this.location = data.location
      // MAKE URL FOR IIP
      this.url = data.url
      this.viewer.open(this.url);

      this.viewer.mpp = this.mpp;
      this.viewer.mpp_x = this.mpp_x;
      this.viewer.mpp_y = this.mpp_y;

      //set scalebar
      if (this.mpp && this.mpp != 1e9) this.createScalebar(this.mpp)
      var imagingHelper = new OpenSeadragonImaging.ImagingHelper({
        viewer: this.viewer
      });
      imagingHelper.setMaxZoom(1);
      // create item to pass to the callback function, previously x[0] (slide data)
      let x = {}
      x['_id'] = this.slideId
      x.name = this.slideName
      // other slide data
      x.mpp = this.mpp;
      x.mpp_x = this.mpp_x;
      x.mpp_y = this.mpp_y;
      x.location = this.location;
      x.url = this.url;
      x.rawData = this.rawData
      if (func && typeof func === 'function') {
        func.call(null, x);
      }
      Loading.text.textContent = `Loading Slide's Tiles...`;
      // we may want another init.js or our own callback
    }).catch(e => {
      console.error(e)
      Loading.text.textContent = "ERROR - PathDB Image Error (Try A Refresh)"
      //if(func && typeof func === 'function') func.call(null,{hasError:true,message:e});
    })

  }
}

PathDbMods()
console.warn("This Setup Is Intended For Pathdb")
<|endoftext|>


<commit_before>window.urb.seqn_u = 1
window.urb.dely = 0
window.urb.puls = false
window.urb.cabs = {}
if(!window.urb.appl) window.urb.appl = null

window.urb.req = function(method,url,params,json,cb) {
  var xhr = new XMLHttpRequest()
  method = method.toUpperCase()
  if(method == "PUT" || method == "DELETE")
    xhr.open("POST", url+"?"+method)
  else xhr.open(method, url)

  if(json)
    xhr.setRequestHeader("content-type", "text/json")

  _data = {oryx: window.urb.oryx}
  if(params.xyro) { _data.xyro = params.xyro; }
  if(params.ship) { _data.ship = params.ship; }
  if(params.path) { _data.path = params.path; }
  if(params.appl) { _data.appl = params.appl; }
  if(params.mark) { _data.mark = params.mark; }
  if(cb) {
    xhr.onload = function() {
      try {
        err = null
        res = {
          status:this.status,
          data: JSON.parse(this.responseText)
        }
        if(res.data.reload)
          res.reload = res.data.reload
      } catch(e) {
        if(urb.wall || true) document.write(this.responseText) // XX
        err = {
          message:"Failed to parse JSON",
          raw:this.responseText
        }
        res = null
      }
      cb(err,res)
    }
    xhr.onerror = function() {
      cb({
        status:this.status,
        data:this.responseText
      })
    }
  }
  xhr.send(JSON.stringify(_data))
}

window.urb.reqq = []
window.urb.qreq = function(method,url,params,json,cb) {
  walk = function() {
    qobj = {}
    qobj.oargs = window.urb.reqq[0]
    qobj.nargs = [].slice.apply(qobj.oargs,[0,4])
    qobj.nargs.push(function(){
      if(this.oargs[4])
        this.oargs[4].apply(window.urb,arguments)
      window.urb.reqq.shift()
      if(window.urb.reqq.length > 0)
        walk()
    }.bind(qobj))
    window.urb.req.apply(this,qobj.nargs)
  }
  l = window.urb.reqq.length
  window.urb.reqq.push(arguments);
  if(l == 0) { walk() }
}

window.urb.gsig = function(params) {
  var path = params.path
  if(!path) path = ""
  if(path[0] != "/") path = "/"+path
  return  "~"+params.ship+"/"+
          params.appl+
          path.replace(/[^\x00-\x7F]/g, "")
}

window.urb.poll = function(params) {
  if(!params) throw new Error("You must supply params to urb.poll.")

  var url, $this

  seqn = this.seqn_u
  if(params.seqn) seqn = params.seqn()

  url = "/~/of/"+this.ixor+"?poll="+seqn

  this.puls = true

  $this = this
  this.req("get",url,params,true,function(err,resp) {
    if(resp){
      if(resp.beat)
        return $this.poll(params)
      switch(resp.data.type){
          case "news":
        return document.location.reload()  // XX check autoreload
          case "rush":
        var fn = $this.gsig(resp.data.from)
        if($this.cabs[fn])
          $this.cabs[fn].call(this,err,
            {status: resp.status, data: resp.data.data.json}) // XX non-json
        break;
          default:
        throw new Error("Lost event %"+resp.type)
      }
    }

    dely = params.dely ? params.dely : $this.dely

    if(err)
      dely = dely+Math.ceil(dely*.02)
    else {
      $this.dely = 0
      if(params.incs)
        params.incs()
      else
        $this.seqn_u++
    }

    setTimeout(function() {
      $this.poll(params)
    },dely)
  })
}

// if (window.urb.auto) {  // need dependencies
//   var tries = 0
//   var cnt = 0
//   var param = {
//     type:"pol"
//   }
//   window.urb.poll(param)
// }

// window.urb.heartbeat = function() {
//   this.poll({
//     type:"heb",
//     ship:this.ship,
//     dely:30000,
//     seqn:function() {
//       return window.urb.seqn_h
//     },
//     incs:function() {
//       window.urb.seqn_h = window.urb.seqn_h+1
//     }
//   },function() {
//     console.log('heartbeat.')
//   })
// }
// window.urb.heartbeat()

//  //  /  //  /  //  //
// end old %eyre code //
//  //  /  //  /  //  //

window.urb.seqn_s = 0

// TODO urb.send(data, [params/params.appl]?, cb?)
window.urb.send = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.send.")
  if(!params.appl && !this.appl){
    throw new Error("You must specify an appl for urb.send.")
  }

  var url, $this

  params.ship = params.ship ? params.ship : this.ship
  params.appl = params.appl ? params.appl : this.appl
  params.mark = params.mark ? params.mark : "json"
  params.xyro = params.data ? params.data : {}

  url = ["to",params.appl,params.mark]
  url = "/~/"+url.join("/")

  this.seqn_s++

  $this = this
  this.qreq('post',url,params,true,function(err,data) {
    if(err) { $this.seqn_s--; }
    if(cb) { cb.apply(this,arguments); }
  })
}

window.urb.subscribe = function(params,cb) {   //  legacy interface
  if(!params) throw new Error("You must supply params to urb.subscribe")
  return window.urb.bind(params.path, params, cb)
}
window.urb.bind = function(path, cb){ // or bind(path, params, cb, nice-cb?)
  var params = {appl: window.urb.appl}
  if(arguments.length == 3){params = cb; cb = arguments[2]}

  if(!path) throw new Error("You must specify a path for urb.bind.")
  if(!params.appl) throw new Error("You must specify an appl for urb.bind.")
  if(!cb) throw new Error("You must supply a callback to urb.bind.")

  if(path[0] !== "/") path = "/"+path

  params.path = path
  params.ship = params.ship ? params.ship : this.ship
  params.appl = params.appl ? params.appl : this.appl

  var method, perm, url, $this

  this.cabs[this.gsig(params)] = cb

  url = "/~/is/"+this.gsig(params)

  $this = this
  this.qreq("put",url,params,true,function(err,resp) {
    if(cb) { cb.apply(this,[err,{status: resp.status, data: resp.data}])}
    //  XX give raw data
    //
    if(!err && !$this.puls) $this.poll(params)
  })
}

window.urb.unsubscribe = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.unsubscribe.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.unsubscribe.")
    params.appl = urb.appl
  }
  if(!params.path)
    throw new Error("You must specify a path for urb.unsubscribe.")
  params.ship = params.ship ? params.ship : this.ship

  method = "delete"
  type = "uns"
  url = [this.perms[type],this.user,this.port]
  url = "/"+url.join("/")

  var $this = this
  this.req(method,url,params,true,function(err,resp) {
    cb(err,resp)
  })
}

window.urb.util = {
  toDate: function (dat){
    var mils = Math.floor((0x10000 * dat.getUTCMilliseconds()) / 1000).toString(16)
    function pad(num, str){
      return ((new Array(num + 1)).join('0') + str).substr(-num,num)
    }
    return  '~' + dat.getUTCFullYear() +
            '.' + (dat.getUTCMonth() + 1) +
            '.' + dat.getUTCDate() +
           '..' + pad(2, dat.getUTCHours()) +
            '.' + pad(2, dat.getUTCMinutes()) +
            '.' + pad(2, dat.getUTCSeconds()) +
           '..' + pad(4, mils)
  }
}
<commit_msg>Separate subscription-success and data callbacks, leaving legacy interface in place<commit_after>window.urb.seqn_u = 1
window.urb.dely = 0
window.urb.puls = false
window.urb.cabs = {}
if(!window.urb.appl) window.urb.appl = null

window.urb.req = function(method,url,params,json,cb) {
  var xhr = new XMLHttpRequest()
  method = method.toUpperCase()
  if(method == "PUT" || method == "DELETE")
    xhr.open("POST", url+"?"+method)
  else xhr.open(method, url)

  if(json)
    xhr.setRequestHeader("content-type", "text/json")

  _data = {oryx: window.urb.oryx}
  if(params.xyro) { _data.xyro = params.xyro; }
  if(params.ship) { _data.ship = params.ship; }
  if(params.path) { _data.path = params.path; }
  if(params.appl) { _data.appl = params.appl; }
  if(params.mark) { _data.mark = params.mark; }
  if(cb) {
    xhr.onload = function() {
      try {
        err = null
        res = {
          status:this.status,
          data: JSON.parse(this.responseText)
        }
        if(res.data.reload)
          res.reload = res.data.reload
      } catch(e) {
        if(urb.wall || true) document.write(this.responseText) // XX
        err = {
          message:"Failed to parse JSON",
          raw:this.responseText
        }
        res = null
      }
      cb(err,res)
    }
    xhr.onerror = function() {
      cb({
        status:this.status,
        data:this.responseText
      })
    }
  }
  xhr.send(JSON.stringify(_data))
}

window.urb.reqq = []
window.urb.qreq = function(method,url,params,json,cb) {
  walk = function() {
    qobj = {}
    qobj.oargs = window.urb.reqq[0]
    qobj.nargs = [].slice.apply(qobj.oargs,[0,4])
    qobj.nargs.push(function(){
      if(this.oargs[4])
        this.oargs[4].apply(window.urb,arguments)
      window.urb.reqq.shift()
      if(window.urb.reqq.length > 0)
        walk()
    }.bind(qobj))
    window.urb.req.apply(this,qobj.nargs)
  }
  l = window.urb.reqq.length
  window.urb.reqq.push(arguments);
  if(l == 0) { walk() }
}

window.urb.gsig = function(params) {
  var path = params.path
  if(!path) path = ""
  if(path[0] != "/") path = "/"+path
  return  "~"+params.ship+"/"+
          params.appl+
          path.replace(/[^\x00-\x7F]/g, "")
}

window.urb.poll = function(params) {
  if(!params) throw new Error("You must supply params to urb.poll.")

  var url, $this

  seqn = this.seqn_u
  if(params.seqn) seqn = params.seqn()

  url = "/~/of/"+this.ixor+"?poll="+seqn

  this.puls = true

  $this = this
  this.req("get",url,params,true,function(err,res) {
    if(res){
      if(res.data.beat)
        return $this.poll(params)
      switch(res.data.type){
          case "news":
        return document.location.reload()  // XX check autoreload
          case "rush":
        var fn = $this.gsig(res.data.from)
        if($this.cabs[fn])
          $this.cabs[fn].call(this,err,
            {status: res.status, data: res.data.data.json}) // XX non-json
        break;
          default:
        throw new Error("Lost event %"+res.type)
      }
    }

    dely = params.dely ? params.dely : $this.dely

    if(err)
      dely = dely+Math.ceil(dely*.02)
    else {
      $this.dely = 0
      if(params.incs)
        params.incs()
      else
        $this.seqn_u++
    }

    setTimeout(function() {
      $this.poll(params)
    },dely)
  })
}

// if (window.urb.auto) {  // need dependencies
//   var tries = 0
//   var cnt = 0
//   var param = {
//     type:"pol"
//   }
//   window.urb.poll(param)
// }

// window.urb.heartbeat = function() {
//   this.poll({
//     type:"heb",
//     ship:this.ship,
//     dely:30000,
//     seqn:function() {
//       return window.urb.seqn_h
//     },
//     incs:function() {
//       window.urb.seqn_h = window.urb.seqn_h+1
//     }
//   },function() {
//     console.log('heartbeat.')
//   })
// }
// window.urb.heartbeat()

//  //  /  //  /  //  //
// end old %eyre code //
//  //  /  //  /  //  //

window.urb.seqn_s = 0

// TODO urb.send(data, [params/params.appl]?, cb?)
window.urb.send = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.send.")
  if(!params.appl && !this.appl){
    throw new Error("You must specify an appl for urb.send.")
  }

  var url, $this

  params.ship = params.ship ? params.ship : this.ship
  params.appl = params.appl ? params.appl : this.appl
  params.mark = params.mark ? params.mark : "json"
  params.xyro = params.data ? params.data : {}

  url = ["to",params.appl,params.mark]
  url = "/~/"+url.join("/")

  this.seqn_s++

  $this = this
  this.qreq('post',url,params,true,function(err,data) {
    if(err) { $this.seqn_s--; }
    if(cb) { cb.apply(this,arguments); }
  })
}

window.urb.subscribe = function(params,cb) {   //  legacy interface
  if(!params) throw new Error("You must supply params to urb.subscribe")
  return window.urb.bind(params.path, params, cb, cb)
}
window.urb.bind = function(path, cb){ // or bind(path, params, cb, nicecb?)
  var params, nicecb
  if(arguments.length > 2)
    {params = cb; cb = arguments[2], nicecb = arguments[3]}
  else params = {}

  params.path = path
  params.ship = params.ship ? params.ship : this.ship
  params.appl = params.appl ? params.appl : this.appl

  if(!path) throw new Error("You must specify a path for urb.bind.")
  if(!params.appl) throw new Error("You must specify an appl for urb.bind.")
  if(!cb) throw new Error("You must supply a callback to urb.bind.")

  if(path[0] !== "/") path = "/"+path

  var method, perm, url, $this

  this.cabs[this.gsig(params)] = cb

  url = "/~/is/"+this.gsig(params)

  $this = this
  this.qreq("put",url,params,true,function(err,res) {
    if(nicecb) { nicecb.apply(this,[err,{status: res.status, data: res.data}])}
    //  XX give raw data
    //
    if(!err && !$this.puls) $this.poll(params)
  })
}

window.urb.unsubscribe = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.unsubscribe.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.unsubscribe.")
    params.appl = urb.appl
  }
  if(!params.path)
    throw new Error("You must specify a path for urb.unsubscribe.")
  params.ship = params.ship ? params.ship : this.ship

  method = "delete"
  type = "uns"
  url = [this.perms[type],this.user,this.port]
  url = "/"+url.join("/")

  var $this = this
  this.req(method,url,params,true,function(err,res) {
    cb(err,res)
  })
}

window.urb.util = {
  toDate: function (dat){
    var mils = Math.floor((0x10000 * dat.getUTCMilliseconds()) / 1000).toString(16)
    function pad(num, str){
      return ((new Array(num + 1)).join('0') + str).substr(-num,num)
    }
    return  '~' + dat.getUTCFullYear() +
            '.' + (dat.getUTCMonth() + 1) +
            '.' + dat.getUTCDate() +
           '..' + pad(2, dat.getUTCHours()) +
            '.' + pad(2, dat.getUTCMinutes()) +
            '.' + pad(2, dat.getUTCSeconds()) +
           '..' + pad(4, mils)
  }
}
<|endoftext|>


<commit_before>var cheerio = require('cheerio');

function parseResultBody(body) {
    $ = cheerio.load(body);

    console.log($('[id^=win0divGPSSR_CLSRSLT_WRK_GROUPBOX2]').length);
}

module.exports = {
    parseResultBody: parseResultBody
}<commit_msg>Added title parser<commit_after>var cheerio = require('cheerio');

function parseResultBody(body) {
    $ = cheerio.load(body);

    var headers = resultsToArray($, '[id^=win0divGPSSR_CLSRSLT_WRK_GROUPBOX2]');
    console.log(headers);
}

function resultsToArray(body, parseString) {
    var results = body(parseString);
    var resultsArray = [];

    results.each(function(i) {
        resultsArray[i] = $(this).text().trim();
    });

    return resultsArray;
}

module.exports = {
    parseResultBody: parseResultBody
}<|endoftext|>


<commit_before>'use strict'

export default function (cepRawValue) {
  return new Promise((resolve, reject) => {
    validateInput(cepRawValue)
      .then(removeSpecialCharacters)
      .then(finish)
      .catch(reject)

    function validateInput (cepRawValue) {
      return new Promise(function (resolve, reject) {
        var cepTypeOf = typeof cepRawValue

        if (cepTypeOf === 'number' || cepTypeOf === 'string') {
          return resolve(cepRawValue)
        }

        return reject({
          type: 'type_error',
          message: 'You need to call the constructor with a String or Number.'
        })
      })
    }

    function removeSpecialCharacters (cepRawValue) {
      return new Promise((resolve, reject) => {
        let cepCleanValue = cepRawValue.toString().replace(/[^0-9]+/ig, '')
        resolve(cepCleanValue)
      })
    }

    function finish (cepResult) {
      resolve(cepResult)
    }
  })
}
<commit_msg>feat(error): melhora e centraliza o handle de erros<commit_after>'use strict'

export default function (cepRawValue) {
  return new Promise((resolve, reject) => {
    validateInput(cepRawValue)
      .then(removeSpecialCharacters)
      .then(finish)
      .catch(handleError)

    function validateInput (cepRawValue) {
      return new Promise(function (resolve, reject) {
        var cepTypeOf = typeof cepRawValue

        if (cepTypeOf === 'number' || cepTypeOf === 'string') {
          return resolve(cepRawValue)
        }

        throw new TypeError('You need to call the constructor with a String or Number.')
      })
    }

    function removeSpecialCharacters (cepRawValue) {
      return new Promise((resolve, reject) => {
        let cepCleanValue = cepRawValue.toString().replace(/[^0-9]+/ig, '')
        resolve(cepCleanValue)
      })
    }

    function finish (cepResult) {
      resolve(cepResult)
    }

    function handleError (error) {
      if (error instanceof TypeError) {
        return reject({
          type: 'type_error',
          message: error.message
        })
      }

      return reject({
        type: 'internal_error',
        message: 'Internal error.'
      })
    }
  })
}
<|endoftext|>


<commit_before>define(
  'ephox.robin.api.general.Clumps',

  [
    'ephox.compass.Arr',
    'ephox.perhaps.Option',
    'ephox.phoenix.api.general.Split',
    'ephox.robin.clumps.Clumps',
    'ephox.robin.clumps.EntryPoints',
    'ephox.robin.clumps.Fractures'
  ],

  function (Arr, Option, Split, Clumps, EntryPoints, Fractures) {
    /*
     * clumping fracture: *fractures* method.
     *  - this breaks the full range specified by (start, soffset) -> (finish, foffset) into
     *    clumps based on boundary tags. Each clump (which will NOT HAVE block elements) is
     *    then fractured via *fracture* and the resulting list/array is returned.
     */
    var same = function (universe, start, soffset, foffset) {
      var middle = Split.splitByPair(universe, start, soffset, foffset);
      return Option.some([ middle ]);
    };

    var diff = function (universe, isRoot, start, soffset, finish, foffset, ceiling) {
      var rightSide = EntryPoints.toRight(universe, isRoot, finish, foffset);
      var leftSide = EntryPoints.toLeft(universe, isRoot, start, soffset);
      return Fractures.fracture(universe, isRoot, leftSide, rightSide, ceiling);
    };

    /* inline fracture: *fracture* method.
     *  - this identifies the slice of child nodes from a common ancestor that defines the
     *    clump boundary: (start, soffset) -> (finish, foffset). It assumes that it is
     *    a *true* clump (i.e. contains NO block elements), so all of the children
     *    identified can be wrapped by an INLINE tag. Note, clumps are identified via the
     *    *Clumps.collect* method.
     *
     *    This may not need to be exposed, and is currently exposed just for testing.
     */
    var fracture = function (universe, isRoot, start, soffset, finish, foffset, ceiling) {
      var sameText = universe.property().isText(start) && universe.eq(start, finish);
      return sameText ? same(universe, start, soffset, foffset) : diff(universe, isRoot, start, soffset, finish, foffset, ceiling);
    };

    // TODO: Handle backwards selections ! Maybe higher up when we definitely have the DOM.
    var fractures = function (universe, isRoot, start, soffset, finish, foffset, ceiling) {
      var clumps = Clumps.collect(universe, isRoot, start, soffset, finish, foffset);
      return Arr.bind(clumps, function (clump, i) {
        return fracture(universe, isRoot, clump.start(), clump.soffset(), clump.finish(), clump.foffset(), ceiling).toArray();
      });
    };

    return {
      fractures: fractures,
      fracture: fracture
    };
  }
);<commit_msg>TBIO-1766: cleanup<commit_after>define(
  'ephox.robin.api.general.Clumps',

  [
    'ephox.compass.Arr',
    'ephox.perhaps.Option',
    'ephox.phoenix.api.general.Split',
    'ephox.robin.clumps.Clumps',
    'ephox.robin.clumps.EntryPoints',
    'ephox.robin.clumps.Fractures'
  ],

  function (Arr, Option, Split, Clumps, EntryPoints, Fractures) {
    /*
     * clumping fracture: *fractures* method.
     *  - this breaks the full range specified by (start, soffset) -> (finish, foffset) into
     *    clumps based on boundary tags. Each clump (which will NOT HAVE block elements) is
     *    then fractured via *fracture* and the resulting list/array is returned.
     */
    var same = function (universe, start, soffset, foffset) {
      var middle = Split.splitByPair(universe, start, soffset, foffset);
      return Option.some([ middle ]);
    };

    var diff = function (universe, isRoot, start, soffset, finish, foffset, ceiling) {
      var rightSide = EntryPoints.toRight(universe, isRoot, finish, foffset);
      var leftSide = EntryPoints.toLeft(universe, isRoot, start, soffset);
      return Fractures.fracture(universe, isRoot, leftSide, rightSide, ceiling);
    };

    /* inline fracture: *fracture* method.
     *  - this identifies the slice of child nodes from a common ancestor that defines the
     *    clump boundary: (start, soffset) -> (finish, foffset). It assumes that it is
     *    a *true* clump (i.e. contains NO block elements), so all of the children
     *    identified can be wrapped by an INLINE tag. Note, clumps are identified via the
     *    *Clumps.collect* method.
     *
     *    This may not need to be exposed, and is currently exposed just for testing.
     */
    var fracture = function (universe, isRoot, start, soffset, finish, foffset, ceiling) {
      var sameText = universe.property().isText(start) && universe.eq(start, finish);
      return sameText ? same(universe, start, soffset, foffset) : diff(universe, isRoot, start, soffset, finish, foffset, ceiling);
    };

    var fractures = function (universe, isRoot, start, soffset, finish, foffset, ceiling) {
      var clumps = Clumps.collect(universe, isRoot, start, soffset, finish, foffset);
      return Arr.bind(clumps, function (clump, i) {
        return fracture(universe, isRoot, clump.start(), clump.soffset(), clump.finish(), clump.foffset(), ceiling).toArray();
      });
    };

    return {
      fractures: fractures,
      fracture: fracture
    };
  }
);<|endoftext|>


<commit_before>function myClick() {
      setTimeout(
         function() {
            _satellite.track('dtm-direct-call-rule');
            alert('Bang!');
         }, 3000);
   }
<commit_msg>Update on-click.js<commit_after>function myClick() {
      setTimeout(
         function() {
            _satellite.track('dtm-direct-call-rule');
            //alert('Bang!');
         }, 3000);
   }
<|endoftext|>


<commit_before>var isUploadSuccess = 'hoge';

$(function(){
  var timerID;
  var timerArray = new Array();
  var timer;
  timelineAllLoad();

  if ( gorgon.timer != undefined )
  {
    timer = gorgon.timer;
  }
  else
  {
    timer = 15000;
  }

  timerID = setInterval('timelineDifferenceLoad()', timer);
  if ( gorgon.notify !== undefined )
  {
    $('#timeline-desktopify').desktopify({
      unsupported : function(){
        $('#timeline-desktopify').hide();
      }
    }).trigger('click');
  }

  $('#timeline-submit-button').click( function() {

    $('#timeline-submit-error').text('');
    $('#timeline-submit-error').hide();
    $('#timeline-submit-loader').show();
    $('#photo-file-name').text('');

    var body = $('#timeline-textarea').val();

    if (gorgon)
    {
      var data = {
        body: body,
        target: gorgon.post.foreign,
        target_id: gorgon.post.foreignId,
        apiKey: openpne.apiKey,
        public_flag: $('#timeline-public-flag option:selected').val()
      };
    }
    else
    {
      var data = {
        body: body,
        apiKey: openpne.apiKey
      };
    }

    tweetByData(data);
  });

  $('#timeline-loadmore').click( function() {
    $('#timeline-loadmore').hide();
    $('#timeline-loadmore-loading').show();
    timelineLoadmore();
  });

  $('.timeline-comment-loadmore').live('click', function() {
    var timelineId = $(this).attr('data-timeline-id');
    var commentlist = $('#commentlist-' + timelineId);
    var commentLength = commentlist.children('.timeline-post-comment').length;
    $('#timeline-comment-loader-' + timelineId).show();

    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'timeline/commentSearch.json?apiKey=' + openpne.apiKey,
      data: {
        'timeline_id': timelineId,
        'count': commentLength + 20
      },
      success: function(json){
        commentlist.children('.timeline-post-comment').remove();
        $('#timelineCommentTemplate').tmpl(json.data.reverse()).prependTo('#commentlist-' + timelineId);
        $('#timeline-comment-loader-' + timelineId).hide();

        if (json.data.length < commentLength + 20)
        {
          $('#timeline-comment-loadmore-' + timelineId).hide();
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#commentlist-' + timelineId).hide();
      }
    });
  });

  $('#timeline-submit-upload').change(function() {
    var fileName = $('#timeline-submit-upload').val();
    if (20 > fileName.length)
    {
      $('#photo-file-name').text(fileName);
    }
    else
    {
      $('#photo-file-name').text(fileName.substring(0, 19) + '…');
    }
  });

  $('#timeline-upload-photo-button').click(function() {
    $('#timeline-submit-upload').click();
  });
});

function timelineAllLoad() {
  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'timeline/search.json',
      data: gorgon,
      success: function(json){
        renderJSON(json, 'all');
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
  else
  {
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'timeline/search.json?apiKey=' + openpne.apiKey,
      success: function(json){
        renderJSON(json, 'all');
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
}

function timelineDifferenceLoad() {
  var lastId = $('#timeline-list').attr('data-last-id');

  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  $.getJSON( openpne.apiBase + 'timeline/search.json?count=20&since_id=' + lastId, gorgon, function(json){
    if (json.data)
    {
      renderJSON(json, 'diff');
    }
  });
}

function timelineLoadmore() {
  var loadmoreId = $('#timeline-list').attr('data-loadmore-id');
  loadmoreId = loadmoreId - 1;
  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  gorgon.max_id = loadmoreId;

  $.ajax({
    type: 'GET',
    url: openpne.apiBase + 'timeline/search.json',
    data: gorgon,
    success: function(json){
      renderJSON(json, 'more');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      $('#timeline-loadmore-loading').hide();
    }
  });
}

function renderJSON(json, mode) {
  if (undefined == mode)
  {
    mode = 'all';
  }
  if ('all' == mode)
  {
    $('#timeline-list').empty();
  }
  if(json.data && 0 < viewPhoto)
  {
    for(i=0;i<json.data.length;i++)
    {
      if (!json.data[i].body_html.match(/img.*src=/))
      {
        if (json.data[i].body.match(/\.(jpg|jpeg|bmg|png|gif)/gi))
        {
          json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+.(jpg|jpeg|bmg|png|gif))/gi, '

');
        }
        else if (json.data[i].body.match(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi))
        {
          json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi, '

$1
');
        }
      }
    }
  }

  $timelineData = $('#timelineTemplate').tmpl(json.data);
  $('.timeline-comment-button', $timelineData).timelineComment();
  $('.timeline-comment-link', $timelineData).click(function(){
    $commentBoxArea = $(this).parent().siblings().find('.timeline-post-comment-form');
    $commentBoxArea.show();
    $commentBoxArea.children('.timeline-post-comment-form-input').focus();
  });
  if ('diff' == mode)
  {
    $timelineData.prependTo('#timeline-list');
  }
  else
  {
    $timelineData.appendTo('#timeline-list');
  }
  if ('all' == mode || 'diff' == mode)
  {
    if(json.data[0])
    {
      $('#timeline-list').attr('data-last-id', json.data[0].id);
    }
  }
  if ('all' == mode || 'more' == mode)
  {
    var max = json.data.length - 1;
    if (json.data[max])
    {
      $('#timeline-list').attr('data-loadmore-id', json.data[max].id);
    }
  }
  if(json.data)
  {
    for(i=0;i<json.data.length;i++)
    {
      if(json.data[i].replies)
      {
        $('#timelineCommentTemplate').tmpl(json.data[i].replies.reverse()).prependTo('#commentlist-' +json.data[i].id);
        $('#timeline-post-comment-form-' + json.data[i].id, $timelineData).show();
      }
      if(10 < parseInt(json.data[i].repliesCount))
      {
        $('#timeline-comment-loadmore-' + json.data[i].id).show();
      }
    }
  }
  $('button.timeline-post-delete-button').timelineDelete();
  $('.timeline-post-delete-confirm-link').colorbox({
    inline: true,
    width: '610px',
    opacity: '0.8',
    onOpen: function(){
      $($(this).attr('href')).show();
    },
    onCleanup: function(){
      $($(this).attr('href')).hide();
    },
    onClosed: function(){
      timelineAllLoad();
    }
  });
  if ('all' == mode)
  {
    $('#timeline-loading').hide();
  }
  if ('more' == mode)
  {
    $('#timeline-loadmore').show();
    $('#timeline-loadmore-loading').hide();
  }
}

function convertTag(str) {
  str = str.replace(/&/g,'&');
  str = str.replace(/"/g,'"');
  str = str.replace(/'/g,''');
  str = str.replace(/</g,'<');
  str = str.replace(/>/g,'>');
  return str;
}

function lengthCheck(obj)
{
  if (MAXLENGTH < obj.value.length)
  {
    $('#timeline-submit-button').attr('disabled','disabled');
  }
  else if ($('#timeline-submit-button').attr('disabled'))
  {
    $('#timeline-submit-button').removeAttr('disabled');
  }
}

function tweetByData(data)
{
  //reference　http://lagoscript.org/jquery/upload/documentation
  $('#timeline-submit-upload').upload(
    openpne.apiBase + 'timeline/post.json', data,
    function (res) {

      alert(typeof(res));

      returnData = JSON.parse(res);

      if (returnData.status === "error") {

        var errorMessages = {
          file_size: 'ファイルサイズは' + fileMaxSize + 'までです',
          upload: 'アップロードに失敗しました',
          not_image: '画像をアップロードしてください',
          tweet: '投稿に失敗しました'
        };

        var errorType = returnData.type;

        $('#timeline-submit-error').text(errorMessages[errorType]);
        $('#timeline-submit-error').show();

      } else {
        $('#timeline-submit-error').text('');
        timelineAllLoad();
      }

      $('#timeline-submit-upload').val('');
      $('#timeline-textarea').val('');
      $('#timeline-submit-loader').hide();
      $('#timeline-textarea').val('');
      $('#counter').text(MAXLENGTH);

    },
    'text' //なぜかJSON形式でうけとることができなかった
    );
}
<commit_msg>IEのテスト<commit_after>var isUploadSuccess = 'hoge';

$(function(){
  var timerID;
  var timerArray = new Array();
  var timer;
  timelineAllLoad();

  if ( gorgon.timer != undefined )
  {
    timer = gorgon.timer;
  }
  else
  {
    timer = 15000;
  }

  timerID = setInterval('timelineDifferenceLoad()', timer);
  if ( gorgon.notify !== undefined )
  {
    $('#timeline-desktopify').desktopify({
      unsupported : function(){
        $('#timeline-desktopify').hide();
      }
    }).trigger('click');
  }

  $('#timeline-submit-button').click( function() {

    $('#timeline-submit-error').text('');
    $('#timeline-submit-error').hide();
    $('#timeline-submit-loader').show();
    $('#photo-file-name').text('');

    var body = $('#timeline-textarea').val();

    if (gorgon)
    {
      var data = {
        body: body,
        target: gorgon.post.foreign,
        target_id: gorgon.post.foreignId,
        apiKey: openpne.apiKey,
        public_flag: $('#timeline-public-flag option:selected').val()
      };
    }
    else
    {
      var data = {
        body: body,
        apiKey: openpne.apiKey
      };
    }

    tweetByData(data);
  });

  $('#timeline-loadmore').click( function() {
    $('#timeline-loadmore').hide();
    $('#timeline-loadmore-loading').show();
    timelineLoadmore();
  });

  $('.timeline-comment-loadmore').live('click', function() {
    var timelineId = $(this).attr('data-timeline-id');
    var commentlist = $('#commentlist-' + timelineId);
    var commentLength = commentlist.children('.timeline-post-comment').length;
    $('#timeline-comment-loader-' + timelineId).show();

    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'timeline/commentSearch.json?apiKey=' + openpne.apiKey,
      data: {
        'timeline_id': timelineId,
        'count': commentLength + 20
      },
      success: function(json){
        commentlist.children('.timeline-post-comment').remove();
        $('#timelineCommentTemplate').tmpl(json.data.reverse()).prependTo('#commentlist-' + timelineId);
        $('#timeline-comment-loader-' + timelineId).hide();

        if (json.data.length < commentLength + 20)
        {
          $('#timeline-comment-loadmore-' + timelineId).hide();
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#commentlist-' + timelineId).hide();
      }
    });
  });

  $('#timeline-submit-upload').change(function() {
    var fileName = $('#timeline-submit-upload').val();
    if (20 > fileName.length)
    {
      $('#photo-file-name').text(fileName);
    }
    else
    {
      $('#photo-file-name').text(fileName.substring(0, 19) + '…');
    }
  });

  $('#timeline-upload-photo-button').click(function() {
    $('#timeline-submit-upload').click();
  });
});

function timelineAllLoad() {
  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'timeline/search.json',
      data: gorgon,
      success: function(json){
        renderJSON(json, 'all');
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
  else
  {
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'timeline/search.json?apiKey=' + openpne.apiKey,
      success: function(json){
        renderJSON(json, 'all');
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
}

function timelineDifferenceLoad() {
  var lastId = $('#timeline-list').attr('data-last-id');

  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  $.getJSON( openpne.apiBase + 'timeline/search.json?count=20&since_id=' + lastId, gorgon, function(json){
    if (json.data)
    {
      renderJSON(json, 'diff');
    }
  });
}

function timelineLoadmore() {
  var loadmoreId = $('#timeline-list').attr('data-loadmore-id');
  loadmoreId = loadmoreId - 1;
  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  gorgon.max_id = loadmoreId;

  $.ajax({
    type: 'GET',
    url: openpne.apiBase + 'timeline/search.json',
    data: gorgon,
    success: function(json){
      renderJSON(json, 'more');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      $('#timeline-loadmore-loading').hide();
    }
  });
}

function renderJSON(json, mode) {
  if (undefined == mode)
  {
    mode = 'all';
  }
  if ('all' == mode)
  {
    $('#timeline-list').empty();
  }
  if(json.data && 0 < viewPhoto)
  {
    for(i=0;i<json.data.length;i++)
    {
      if (!json.data[i].body_html.match(/img.*src=/))
      {
        if (json.data[i].body.match(/\.(jpg|jpeg|bmg|png|gif)/gi))
        {
          json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+.(jpg|jpeg|bmg|png|gif))/gi, '

');
        }
        else if (json.data[i].body.match(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi))
        {
          json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi, '

$1
');
        }
      }
    }
  }

  $timelineData = $('#timelineTemplate').tmpl(json.data);
  $('.timeline-comment-button', $timelineData).timelineComment();
  $('.timeline-comment-link', $timelineData).click(function(){
    $commentBoxArea = $(this).parent().siblings().find('.timeline-post-comment-form');
    $commentBoxArea.show();
    $commentBoxArea.children('.timeline-post-comment-form-input').focus();
  });
  if ('diff' == mode)
  {
    $timelineData.prependTo('#timeline-list');
  }
  else
  {
    $timelineData.appendTo('#timeline-list');
  }
  if ('all' == mode || 'diff' == mode)
  {
    if(json.data[0])
    {
      $('#timeline-list').attr('data-last-id', json.data[0].id);
    }
  }
  if ('all' == mode || 'more' == mode)
  {
    var max = json.data.length - 1;
    if (json.data[max])
    {
      $('#timeline-list').attr('data-loadmore-id', json.data[max].id);
    }
  }
  if(json.data)
  {
    for(i=0;i<json.data.length;i++)
    {
      if(json.data[i].replies)
      {
        $('#timelineCommentTemplate').tmpl(json.data[i].replies.reverse()).prependTo('#commentlist-' +json.data[i].id);
        $('#timeline-post-comment-form-' + json.data[i].id, $timelineData).show();
      }
      if(10 < parseInt(json.data[i].repliesCount))
      {
        $('#timeline-comment-loadmore-' + json.data[i].id).show();
      }
    }
  }
  $('button.timeline-post-delete-button').timelineDelete();
  $('.timeline-post-delete-confirm-link').colorbox({
    inline: true,
    width: '610px',
    opacity: '0.8',
    onOpen: function(){
      $($(this).attr('href')).show();
    },
    onCleanup: function(){
      $($(this).attr('href')).hide();
    },
    onClosed: function(){
      timelineAllLoad();
    }
  });
  if ('all' == mode)
  {
    $('#timeline-loading').hide();
  }
  if ('more' == mode)
  {
    $('#timeline-loadmore').show();
    $('#timeline-loadmore-loading').hide();
  }
}

function convertTag(str) {
  str = str.replace(/&/g,'&');
  str = str.replace(/"/g,'"');
  str = str.replace(/'/g,''');
  str = str.replace(/</g,'<');
  str = str.replace(/>/g,'>');
  return str;
}

function lengthCheck(obj)
{
  if (MAXLENGTH < obj.value.length)
  {
    $('#timeline-submit-button').attr('disabled','disabled');
  }
  else if ($('#timeline-submit-button').attr('disabled'))
  {
    $('#timeline-submit-button').removeAttr('disabled');
  }
}

function tweetByData(data)
{
  //reference　http://lagoscript.org/jquery/upload/documentation
  $('#timeline-submit-upload').upload(
    openpne.apiBase + 'timeline/post.json', data,
    function (res) {

      $("h3").text(res);

      console.log($("h3"));

      returnData = JSON.parse(res);

      if (returnData.status === "error") {

        var errorMessages = {
          file_size: 'ファイルサイズは' + fileMaxSize + 'までです',
          upload: 'アップロードに失敗しました',
          not_image: '画像をアップロードしてください',
          tweet: '投稿に失敗しました'
        };

        var errorType = returnData.type;

        $('#timeline-submit-error').text(errorMessages[errorType]);
        $('#timeline-submit-error').show();

      } else {
        $('#timeline-submit-error').text('');
        timelineAllLoad();
      }

      $('#timeline-submit-upload').val('');
      $('#timeline-textarea').val('');
      $('#timeline-submit-loader').hide();
      $('#timeline-textarea').val('');
      $('#counter').text(MAXLENGTH);

    },
    'text' //なぜかJSON形式でうけとることができなかった
    );
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  colors: {
    black: '#495057',
    red: '#FF6D87',
    green: '#32F7C6',
    yellow: '#FFA924',
    blue: '#04A7D8',
    magenta: '#A79AFF',
    cyan: '#14C4D4',
    white: '#FFFFFF',
    lightBlack: '#CED4DA',
    lightRed: '#FF6D87',
    lightGreen: '#32F7C6',
    lightYellow: '#FFA924',
    lightBlue: '#04A7D8',
    lightMagenta: '#A79AFF',
    lightCyan: '#14C4D4',
    lightWhite: '#FFFFFF',
  },

  // Default
  backgroundColor: '#FFFFFF',
  foregroundColor: '#495057',
  cursorColor: '#00BAFF',
  borderColor: 'transparent',

  // Accent color
  accentColor: '#212529',

  // Other
  inactiveTabTitleColor: 'rgba(134, 142, 150, 0.2)',
  activeTabTitleColor: '#868e96',

  // css
  termCSS: `
  .cursor-node[focus=true] {
    mix-blend-mode: normal;
  }`,
};
<commit_msg>:lipstick: Update apex tab-title color<commit_after>'use strict';

module.exports = {
  colors: {
    black: '#495057',
    red: '#FF6D87',
    green: '#32F7C6',
    yellow: '#FFA924',
    blue: '#04A7D8',
    magenta: '#A79AFF',
    cyan: '#14C4D4',
    white: '#FFFFFF',
    lightBlack: '#CED4DA',
    lightRed: '#FF6D87',
    lightGreen: '#32F7C6',
    lightYellow: '#FFA924',
    lightBlue: '#04A7D8',
    lightMagenta: '#A79AFF',
    lightCyan: '#14C4D4',
    lightWhite: '#FFFFFF',
  },

  // Default
  backgroundColor: '#FFFFFF',
  foregroundColor: '#495057',
  cursorColor: '#00BAFF',
  borderColor: 'transparent',

  // Accent color
  accentColor: '#212529',

  // Other
  inactiveTabTitleColor: '#868E96',
  activeTabTitleColor: '#212529',

  // css
  termCSS: `
  .cursor-node[focus=true] {
    mix-blend-mode: normal;
  }`,
};
<|endoftext|>


<commit_before>'use strict';

module.exports = (() => {
  let apiEndpoint = 'https://play.dhis2.org/demo/api/26'; // default
  let generateHtmlReport = true;
  const RESOURCE_TYPES = {
    OPTION_SET: 'option set',
    DATA_ELEMENT: 'data element',
    ORGANISATION_UNIT: 'organisation unit',
    DATASET: 'dataset',
    CATEGORY_COMBINATION: 'category combination',
    INDICATOR: 'indicator'
  };

  const authorityExistsInUserRoles = (authority, userRoles = []) => {
    if (authority && userRoles.length > 0) {
      for (const index in userRoles) {
        const authorities = userRoles[index].authorities || [];
        if (authorities.includes(authority)) {
          return true;
        }
      }
    }

    return false;
  };

  const generateResourceTypeEndpoint = (resourceType) => {
    let endpoint = '';
    switch (resourceType) {
      case RESOURCE_TYPES.OPTION_SET:
        endpoint = apiEndpoint + '/optionSets';
        break;
      case RESOURCE_TYPES.ORGANISATION_UNIT:
        endpoint = apiEndpoint + '/organisationUnits';
        break;
      case RESOURCE_TYPES.DATA_ELEMENT:
        endpoint = apiEndpoint + '/dataElements';
        break;
      case RESOURCE_TYPES.DATASET:
        endpoint = apiEndpoint + '/dataSets';
        break;
      case RESOURCE_TYPES.CATEGORY_COMBINATION:
        endpoint = apiEndpoint + '/categoryCombos';
        break;
      case RESOURCE_TYPES.INDICATOR:
        endpoint = apiEndpoint + '/indicators';
        break;
      default:
        throw new Error('There is no resource type defined for: ' + resourceType);
    }

    return endpoint;
  };

  return {
    resourceTypes: RESOURCE_TYPES,
    apiEndpoint: (newApiEndpoint) => {
      if (newApiEndpoint) {
        apiEndpoint = newApiEndpoint;
      } else {
        return apiEndpoint;
      }
    },
    generateHtmlReport: (generate) => {
      if (typeof generate === 'undefined') {
        return generateHtmlReport;
      } else {
        generateHtmlReport = generate;
      }
    },
    isAuthorisedToAddDataElementWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_DATAELEMENT_PUBLIC_ADD', userRoles);
    },
    isAuthorisedToAddOrganisationUnitWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_ORGANISATIONUNIT_ADD', userRoles);
    },
    isAuthorisedToAddOptionSetWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_OPTIONSET_PUBLIC_ADD', userRoles);
    },
    isAuthorisedToDeleteOptionSetWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_OPTIONSET_DELETE', userRoles);
    },
    isAuthorisedToAddDataSetWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_DATASET_PUBLIC_ADD', userRoles);
    },
    initializePromiseUrlUsingWorldContext: (world, url) => {
      return world.axios({
        method: world.method || 'get',
        url: url,
        data: world.requestData || {},
        auth: world.authRequestObject
      });
    },
    generateUniqIds: (numberOfIds) => {
      const currentTimestamp = Math.floor(Date.now() / 100);    // 11 digits
      const ids = [];
      const numberOfIdsTemp = numberOfIds || 1;
      for (let seed = 0; seed < numberOfIdsTemp; seed++) {
        ids.push((currentTimestamp - seed) + '');
      }

      return numberOfIds ? ids : ids[0];
    },
    generateUrlForResourceType: (resourceType) => {
      return generateResourceTypeEndpoint(resourceType);
    },
    generateUrlForResourceTypeWithId: (resourceType, resourceId) => {
      const endpoint = generateResourceTypeEndpoint(resourceType);

      if (resourceId) {
        return endpoint + '/' + resourceId;
      }

      return endpoint;
    },
    generateUrlToEndpointWithParams: (resourceType, paramsDictionary = {}) => {
      let url = generateResourceTypeEndpoint(resourceType) + '?';
      for (const key in paramsDictionary) {
        url = url + key + '=' + paramsDictionary[key] + '&';
      }

      return url;
    }
  };
})();
<commit_msg>Code cleanup<commit_after>'use strict';

module.exports = (() => {
  let apiEndpoint = 'https://play.dhis2.org/demo/api/26'; // default
  let generateHtmlReport = true;
  const RESOURCE_TYPES = {
    OPTION_SET: 'option set',
    DATA_ELEMENT: 'data element',
    ORGANISATION_UNIT: 'organisation unit',
    DATASET: 'dataset',
    CATEGORY_COMBINATION: 'category combination',
    INDICATOR: 'indicator'
  };

  const authorityExistsInUserRoles = (authority, userRoles = []) => {
    if (authority && userRoles.length > 0) {
      for (const index in userRoles) {
        const authorities = userRoles[index].authorities || [];
        if (authorities.includes(authority)) {
          return true;
        }
      }
    }

    return false;
  };

  const generateResourceTypeEndpoint = (resourceType) => {
    let endpoint = '';
    switch (resourceType) {
      case RESOURCE_TYPES.OPTION_SET:
        endpoint = apiEndpoint + '/optionSets';
        break;
      case RESOURCE_TYPES.ORGANISATION_UNIT:
        endpoint = apiEndpoint + '/organisationUnits';
        break;
      case RESOURCE_TYPES.DATA_ELEMENT:
        endpoint = apiEndpoint + '/dataElements';
        break;
      case RESOURCE_TYPES.DATASET:
        endpoint = apiEndpoint + '/dataSets';
        break;
      case RESOURCE_TYPES.CATEGORY_COMBINATION:
        endpoint = apiEndpoint + '/categoryCombos';
        break;
      case RESOURCE_TYPES.INDICATOR:
        endpoint = apiEndpoint + '/indicators';
        break;
      default:
        throw new Error('There is no resource type defined for: ' + resourceType);
    }

    return endpoint;
  };

  return {
    resourceTypes: RESOURCE_TYPES,
    apiEndpoint: (newApiEndpoint) => {
      if (newApiEndpoint) {
        apiEndpoint = newApiEndpoint;
      } else {
        return apiEndpoint;
      }
    },
    generateHtmlReport: (generate) => {
      if (typeof generate === 'undefined') {
        return generateHtmlReport;
      } else {
        generateHtmlReport = generate;
      }
    },
    isAuthorisedToAddDataElementWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_DATAELEMENT_PUBLIC_ADD', userRoles);
    },
    isAuthorisedToAddOrganisationUnitWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_ORGANISATIONUNIT_ADD', userRoles);
    },
    isAuthorisedToAddOptionSetWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_OPTIONSET_PUBLIC_ADD', userRoles);
    },
    isAuthorisedToDeleteOptionSetWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_OPTIONSET_DELETE', userRoles);
    },
    isAuthorisedToAddDataSetWith: (userRoles = []) => {
      return authorityExistsInUserRoles('F_DATASET_PUBLIC_ADD', userRoles);
    },
    initializePromiseUrlUsingWorldContext: (world, url) => {
      return world.axios({
        method: world.method || 'get',
        url: url,
        data: world.requestData || {},
        auth: world.authRequestObject
      });
    },
    generateUniqIds: (numberOfIds) => {
      const currentTimestamp = Math.floor(Date.now() / 100);    // 11 digits
      const ids = [];
      const numberOfIdsTemp = numberOfIds || 1;
      for (let seed = 0; seed < numberOfIdsTemp; seed++) {
        ids.push('' + (currentTimestamp - seed));
      }

      return numberOfIds ? ids : ids[0];
    },
    generateUrlForResourceType: (resourceType) => {
      return generateResourceTypeEndpoint(resourceType);
    },
    generateUrlForResourceTypeWithId: (resourceType, resourceId) => {
      const endpoint = generateResourceTypeEndpoint(resourceType);

      if (resourceId) {
        return endpoint + '/' + resourceId;
      }

      return endpoint;
    },
    generateUrlToEndpointWithParams: (resourceType, paramsDictionary = {}) => {
      let url = generateResourceTypeEndpoint(resourceType);
      if (paramsDictionary && Object.keys(paramsDictionary).length > 0) {
        url += '?';
      }

      for (const key in paramsDictionary) {
        url = url + key + '=' + paramsDictionary[key] + '&';
      }

      return url;
    }
  };
})();
<|endoftext|>


<commit_before>define(
  'ephox.snooker.model.TableMerge',

  [
    'ephox.compass.Arr',
    'ephox.peanut.Fun',
    'ephox.snooker.model.Fitment',
    'ephox.snooker.operate.MergingOperations'
  ],

  function (Arr, Fun, Fitment, MergingOperations) {
    // an arbitary limit, to stop retrying incase we hit stack overflows.
    // Its expected that most retries will be under 3 and thats for really edgy cases.
    var RETRIES = 1000;

    var skip = function (start, current, replacement, x) {
      /*
        If the current Position is before or after the insertion point skip over it.
                      let,
                         listA = a, b, c, d, e
                         listB =       1, 2
        merge gridB into listA = a, b, 1, 2, e
        this fn will skip over a, b and e, same concept applies for both rows & columns
      */
      var end = start + replacement;
      return start > current || end <= current;
    };

    var isSpanning = function (grid, row, col, candidate, comparator) {
      var matching = Fun.curry(comparator, candidate);
      var rowArray = grid[row];

      // sanity check, 1x1 has no spans
      return grid.length > 1 && rowArray.length > 1 &&
      (
        // search left, if we're not on the left edge
        (col > 0 && matching(rowArray[col-1])) ||
        // search right, if we're not on the right edge
        (col < rowArray.length - 1 && matching(rowArray[col+1])) ||
        // search up, if we're not on the top edge
        (row > 0 && matching(grid[row-1][col])) ||
        // search down, if we're not on the bottom edge
        (row < grid.length - 1 && matching(grid[row+1][col]))
      );
    };

    var mergeTables = function (startAddress, gridA, gridB, generator, comparator) {
      // Assumes
      //  - gridA is square and gridB is square
      var startRow = startAddress.row();
      var startCol = startAddress.column();
      var mergeHeight = gridB.length;
      var mergeWidth = gridB[0].length;
      var endRow = startRow + mergeHeight;
      var endCol = startCol + mergeWidth;

      // embrace the mutation - I think this is easier to follow? To discuss.
      for (var r = startRow; r < endRow; r++) {
        for (var c = startCol; c < endCol; c++) {
          var cell = gridA[r][c];
          if (isSpanning(gridA, r, c, cell, comparator)) {
            // mutation within mutation, it's mutatception
            MergingOperations.unmerge(gridA, cell, comparator, generator.cell);
          }
          gridA[r][c] = generator.replace(gridB[r - startRow][c - startCol]);
        }
      }
      return gridA;
      // return Arr.map(gridA, function (row, r) {
      //   var repRow = r - startRow;
      //   var skipRow = skip(startRow, r, mergeHeight);
      //   if (skipRow) return row;

      //   else return Arr.map(row, function (cell, c) {
      //     var repCol = c - startCol;
      //     var skipCell = skip(startCol, c, mergeWidth);
      //     if (skipCell) return cell;
      //     else {
      //       if (isSpanning(gridA, r, c, cell, comparator)) {
      //         MergingOperations.unmerge(gridA, cell, comparator, generator.cell);
      //       }
      //       return generator.replace(gridB[repRow][repCol]);
      //     }
      //   });
      // });
    };

    var merge = function (startAddress, gridA, gridB, generator, comparator) {
var start = new Date().getTime();

      var delta = Fitment.measure(startAddress, gridA, gridB);
      var fittedGrid = Fitment.tailor(startAddress, gridA, delta, generator);
      var xx = mergeTables(startAddress, fittedGrid, gridB, generator, comparator);

var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);
      return xx; // inline, only here for logging (aka showing off)

    };

    return {
      merge: merge
    };
  }
);<commit_msg>isSpanning can calculate the candidate itself<commit_after>define(
  'ephox.snooker.model.TableMerge',

  [
    'ephox.compass.Arr',
    'ephox.peanut.Fun',
    'ephox.snooker.model.Fitment',
    'ephox.snooker.operate.MergingOperations'
  ],

  function (Arr, Fun, Fitment, MergingOperations) {
    // an arbitary limit, to stop retrying incase we hit stack overflows.
    // Its expected that most retries will be under 3 and thats for really edgy cases.
    var RETRIES = 1000;

    var skip = function (start, current, replacement, x) {
      /*
        If the current Position is before or after the insertion point skip over it.
                      let,
                         listA = a, b, c, d, e
                         listB =       1, 2
        merge gridB into listA = a, b, 1, 2, e
        this fn will skip over a, b and e, same concept applies for both rows & columns
      */
      var end = start + replacement;
      return start > current || end <= current;
    };

    var isSpanning = function (grid, row, col, comparator) {
      var candidate = grid[row][col];
      var matching = Fun.curry(comparator, candidate);
      var rowArray = grid[row];

      // sanity check, 1x1 has no spans
      return grid.length > 1 && rowArray.length > 1 &&
      (
        // search left, if we're not on the left edge
        (col > 0 && matching(rowArray[col-1])) ||
        // search right, if we're not on the right edge
        (col < rowArray.length - 1 && matching(rowArray[col+1])) ||
        // search up, if we're not on the top edge
        (row > 0 && matching(grid[row-1][col])) ||
        // search down, if we're not on the bottom edge
        (row < grid.length - 1 && matching(grid[row+1][col]))
      );
    };

    var mergeTables = function (startAddress, gridA, gridB, generator, comparator) {
      // Assumes
      //  - gridA is square and gridB is square
      var startRow = startAddress.row();
      var startCol = startAddress.column();
      var mergeHeight = gridB.length;
      var mergeWidth = gridB[0].length;
      var endRow = startRow + mergeHeight;
      var endCol = startCol + mergeWidth;

      // embrace the mutation - I think this is easier to follow? To discuss.
      for (var r = startRow; r < endRow; r++) {
        for (var c = startCol; c < endCol; c++) {
          if (isSpanning(gridA, r, c, comparator)) {
            // mutation within mutation, it's mutatception
            MergingOperations.unmerge(gridA, gridA[r][c], comparator, generator.cell);
          }
          gridA[r][c] = generator.replace(gridB[r - startRow][c - startCol]);
        }
      }
      return gridA;
      // return Arr.map(gridA, function (row, r) {
      //   var repRow = r - startRow;
      //   var skipRow = skip(startRow, r, mergeHeight);
      //   if (skipRow) return row;

      //   else return Arr.map(row, function (cell, c) {
      //     var repCol = c - startCol;
      //     var skipCell = skip(startCol, c, mergeWidth);
      //     if (skipCell) return cell;
      //     else {
      //       if (isSpanning(gridA, r, c, comparator)) {
      //         MergingOperations.unmerge(gridA, cell, comparator, generator.cell);
      //       }
      //       return generator.replace(gridB[repRow][repCol]);
      //     }
      //   });
      // });
    };

    var merge = function (startAddress, gridA, gridB, generator, comparator) {
var start = new Date().getTime();

      var delta = Fitment.measure(startAddress, gridA, gridB);
      var fittedGrid = Fitment.tailor(startAddress, gridA, delta, generator);
      var xx = mergeTables(startAddress, fittedGrid, gridB, generator, comparator);

var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);
      return xx; // inline, only here for logging (aka showing off)

    };

    return {
      merge: merge
    };
  }
);<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {Motion, spring} from 'react-motion';
import Menu from '../../lib'

export default class Example extends Component{
  constructor(props) {
    super(props);
    this.state = {
      menu1:{isOpen: false},
      menu2:{isOpen: false},
      menu3:{isOpen: false},
      menu4:{isOpen: false}
    };
  }
  handleOnOpen(name) {
    this.setState({[name] : {isOpen: true}});
    console.log("open");
  }

  handleOnClose(name) {
    this.setState({[name] : {isOpen: false}});
    console.log("close");
  }
  render() {
    return (

        <Menu
          name="menu2"
          direction="horizontal"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#E74C3C",
            border: "solid 1px #E74C3C",
            borderRadius: "40%"
          }}
          distance={-80}
          width={50}
          height={50}
          y={500}
          x={-150} >

        </Menu>
        <Menu
          name="menu1"
          direction="vertical"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#16A085",
            border: "solid 1px #16A085",
            borderRadius: "50%"
          }}
          distance={80}
          width={50}
          height={50}
          y={500}
          x={-50} >

        </Menu>
        <Menu
          name="menu2"
          direction="vertical"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#34495E",
            border: "solid 1px #34495E",
            borderRadius: "10%"
          }}
          distance={-80}
          width={50}
          height={50}
          y={500}
          x={50} >

        </Menu>
        <Menu
          name="menu2"
          direction="horizontal"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#D35400",
            border: "solid 1px #D35400#D35400#D35400",
            borderRadius: "20%"
          }}
          distance={80}
          width={50}
          height={50}
          y={500}
          x={150} >

        </Menu>

    );
  }
}
<commit_msg>Fix example menu name<commit_after>import React, {Component} from 'react';
import {Motion, spring} from 'react-motion';
import Menu from '../../lib'

export default class Example extends Component{
  constructor(props) {
    super(props);
    this.state = {
      menu1:{isOpen: false},
      menu2:{isOpen: false},
      menu3:{isOpen: false},
      menu4:{isOpen: false}
    };
  }
  handleOnOpen(name) {
    this.setState({[name] : {isOpen: true}});
    console.log("open");
  }

  handleOnClose(name) {
    this.setState({[name] : {isOpen: false}});
    console.log("close");
  }
  render() {
    return (

        <Menu
          name="menu1"
          direction="horizontal"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#E74C3C",
            border: "solid 1px #E74C3C",
            borderRadius: "40%"
          }}
          distance={-80}
          width={50}
          height={50}
          y={500}
          x={-150} >

        </Menu>
        <Menu
          name="menu2"
          direction="vertical"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#16A085",
            border: "solid 1px #16A085",
            borderRadius: "50%"
          }}
          distance={80}
          width={50}
          height={50}
          y={500}
          x={-50} >

        </Menu>
        <Menu
          name="menu3"
          direction="vertical"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#34495E",
            border: "solid 1px #34495E",
            borderRadius: "10%"
          }}
          distance={-80}
          width={50}
          height={50}
          y={500}
          x={50} >

        </Menu>
        <Menu
          name="menu4"
          direction="horizontal"
          onOpen={this.handleOnOpen.bind(this)}
          onClose={this.handleOnClose.bind(this)}
          customStyle={{
            color: "#fff",
            textAlign:"center",
            lineHeight:"50px",
            backgroundColor: "#D35400",
            border: "solid 1px #D35400#D35400#D35400",
            borderRadius: "20%"
          }}
          distance={80}
          width={50}
          height={50}
          y={500}
          x={150} >

        </Menu>

    );
  }
}
<|endoftext|>


<commit_before>const {dialog} = require('electron').remote,
      ipc = require('electron').ipcRenderer,
      PouchDB = require('pouchdb');

var bibUtil = require("../util/usfm_to_json.js"),
    fs = require("fs"),
    path = require("path");

/*const PouchDB = require('pouchdb');
var refDb = new PouchDB('reference');
refDb.destroy().then(function (response) {
    console.log(response);
    console.log('done destroying.');
  // success
}).catch(function (err) {
  console.log(err);
});
db.get('targetBible').then(function (doc) {
    console.log(doc);
}).catch(function (err) {
    console.log(err);
});*/

document.getElementById('export-path').addEventListener('click', function (e) {
    dialog.showOpenDialog({properties: ['openDirectory'],
			   filters: [{name: 'All Files', extensions: ['*']}],
			   title: "Select export destination folder"
			  }, function (selectedDir) {
			      if(selectedDir != null) {
				  e.target.value = selectedDir;
			      }
			  });
});

document.getElementById('save-btn').addEventListener('click', function (e) {
    db = new PouchDB('database');
    db.get('targetBible').then(function (doc) {
	console.log(doc);
	db.put({
	    _id: 'targetBible',
	    _rev: doc._rev,
	    targetLang: document.getElementById('target-lang').value,
	    targetVersion: document.getElementById('target-version').value,
	    targetPath: document.getElementById('export-path').value
	}).then(function (e) {
	    db.close();
	});
    }).catch(function (err) {
	db.put({
	    _id: 'targetBible',
	    targetLang: document.getElementById('target-lang').value,
	    targetVersion: document.getElementById('target-version').value,
	    targetPath: document.getElementById('export-path').value
	}).then(function (e) {
	    db.close();
	}).catch(function (err) {
	    db.close();
	});
    });
});

document.getElementById('ref-import-btn').addEventListener('click', function (e) {
    var refDb = new PouchDB('reference'),
	ref_id_value = document.getElementById('ref-lang-code').value.toLowerCase() + '_' + document.getElementById('ref-version').value.toLowerCase(),
	ref_entry = {},
    	files = fs.readdirSync(document.getElementById('ref-path').value);
    ref_entry.ref_id = ref_id_value;
    ref_entry.ref_name =  document.getElementById('ref-name').value;
    ref_entry.isDefault = false;
    refDb.get('refs').then(function (doc) {
	var refExistsFlag = false;
	console.log('see this.');
	var updatedDoc = doc.ref_ids.forEach(function (ref_doc) {
	    if(ref_doc.ref_id === ref_id_value) {
		refExistsFlag = true;
	    }
	});
	if(!refExistsFlag) {
	    doc.ref_ids.push(ref_entry);
	    refDb.put(doc).then(function (res) {
		refDb.close();
		saveJsonToDB(files);
	    });
	} else {
	    refDb.close();
	    saveJsonToDB(files);
	}
    }).catch(function (err) {
	var refs = {
	    _id: 'refs',
	    ref_ids: []
	};
	ref_entry.isDefault = true;
	refs.ref_ids.push(ref_entry);
	refDb.put(refs).then(function (res) {
	    refDb.close();
	    saveJsonToDB(files);
	});
    });
});

function saveJsonToDB(files) {
        files.forEach(function (file) {
	var filePath = path.join(document.getElementById('ref-path').value.toLowerCase(), file);
	//				      console.log(filePath + ' ' + fs.statSync(filePath).isFile());
	if(fs.statSync(filePath).isFile()) {
	    var options = {
		lang: document.getElementById('ref-lang-code').value.toLowerCase(),
		version: document.getElementById('ref-version').value.toLowerCase(),
		usfmFile: filePath
	    }
	    bibUtil.toJson(options);
	}
    });
}

document.getElementById('ref-path').addEventListener('click', function (e) {
    dialog.showOpenDialog({properties: ['openDirectory'],
			   filters: [{name: 'All Files', extensions: ['*']}],
			   title: "Select reference version folder"
			  }, function (selectedDir) {
			      if(selectedDir != null) {
				  e.target.value = selectedDir;
			      }
			  });
});
<commit_msg>Removing db.close()<commit_after>const {dialog} = require('electron').remote,
      ipc = require('electron').ipcRenderer,
      PouchDB = require('pouchdb');

var bibUtil = require("../util/usfm_to_json.js"),
    fs = require("fs"),
    path = require("path");

/*const PouchDB = require('pouchdb');
var refDb = new PouchDB('reference');
refDb.destroy().then(function (response) {
    console.log(response);
    console.log('done destroying.');
  // success
}).catch(function (err) {
  console.log(err);
});
db.get('targetBible').then(function (doc) {
    console.log(doc);
}).catch(function (err) {
    console.log(err);
});*/

document.getElementById('export-path').addEventListener('click', function (e) {
    dialog.showOpenDialog({properties: ['openDirectory'],
			   filters: [{name: 'All Files', extensions: ['*']}],
			   title: "Select export destination folder"
			  }, function (selectedDir) {
			      if(selectedDir != null) {
				  e.target.value = selectedDir;
			      }
			  });
});

document.getElementById('save-btn').addEventListener('click', function (e) {
    db = new PouchDB('database');
    db.get('targetBible').then(function (doc) {
	console.log(doc);
	db.put({
	    _id: 'targetBible',
	    _rev: doc._rev,
	    targetLang: document.getElementById('target-lang').value,
	    targetVersion: document.getElementById('target-version').value,
	    targetPath: document.getElementById('export-path').value
	}).then(function (e) {
	    db.close();
	});
    }).catch(function (err) {
	db.put({
	    _id: 'targetBible',
	    targetLang: document.getElementById('target-lang').value,
	    targetVersion: document.getElementById('target-version').value,
	    targetPath: document.getElementById('export-path').value
	}).then(function (e) {
	    db.close();
	}).catch(function (err) {
	    db.close();
	});
    });
});

document.getElementById('ref-import-btn').addEventListener('click', function (e) {
    var refDb = new PouchDB('reference'),
	ref_id_value = document.getElementById('ref-lang-code').value.toLowerCase() + '_' + document.getElementById('ref-version').value.toLowerCase(),
	ref_entry = {},
    	files = fs.readdirSync(document.getElementById('ref-path').value);
    ref_entry.ref_id = ref_id_value;
    ref_entry.ref_name =  document.getElementById('ref-name').value;
    ref_entry.isDefault = false;
    refDb.get('refs').then(function (doc) {
	var refExistsFlag = false;
	console.log('see this.');
	var updatedDoc = doc.ref_ids.forEach(function (ref_doc) {
	    if(ref_doc.ref_id === ref_id_value) {
		refExistsFlag = true;
	    }
	});
	if(!refExistsFlag) {
	    doc.ref_ids.push(ref_entry);
	    refDb.put(doc).then(function (res) {
		saveJsonToDB(files);
	    });
	} else {
	    saveJsonToDB(files);
	}
    }).catch(function (err) {
	var refs = {
	    _id: 'refs',
	    ref_ids: []
	};
	ref_entry.isDefault = true;
	refs.ref_ids.push(ref_entry);
	refDb.put(refs).then(function (res) {
	    saveJsonToDB(files);
	});
    });
});

function saveJsonToDB(files) {
        files.forEach(function (file) {
	var filePath = path.join(document.getElementById('ref-path').value, file);
	//				      console.log(filePath + ' ' + fs.statSync(filePath).isFile());
	if(fs.statSync(filePath).isFile()) {
	    var options = {
		lang: document.getElementById('ref-lang-code').value.toLowerCase(),
		version: document.getElementById('ref-version').value.toLowerCase(),
		usfmFile: filePath
	    }
	    bibUtil.toJson(options);
	}
    });
}

document.getElementById('ref-path').addEventListener('click', function (e) {
    dialog.showOpenDialog({properties: ['openDirectory'],
			   filters: [{name: 'All Files', extensions: ['*']}],
			   title: "Select reference version folder"
			  }, function (selectedDir) {
			      if(selectedDir != null) {
				  e.target.value = selectedDir;
			      }
			  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { injectIntl } from 'react-intl';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../../Icon';
import Headline from '../../Headline';
import IconButton from '../../IconButton';
import css from '../Accordion.css';

class FilterAccordionHeader extends React.Component {
  static propTypes = {
    autoFocus: PropTypes.bool,
    contentId: PropTypes.string,
    disabled: PropTypes.bool,
    displayClearButton: PropTypes.bool,
    displayWhenClosed: PropTypes.element,
    displayWhenOpen: PropTypes.element,
    headingLevel: PropTypes.oneOf([1, 2, 3, 4, 5, 6]),
    id: PropTypes.string,
    intl: PropTypes.object,
    label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
    name: PropTypes.string,
    onClearFilter: PropTypes.func,
    onToggle: PropTypes.func,
    open: PropTypes.bool,
    toggleRef: PropTypes.func,
  };

  static defaultProps = {
    displayClearButton: true,
    headingLevel: 3
  };

  handleHeaderClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const { id, label } = this.props;
    this.props.onToggle({ id, label });
  }

  handleClearButtonClick = () => {
    this.props.onClearFilter(this.props.name);
  }

  handleKeyPress = (e) => {
    e.preventDefault();
    if (e.charCode === 13) { // 13 = enter
      const { id, label } = this.props;
      this.props.onToggle({ id, label });
    }
  }

  render() {
    const {
      label,
      open,
      disabled,
      displayWhenOpen,
      displayWhenClosed,
      displayClearButton,
      onClearFilter,
      contentId,
      headingLevel,
      intl: {
        formatMessage,
      },
    } = this.props;
    const clearButtonVisible = displayClearButton && typeof onClearFilter === 'function';
    const labelText = formatMessage({ id: `${label?.props?.id ?? '-'}` });

    return (

        <Headline size="small" tag={`h${headingLevel}`} block={!clearButtonVisible}>
          <button
            type="button"
            tabIndex="0"
            onClick={this.handleHeaderClick}
            onKeyPress={this.handleKeyPress}
            aria-label={`${labelText} filter list`}
            aria-controls={contentId}
            aria-expanded={open}
            disabled={disabled}
            className={classNames(css.filterSetHeader, { [css.clearButtonVisible]: clearButtonVisible })}
            role="tab"
            autoFocus={this.props.autoFocus}
            ref={this.props.toggleRef}
            id={`accordion-toggle-button-${this.props.id}`}
          >
            {
              disabled ? null :
              <Icon
                iconClassName={css.filterSetHeaderIcon}
                size="small"
                icon={`caret-${open ? 'up' : 'down'}`}
              />
            }

{label}

          </button>
        </Headline>
        { clearButtonVisible ?
          <IconButton
            data-test-clear-button
            size="small"
            iconSize="small"
            icon="times-circle-solid"
            aria-label={`Clear selected filters for "${label}"`}
            onClick={this.handleClearButtonClick}
          /> : null
        }
        {open ? displayWhenOpen : displayWhenClosed}

    );
  }
}

export default injectIntl(FilterAccordionHeader);
<commit_msg>STCOM-703: Add changes<commit_after>import React from 'react';
import { injectIntl } from 'react-intl';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../../Icon';
import Headline from '../../Headline';
import IconButton from '../../IconButton';
import css from '../Accordion.css';

class FilterAccordionHeader extends React.Component {
  static propTypes = {
    autoFocus: PropTypes.bool,
    contentId: PropTypes.string,
    disabled: PropTypes.bool,
    displayClearButton: PropTypes.bool,
    displayWhenClosed: PropTypes.element,
    displayWhenOpen: PropTypes.element,
    headingLevel: PropTypes.oneOf([1, 2, 3, 4, 5, 6]),
    id: PropTypes.string,
    intl: PropTypes.object,
    label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
    name: PropTypes.string,
    onClearFilter: PropTypes.func,
    onToggle: PropTypes.func,
    open: PropTypes.bool,
    toggleRef: PropTypes.func,
  };

  static defaultProps = {
    displayClearButton: true,
    headingLevel: 3
  };

  handleHeaderClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const { id, label } = this.props;
    this.props.onToggle({ id, label });
  }

  handleClearButtonClick = () => {
    this.props.onClearFilter(this.props.name);
  }

  handleKeyPress = (e) => {
    e.preventDefault();
    if (e.charCode === 13) { // 13 = enter
      const { id, label } = this.props;
      this.props.onToggle({ id, label });
    }
  }

  render() {
    const {
      label,
      open,
      disabled,
      displayWhenOpen,
      displayWhenClosed,
      displayClearButton,
      onClearFilter,
      contentId,
      headingLevel,
      intl: {
        formatMessage,
      },
    } = this.props;
    const clearButtonVisible = displayClearButton && typeof onClearFilter === 'function';
    const labelText = formatMessage({ id: `${label?.props?.id}` }) || '-';

    return (

        <Headline size="small" tag={`h${headingLevel}`} block={!clearButtonVisible}>
          <button
            type="button"
            tabIndex="0"
            onClick={this.handleHeaderClick}
            onKeyPress={this.handleKeyPress}
            aria-label={`${labelText} filter list`}
            aria-controls={contentId}
            aria-expanded={open}
            disabled={disabled}
            className={classNames(css.filterSetHeader, { [css.clearButtonVisible]: clearButtonVisible })}
            role="tab"
            autoFocus={this.props.autoFocus}
            ref={this.props.toggleRef}
            id={`accordion-toggle-button-${this.props.id}`}
          >
            {
              disabled ? null :
              <Icon
                iconClassName={css.filterSetHeaderIcon}
                size="small"
                icon={`caret-${open ? 'up' : 'down'}`}
              />
            }

{label}

          </button>
        </Headline>
        { clearButtonVisible ?
          <IconButton
            data-test-clear-button
            size="small"
            iconSize="small"
            icon="times-circle-solid"
            aria-label={`Clear selected filters for "${label}"`}
            onClick={this.handleClearButtonClick}
          /> : null
        }
        {open ? displayWhenOpen : displayWhenClosed}

    );
  }
}

export default injectIntl(FilterAccordionHeader);
<|endoftext|>


<commit_before>module.exports = {
    dependencies: {
        "ds.slideMenu": "0.1"
    }
};<commit_msg>maybe changes from chads fix of the android deployment issue<commit_after><|endoftext|>


<commit_before>
var connect = require('../')
  , http = require('http');

// visit form.html

var app = connect()
  .use(connect.static(__dirname + '/public'))
  .use(connect.bodyParser())
  .use(function(req, res, next){
    if ('GET' != req.method) return next();
    res.statusCode = 302;
    res.setHeader('Location', 'form.html');
    res.end();
  })
  .use(function(req, res){
    res.setHeader('Content-Type', 'text/html');
    res.write('
thanks ' + req.body.name + '
');
    res.write('
');

    if (Array.isArray(req.files.images)) {
      req.files.images.forEach(function(image){
        var kb = image.size / 1024 | 0;
        res.write('
uploaded ' + image.name + ' ' + kb + 'kb
');
      });
    } else {
      var image = req.files.images;
      var kb = image.size / 1024 | 0;
      res.write('
uploaded ' + image.name + ' ' + kb + 'kb
');
    }

    res.end('
');
  });

http.Server(app).listen(3000);
console.log('Server started on port 3000');<commit_msg>tweak bodyParser example<commit_after>
var connect = require('../')
  , http = require('http');

// visit form.html

var app = connect()
  .use(connect.static(__dirname + '/public'))
  .use(connect.bodyParser())
  .use(form)
  .use(upload);

function form(req, res, next){
  if ('GET' != req.method) return next();
  res.statusCode = 302;
  res.setHeader('Location', 'form.html');
  res.end();
}

function upload(req, res){
  res.setHeader('Content-Type', 'text/html');
  res.write('
thanks ' + req.body.name + '
');
  res.write('
');

  if (Array.isArray(req.files.images)) {
    req.files.images.forEach(function(image){
      var kb = image.size / 1024 | 0;
      res.write('
uploaded ' + image.name + ' ' + kb + 'kb
');
    });
  } else {
    var image = req.files.images;
    var kb = image.size / 1024 | 0;
    res.write('
uploaded ' + image.name + ' ' + kb + 'kb
');
  }

  res.end('
');
}

http.Server(app).listen(3000);
console.log('Server started on port 3000');<|endoftext|>