<commit_before>Physics.Circle = function(config) {
  /** Position and Velocity **/
  this.pos = config.pos || new Vector2(config.x, config.y);
  this.vel = config.vel || new Vector2();

  /** Bounciness **/
  this.bcf = config.bcf || 0.75;

  /** Radius **/
  this.rad = config.rad || 15;

  /** Array of Constraints **/
  this.constraints = [];

  /** Physical Sleep **/
  this.asleep = false;

  /** Array of Position Adjustments **/
  this.posAdjustments = [];

  /** Mass **/
  this.mass = config.mass || 1;

  /** Fixed or Not **/
  this.fixed = config.fixed || false;

  /** Variables Used When Submerged**/
  this.buoyancyForce = 0;
  this.waterDrag = 1;
};
Physics.Circle.prototype.update = function() {
  if(this.fixed) {
    this.asleep = false;
    this.vel = new Vector2();
    return;
  }

  if(vectMag(this.vel) > Physics.sleepThreshold || this.buoyancyForce > 0) {
    this.asleep = false;
  }
  this.pos.add(this.vel)//Add velocity to position

  this.vel.y += Physics.gravityForce - this.buoyancyForce;//Gravity

  this.vel.mult(this.waterDrag * (this.asleep ? Physics.asleepAirResistance : Physics.airResistance));//Air resistance

  this.buoyancyForce = 0;
  this.waterDrag = 1;

  this.manageAdjustments();
};
Physics.Circle.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = "#FF0000";
  ctx.ellipse(this.pos.x, this.pos.y, this.rad, this.rad, 0, 0, 6.279);
  ctx.fill();
};
Physics.Circle.prototype.display = function() {
  if(this.move) {
    this.move();
  }
  this.update();
  this.draw();
};
Physics.Circle.prototype.moveTowards = function(target, force) {
  this.applyForce(Vector2.mult(Vector2.normalize(Vector2.sub(target, this.pos)), force));
};
Physics.Circle.prototype.moveFrom = function(target, force) {
  this.applyForce(Vector2.mult(Vector2.normalize(Vector2.sub(this.pos, target)), force));
};
Physics.Circle.prototype.manageAdjustments = function() {
  if(this.posAdjustments.length === 0) {
    return;
  }

  var adjustmentAvg = new Vector2();
  for(var i = 0; i < this.posAdjustments.length; i++) {
    adjustmentAvg.add(this.posAdjustments[i]);
  }
  this.pos = Vector2.lerp(this.pos, Vector2d.div(adjustmentAvg, this.posAdjustments.length), Physics.constraintAdjustment);

  this.posAdjustments = [];
};
Physics.Circle.prototype.trySleep = function() {
  if(Vector2.magSq(this.vel) < Physics.sleepThreshold * Physics.sleepThreshold) {
    this.asleep = true;
  }
};
Physics.Circle.prototype.collideLine = function(line) {
  if(line.one.x === line.two.x ||
     line.one.y === line.two.y) { return; }

  if(!circleCollidingLine(line.one, line.two, this.pos, this.rad + line.rad)) {
    return;
  }
  if(!intersecting(this.pos, Vector2.reflect(this.pos, line.one, line.two), line.one, line.two)) {
    var n = (Vector2.dist(this.pos, line.one) < Vector2.dist(this.pos, line.two)) ? line.one : line.two;
    this.vel = Vector2.mult(Vector2.sub(Vector2.reflect(Vector2.sub(this.pos, this.vel), n, this.pos), this.pos), line.bcf * this.bcf);
    this.pos = Vector2.sub(n, Vector2d.mult(Vector2.normalize(Vector2.sub(n, this.pos)), this.rad + line.rad));
  }
  else{
    var n = intersection(this.pos, Vector2.reflect(this.pos, line.one, line.two), line.one, line.two);
    this.vel = Vector2.mult(Vector2.sub(n, Vector2.reflect(Vector2.sub(n, this.vel), n, Vector2.add(n, [1, PM(line.one, line.two)]))), -line.bcf * this.bcf);
    this.pos = Vector2.add(n, Vector2.mult(Vector2.norm(new Vector2(1, PM(line.one, line.two))), (this.rad + line.rad) * (this.pos.y > n.y ? -1 : 1) * (line.one.x > line.two.x ? -1 : 1) * (line.one.y > line.two.y ? -1 : 1)));
  }
  this.trySleep();
};
Physics.Circle.prototype.collideStaticDynamic = function(that) {
  that.pos = Vector2.lerp(
    that.pos,
    Vector2.add(this.pos,
      Vector2.mult(
        Vector2.normalize(
          Vector2.sub(that.pos, this.pos)
        ),
      this.rad + that.rad)
    ),
    0.15
  );
  that.vel = Vector2.mult(
    Vector2.sub(
      Vector2.reflect(
        Vector2.sub(that.pos, that.vel),
      this.pos, that.pos),
    that.pos),
  this.bcf * that.bcf);
  that.pos = Vector2.add(that.pos, that.vel);
};
Physics.Circle.prototype.collideDynamicStatic = function(that) {
  this.pos = Vector2.lerp(
    this.pos,
    Vector2.add(that.pos,
      Vector2.mult(
        Vector2.normalize(
          Vector2.sub(this.pos, that.pos)
        ),
      this.rad + that.rad)
    ),
    0.15
  );
  this.vel = Vector2.mult(
    Vector2.sub(
      Vector2.reflect(
        Vector2.sub(this.pos, this.vel),
      that.pos, this.pos),
    this.pos),
  this.bcf * that.bcf);
  this.pos = Vector2.add(this.pos, this.vel);
};
Physics.Circle.prototype.collideDynamicDynamic = function(that) {
  var mid = Vector2.mid(this.pos, that.pos);
  var difference = Vector2.norm(Vector2.sub(this.pos, that.pos));

  this.pos = Vector2.lerp(this.pos, Vector2.add(mid, Vector2.mult(difference, this.rad + that.rad)), 0.15);
  that.pos = Vector2.lerp(that.pos, Vector2.sub(mid, Vector2.mult(difference, this.rad + that.rad)), 0.15);

  var thisComponentOld = Vector2.dot(this.vel, difference);
  var thatComponentOld = Vector2.dot(that.vel, difference);

  var thisComponentNew = thatComponentOld * that.mass/this.mass;
  var thatComponentNew = thisComponentOld * this.mass/that.mass;

  this.vel = Vector2.add(this.vel, Vector2.mult(difference, (thisComponentNew - thisComponentOld) * this.bcf * that.bcf));
  that.vel = Vector2.add(that.vel, Vector2.mult(difference, (thatComponentNew - thatComponentOld) * this.bcf * that.bcf));
};
Physics.Circle.prototype.collideCircle = function(that) {
  if(this.fixed && that.fixed) {
    return;
  }
  if(Vector2.magSq(Vector2.sub(this.pos, that.pos)) > ((this.rad + that.rad) * (this.rad + that.rad))) {
    return;
  }
  if(this.fixed) {
    this.collideStaticDynamic(that);
    return;
  }
  if(that.fixed) {
    this.collideDynamicStatic(that);
    return;
  }
  this.collideDynamicDynamic(that);
};
Physics.Circle.prototype.applyForce = function(velChange) {
  this.vel = Vector2.add(this.vel, Vector2.div(velChange, this.mass));
};
<commit_msg>Update circle.js<commit_after>Physics.Circle = function(config) {
  /** Position and Velocity **/
  this.pos = config.pos || new Vector2(config.x, config.y);
  this.vel = config.vel || new Vector2();

  /** Bounciness **/
  this.bcf = config.bcf || 0.75;

  /** Radius **/
  this.rad = config.rad || 15;

  /** Array of Constraints **/
  this.constraints = [];

  /** Physical Sleep **/
  this.asleep = false;

  /** Array of Position Adjustments **/
  this.posAdjustments = [];

  /** Mass **/
  this.mass = config.mass || 1;

  /** Fixed or Not **/
  this.fixed = config.fixed || false;

  /** Variables Used When Submerged**/
  this.buoyancyForce = 0;
  this.waterDrag = 1;
};
Physics.Circle.prototype.update = function() {
  if(this.fixed) {
    this.asleep = false;
    this.vel = new Vector2();
    return;
  }

  if(vectMag(this.vel) > Physics.sleepThreshold || this.buoyancyForce > 0) {
    this.asleep = false;
  }
  this.pos.add(this.vel)//Add velocity to position

  this.vel.y += Physics.gravityForce - this.buoyancyForce;//Gravity

  this.vel.mult(this.waterDrag * (this.asleep ? Physics.asleepAirResistance : Physics.airResistance));//Air resistance

  this.buoyancyForce = 0;
  this.waterDrag = 1;

  this.manageAdjustments();
};
Physics.Circle.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = "#FF0000";
  ctx.ellipse(this.pos.x, this.pos.y, this.rad, this.rad, 0, 0, 6.279);
  ctx.fill();
};
Physics.Circle.prototype.display = function() {
  if(this.move) {
    this.move();
  }
  this.update();
  this.draw();
};
Physics.Circle.prototype.moveTowards = function(target, force) {
  this.applyForce(Vector2.mult(Vector2.normalize(Vector2.sub(target, this.pos)), force));
};
Physics.Circle.prototype.moveFrom = function(target, force) {
  this.applyForce(Vector2.mult(Vector2.normalize(Vector2.sub(this.pos, target)), force));
};
Physics.Circle.prototype.manageAdjustments = function() {
  if(this.posAdjustments.length === 0) {
    return;
  }

  var adjustmentAvg = new Vector2();
  for(var i = 0; i < this.posAdjustments.length; i++) {
    adjustmentAvg.add(this.posAdjustments[i]);
  }
  this.pos = Vector2.lerp(this.pos, Vector2d.div(adjustmentAvg, this.posAdjustments.length), Physics.constraintAdjustment);

  this.posAdjustments = [];
};
Physics.Circle.prototype.trySleep = function() {
  if(Vector2.magSq(this.vel) < Physics.sleepThreshold * Physics.sleepThreshold) {
    this.asleep = true;
  }
};
Physics.Circle.prototype.collideLine = function(line) {
  if(line.one.x === line.two.x ||
     line.one.y === line.two.y) { return; }

  if(!circleCollidingLine(line.one, line.two, this.pos, this.rad + line.rad)) {
    return;
  }
  if(!intersecting(this.pos, Vector2.reflect(this.pos, line.one, line.two), line.one, line.two)) {
    var n = (Vector2.dist(this.pos, line.one) < Vector2.dist(this.pos, line.two)) ? line.one : line.two;
    this.vel = Vector2.mult(Vector2.sub(Vector2.reflect(Vector2.sub(this.pos, this.vel), n, this.pos), this.pos), line.bcf * this.bcf);
    this.pos = Vector2.sub(n, Vector2d.mult(Vector2.normalize(Vector2.sub(n, this.pos)), this.rad + line.rad));
  }
  else{
    var n = intersection(this.pos, Vector2.reflect(this.pos, line.one, line.two), line.one, line.two);
    this.vel = Vector2.mult(Vector2.sub(n, Vector2.reflect(Vector2.sub(n, this.vel), n, Vector2.add(n, [1, PM(line.one, line.two)]))), -line.bcf * this.bcf);
    this.pos = Vector2.add(n, Vector2.mult(Vector2.norm(new Vector2(1, PM(line.one, line.two))), (this.rad + line.rad) * (this.pos.y > n.y ? -1 : 1) * (line.one.x > line.two.x ? -1 : 1) * (line.one.y > line.two.y ? -1 : 1)));
  }
  this.trySleep();
};
Physics.Circle.prototype.collideStaticDynamic = function(that) {
  that.pos = Vector2.lerp(
    that.pos,
    Vector2.add(this.pos,
      Vector2.mult(
        Vector2.normalize(
          Vector2.sub(that.pos, this.pos)
        ),
      this.rad + that.rad)
    ),
    Physics.circleAdjustment
  );
  that.vel = Vector2.mult(
    Vector2.sub(
      Vector2.reflect(
        Vector2.sub(that.pos, that.vel),
      this.pos, that.pos),
    that.pos),
  this.bcf * that.bcf);
  that.pos = Vector2.add(that.pos, that.vel);
};
Physics.Circle.prototype.collideDynamicStatic = function(that) {
  this.pos = Vector2.lerp(
    this.pos,
    Vector2.add(that.pos,
      Vector2.mult(
        Vector2.normalize(
          Vector2.sub(this.pos, that.pos)
        ),
      this.rad + that.rad)
    ),
    Physics.circleAdjustment
  );
  this.vel = Vector2.mult(
    Vector2.sub(
      Vector2.reflect(
        Vector2.sub(this.pos, this.vel),
      that.pos, this.pos),
    this.pos),
  this.bcf * that.bcf);
  this.pos = Vector2.add(this.pos, this.vel);
};
Physics.Circle.prototype.collideDynamicDynamic = function(that) {
  var mid = Vector2.mid(this.pos, that.pos);
  var difference = Vector2.norm(Vector2.sub(this.pos, that.pos));

  this.pos = Vector2.lerp(this.pos, Vector2.add(mid, Vector2.mult(difference, this.rad + that.rad)), Physics.circleAdjustment);
  that.pos = Vector2.lerp(that.pos, Vector2.sub(mid, Vector2.mult(difference, this.rad + that.rad)), Physics.circleAdjustment);

  var thisComponentOld = Vector2.dot(this.vel, difference);
  var thatComponentOld = Vector2.dot(that.vel, difference);

  var thisComponentNew = thatComponentOld * that.mass/this.mass;
  var thatComponentNew = thisComponentOld * this.mass/that.mass;

  this.vel = Vector2.add(this.vel, Vector2.mult(difference, (thisComponentNew - thisComponentOld) * this.bcf * that.bcf));
  that.vel = Vector2.add(that.vel, Vector2.mult(difference, (thatComponentNew - thatComponentOld) * this.bcf * that.bcf));
};
Physics.Circle.prototype.collideCircle = function(that) {
  if(this.fixed && that.fixed) {
    return;
  }
  if(Vector2.magSq(Vector2.sub(this.pos, that.pos)) > ((this.rad + that.rad) * (this.rad + that.rad))) {
    return;
  }
  if(this.fixed) {
    this.collideStaticDynamic(that);
    return;
  }
  if(that.fixed) {
    this.collideDynamicStatic(that);
    return;
  }
  this.collideDynamicDynamic(that);
};
Physics.Circle.prototype.applyForce = function(velChange) {
  this.vel = Vector2.add(this.vel, Vector2.div(velChange, this.mass));
};
<|endoftext|>


<commit_before>import objectAssign from "object-assign";
import { actions as mappingActions } from "./mapping";
import * as turfHelpers from "@turf/helpers";
import inside from "@turf/inside";
import { constants as mappingConstants } from "./mapping";
import { getPolygonfromBBox } from "../../utils/gisHelper";

import { WUNDAAPI } from "../../constants/services";

///TYPES
export const types = {
  SET_DOCUMENT_LOADING_INDICATOR: "BPLAENE/SET_DOCUMENT_LOADING_INDICATOR",
  SET_DOCUMENT_HAS_LOADING_ERROR: "BPLAENE/SET_DOCUMENT_HAS_LOADING_ERROR",
  SET_PREPARED_DOWNLOAD: "BPLAENE/SET_PREPARED_DOWNLOAD"
};

///INITIAL STATE
const initialState = {
  documentsLoading: false,
  documentsLoadingError: false,
  preparedDownload: null
};

///REDUCER
export default function bplanReducer(state = initialState, action) {
  let newState;
  switch (action.type) {
    case types.SET_DOCUMENT_LOADING_INDICATOR: {
      newState = objectAssign({}, state);
      newState.documentsLoading = action.isLoading;
      if (newState.documentsLoading === false) {
        newState.documentsLoadingError = false;
      }
      return newState;
    }
    case types.SET_DOCUMENT_HAS_LOADING_ERROR: {
      newState = objectAssign({}, state);
      newState.documentsLoadingError = action.hasError;
      return newState;
    }
    case types.SET_PREPARED_DOWNLOAD: {
      newState = objectAssign({}, state);
      newState.preparedDownload = action.download;
      return newState;
    }

    default:
      return state;
  }
}

///SIMPLEACTIONCREATORS
function setDocumentLoadingIndicator(isLoading) {
  return {
    type: types.SET_DOCUMENT_LOADING_INDICATOR,
    isLoading
  };
}
function setDocumentHasLoadingError(hasError) {
  return {
    type: types.SET_DOCUMENT_HAS_LOADING_ERROR,
    hasError
  };
}
function setPreparedDownload(download) {
  return {
    type: types.SET_PREPARED_DOWNLOAD,
    download
  };
}

//COMPLEXACTIONS

export function searchForPlans(gazObject, overriddenWKT) {
  return function(dispatch, getState) {
    dispatch(mappingActions.setSearchProgressIndicator(true));
    const state = getState();
    let wkt;
    if (overriddenWKT) {
      wkt = overriddenWKT;
    } else if (Array.isArray(gazObject) && gazObject[0].more.v) {
      console.log("BPLAN QUERY " + gazObject[0].x + " ," + gazObject[0].y);
      wkt = `POINT (${gazObject[0].x} ${gazObject[0].y} )`;
    } else {
      wkt = getPolygonfromBBox(state.mapping.boundingBox);
    }
    let query = {
      list: [
        {
          key: "wktString",
          value: wkt
        },
        {
          key: "status",
          value: ""
        },
        {
          key: "srs",
          value: 25832
        },
        {
          key: "urlprefix",
          value: "https://wunda-geoportal-docs.cismet.de"
        }
      ]
    };
    //console.log(WUNDAAPI + '/searches/WUNDA_BLAU.BPlanAPISearch/results?role=all&limit=100&offset=0')
    //console.log(JSON.stringify(query));
    fetch(WUNDAAPI + "/searches/WUNDA_BLAU.BPlanAPISearch/results?role=all&limit=100&offset=0", {
      method: "post",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(query)
    }).then(function(response) {
      if (response.status >= 200 && response.status < 300) {
        response.json().then(function(result) {
          let featureArray = [];
          let counter = 0;
          let lastFeature = null;
          let selectionIndexWish = 0;
          let planMatch = false;
          let gazPoint;
          if (gazObject != null && gazObject.length === 1 && gazObject[0] != null) {
            gazPoint = turfHelpers.point([gazObject[0].x, gazObject[0].y]);
          }
          for (let objArr of result.$collection) {
            let feature = convertPropArrayToFeature(objArr, counter);

            if (
              lastFeature != null &&
              JSON.stringify(feature.geometry) === JSON.stringify(lastFeature.geometry)
            ) {
              lastFeature.twin = counter;
              feature.twin = counter - 1;
            }

            //check whether the gazetteer-object has a property verfahrensnummer
            //if this verfahrensnummer matches the nummer of the feature this
            //should be the only feature in the resultset

            if (gazObject != null && gazObject.length === 1 && gazObject[0] != null) {
              const gazHitWithStatus = gazObject[0].string.indexOf("(") !== -1;
              const gazHitMatchesObjectVerfahrensnummer =
                gazObject[0].more.v === feature.properties.nummer;
              const embeddedStatusInGazHit = gazObject[0].string.substring(
                gazObject[0].string.indexOf("(") + 1,
                gazObject[0].string.indexOf(")")
              );
              const gazHitMatchesEmbeddedStatus =
                embeddedStatusInGazHit === feature.properties.status;
              if (
                (!gazHitWithStatus && gazHitMatchesObjectVerfahrensnummer) ||
                (gazHitWithStatus &&
                  gazHitMatchesObjectVerfahrensnummer &&
                  gazHitMatchesEmbeddedStatus)
              ) {
                featureArray = [feature];
                planMatch = true;
                break;
              }
            }

            if (gazPoint != null && inside(gazPoint, feature)) {
              selectionIndexWish = counter;
            }

            featureArray.push(feature);
            lastFeature = feature;
            counter++;
          }

          dispatch(mappingActions.setSearchProgressIndicator(false));
          dispatch(mappingActions.setFeatureCollection(featureArray));
          if (featureArray.length > 0) {
            dispatch(mappingActions.setSelectedFeatureIndex(selectionIndexWish));
          }
          if (gazObject != null && gazObject.length === 1 && gazObject[0] != null) {
            //let p=turf.point([gazObject[0].x,gazObject[0].y]);
            if (planMatch) {
              //vorher turf.inside(p,featureArray[selectionIndexWish])
              dispatch(
                mappingActions.fitFeatureBounds(
                  featureArray[selectionIndexWish],
                  mappingConstants.AUTO_FIT_MODE_STRICT
                )
              );
            }
          }
        });
      } else if (response.status === 401) {
        dispatch(mappingActions.setSearchProgressIndicator(false));
      }
    });
  };
}

function convertPropArrayToFeature(propArray, counter) {
  let plaene_rk;
  let geom = JSON.parse(propArray[6]);

  if (propArray[3] != null) {
    plaene_rk = JSON.parse(propArray[3]);
  } else {
    plaene_rk = [];
  }
  let plaene_nrk;
  if (propArray[4] != null) {
    plaene_nrk = JSON.parse(propArray[4]);
  } else {
    plaene_nrk = [];
  }
  let docs;
  if (propArray[5] != null) {
    docs = JSON.parse(propArray[5]);
    docs.push({
      file: "_Info_BPlan-Zusatzdokumente_WUP_1-0.pdf",
      url:
        "https://wunda-geoportal-docs.cismet.de/bplaene_dokumente/Info_BPlan-Zusatzdokumente_WUP_1-0.pdf"
    });
  } else {
    docs = [];
  }
  return {
    id: propArray[0] + "." + counter,
    type: "Feature",
    selected: false,
    geometry: geom,
    crs: {
      type: "name",
      properties: {
        name: "urn:ogc:def:crs:EPSG::25832"
      }
    },
    properties: {
      nummer: propArray[0],
      name: propArray[1],
      status: propArray[2],
      plaene_rk: plaene_rk,
      plaene_nrk: plaene_nrk,
      docs: docs,
      twin: null
    }
  };
}

//EXPORT ACTIONS
export const actions = {
  setDocumentLoadingIndicator,
  setDocumentHasLoadingError,
  setPreparedDownload,
  searchForPlans
};
<commit_msg>:bug: fixing a bug in bplaene that occured in rare cases (multiple results and name matching in one of the last entries)<commit_after>import objectAssign from "object-assign";
import { actions as mappingActions } from "./mapping";
import * as turfHelpers from "@turf/helpers";
import inside from "@turf/inside";
import { constants as mappingConstants } from "./mapping";
import { getPolygonfromBBox } from "../../utils/gisHelper";

import { WUNDAAPI } from "../../constants/services";

///TYPES
export const types = {
  SET_DOCUMENT_LOADING_INDICATOR: "BPLAENE/SET_DOCUMENT_LOADING_INDICATOR",
  SET_DOCUMENT_HAS_LOADING_ERROR: "BPLAENE/SET_DOCUMENT_HAS_LOADING_ERROR",
  SET_PREPARED_DOWNLOAD: "BPLAENE/SET_PREPARED_DOWNLOAD"
};

///INITIAL STATE
const initialState = {
  documentsLoading: false,
  documentsLoadingError: false,
  preparedDownload: null
};

///REDUCER
export default function bplanReducer(state = initialState, action) {
  let newState;
  switch (action.type) {
    case types.SET_DOCUMENT_LOADING_INDICATOR: {
      newState = objectAssign({}, state);
      newState.documentsLoading = action.isLoading;
      if (newState.documentsLoading === false) {
        newState.documentsLoadingError = false;
      }
      return newState;
    }
    case types.SET_DOCUMENT_HAS_LOADING_ERROR: {
      newState = objectAssign({}, state);
      newState.documentsLoadingError = action.hasError;
      return newState;
    }
    case types.SET_PREPARED_DOWNLOAD: {
      newState = objectAssign({}, state);
      newState.preparedDownload = action.download;
      return newState;
    }

    default:
      return state;
  }
}

///SIMPLEACTIONCREATORS
function setDocumentLoadingIndicator(isLoading) {
  return {
    type: types.SET_DOCUMENT_LOADING_INDICATOR,
    isLoading
  };
}
function setDocumentHasLoadingError(hasError) {
  return {
    type: types.SET_DOCUMENT_HAS_LOADING_ERROR,
    hasError
  };
}
function setPreparedDownload(download) {
  return {
    type: types.SET_PREPARED_DOWNLOAD,
    download
  };
}

//COMPLEXACTIONS

export function searchForPlans(gazObject, overriddenWKT) {
  return function(dispatch, getState) {
    dispatch(mappingActions.setSearchProgressIndicator(true));
    const state = getState();
    let wkt;
    if (overriddenWKT) {
      wkt = overriddenWKT;
    } else if (Array.isArray(gazObject) && gazObject[0].more.v) {
      console.log("BPLAN QUERY " + gazObject[0].x + " ," + gazObject[0].y);
      wkt = `POINT (${gazObject[0].x} ${gazObject[0].y} )`;
    } else {
      wkt = getPolygonfromBBox(state.mapping.boundingBox);
    }
    let query = {
      list: [
        {
          key: "wktString",
          value: wkt
        },
        {
          key: "status",
          value: ""
        },
        {
          key: "srs",
          value: 25832
        },
        {
          key: "urlprefix",
          value: "https://wunda-geoportal-docs.cismet.de"
        }
      ]
    };
    //console.log(WUNDAAPI + '/searches/WUNDA_BLAU.BPlanAPISearch/results?role=all&limit=100&offset=0')
    //console.log(JSON.stringify(query));
    fetch(WUNDAAPI + "/searches/WUNDA_BLAU.BPlanAPISearch/results?role=all&limit=100&offset=0", {
      method: "post",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(query)
    }).then(function(response) {
      if (response.status >= 200 && response.status < 300) {
        response.json().then(function(result) {
          let featureArray = [];
          let counter = 0;
          let lastFeature = null;
          let selectionIndexWish = 0;
          let planMatch = false;
          let gazPoint;
          if (gazObject != null && gazObject.length === 1 && gazObject[0] != null) {
            gazPoint = turfHelpers.point([gazObject[0].x, gazObject[0].y]);
          }
          for (let objArr of result.$collection) {
            let feature = convertPropArrayToFeature(objArr, counter);

            if (
              lastFeature != null &&
              JSON.stringify(feature.geometry) === JSON.stringify(lastFeature.geometry)
            ) {
              lastFeature.twin = counter;
              feature.twin = counter - 1;
            }

            //check whether the gazetteer-object has a property verfahrensnummer
            //if this verfahrensnummer matches the nummer of the feature this
            //should be the only feature in the resultset

            if (gazObject != null && gazObject.length === 1 && gazObject[0] != null) {
              const gazHitWithStatus = gazObject[0].string.indexOf("(") !== -1;
              const gazHitMatchesObjectVerfahrensnummer =
                gazObject[0].more.v === feature.properties.nummer;
              const embeddedStatusInGazHit = gazObject[0].string.substring(
                gazObject[0].string.indexOf("(") + 1,
                gazObject[0].string.indexOf(")")
              );
              const gazHitMatchesEmbeddedStatus =
                embeddedStatusInGazHit === feature.properties.status;
              if (
                (!gazHitWithStatus && gazHitMatchesObjectVerfahrensnummer) ||
                (gazHitWithStatus &&
                  gazHitMatchesObjectVerfahrensnummer &&
                  gazHitMatchesEmbeddedStatus)
              ) {
                featureArray = [feature];
                selectionIndexWish = 0; // set it to 0  (again) because it could have been set to another value
                planMatch = true;
                break;
              }
            }

            if (gazPoint != null && inside(gazPoint, feature)) {
              selectionIndexWish = counter;
            }

            featureArray.push(feature);
            lastFeature = feature;
            counter++;
          }

          dispatch(mappingActions.setSearchProgressIndicator(false));
          dispatch(mappingActions.setFeatureCollection(featureArray));
          if (featureArray.length > 0) {
            dispatch(mappingActions.setSelectedFeatureIndex(selectionIndexWish));
          }
          if (gazObject != null && gazObject.length === 1 && gazObject[0] != null) {
            //let p=turf.point([gazObject[0].x,gazObject[0].y]);
            if (planMatch) {
              //vorher turf.inside(p,featureArray[selectionIndexWish])
              dispatch(
                mappingActions.fitFeatureBounds(
                  featureArray[selectionIndexWish],
                  mappingConstants.AUTO_FIT_MODE_STRICT
                )
              );
            }
          }
        });
      } else if (response.status === 401) {
        dispatch(mappingActions.setSearchProgressIndicator(false));
      }
    });
  };
}

function convertPropArrayToFeature(propArray, counter) {
  let plaene_rk;
  let geom = JSON.parse(propArray[6]);

  if (propArray[3] != null) {
    plaene_rk = JSON.parse(propArray[3]);
  } else {
    plaene_rk = [];
  }
  let plaene_nrk;
  if (propArray[4] != null) {
    plaene_nrk = JSON.parse(propArray[4]);
  } else {
    plaene_nrk = [];
  }
  let docs;
  if (propArray[5] != null) {
    docs = JSON.parse(propArray[5]);
    docs.push({
      file: "_Info_BPlan-Zusatzdokumente_WUP_1-0.pdf",
      url:
        "https://wunda-geoportal-docs.cismet.de/bplaene_dokumente/Info_BPlan-Zusatzdokumente_WUP_1-0.pdf"
    });
  } else {
    docs = [];
  }
  return {
    id: propArray[0] + "." + counter,
    type: "Feature",
    selected: false,
    geometry: geom,
    crs: {
      type: "name",
      properties: {
        name: "urn:ogc:def:crs:EPSG::25832"
      }
    },
    properties: {
      nummer: propArray[0],
      name: propArray[1],
      status: propArray[2],
      plaene_rk: plaene_rk,
      plaene_nrk: plaene_nrk,
      docs: docs,
      twin: null
    }
  };
}

//EXPORT ACTIONS
export const actions = {
  setDocumentLoadingIndicator,
  setDocumentHasLoadingError,
  setPreparedDownload,
  searchForPlans
};
<|endoftext|>


<commit_before>/*
   _____
  / ____|                                       /\
 | |     ___  _ __ ___  _ __   __ _ _ __ ___   /  \   _ __ _ __ __ _ _   _ ___
 | |    / _ \| '_ ` _ \| '_ \ / _` | '__/ _ \ / /\ \ | '__| '__/ _` | | | / __|
 | |___| (_) | | | | | | |_) | (_| | | |  __// ____ \| |  | | | (_| | |_| \__ \
  \_____\___/|_| |_| |_| .__/ \__,_|_|  \___/_/    \_\_|  |_|  \__,_|\__, |___/
                       | |                                            __/ |
                       |_|                                           |___/
*/

function TESTarrayCompare() {

  var arr1 = [1, 2];
  var arr2 = [1, 2];

  var arr3 = ['m', 'l'];
  var arr4 = ['m', 'l'];

  Logger.log(arr1 === arr2);                                  // false: [1, 2] != [1, 2]
  Logger.log(get2ArraysEquals(arr1, arr2));                   // true:  [1, 2] =  [1, 2]
  Logger.log(false || get2ArraysEquals(arr4, arr3));          // true
}

function get2ArraysEquals(arr1, arr2) {

    //For the first loop, we only check for types
    for (propName in arr1) {
        //Check for inherited methods and properties - like .equals itself
        //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
        //Return false if the return value is different
        if (arr1.hasOwnProperty(propName) != arr2.hasOwnProperty(propName)) {
            return false;
        }
        //Check instance type
        else if (typeof arr1[propName] != typeof arr2[propName]) {
            //Different types => not equal
            return false;
        }
    }
    //Now a deeper check using other objects property names
    for(propName in arr2) {
        //We must check instances anyway, there may be a property that only exists in object2
            //I wonder, if remembering the checked values from the first loop would be faster or not
        if (arr1.hasOwnProperty(propName) != arr2.hasOwnProperty(propName)) {
            return false;
        }
        else if (typeof arr1[propName] != typeof arr2[propName]) {
            return false;
        }
        //If the property is inherited, do not check any more (it must be equa if both objects inherit it)
        if(!arr1.hasOwnProperty(propName))
          continue;

        //Now the detail check and recursion

        //This returns the script back to the array comparing
        /**REQUIRES Array.equals**/
        if (arr1[propName] instanceof Array && arr2[propName] instanceof Array) {
                   // recurse into the nested arrays
           if (!arr1[propName].equals(arr2[propName]))
                        return false;
        }
        else if (arr1[propName] instanceof Object && arr2[propName] instanceof Object) {
                   // recurse into another objects
                   //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
           if (!arr1[propName].equals(object2[propName]))
                        return false;
        }
        //Normal value comparison for strings and numbers
        else if(arr1[propName] != arr2[propName]) {
           return false;
        }
    }
    //If everything passed, let's say YES
    return true;
}

/*

   _____                            _
  / ____|                          | |
 | |  __  ___ _ __   __ _ _ __ __ _| |_ ___  _ __
 | | |_ |/ _ \ '_ \ / _` | '__/ _` | __/ _ \| '__|
 | |__| |  __/ | | | (_| | | | (_| | || (_) | |
  \_____|\___|_| |_|\__,_|_|  \__,_|\__\___/|_|

*/

/*
  generate array with n elements
  fill it with random numbers

  Math.random();        // ~ 0.07438184694369299

*/
function getRandomArray(n) {

  var arr = [];

  for (var i = 0; i < n; i++) {
    arr[i] = Math.random();
  }

  return arr;

}
function TESTgetRandomArray() {
  var n = 50;

  Logger.log(getRandomArray(n));

}

/*
  generate array with n elements
  fill it with random integer numbers

  Math.floor(Math.random() * 500) + 1;        // ~ 268

*/
function getRandomArrayOfIntegers(n, min, max) {
  max = max || 1;
  min = min || 0;
  var arr = [];

  for (var i = 0; i < n; i++) {
    arr[i] = Math.floor(Math.random() * max) + min;
  }

  return arr;

}

function TESTgetRandomArrayOfIntegers() {
  var n = 50;
  var min = 1;
  var max = 500

  Logger.log(getRandomArrayOfIntegers(n, min, max));

}
<commit_msg>Update Arrays.js<commit_after>/*
   _____
  / ____|                                       /\
 | |     ___  _ __ ___  _ __   __ _ _ __ ___   /  \   _ __ _ __ __ _ _   _ ___
 | |    / _ \| '_ ` _ \| '_ \ / _` | '__/ _ \ / /\ \ | '__| '__/ _` | | | / __|
 | |___| (_) | | | | | | |_) | (_| | | |  __// ____ \| |  | | | (_| | |_| \__ \
  \_____\___/|_| |_| |_| .__/ \__,_|_|  \___/_/    \_\_|  |_|  \__,_|\__, |___/
                       | |                                            __/ |
                       |_|                                           |___/
*/

function TESTarrayCompare() {

  var arr1 = [1, 2];
  var arr2 = [1, 2];

  var arr3 = ['m', 'l'];
  var arr4 = ['m', 'l'];

  Logger.log(arr1 === arr2);                                  // false: [1, 2] != [1, 2]
  Logger.log(get2ArraysEquals(arr1, arr2));                   // true:  [1, 2] =  [1, 2]
  Logger.log(false || get2ArraysEquals(arr4, arr3));          // true
}

function get2ArraysEquals(arr1, arr2) {

    //For the first loop, we only check for types
    for (propName in arr1) {
        //Check for inherited methods and properties - like .equals itself
        //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
        //Return false if the return value is different
        if (arr1.hasOwnProperty(propName) != arr2.hasOwnProperty(propName)) {
            return false;
        }
        //Check instance type
        else if (typeof arr1[propName] != typeof arr2[propName]) {
            //Different types => not equal
            return false;
        }
    }
    //Now a deeper check using other objects property names
    for(propName in arr2) {
        //We must check instances anyway, there may be a property that only exists in object2
            //I wonder, if remembering the checked values from the first loop would be faster or not
        if (arr1.hasOwnProperty(propName) != arr2.hasOwnProperty(propName)) {
            return false;
        }
        else if (typeof arr1[propName] != typeof arr2[propName]) {
            return false;
        }
        //If the property is inherited, do not check any more (it must be equa if both objects inherit it)
        if(!arr1.hasOwnProperty(propName))
          continue;

        //Now the detail check and recursion

        //This returns the script back to the array comparing
        /**REQUIRES Array.equals**/
        if (arr1[propName] instanceof Array && arr2[propName] instanceof Array) {
                   // recurse into the nested arrays
           if (!arr1[propName].equals(arr2[propName]))
                        return false;
        }
        else if (arr1[propName] instanceof Object && arr2[propName] instanceof Object) {
                   // recurse into another objects
                   //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
           if (!arr1[propName].equals(object2[propName]))
                        return false;
        }
        //Normal value comparison for strings and numbers
        else if(arr1[propName] != arr2[propName]) {
           return false;
        }
    }
    //If everything passed, let's say YES
    return true;
}

/*

   _____                            _
  / ____|                          | |
 | |  __  ___ _ __   __ _ _ __ __ _| |_ ___  _ __
 | | |_ |/ _ \ '_ \ / _` | '__/ _` | __/ _ \| '__|
 | |__| |  __/ | | | (_| | | | (_| | || (_) | |
  \_____|\___|_| |_|\__,_|_|  \__,_|\__\___/|_|

*/

/*
  generate array with n elements
  fill it with random numbers

  Math.random();        // ~ 0.07438184694369299

*/
function getRandomArray(n) {

  var arr = [];

  for (var i = 0; i < n; i++) {
    arr[i] = Math.random();
  }

  return arr;

}
function TESTgetRandomArray() {
  var n = 50;

  Logger.log(getRandomArray(n));

}

/*
  generate array with n elements
  fill it with random integer numbers

  Math.floor(Math.random() * 500) + 1;        // ~ 268

*/
function getRandomArrayOfIntegers(n, min, max) {
  max = max || 1;
  min = min || 0;
  var arr = [];

  for (var i = 0; i < n; i++) {
    arr[i] = Math.floor(Math.random() * max) + min;
  }

  return arr;

}

function TESTgetRandomArrayOfIntegers() {
  var n = 50;
  var min = 1;
  var max = 500

  Logger.log(getRandomArrayOfIntegers(n, min, max));

}

function test_filterArraysByKeyArray()
{
  var key = [1, 0, 1];
  var value = 1;
  var arrays = [
    ['M', 'not M', 'L'],
    ['Star Wars', 'booo', 'Stat Trek']
  ];

  filterArraysByKeyArray(key, value, arrays);

  Logger.log(arrays[0]);
  Logger.log(arrays[1]);
}
function filterArraysByKeyArray(key, value, arrays)
{
  function check(elt, i) { return value === key[i]; }
  for (var i = 0, l = arrays.length; i < l; ++i)
  {
    arrays[i] = arrays[i].filter(check);
  }
  return 0;
}
<|endoftext|>


<commit_before>define(function (require) {
    "use strict";

    var IPython = require('base/js/namespace');
    var $ = require('jquery');
    //var events = require("base/js/events");
    var dockspawn = require('/nbextensions/phy/static/dock-spawn/dist/js/dockspawn.js');
    //var codecell = require('notebook/js/codecell');
    var dockId = 0;

    var hm = require('/nbextensions/phy/static/notebooksession.js');

    var storeKey = 'manual_clustering_dockspawn_layout_state';

    // Convert a div to the dock manager. Panels can then be docked on to it
    //var divDockManager = document.getElementById('ipython-main-app');
    var divDockManager = document.getElementById('dockspawn-main');
    var dockManager = new dockspawn.DockManager(divDockManager);
    dockManager.initialize();

    var lastState = localStorage.getItem(storeKey);
    lastState = undefined;
    if (lastState) {
        dockManager.loadState(lastState);
    }

    // Let the dock manager element fill in the entire screen
    window.onresize = function () {
        dockManager.resize(
            window.innerWidth - (divDockManager.clientLeft + divDockManager.offsetLeft),
            window.innerHeight - (divDockManager.clientTop + divDockManager.offsetTop)
        );
    };
    window.onresize();

    dockManager.addLayoutListener({
        onDock: function(self, dockNode)                   {localStorage.setItem(storeKey, dockManager.saveState());},
        onUndock:function(self, dockNode)                  {localStorage.setItem(storeKey, dockManager.saveState());},
        onCreateDialog:function(self, dialog)              {localStorage.setItem(storeKey, dockManager.saveState());},
        onChangeDialogPosition:function(self, dialog, x, y){localStorage.setItem(storeKey, dockManager.saveState());},
        onResumeLayout:function(self)                      {localStorage.setItem(storeKey, dockManager.saveState());},
        onClosePanel:function(self, panel)                 {localStorage.setItem(storeKey, dockManager.saveState());},
        onHideDialog:function(self, dialog)                {localStorage.setItem(storeKey, dockManager.saveState());},
        onShowDialog:function(self, dialog)                {localStorage.setItem(storeKey, dockManager.saveState());}
    });

    if (!lastState) {
        var ph1 = new dockspawn.PanelContainer(document.getElementById("placeholder1"), dockManager);
        var ph2 = new dockspawn.PanelContainer(document.getElementById("placeholder2"), dockManager);
        var ph3 = new dockspawn.PanelContainer(document.getElementById("placeholder3"), dockManager);
        var ph4 = new dockspawn.PanelContainer(document.getElementById("placeholder4"), dockManager);

        var documentNode = dockManager.context.model.documentManagerNode;
        dockManager.dockFill(documentNode, ph1);
        var rr = dockManager.dockRight(documentNode, ph2, 0.20);
        dockManager.dockDown(rr, ph3, 0.30);
        dockManager.dockDown(rr, ph4, 0.30);

        //     // Convert existing elements on the page into "Panels".
    //     // They can then be docked on to the dock manager
    //     // Panels get a titlebar and a close button, and can also be
    //     // converted to a floating dialog box which can be dragged / resized
    //     var solution = new dockspawn.PanelContainer(document.getElementById("solution_window"), dockManager);
    //     var properties = new dockspawn.PanelContainer(document.getElementById("properties_window"), dockManager);
    //     var toolbox = new dockspawn.PanelContainer(document.getElementById("toolbox_window"), dockManager);
    //     var outline = new dockspawn.PanelContainer(document.getElementById("outline_window"), dockManager);
    //     var problems = new dockspawn.PanelContainer(document.getElementById("problems_window"), dockManager);
    //     var output = new dockspawn.PanelContainer(document.getElementById("output_window"), dockManager);
    //     var editor1 = new dockspawn.PanelContainer(document.getElementById("editor1_window"), dockManager);
    //     var editor2 = new dockspawn.PanelContainer(document.getElementById("editor2_window"), dockManager);
    //     var infovis = new dockspawn.PanelContainer(document.getElementById("infovis"), dockManager);
    //     var nb = new dockspawn.PanelContainer(document.getElementById("notebook_panel"), dockManager);

    //     // Dock the panels on the dock manager
    //     var documentNode = dockManager.context.model.documentManagerNode;
    //     var outlineNode = dockManager.dockLeft(documentNode, outline, 0.15);
    //     var solutionNode = dockManager.dockFill(outlineNode, solution);
    //     var propertiesNode = dockManager.dockDown(outlineNode, properties, 0.6);
    //     var outputNode = dockManager.dockDown(documentNode, output, 0.2);
    //     var problemsNode = dockManager.dockRight(outputNode, problems, 0.40);
    //     var toolboxNode = dockManager.dockRight(documentNode, toolbox, 0.20);
    //     var editor1Node = dockManager.dockFill(documentNode, editor1);
    //     var editor2Node = dockManager.dockFill(documentNode, editor2);
    //     var infovisNode = dockManager.dockFill(documentNode, infovis);
    //     dockManager.floatDialog(nb, 100, 100);
    }

    var myhack = new hm.HackMe('proto_kwik.ipynb', 'proto/proto_kwik.ipynb');
    myhack.start();
    var events = require('base/js/events');

    events.on('kernel_connected.Kernel', function(){
        console.log('session done');
        myhack.create_result_cell('#placeholder1', "from phy.cluster.manual.interface import start_manual_clustering; session = start_manual_clustering('/home/ctaf/src/cortex/data/test_hybrid_120sec.kwik', backend='ipynb_webgl')");
        myhack.create_result_cell('#placeholder2', "1+1");
        myhack.create_cell('#placeholder3', "from phy.cluster.manual.interface import start_manual_clustering; session = start_manual_clustering('/home/ctaf/src/cortex/data/test_hybrid_120sec.kwik', backend='ipynb_webgl')");
        myhack.create_cell('#placeholder4');
    });
});
<commit_msg>manual_clustering.js: save/load layout<commit_after>define(function (require) {
    "use strict";

    var IPython = require('base/js/namespace');
    var $ = require('jquery');
    //var events = require("base/js/events");
    var dockspawn = require('/nbextensions/phy/static/dock-spawn/dist/js/dockspawn.js');
    //var codecell = require('notebook/js/codecell');
    var dockId = 0;

    var hm = require('/nbextensions/phy/static/notebooksession.js');

    var storeKey = 'manual_clustering_dockspawn_layout_state';

    // Convert a div to the dock manager. Panels can then be docked on to it
    //var divDockManager = document.getElementById('ipython-main-app');
    var divDockManager = document.getElementById('dockspawn-main');
    var dockManager = new dockspawn.DockManager(divDockManager);
    dockManager.initialize();

    var lastState = localStorage.getItem(storeKey);
    //lastState = undefined;
    if (lastState) {
        dockManager.loadState(lastState);
    }

    // Let the dock manager element fill in the entire screen
    window.onresize = function () {
        dockManager.resize(
            window.innerWidth - (divDockManager.clientLeft + divDockManager.offsetLeft),
            window.innerHeight - (divDockManager.clientTop + divDockManager.offsetTop)
        );
    };
    window.onresize();

    dockManager.addLayoutListener({
        onDock: function(self, dockNode)                   {localStorage.setItem(storeKey, dockManager.saveState());},
        onUndock:function(self, dockNode)                  {localStorage.setItem(storeKey, dockManager.saveState());},
        onCreateDialog:function(self, dialog)              {localStorage.setItem(storeKey, dockManager.saveState());},
        onChangeDialogPosition:function(self, dialog, x, y){localStorage.setItem(storeKey, dockManager.saveState());},
        onResumeLayout:function(self)                      {localStorage.setItem(storeKey, dockManager.saveState());},
        onClosePanel:function(self, panel)                 {localStorage.setItem(storeKey, dockManager.saveState());},
        onHideDialog:function(self, dialog)                {localStorage.setItem(storeKey, dockManager.saveState());},
        onShowDialog:function(self, dialog)                {localStorage.setItem(storeKey, dockManager.saveState());}
    });

    if (!lastState) {
        var ph1 = new dockspawn.PanelContainer(document.getElementById("placeholder1"), dockManager);
        var ph2 = new dockspawn.PanelContainer(document.getElementById("placeholder2"), dockManager);
        var ph3 = new dockspawn.PanelContainer(document.getElementById("placeholder3"), dockManager);
        var ph4 = new dockspawn.PanelContainer(document.getElementById("placeholder4"), dockManager);

        var documentNode = dockManager.context.model.documentManagerNode;
        dockManager.dockFill(documentNode, ph1);
        var rr = dockManager.dockRight(documentNode, ph2, 0.20);
        dockManager.dockDown(rr, ph3, 0.30);
        dockManager.dockDown(rr, ph4, 0.30);

        //     // Convert existing elements on the page into "Panels".
    //     // They can then be docked on to the dock manager
    //     // Panels get a titlebar and a close button, and can also be
    //     // converted to a floating dialog box which can be dragged / resized
    //     var solution = new dockspawn.PanelContainer(document.getElementById("solution_window"), dockManager);
    //     var properties = new dockspawn.PanelContainer(document.getElementById("properties_window"), dockManager);
    //     var toolbox = new dockspawn.PanelContainer(document.getElementById("toolbox_window"), dockManager);
    //     var outline = new dockspawn.PanelContainer(document.getElementById("outline_window"), dockManager);
    //     var problems = new dockspawn.PanelContainer(document.getElementById("problems_window"), dockManager);
    //     var output = new dockspawn.PanelContainer(document.getElementById("output_window"), dockManager);
    //     var editor1 = new dockspawn.PanelContainer(document.getElementById("editor1_window"), dockManager);
    //     var editor2 = new dockspawn.PanelContainer(document.getElementById("editor2_window"), dockManager);
    //     var infovis = new dockspawn.PanelContainer(document.getElementById("infovis"), dockManager);
    //     var nb = new dockspawn.PanelContainer(document.getElementById("notebook_panel"), dockManager);

    //     // Dock the panels on the dock manager
    //     var documentNode = dockManager.context.model.documentManagerNode;
    //     var outlineNode = dockManager.dockLeft(documentNode, outline, 0.15);
    //     var solutionNode = dockManager.dockFill(outlineNode, solution);
    //     var propertiesNode = dockManager.dockDown(outlineNode, properties, 0.6);
    //     var outputNode = dockManager.dockDown(documentNode, output, 0.2);
    //     var problemsNode = dockManager.dockRight(outputNode, problems, 0.40);
    //     var toolboxNode = dockManager.dockRight(documentNode, toolbox, 0.20);
    //     var editor1Node = dockManager.dockFill(documentNode, editor1);
    //     var editor2Node = dockManager.dockFill(documentNode, editor2);
    //     var infovisNode = dockManager.dockFill(documentNode, infovis);
    //     dockManager.floatDialog(nb, 100, 100);
    }

    var myhack = new hm.HackMe('proto_kwik.ipynb', 'proto/proto_kwik.ipynb');
    myhack.start();
    var events = require('base/js/events');

    events.on('kernel_connected.Kernel', function(){
        console.log('session done');
        myhack.create_result_cell('#placeholder1', "from phy.cluster.manual.interface import start_manual_clustering; session = start_manual_clustering('/home/ctaf/src/cortex/data/test_hybrid_120sec.kwik', backend='ipynb_webgl')");
        myhack.create_result_cell('#placeholder2', "1+1");
        myhack.create_cell('#placeholder3', "from phy.cluster.manual.interface import start_manual_clustering; session = start_manual_clustering('/home/ctaf/src/cortex/data/test_hybrid_120sec.kwik', backend='ipynb_webgl')");
        myhack.create_cell('#placeholder4');
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var metadata = require('../package.json');
var path = require('path');
var program = require('commander');

function getPackage(source) {
	var version = parseInt(/^v(\d+)\./.exec(process.version)[1]) >= 6 ? 'es6' : 'es5'

	if(source === 'github') {
		return 'compiler-bin-js-' + version;
	}
	else {
		return 'compiler-bin-' + version;
	}
}

program
	.command('dependency')
	.action(function() {
		if(metadata._requested && metadata._requested.registry) {
			console.log('@kaoscript/' + getPackage())
		}
		else {
			console.log('github:kaoscript/' + getPackage('github'))
		}
	});

program
	.command('binary')
	.action(function() {
		var data = fs.readFileSync(path.join(__dirname, '..', 'node_modules', '@kaoscript', getPackage(), 'compiler.js'));

		fs.writeFileSync(path.join(__dirname, '..', 'lib', 'compiler.js'), data);
	});

program.parse(process.argv);<commit_msg>install script is requesting a version<commit_after>var fs = require('fs');
var metadata = require('../package.json');
var path = require('path');
var program = require('commander');

function getPackage(source) {
	var version = parseInt(/^v(\d+)\./.exec(process.version)[1]) >= 6 ? 'es6' : 'es5'

	if(source === 'github') {
		return 'compiler-bin-js-' + version;
	}
	else {
		return 'compiler-bin-' + version;
	}
}

program
	.command('dependency')
	.action(function() {
		if(metadata._requested && metadata._requested.registry) {
			console.log('@kaoscript/' + getPackage() + '@^' + metadata.version.split('.').slice(0, 2).join('.'))
		}
		else {
			console.log('github:kaoscript/' + getPackage('github'))
		}
	});

program
	.command('binary')
	.action(function() {
		var data = fs.readFileSync(path.join(__dirname, '..', 'node_modules', '@kaoscript', getPackage(), 'compiler.js'));

		fs.writeFileSync(path.join(__dirname, '..', 'lib', 'compiler.js'), data);
	});

program.parse(process.argv);<|endoftext|>


<commit_before>(function(root) {

  'use strict';

  root.app = root.app || {};
  root.app.pubsub  = root.app.pubsub || {};

  var QueryParams = Backbone.Model.extend({});

  root.app.Router = Backbone.Router.extend({

    routes: {
      '(/)': 'welcome',
      'about(/)': 'about',
      'actors/:id/:locationId(/)': 'actors',
      'actions/:id/:locationId(/)': 'actions'
    },

    initialize: function() {
      this.queryParams = new QueryParams();
      this.currentRoute = { name: null, params: [] };

      this.retrieveQueryParams();
      this.setListeners();
    },

    setListeners: function() {
      this.listenTo(this.queryParams, 'change', this.queryParamsOnChange);
      this.listenTo(this, 'route', this.saveCurrentRoute);
    },

    /* Save the current route and its parameters */
    saveCurrentRoute: function() {
      this.currentRoute = {
        name: arguments[0],
        params: [].slice.call(arguments, 1)[0]
      };
    },

    /* Return the current route */
    getCurrentRoute: function() {
      return this.currentRoute;
    },

    /* Save the query params passed as argument inside the queryParams model */
    setQueryParams: function(params) {
      this.queryParams.set(params);
    },

    /* Set the string passed as argument as the query params of the URL without
     * any transformation and retrieve the params from it right after */
    setRawQueryParams: function(rawQueryParams) {
      /* We reset the URL first */
      history.replaceState(null, null, '?');
      /* Then we silently reset the model */
      this.queryParams.clear({ silent: true });
      /* Finally we apply the desired params */
      history.replaceState(null, null, rawQueryParams);
      this.retrieveQueryParams();
    },

    /* Return a JSON representation of the queryParams model */
    getQueryParams: function() {
      return this.queryParams.toJSON();
    },

    /* Called when the query params are updated: call method to updated the URL
     * and trigger the change */
    queryParamsOnChange: function() {
      this.updateUrlFromQueryParams();
      this.triggerQueryParams();
    },

    /* Trigger an event change:queryParams with the attributes from the model
     * queryParams */
    triggerQueryParams: function() {
      this.trigger('change:queryParams', this.getQueryParams());
    },

    /* Update the query part of the URL with the attributes contained in the
     * model queryParams */
    updateUrlFromQueryParams: function() {
      var serializedParams = _.reduce(this.getQueryParams(),
        function(str, value, key) {
        if(value.length > 0) {
          if(_.isArray(value)) {
            /* If the array is empty, we don't add anything to the URL */
            if(value.length === 0) return str;

            return str + (str.length === 0 ? '?' : '&') + key + '[]=' +
              value.join(',');
          }
          return str + (str.length === 0 ? '?' : '&') + key + '=' + value;
        } else {
          return str;
        }
      }, '');

      history.replaceState(null, null, serializedParams);
    },

    /* Get the query params from the URL and save them to the model
     * NOTE: when this method is called from initialize, the change events won't
     * be caught by queryParamsOnChange because it's called before the listeners
     * are initialized */
    retrieveQueryParams: function() {
      var query = location.search.replace('?', '');
      /* If we don't have query params, we exit the method */
      if(query.length === 0) {
        return;
      }

      var pairs = query.split('&');
      _.each(pairs, function(pair) {
        if(pair.split('=').length !== 2) {
          console.warn('Invalid query parameter: ' + pair);
        } else {
          var key   = pair.split('=')[0],
              value = pair.split('=')[1];

          var isArray = /\[\]$/.test(key);
          if(isArray) {
            value = value.length === 0 ? [] : value.split(',');
            key = key.replace('[]', '');
          }

          this.queryParams.set(key, value);
        }
      }, this);
    }

  });

})(this);
<commit_msg>Fixes an issue that prevented a saved search to present the same results<commit_after>(function(root) {

  'use strict';

  root.app = root.app || {};
  root.app.pubsub  = root.app.pubsub || {};

  var QueryParams = Backbone.Model.extend({});

  root.app.Router = Backbone.Router.extend({

    routes: {
      '(/)': 'welcome',
      'about(/)': 'about',
      'actors/:id/:locationId(/)': 'actors',
      'actions/:id/:locationId(/)': 'actions'
    },

    initialize: function() {
      this.queryParams = new QueryParams();
      this.currentRoute = { name: null, params: [] };

      this.retrieveQueryParams();
      this.setListeners();
    },

    setListeners: function() {
      this.listenTo(this.queryParams, 'change', this.queryParamsOnChange);
      this.listenTo(this, 'route', this.saveCurrentRoute);
    },

    /* Save the current route and its parameters */
    saveCurrentRoute: function() {
      this.currentRoute = {
        name: arguments[0],
        params: [].slice.call(arguments, 1)[0]
      };
    },

    /* Return the current route */
    getCurrentRoute: function() {
      return this.currentRoute;
    },

    /* Save the query params passed as argument inside the queryParams model */
    setQueryParams: function(params) {
      this.queryParams.set(params);
    },

    /* Set the string passed as argument as the query params of the URL without
     * any transformation and retrieve the params from it right after */
    setRawQueryParams: function(rawQueryParams) {
      /* We reset the URL first */
      history.replaceState(null, null, '?');
      /* Then we silently reset the model */
      this.queryParams.clear({ silent: true });
      /* Finally we apply the desired params */
      history.replaceState(null, null, rawQueryParams);
      this.retrieveQueryParams();
    },

    /* Return a JSON representation of the queryParams model */
    getQueryParams: function() {
      return this.queryParams.toJSON();
    },

    /* Called when the query params are updated: call method to updated the URL
     * and trigger the change */
    queryParamsOnChange: function() {
      this.updateUrlFromQueryParams();
      this.triggerQueryParams();
    },

    /* Trigger an event change:queryParams with the attributes from the model
     * queryParams */
    triggerQueryParams: function() {
      this.trigger('change:queryParams', this.getQueryParams());
    },

    /* Update the query part of the URL with the attributes contained in the
     * model queryParams */
    updateUrlFromQueryParams: function() {
      var serializedParams = _.reduce(this.getQueryParams(),
        function(str, value, key) {
        if(value.length > 0) {
          if(_.isArray(value)) {
            /* If the array is empty, we don't add anything to the URL */
            if(value.length === 0) return str;

            return str + (str.length === 0 ? '?' : '&') + key + '[]=' +
              value.join(',');
          }
          return str + (str.length === 0 ? '?' : '&') + key + '=' + value;
        } else {
          return str;
        }
      }, '');

      history.replaceState(null, null, serializedParams);
    },

    /* Get the query params from the URL and save them to the model
     * NOTE: when this method is called from initialize, the change events won't
     * be caught by queryParamsOnChange because it's called before the listeners
     * are initialized */
    retrieveQueryParams: function() {
      var query = location.search.replace('?', '');
      /* If we don't have query params, we exit the method */
      if(query.length === 0) {
        return;
      }

      var pairs = query.split('&'),
          params = {};
      _.each(pairs, function(pair) {
        if(pair.split('=').length !== 2) {
          console.warn('Invalid query parameter: ' + pair);
        } else {
          var key   = pair.split('=')[0],
              value = pair.split('=')[1];

          var isArray = /\[\]$/.test(key);
          if(isArray) {
            value = value.length === 0 ? [] : value.split(',');
            key = key.replace('[]', '');
          }

          params[key] = value;
        }
      });

      this.queryParams.set(params);
    }

  });

})(this);
<|endoftext|>


<commit_before>(function () {
    'use strict';

    /**
     * @param Base
     * @param {$rootScope.Scope} $scope
     * @param {ModalManager} modalManager
     * @param {BalanceWatcher} balanceWatcher
     * @param {Waves} waves
     * @param {User} user
     */
    const controller = function (Base, $scope, modalManager, waves, balanceWatcher, user) {

        const { SIGN_TYPE } = require('@waves/signature-adapter');
        const { WAVES_ID } = require('@waves/signature-generator');
        const ds = require('data-service');
        const $ = require('jquery');
        const BASE_64_PREFIX = 'base64:';

        class TokensCtrl extends Base {

            /**
             * Link to angular form object
             * @type {form.FormController}
             */
            createForm = null;
            /**
             * Token name
             * @type {string}
             */
            name = '';
            /**
             * Token description
             * @type {string}
             */
            description = '';
            /**
             * Can reissue this token
             * @type {boolean}
             */
            issue = true;
            /**
             * Count of generated tokens
             * @type {BigNumber}
             */
            count = null;
            /**
             * Precision of token
             * @type {number}
             */
            precision = 0;
            /**
             * @type {BigNumber}
             */
            maxCoinsCount = null;
            /**
             * Has money for fee
             * @type {boolean}
             */
            invalid = false;
            /**
             * @type {string}
             */
            script = '';
            /**
             * @type {boolean}
             */
            isValidScript = true;
            /**
             * @type {boolean}
             */
            scriptPending = false;
            /**
             * @type {Money}
             */
            fee = null;
            /**
             * @type {boolean}
             */
            hasAssetScript = false;
            /**
             * @type {JQueryXHR | null}
             * @private
             */
            _scriptValidationXHR = null;
            /**
             * @type {Money}
             * @private
             */
            _balance;

            constructor() {
                super($scope);

                this.receive(balanceWatcher.change, this._onChangeBalance, this);

                this.observe('precision', this._onChangePrecision);
                this.observe('script', this._onChangeScript);

                waves.node.getFee({ type: SIGN_TYPE.ISSUE })
                    .then(money => {
                        this.fee = money;

                        this._onChangeBalance();
                        $scope.$apply();
                    });
            }

            generate(signable) {
                return modalManager.showConfirmTx(signable)
                    .then(() => this._reset());
            }

            createSignable() {
                const precision = Number(this.precision.toString());
                const quantity = this.count.times(Math.pow(10, precision));
                const script = this.hasAssetScript && this.script ? `${BASE_64_PREFIX}${this.script}` : '';

                const tx = waves.node.transactions.createTransaction({
                    type: SIGN_TYPE.ISSUE,
                    name: this.name,
                    description: this.description,
                    reissuable: this.issue,
                    quantity,
                    precision,
                    script,
                    fee: this.fee
                });

                return ds.signature.getSignatureApi().makeSignable({ type: tx.type, data: tx });
            }

            /**
             * @return {null}
             * @private
             */
            _onChangeScript() {
                if (this._scriptValidationXHR) {
                    this._scriptValidationXHR.abort();
                    this.scriptPending = false;
                }
                const script = this.script.replace(BASE_64_PREFIX, '');

                if (!script) {
                    this.isValidScript = true;
                    this.scriptPending = false;
                    return null;
                }

                this.isValidScript = true;
                this.scriptPending = true;
                this._scriptValidationXHR = $.ajax({
                    method: 'POST',
                    url: `${user.getSetting('network.node')}/utils/script/estimate`,
                    data: script
                });

                this._scriptValidationXHR
                    .then(() => {
                        this.isValidScript = true;
                    })
                    .catch(() => {
                        this.isValidScript = false;
                    })
                    .always(() => {
                        this.scriptPending = false;
                        $scope.$apply();
                    });
            }

            /**
             * @param {BigNumber} value
             * @private
             */
            _onChangePrecision({ value }) {
                if (value && value <= 8) {
                    this.maxCoinsCount = WavesApp.maxCoinsCount.div(Math.pow(10, Number(value)));
                }
            }

            /**
             * Current can i send transaction (balance gt fee)
             * @private
             */
            _onChangeBalance() {
                this._balance = balanceWatcher.getBalance()[WAVES_ID];

                this.invalid = (!this.fee || !this._balance) ||
                    this._balance.getTokens().lt(this.fee.getTokens());

                $scope.$apply();
            }

            /**
             * @private
             */
            _reset() {

                this.name = '';
                this.description = '';
                this.issue = true;
                this.count = new BigNumber(0);
                this.precision = 0;
                this.maxCoinsCount = null;
                this.script = '';
                this.hasAssetScript = false;

                this.createForm.$setPristine();
                this.createForm.$setUntouched();

                $scope.$apply();
            }

        }

        return new TokensCtrl();
    };

    controller.$inject = ['Base', '$scope', 'modalManager', 'waves', 'balanceWatcher', 'user'];

    angular.module('app.tokens')
        .controller('TokensCtrl', controller);
})();

<commit_msg>CLIENT-1767: fix<commit_after>(function () {
    'use strict';

    /**
     * @param Base
     * @param {$rootScope.Scope} $scope
     * @param {ModalManager} modalManager
     * @param {BalanceWatcher} balanceWatcher
     * @param {Waves} waves
     * @param {User} user
     */
    const controller = function (Base, $scope, modalManager, waves, balanceWatcher, user) {

        const { SIGN_TYPE } = require('@waves/signature-adapter');
        const { WAVES_ID } = require('@waves/signature-generator');
        const ds = require('data-service');
        const $ = require('jquery');
        const BASE_64_PREFIX = 'base64:';

        class TokensCtrl extends Base {

            /**
             * Link to angular form object
             * @type {form.FormController}
             */
            createForm = null;
            /**
             * Token name
             * @type {string}
             */
            name = '';
            /**
             * Token description
             * @type {string}
             */
            description = '';
            /**
             * Can reissue this token
             * @type {boolean}
             */
            issue = true;
            /**
             * Count of generated tokens
             * @type {BigNumber}
             */
            count = null;
            /**
             * Precision of token
             * @type {number}
             */
            precision = 0;
            /**
             * @type {BigNumber}
             */
            maxCoinsCount = WavesApp.maxCoinsCount;
            /**
             * Has money for fee
             * @type {boolean}
             */
            invalid = false;
            /**
             * @type {string}
             */
            script = '';
            /**
             * @type {boolean}
             */
            isValidScript = true;
            /**
             * @type {boolean}
             */
            scriptPending = false;
            /**
             * @type {Money}
             */
            fee = null;
            /**
             * @type {boolean}
             */
            hasAssetScript = false;
            /**
             * @type {JQueryXHR | null}
             * @private
             */
            _scriptValidationXHR = null;
            /**
             * @type {Money}
             * @private
             */
            _balance;

            constructor() {
                super($scope);

                this.receive(balanceWatcher.change, this._onChangeBalance, this);

                this.observe('precision', this._onChangePrecision);
                this.observe('script', this._onChangeScript);

                waves.node.getFee({ type: SIGN_TYPE.ISSUE })
                    .then(money => {
                        this.fee = money;

                        this._onChangeBalance();
                        $scope.$apply();
                    });
            }

            generate(signable) {
                return modalManager.showConfirmTx(signable)
                    .then(() => this._reset());
            }

            createSignable() {
                const precision = Number(this.precision.toString());
                const quantity = this.count.times(Math.pow(10, precision));
                const script = this.hasAssetScript && this.script ? `${BASE_64_PREFIX}${this.script}` : '';

                const tx = waves.node.transactions.createTransaction({
                    type: SIGN_TYPE.ISSUE,
                    name: this.name,
                    description: this.description,
                    reissuable: this.issue,
                    quantity,
                    precision,
                    script,
                    fee: this.fee
                });

                return ds.signature.getSignatureApi().makeSignable({ type: tx.type, data: tx });
            }

            /**
             * @return {null}
             * @private
             */
            _onChangeScript() {
                if (this._scriptValidationXHR) {
                    this._scriptValidationXHR.abort();
                    this.scriptPending = false;
                }
                const script = this.script.replace(BASE_64_PREFIX, '');

                if (!script) {
                    this.isValidScript = true;
                    this.scriptPending = false;
                    return null;
                }

                this.isValidScript = true;
                this.scriptPending = true;
                this._scriptValidationXHR = $.ajax({
                    method: 'POST',
                    url: `${user.getSetting('network.node')}/utils/script/estimate`,
                    data: script
                });

                this._scriptValidationXHR
                    .then(() => {
                        this.isValidScript = true;
                    })
                    .catch(() => {
                        this.isValidScript = false;
                    })
                    .always(() => {
                        this.scriptPending = false;
                        $scope.$apply();
                    });
            }

            /**
             * @param {BigNumber} value
             * @private
             */
            _onChangePrecision({ value }) {
                if (value && value <= 8) {
                    this.maxCoinsCount = WavesApp.maxCoinsCount.div(Math.pow(10, Number(value)));
                }
            }

            /**
             * Current can i send transaction (balance gt fee)
             * @private
             */
            _onChangeBalance() {
                this._balance = balanceWatcher.getBalance()[WAVES_ID];

                this.invalid = (!this.fee || !this._balance) ||
                    this._balance.getTokens().lt(this.fee.getTokens());

                $scope.$apply();
            }

            /**
             * @private
             */
            _reset() {

                this.name = '';
                this.description = '';
                this.issue = true;
                this.count = new BigNumber(0);
                this.precision = 0;
                this.maxCoinsCount = WavesApp.maxCoinsCount;
                this.script = '';
                this.hasAssetScript = false;

                this.createForm.$setPristine();
                this.createForm.$setUntouched();

                $scope.$apply();
            }

        }

        return new TokensCtrl();
    };

    controller.$inject = ['Base', '$scope', 'modalManager', 'waves', 'balanceWatcher', 'user'];

    angular.module('app.tokens')
        .controller('TokensCtrl', controller);
})();

<|endoftext|>


<commit_before>var child = require('child_process');
var spawn = child.spawn;
var exec = child.exec;
var execSync = child.execSync;

var path = require('path');
var fs = require('fs');

var fmppName = process.platform === 'win32' ? 'fmpp.bat' : 'fmpp';
var fmpp = path.join(__dirname, '../fmpp', fmppName);

function run(args, done) {

  var command = fmpp + ' ' + args.join(' ');

  exec(command,
    function(error, stdout, stderr) {

      done(error || stderr, stdout);

    });
}

function runSync(args) {
  var command = fmpp + ' ' + args.join(' ');

  if(execSync) {
    // On node.js v0.12, there comes execSync() method which exactly we want
    return execSync(command);
  } else {
    // Here is inefficiency and ugliness hack for older version of node.js
    exec(command + ' 2>&1 1>output && echo done! > done');
    while(!fs.existsSync('done')) {}

    var output = fs.readFileSync('output');
    fs.unlinkSync('output');
    fs.unlinkSync('done');

    return '' + output;
  }
}

exports.run = run;
exports.runSync = runSync;
<commit_msg>实际上不需要 spawn 了<commit_after>var child = require('child_process');
var exec = child.exec;
var execSync = child.execSync;

var path = require('path');
var fs = require('fs');

var fmppName = process.platform === 'win32' ? 'fmpp.bat' : 'fmpp';
var fmpp = path.join(__dirname, '../fmpp', fmppName);

function run(args, done) {

  var command = fmpp + ' ' + args.join(' ');

  exec(command,
    function(error, stdout, stderr) {

      done(error || stderr, stdout);

    });
}

function runSync(args) {
  var command = fmpp + ' ' + args.join(' ');

  if(execSync) {
    // On node.js v0.12, there comes execSync() method which exactly we want
    return execSync(command);
  } else {
    // Here is inefficiency and ugliness hack for older version of node.js
    exec(command + ' 2>&1 1>output && echo done! > done');
    while(!fs.existsSync('done')) {}

    var output = fs.readFileSync('output');
    fs.unlinkSync('output');
    fs.unlinkSync('done');

    return '' + output;
  }
}

exports.run = run;
exports.runSync = runSync;
<|endoftext|>


<commit_before>/* global APP, $ */
//maps keycode to character, id of popover for given function and function
var shortcuts = {};
function initShortcutHandlers() {
    shortcuts = {
        27: {
            character: "Esc",
            function: function() {
                APP.UI.showKeyboardShortcutsPanel(false);
            }
        },
        67: {
            character: "C",
            id: "toggleChatPopover",
            function: function() {
                APP.UI.toggleChat();
            }
        },
        68: {
            character: "D",
            id: "toggleDesktopSharingPopover",
            function: function () {
                APP.conference.toggleScreenSharing();
            }
        },
        70: {
            character: "F",
            id: "filmstripPopover",
            function: function() {
                APP.UI.toggleFilmStrip();
            }
        },
        77: {
            character: "M",
            id: "mutePopover",
            function: function() {
                APP.conference.toggleAudioMuted();
            }
        },
        82: {
            character: "R",
            function: function() {
                APP.conference.maybeToggleRaisedHand();
            }

        },
        84: {
            character: "T",
            function: function() {
                APP.conference.muteAudio(true);
            }
        },
        86: {
            character: "V",
            id: "toggleVideoPopover",
            function: function() {
                APP.conference.toggleVideoMuted();
            }
        },
        191: {
            character: "/",
            function: function(e) {
                // Only trigger on "?", not on "/".
                if (e.shiftKey) {
                    APP.UI.toggleKeyboardShortcutsPanel();
                }
            }
        }
    };
}

var KeyboardShortcut = {
    init: function () {
        initShortcutHandlers();
        window.onkeyup = function(e) {
            var keycode = e.which;
            if(!($(":focus").is("input[type=text]") ||
                $(":focus").is("input[type=password]") ||
                $(":focus").is("textarea"))) {
                if (typeof shortcuts[keycode] === "object") {
                    shortcuts[keycode].function(e);
                }
                else if (keycode >= "0".charCodeAt(0) &&
                    keycode <= "9".charCodeAt(0)) {
                    APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
                }
                //esc while the smileys are visible hides them
            } else if (keycode === 27 &&
                $('#smileysContainer').is(':visible')) {
                APP.UI.toggleSmileys();
            }
        };

        window.onkeydown = function(e) {
            if(!($(":focus").is("input[type=text]") ||
                $(":focus").is("input[type=password]") ||
                $(":focus").is("textarea"))) {
                if(e.which === "T".charCodeAt(0)) {
                    if(APP.conference.isLocalAudioMuted())
                        APP.conference.muteAudio(false);
                }
            }
        };
        var self = this;
        $('body').popover({ selector: '[data-toggle=popover]',
            trigger: 'click hover',
            content: function() {
                return this.getAttribute("content") +
                    self.getShortcut(this.getAttribute("shortcut"));
            }
        });
    },
    /**
     *
     * @param id indicates the popover associated with the shortcut
     * @returns {string} the keyboard shortcut used for the id given
     */
    getShortcut: function (id) {
        for (var keycode in shortcuts) {
            if (shortcuts.hasOwnProperty(keycode)) {
                if (shortcuts[keycode].id === id) {
                    return " (" + shortcuts[keycode].character + ")";
                }
            }
        }
        return "";
    }
};

module.exports = KeyboardShortcut;
<commit_msg>Improve keyboard shortcut handling<commit_after>/* global APP, $ */
//maps keycode to character, id of popover for given function and function
var shortcuts = {};
function initShortcutHandlers() {
    shortcuts = {
        "ESCAPE": {
            character: "Esc",
            function: function() {
                APP.UI.showKeyboardShortcutsPanel(false);
            }
        },
        "C": {
            character: "C",
            id: "toggleChatPopover",
            function: function() {
                APP.UI.toggleChat();
            }
        },
        "D": {
            character: "D",
            id: "toggleDesktopSharingPopover",
            function: function () {
                APP.conference.toggleScreenSharing();
            }
        },
        "F": {
            character: "F",
            id: "filmstripPopover",
            function: function() {
                APP.UI.toggleFilmStrip();
            }
        },
        "M": {
            character: "M",
            id: "mutePopover",
            function: function() {
                APP.conference.toggleAudioMuted();
            }
        },
        "R": {
            character: "R",
            function: function() {
                APP.conference.maybeToggleRaisedHand();
            }

        },
        "T": {
            character: "T",
            function: function() {
                APP.conference.muteAudio(true);
            }
        },
        "V": {
            character: "V",
            id: "toggleVideoPopover",
            function: function() {
                APP.conference.toggleVideoMuted();
            }
        },
        "?": {
            character: "?",
            function: function(e) {
                APP.UI.toggleKeyboardShortcutsPanel();
            }
        }
    };
}

var KeyboardShortcut = {
    init: function () {
        initShortcutHandlers();
        var self = this;
        window.onkeyup = function(e) {
            var key = self.getKeyboardKey(e).toUpperCase();
            var num = parseInt(key, 10);
            if(!($(":focus").is("input[type=text]") ||
                $(":focus").is("input[type=password]") ||
                $(":focus").is("textarea"))) {
                if (shortcuts.hasOwnProperty(key)) {
                    shortcuts[key].function(e);
                }
                else if (!isNaN(num) && num >= 0 && num <= 9) {
                    APP.UI.clickOnVideo(num + 1);
                }
            //esc while the smileys are visible hides them
            } else if (key === "ESCAPE" &&
                $('#smileysContainer').is(':visible')) {
                APP.UI.toggleSmileys();
            }
        };

        window.onkeydown = function(e) {
            if(!($(":focus").is("input[type=text]") ||
                $(":focus").is("input[type=password]") ||
                $(":focus").is("textarea"))) {
                var key = self.getKeyboardKey(e).toUpperCase();
                if(key === "T") {
                    if(APP.conference.isLocalAudioMuted())
                        APP.conference.muteAudio(false);
                }
            }
        };
        $('body').popover({ selector: '[data-toggle=popover]',
            trigger: 'click hover',
            content: function() {
                return this.getAttribute("content") +
                    self.getShortcut(this.getAttribute("shortcut"));
            }
        });
    },
    /**
     *
     * @param id indicates the popover associated with the shortcut
     * @returns {string} the keyboard shortcut used for the id given
     */
    getShortcut: function (id) {
        for (var key in shortcuts) {
            if (shortcuts.hasOwnProperty(key)) {
                if (shortcuts[key].id === id) {
                    return " (" + shortcuts[key].character + ")";
                }
            }
        }
        return "";
    },
    /**
     * @param e a KeyboardEvent
     * @returns {string} e.key or something close if not supported
     */
    getKeyboardKey: function (e) {
        if (typeof e.key === "string") {
            return e.key;
        }
        if (e.type === "keypress" && (
                (e.which >= 32 && e.which <= 126) ||
                (e.which >= 160 && e.which <= 255) )) {
            return String.fromCharCode(e.which);
        }
        // try to fallback (0-9A-Za-z and QWERTY keyboard)
        switch (e.which) {
        case 27:
            return "Escape";
        case 191:
            return e.shiftKey ? "?" : "/";
        }
        if (e.shiftKey || e.type === "keypress") {
            return String.fromCharCode(e.which);
        } else {
            return String.fromCharCode(e.which).toLowerCase();
        }
    }
};

module.exports = KeyboardShortcut;
<|endoftext|>


<commit_before>module.exports = {
  hasNext,
  getNextIndex,
  hasPrevious,
  getPreviousIndex,
  getCurrentLocalURL
}

const TorrentSummary = require('./torrent-summary')
const TorrentPlayer = require('./torrent-player')

const cache = {
  infoHash: null,
  previousIndex: null,
  currentIndex: null,
  nextIndex: null
}

function hasNext (state) {
  updateCache(state)
  return cache.nextIndex !== null
}

function getNextIndex (state) {
  updateCache(state)
  return cache.nextIndex
}

function hasPrevious (state) {
  updateCache(state)
  return cache.previousIndex !== null
}

function getPreviousIndex (state) {
  updateCache(state)
  return cache.previousIndex
}

function getCurrentLocalURL (state) {
  return state.server
    ? state.server.localURL + '/' + state.playing.fileIndex
    : ''
}

function updateCache (state) {
  const infoHash = state.playing.infoHash
  const fileIndex = state.playing.fileIndex

  if (infoHash === cache.infoHash) {
    switch (fileIndex) {
      case cache.currentIndex:
        return
      case cache.nextIndex:
        cache.previousIndex = cache.currentIndex
        cache.currentIndex = fileIndex
        cache.nextIndex = findNextIndex(state)
        return
      case cache.previousIndex:
        cache.previousIndex = findPreviousIndex(state)
        cache.nextIndex = cache.currentIndex
        cache.currentIndex = fileIndex
        return
    }
  } else {
    cache.infoHash = infoHash
  }

  cache.previousIndex = findPreviousIndex(state)
  cache.currentIndex = fileIndex
  cache.nextIndex = findNextIndex(state)
}

function findPreviousIndex (state) {
  const files = TorrentSummary.getByKey(state, state.playing.infoHash).files
  for (let i = state.playing.fileIndex - 1; i >= 0; i--) {
    if (TorrentPlayer.isPlayable(files[i])) return i
  }
  return null
}

function findNextIndex (state) {
  const files = TorrentSummary.getByKey(state, state.playing.infoHash).files
  for (let i = state.playing.fileIndex + 1; i < files.length; i++) {
    if (TorrentPlayer.isPlayable(files[i])) return i
  }
  return null
}
<commit_msg>Pass title metadata in media url<commit_after>module.exports = {
  hasNext,
  getNextIndex,
  hasPrevious,
  getPreviousIndex,
  getCurrentLocalURL
}

const TorrentSummary = require('./torrent-summary')
const TorrentPlayer = require('./torrent-player')

const cache = {
  infoHash: null,
  previousIndex: null,
  currentIndex: null,
  nextIndex: null
}

function hasNext (state) {
  updateCache(state)
  return cache.nextIndex !== null
}

function getNextIndex (state) {
  updateCache(state)
  return cache.nextIndex
}

function hasPrevious (state) {
  updateCache(state)
  return cache.previousIndex !== null
}

function getPreviousIndex (state) {
  updateCache(state)
  return cache.previousIndex
}

function getCurrentLocalURL (state) {
  return state.server
    ? state.server.localURL + '/' + state.playing.fileIndex + '/' + state.window.title
    : ''
}

function updateCache (state) {
  const infoHash = state.playing.infoHash
  const fileIndex = state.playing.fileIndex

  if (infoHash === cache.infoHash) {
    switch (fileIndex) {
      case cache.currentIndex:
        return
      case cache.nextIndex:
        cache.previousIndex = cache.currentIndex
        cache.currentIndex = fileIndex
        cache.nextIndex = findNextIndex(state)
        return
      case cache.previousIndex:
        cache.previousIndex = findPreviousIndex(state)
        cache.nextIndex = cache.currentIndex
        cache.currentIndex = fileIndex
        return
    }
  } else {
    cache.infoHash = infoHash
  }

  cache.previousIndex = findPreviousIndex(state)
  cache.currentIndex = fileIndex
  cache.nextIndex = findNextIndex(state)
}

function findPreviousIndex (state) {
  const files = TorrentSummary.getByKey(state, state.playing.infoHash).files
  for (let i = state.playing.fileIndex - 1; i >= 0; i--) {
    if (TorrentPlayer.isPlayable(files[i])) return i
  }
  return null
}

function findNextIndex (state) {
  const files = TorrentSummary.getByKey(state, state.playing.infoHash).files
  for (let i = state.playing.fileIndex + 1; i < files.length; i++) {
    if (TorrentPlayer.isPlayable(files[i])) return i
  }
  return null
}
<|endoftext|>


<commit_before>navigator.serviceWorker.register('service-worker.js').then(function() {
    console.log('CLIENT: service worker registration complete.');
}, function(e) {
    console.error(e);
});
<commit_msg>fix lint errors<commit_after>/* eslint-disable prefer-arrow-callback, no-console */
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('service-worker.js').then(function done() {
        console.log('CLIENT: service worker registration complete.');
    }, function c(e) {
        console.error(e);
    });
}
<|endoftext|>