<commit_before>/**
 * @license
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {CodeOwnerService, OwnerStatus} from './code-owners-service.js';

const MAGIC_FILES = ['/COMMIT_MSG', '/MERGE_LIST', '/PATCHSET_LEVEL'];
const STATUS_CODE = {
  PENDING: 'pending',
  PENDING_OLD_PATH: 'pending-old-path',
  MISSING: 'missing',
  MISSING_OLD_PATH: 'missing-old-path',
  APPROVED: 'approved',
  ERROR: 'error',
  ERROR_OLD_PATH: 'error-old-path',
};
const STATUS_ICON = {
  [STATUS_CODE.PENDING]: 'gr-icons:schedule',
  [STATUS_CODE.MISSING]: 'gr-icons:close',
  [STATUS_CODE.PENDING_OLD_PATH]: 'gr-icons:schedule',
  [STATUS_CODE.MISSING_OLD_PATH]: 'gr-icons:close',
  [STATUS_CODE.APPROVED]: 'gr-icons:check',
  [STATUS_CODE.ERROR]: 'gr-icons:info-outline',
};
const STATUS_TOOLTIP = {
  [STATUS_CODE.PENDING]: 'Pending file-owner approval',
  [STATUS_CODE.MISSING]: 'Missing file-owner approval',
  [STATUS_CODE.PENDING_OLD_PATH]: 'Pending approval on pre-renamed file',
  [STATUS_CODE.MISSING_OLD_PATH]: 'Missing owner for pre-renamed file',
  [STATUS_CODE.APPROVED]: 'Approved by file-owner',
  [STATUS_CODE.ERROR]: 'Failed to fetch file-owner status',
};

class BaseEl extends Polymer.Element {
  computeHidden(change, patchRange) {
    if ([change, patchRange].includes(undefined)) return true;
    // if code-owners is not a submit requirement, don't show status column
    if (change.requirements
        && !change.requirements.find(r => r.type === 'code-owners')) {
      return true;
    }

    const latestPatchset = change.revisions[change.current_revision];
    // only show if its comparing against base
    if (patchRange.basePatchNum !== 'PARENT') return true;
    // only show if its latest patchset
    if (`${patchRange.patchNum}` !== `${latestPatchset._number}`) return true;
    return false;
  }

  onInputChanged(restApi, change) {
    if ([restApi, change].includes(undefined)) return;
    this.ownerService = CodeOwnerService.getOwnerService(this.restApi, change);
  }
}

/**
 * Column header element for owner status.
 */
export class OwnerStatusColumnHeader extends BaseEl {
  static get is() {
    return 'owner-status-column-header';
  }

  static get template() {
    return Polymer.html`

      `;
  }

  static get properties() {
    return {
      change: Object,
      reporting: Object,
      patchRange: Object,
      restApi: Object,

      hidden: {
        type: Boolean,
        reflectToAttribute: true,
        computed: 'computeHidden(change, patchRange)',
      },
      ownerService: Object,
    };
  }

  static get observers() {
    return [
      'onInputChanged(restApi, change)',
      'onOwnerServiceChanged(ownerServive)',
    ];
  }
}

customElements.define(OwnerStatusColumnHeader.is, OwnerStatusColumnHeader);

/**
 * Row content element for owner status.
 */
export class OwnerStatusColumnContent extends BaseEl {
  static get is() {
    return 'owner-status-column-content';
  }

  static get properties() {
    return {
      change: Object,
      reporting: Object,
      restApi: Object,

      path: String,
      patchRange: Object,
      hidden: {
        type: Boolean,
        reflectToAttribute: true,
        computed: 'computeHidden(change, patchRange)',
      },
      ownerService: Object,
      statusIcon: {
        type: String,
        computed: '_computeIcon(status)',
      },
      statusInfo: {
        type: String,
        computed: '_computeTooltip(status)',
      },
      status: {
        type: String,
        reflectToAttribute: true,
      },
    };
  }

  static get template() {
    return Polymer.html`

        <gr-tooltip-content title="[[statusInfo]]" has-tooltip>
          <iron-icon icon="[[statusIcon]]"></iron-icon>
        </gr-tooltip-content>
      `;
  }

  static get observers() {
    return [
      'onInputChanged(restApi, change)',
      'computeStatusIcon(ownerService, path)',
    ];
  }

  computeStatusIcon(ownerService, path) {
    if ([ownerService, path].includes(undefined)) return;
    if (MAGIC_FILES.includes(path)) return;

    ownerService.getStatus()
        .then(({codeOwnerStatusMap}) => {
          const statusItem = codeOwnerStatusMap.get(path);
          if (!statusItem) {
            this.status = STATUS_CODE.ERROR;
            return;
          }

          const status = statusItem.status;
          let oldPathStatus = null;
          if (statusItem.oldPath) {
            const oldStatusItem = codeOwnerStatusMap.get(statusItem.oldPath);
            if (!oldStatusItem) {
              // should not happen
            } else {
              oldPathStatus = oldStatusItem.status;
            }
          }

          const newPathStatus = this._computeStatus(status);
          if (!oldPathStatus) {
            this.status = newPathStatus;
          } else {
            this.status = newPathStatus === STATUS_CODE.APPROVED
              ? this._computeStatus(oldPathStatus, /* oldPath= */ true)
              : newPathStatus;
          }
        })
        .catch(e => {
          this.status = STATUS_CODE.ERROR;
          throw e;
        });
  }

  _computeIcon(status) {
    return STATUS_ICON[status];
  }

  _computeTooltip(status) {
    return STATUS_TOOLTIP[status];
  }

  _computeStatus(status, oldPath = false) {
    if (status === OwnerStatus.INSUFFICIENT_REVIEWERS) {
      return oldPath ? STATUS_CODE.MISSING_OLD_PATH : STATUS_CODE.MISSING;
    } else if (status === OwnerStatus.PENDING) {
      return oldPath ? STATUS_CODE.PENDING_OLD_PATH : STATUS_CODE.PENDING;
    } else {
      return STATUS_CODE.APPROVED;
    }
  }
}

customElements.define(OwnerStatusColumnContent.is, OwnerStatusColumnContent);<commit_msg>Fix missing status after publishing edits<commit_after>/**
 * @license
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {CodeOwnerService, OwnerStatus} from './code-owners-service.js';

const MAGIC_FILES = ['/COMMIT_MSG', '/MERGE_LIST', '/PATCHSET_LEVEL'];
const STATUS_CODE = {
  PENDING: 'pending',
  PENDING_OLD_PATH: 'pending-old-path',
  MISSING: 'missing',
  MISSING_OLD_PATH: 'missing-old-path',
  APPROVED: 'approved',
  ERROR: 'error',
  ERROR_OLD_PATH: 'error-old-path',
};
const STATUS_ICON = {
  [STATUS_CODE.PENDING]: 'gr-icons:schedule',
  [STATUS_CODE.MISSING]: 'gr-icons:close',
  [STATUS_CODE.PENDING_OLD_PATH]: 'gr-icons:schedule',
  [STATUS_CODE.MISSING_OLD_PATH]: 'gr-icons:close',
  [STATUS_CODE.APPROVED]: 'gr-icons:check',
  [STATUS_CODE.ERROR]: 'gr-icons:info-outline',
};
const STATUS_TOOLTIP = {
  [STATUS_CODE.PENDING]: 'Pending file-owner approval',
  [STATUS_CODE.MISSING]: 'Missing file-owner approval',
  [STATUS_CODE.PENDING_OLD_PATH]: 'Pending approval on pre-renamed file',
  [STATUS_CODE.MISSING_OLD_PATH]: 'Missing owner for pre-renamed file',
  [STATUS_CODE.APPROVED]: 'Approved by file-owner',
  [STATUS_CODE.ERROR]: 'Failed to fetch file-owner status',
};

class BaseEl extends Polymer.Element {
  computeHidden(change, patchRange) {
    if ([change, patchRange].includes(undefined)) return true;
    // if code-owners is not a submit requirement, don't show status column
    if (change.requirements
        && !change.requirements.find(r => r.type === 'code-owners')) {
      return true;
    }

    const latestPatchset = change.revisions[change.current_revision];
    // only show if its comparing against base
    if (patchRange.basePatchNum !== 'PARENT') return true;
    // Note: in some special cases, patchNum is undefined on latest patchset like
    // after publishing the edit, still show for them
    // TODO: this should be fixed in Gerrit
    if (patchRange.patchNum === undefined) return false;
    // only show if its latest patchset
    if (`${patchRange.patchNum}` !== `${latestPatchset._number}`) return true;
    return false;
  }

  onInputChanged(restApi, change) {
    if ([restApi, change].includes(undefined)) return;
    this.ownerService = CodeOwnerService.getOwnerService(this.restApi, change);
  }
}

/**
 * Column header element for owner status.
 */
export class OwnerStatusColumnHeader extends BaseEl {
  static get is() {
    return 'owner-status-column-header';
  }

  static get template() {
    return Polymer.html`

      `;
  }

  static get properties() {
    return {
      change: Object,
      reporting: Object,
      patchRange: Object,
      restApi: Object,

      hidden: {
        type: Boolean,
        reflectToAttribute: true,
        computed: 'computeHidden(change, patchRange)',
      },
      ownerService: Object,
    };
  }

  static get observers() {
    return [
      'onInputChanged(restApi, change)',
      'onOwnerServiceChanged(ownerServive)',
    ];
  }
}

customElements.define(OwnerStatusColumnHeader.is, OwnerStatusColumnHeader);

/**
 * Row content element for owner status.
 */
export class OwnerStatusColumnContent extends BaseEl {
  static get is() {
    return 'owner-status-column-content';
  }

  static get properties() {
    return {
      change: Object,
      reporting: Object,
      restApi: Object,

      path: String,
      patchRange: Object,
      hidden: {
        type: Boolean,
        reflectToAttribute: true,
        computed: 'computeHidden(change, patchRange)',
      },
      ownerService: Object,
      statusIcon: {
        type: String,
        computed: '_computeIcon(status)',
      },
      statusInfo: {
        type: String,
        computed: '_computeTooltip(status)',
      },
      status: {
        type: String,
        reflectToAttribute: true,
      },
    };
  }

  static get template() {
    return Polymer.html`

        <gr-tooltip-content title="[[statusInfo]]" has-tooltip>
          <iron-icon icon="[[statusIcon]]"></iron-icon>
        </gr-tooltip-content>
      `;
  }

  static get observers() {
    return [
      'onInputChanged(restApi, change)',
      'computeStatusIcon(ownerService, path)',
    ];
  }

  computeStatusIcon(ownerService, path) {
    if ([ownerService, path].includes(undefined)) return;
    if (MAGIC_FILES.includes(path)) return;

    ownerService.getStatus()
        .then(({codeOwnerStatusMap}) => {
          const statusItem = codeOwnerStatusMap.get(path);
          if (!statusItem) {
            this.status = STATUS_CODE.ERROR;
            return;
          }

          const status = statusItem.status;
          let oldPathStatus = null;
          if (statusItem.oldPath) {
            const oldStatusItem = codeOwnerStatusMap.get(statusItem.oldPath);
            if (!oldStatusItem) {
              // should not happen
            } else {
              oldPathStatus = oldStatusItem.status;
            }
          }

          const newPathStatus = this._computeStatus(status);
          if (!oldPathStatus) {
            this.status = newPathStatus;
          } else {
            this.status = newPathStatus === STATUS_CODE.APPROVED
              ? this._computeStatus(oldPathStatus, /* oldPath= */ true)
              : newPathStatus;
          }
        })
        .catch(e => {
          this.status = STATUS_CODE.ERROR;
          throw e;
        });
  }

  _computeIcon(status) {
    return STATUS_ICON[status];
  }

  _computeTooltip(status) {
    return STATUS_TOOLTIP[status];
  }

  _computeStatus(status, oldPath = false) {
    if (status === OwnerStatus.INSUFFICIENT_REVIEWERS) {
      return oldPath ? STATUS_CODE.MISSING_OLD_PATH : STATUS_CODE.MISSING;
    } else if (status === OwnerStatus.PENDING) {
      return oldPath ? STATUS_CODE.PENDING_OLD_PATH : STATUS_CODE.PENDING;
    } else {
      return STATUS_CODE.APPROVED;
    }
  }
}

customElements.define(OwnerStatusColumnContent.is, OwnerStatusColumnContent);<|endoftext|>


<commit_before>import { logger } from "./shims";

var clientSystem = "Unknown";
var projectId, sessionId, geoListenEnabled;
var apiClient = {};

/** Responsible for establishing a session with the Roundware server **/
export class Session {
  /** Create a new Session
   * @param {object} navigator - provides access to the userAgent string
   * @param {Number} newProjectId - identifies the Roundware project to associate with this session
   * @param {Boolean} geoListenEnablement - whether the server should enable geo listening features
   * @param {Object} options - Various configuration parameters for this session
   * @param {apiClient} options.apiClient - the API client object to use for server API calls
  **/
  constructor (navigator,newProjectId,geoListenEnablement,options) {
    clientSystem = navigator.userAgent;

    if (clientSystem.length > 127) {
      // on mobile browsers, this string is longer than the server wants
      clientSystem = clientSystem.slice(0,127);
    }

    projectId = newProjectId;
    geoListenEnabled = geoListenEnablement;

    apiClient = options.apiClient;
  }

  /** @returns {String} human-readable representation of this session **/
  toString() {
    return "Roundware Session #" + sessionId;
  }

  /** Make an asynchronous API call to establish a session with the Roundware server
   * @returns {Promise} represents the pending API call
   **/
  connect() {
    let requestData = {
      project_id: projectId,
      geo_listen_enabled: geoListenEnabled,
      client_system: clientSystem
    };

    return apiClient.post("/sessions/",requestData).
      then((data) => {
        sessionId = data.session_id;
        return sessionId;
      });
  }
}
<commit_msg>fix: correct doc @returns tag<commit_after>import { logger } from "./shims";

var clientSystem = "Unknown";
var projectId, sessionId, geoListenEnabled;
var apiClient = {};

/** Responsible for establishing a session with the Roundware server **/
export class Session {
  /** Create a new Session
   * @param {object} navigator - provides access to the userAgent string
   * @param {Number} newProjectId - identifies the Roundware project to associate with this session
   * @param {Boolean} geoListenEnablement - whether the server should enable geo listening features
   * @param {Object} options - Various configuration parameters for this session
   * @param {apiClient} options.apiClient - the API client object to use for server API calls
  **/
  constructor (navigator,newProjectId,geoListenEnablement,options) {
    clientSystem = navigator.userAgent;

    if (clientSystem.length > 127) {
      // on mobile browsers, this string is longer than the server wants
      clientSystem = clientSystem.slice(0,127);
    }

    projectId = newProjectId;
    geoListenEnabled = geoListenEnablement;

    apiClient = options.apiClient;
  }

  /** @returns {String} human-readable representation of this session **/
  toString() {
    return "Roundware Session #" + sessionId;
  }

  /** Make an asynchronous API call to establish a session with the Roundware server
   * @return {Promise} represents the pending API call
   **/
  connect() {
    let requestData = {
      project_id: projectId,
      geo_listen_enabled: geoListenEnabled,
      client_system: clientSystem
    };

    return apiClient.post("/sessions/",requestData).
      then((data) => {
        sessionId = data.session_id;
        return sessionId;
      });
  }
}
<|endoftext|>


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

var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var globalShortcut = electron.globalShortcut;
var ipcMain = electron.ipcMain;

var mainWindow = null;

var mainWindowOptions = {
  width: 900,
  height: 559,
  frame: false,
  resizable: false,
  devTools: true,
  transparent: true,
  skipTaskbar: true,
  show: true,
  center: true
};

var mainWindowHtml = 'file://' + __dirname + '/main.html';

app.on('window-all-closed', function () {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function () {
  mainWindow = new BrowserWindow(mainWindowOptions);

  mainWindow.loadURL(mainWindowHtml);
  //mainWindow.webContents.openDevTools();
  mainWindow.hide();

  mainWindow.on('closed', function () {
    mainWindow = null;
  });

  mainWindow.on('blur', function () {
    mainWindow.hide();
  });

  globalShortcut.register('alt+space', function () {
    if (mainWindow.isVisible())
      mainWindow.hide();
    else
      mainWindow.show();
  });

  ipcMain.on('hide-main-window', function () {
    mainWindow.hide();
  });

  ipcMain.on('close-main-window', function () {
    app.quit();
  });

  ipcMain.on('reload-window', function() {
    mainWindow.reload();
  });

});
<commit_msg>Changed window aspect ratio to 16:9<commit_after>var electron = require('electron');

var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var globalShortcut = electron.globalShortcut;
var ipcMain = electron.ipcMain;

var mainWindow = null;

var mainWindowOptions = {
  width: 993,
  height: 559,
  frame: false,
  resizable: false,
  devTools: true,
  transparent: true,
  skipTaskbar: true,
  show: true,
  center: true
};

var mainWindowHtml = 'file://' + __dirname + '/main.html';

app.on('window-all-closed', function () {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function () {
  mainWindow = new BrowserWindow(mainWindowOptions);

  mainWindow.loadURL(mainWindowHtml);
  //mainWindow.webContents.openDevTools();
  mainWindow.hide();

  mainWindow.on('closed', function () {
    mainWindow = null;
  });

  mainWindow.on('blur', function () {
    mainWindow.hide();
  });

  globalShortcut.register('alt+space', function () {
    if (mainWindow.isVisible())
      mainWindow.hide();
    else
      mainWindow.show();
  });

  ipcMain.on('hide-main-window', function () {
    mainWindow.hide();
  });

  ipcMain.on('close-main-window', function () {
    app.quit();
  });

  ipcMain.on('reload-window', function() {
    mainWindow.reload();
  });

});
<|endoftext|>


<commit_before>$(document).ready(function() {

     //  var legendControl = L.control.legend({
     //        autoAdd: false
     //   }).addTo(map);

		var lineWeight1m = new L.LinearFunction(new L.Point(50000, 1), new L.Point(1000000, 12));
		var lineWeight50m = new L.LinearFunction(new L.Point(1000001, 12), new L.Point(50000000, 25));
		var lineColor1m = new L.HSLHueFunction(new L.Point(50000, 120), new L.Point(1000000, 10), {outputLuminosity: '60%'});
		var lineColor50m = new L.HSLHueFunction(new L.Point(1000001, 10), new L.Point(50000000, 0), {outputLuminosity: '60%'});

		var lineColor = new L.PiecewiseFunction([lineColor1m, lineColor50m]);
		var lineWeight = new L.PiecewiseFunction([lineWeight1m, lineWeight50m]);

		var firmColor = new L.HSLHueFunction(new L.Point(0, 260), new L.Point(1024, 0),
						{outputLuminosity: '40%', oddity:0, preProcess: function(value) {
							if (this.options.oddity == 1){
								this.options.oddity = 0;
								value = 1024 - value;
                                if(value<0) {return 0-value;}
                                else {	return value; }
								}
							else { this.options.oddity = 1; return value ;}
							}
						});

          for(var i=0; i<schoolData.length; i++) {
	   //  for(var i=0; i<10; i++) {
                var group = L.layerGroup();
                var colorCounter = 0;
                var options= { data: { }, chartOptions: {},
                    weight: 1, radius: 36, fillOpacity: 1,
                    rotation: 0.0, position: { x: 20, y: 0 },
				    tooltipOptions: {
							iconSize: new L.Point(120, 100),
							iconAnchor: new L.Point(-5, 64)
							},
                    barThickness: 26
                };

                for(var k = 0; k <contdata.length; k++) {
                    if(contdata[k].school_inn === schoolData[i].inn) {
                        options.data["'" + contdata[k].supplier_name+ "'"] = contdata[k].supplier_summ;
						//var dataColor = lineColor.evaluate(contdata[k].supplier_summ);
						var dataColor = firmColor.evaluate(colorCounter);
                        colorCounter = colorCounter + 10;
						var text = contdata[k].supplier_name + " - Контракт на " + contdata[k].supplier_summ + " рублей";
						var dataWeight = lineWeight.evaluate(contdata[k].supplier_summ);
						options.chartOptions["'"+ contdata[k].supplier_name+ "'"] =
                           { color: dataColor,
                            fillcolor: dataColor,
                             minValue: 0, maxValue: 50000000
                            } ;
                        var arcedPolyline = new L.ArcedPolyline([[schoolData[i].lat,schoolData[i].lng],
                                    [contdata[k].supplier_lat,contdata[k].supplier_lng] ], {
                                //        distanceToHeight: new L.LinearFunction([0, 0], [4000, 400]),
								        fillColor: dataColor,
										color: dataColor,
								       weight: dataWeight, displaytext: text });
						arcedPolyline.bindPopup(text, {autoPanPadding: L.point(300, 200) });
						arcedPolyline.on("click", function(e) {
							e.target.openPopup();
						});
						arcedPolyline.on("popupclose", function(e) {
								map.setView([55.75, 37.63], 10);
						});
						/*
						arcedPolyline.on("mouseover", function(e) {
								console.log(e.target);

						});
*/

                        group.addLayer(arcedPolyline);
                    }
				}

				var marker = new L.PieChartMarker(new L.LatLng(schoolData[i].lat,schoolData[i].lng),
                               options);
				marker.on("click", function(e) {
					console.log(e.target);
					sidebar.setContent(e.target.toString());
					sidebar.show();
					});
                if (group.getLayers() != 0) {
					group.addLayer(marker);
					if(i===0) { group.addTo(map); }
                    layerControl.addOverlay(group, schoolData[i].kratk_name, {groupName : "Школы Москвы", expanded:true});
				}
             }

        map.on("overlayadd", function(e) { map.setView([55.75, 37.63], 10);})
		map.fire("dataload");
/*

// utility functions - not needed now

        var getSchoolByName= function(name) {
            for(var i=0; i<schoolData.length; i++) {
                if(schoolData[i].kratk_name == name) {
                    return schoolData[i]; }
            }
        }

		// strange function for getting location for layer L.Graph

        var getLocation = function (context, locationField, fieldValues, callback) {
            var key = fieldValues[0];
            var school = getSchoolByName(key);
            var location;

            if (school) {
                var latlng = new L.LatLng(Number(school.lat), Number(school.lng));

                location = {
                    location: latlng,
                    text: key,
                    center: latlng
                };
            }
           // console.log("Got coords! " + location.text + " = " + location.center);
            return location;
        };
        for(var i=0; i<2; i++) {
          if (schoolData[i].lat) {
            L.marker([schoolData[i].lat, schoolData[i].lng]).addTo(map);
            var key = schoolData[i].label;
            console.log("-----------------------------------Going for key " +key);

            var connectLayer = new L.Graph(schoolData, {
                recordsField: null,
                locationMode: L.LocationModes.CUSTOM,
                fromField: 'label',
                toField: 'label',
                codeField: null,
                getLocation: getLocation,
                getEdge: L.Graph.EDGESTYLE.ARC,
                includeLayer: function (record) {
                    return record.label != key;
                },
                setHighlight: function (style) {
                    style.opacity = 1.0;

                    return style;
                },
                unsetHighlight: function (style) {
                    style.opacity = 0.8;

                    return style;
                },
                layerOptions: {
                    fill: false,
                    opacity: 0.8,
                    weight: 0.5,
                    fillOpacity: 1.0,
                    distanceToHeight: new L.LinearFunction([0, 5], [1000, 200])
                },
                legendOptions: {
                    width: 200,
                    numSegments: 5,
                    className: 'legend-line'
                },
                tooltipOptions: {
                    iconSize: new L.Point(80, 64),
                    iconAnchor: new L.Point(-5, 64),
                    className: 'leaflet-div-icon line-legend'
               },
                displayOptions: {
                    cnt: {
                        weight: new L.LinearFunction([0, 1], [schoolData.length, 14]),
                        color: new L.HSLHueFunction([0, 200], [schoolData.length, 330], {
                            outputLuminosity: '60%'
                        }), displayname: schoolData[i].kratk_name,
                    displaytext: schoolData[i].kratk_name}
//
 //
 //               },
 //               onEachRecord: function (layer, record) {
 //                   layer.bindPopup($(L.HTMLUtils.buildTable(record)).wrap('<div/>').parent().html());
                }
            });

*/

});

<commit_msg>Update main.js<commit_after>$(document).ready(function() {

     //  var legendControl = L.control.legend({
     //        autoAdd: false
     //   }).addTo(map);

		var lineWeight1m = new L.LinearFunction(new L.Point(50000, 1), new L.Point(1000000, 12));
		var lineWeight50m = new L.LinearFunction(new L.Point(1000001, 12), new L.Point(50000000, 25));
		var lineColor1m = new L.HSLHueFunction(new L.Point(50000, 120), new L.Point(1000000, 10), {outputLuminosity: '60%'});
		var lineColor50m = new L.HSLHueFunction(new L.Point(1000001, 10), new L.Point(50000000, 0), {outputLuminosity: '60%'});

		var lineColor = new L.PiecewiseFunction([lineColor1m, lineColor50m]);
		var lineWeight = new L.PiecewiseFunction([lineWeight1m, lineWeight50m]);

		var firmColor = new L.HSLHueFunction(new L.Point(0, 260), new L.Point(1024, 0),
						{outputLuminosity: '40%', oddity:0, preProcess: function(value) {
							if (this.options.oddity == 1){
								this.options.oddity = 0;
								value = 1024 - value;
                                if(value<0) {return 0-value;}
                                else {	return value; }
								}
							else { this.options.oddity = 1; return value ;}
							}
						});

          for(var i=0; i<schoolData.length; i++) {
	   //  for(var i=0; i<10; i++) {
                var group = L.layerGroup();
                var colorCounter = 0;
                var options= { data: { }, chartOptions: {},
                    weight: 1, radius: 36, fillOpacity: 1,
                    rotation: 0.0, position: { x: 0, y: 0 },
				    tooltipOptions: {
							iconSize: new L.Point(120, 100),
							iconAnchor: new L.Point(-5, 64)
							},
                    barThickness: 26
                };

                for(var k = 0; k <contdata.length; k++) {
                    if(contdata[k].school_inn === schoolData[i].inn) {
                        options.data["'" + contdata[k].supplier_name+ "'"] = contdata[k].supplier_summ;
						//var dataColor = lineColor.evaluate(contdata[k].supplier_summ);
						var dataColor = firmColor.evaluate(colorCounter);
                        colorCounter = colorCounter + 10;
						var text = contdata[k].supplier_name + " - Контракт на " + contdata[k].supplier_summ + " рублей";
						var dataWeight = lineWeight.evaluate(contdata[k].supplier_summ);
						options.chartOptions["'"+ contdata[k].supplier_name+ "'"] =
                           { color: dataColor,
                            fillcolor: dataColor,
                             minValue: 0, maxValue: 50000000
                            } ;
                        var arcedPolyline = new L.ArcedPolyline([[schoolData[i].lat,schoolData[i].lng],
                                    [contdata[k].supplier_lat,contdata[k].supplier_lng] ], {
                                //        distanceToHeight: new L.LinearFunction([0, 0], [4000, 400]),
								        fillColor: dataColor,
										color: dataColor,
								       weight: dataWeight, displaytext: text });
						arcedPolyline.bindPopup(text, {autoPanPadding: L.point(300, 200) });
						arcedPolyline.on("click", function(e) {
							e.target.openPopup();
						});
						arcedPolyline.on("popupclose", function(e) {
								map.setView([55.75, 37.63], 10);
						});
						/*
						arcedPolyline.on("mouseover", function(e) {
								console.log(e.target);

						});
*/

                        group.addLayer(arcedPolyline);
                    }
				}

				var marker = new L.PieChartMarker(new L.LatLng(schoolData[i].lat,schoolData[i].lng),
                               options);
				marker.on("click", function(e) {
					console.log(e.target);
					sidebar.setContent(e.target.toString());
					sidebar.show();
					});
                if (group.getLayers() != 0) {
					group.addLayer(marker);
					if(i===0) { group.addTo(map); }
                    layerControl.addOverlay(group, schoolData[i].kratk_name, {groupName : "Школы Москвы", expanded:true});
				}
             }

        map.on("overlayadd", function(e) { map.setView([55.75, 37.63], 10);})
		map.fire("dataload");
/*

// utility functions - not needed now

        var getSchoolByName= function(name) {
            for(var i=0; i<schoolData.length; i++) {
                if(schoolData[i].kratk_name == name) {
                    return schoolData[i]; }
            }
        }

		// strange function for getting location for layer L.Graph

        var getLocation = function (context, locationField, fieldValues, callback) {
            var key = fieldValues[0];
            var school = getSchoolByName(key);
            var location;

            if (school) {
                var latlng = new L.LatLng(Number(school.lat), Number(school.lng));

                location = {
                    location: latlng,
                    text: key,
                    center: latlng
                };
            }
           // console.log("Got coords! " + location.text + " = " + location.center);
            return location;
        };
        for(var i=0; i<2; i++) {
          if (schoolData[i].lat) {
            L.marker([schoolData[i].lat, schoolData[i].lng]).addTo(map);
            var key = schoolData[i].label;
            console.log("-----------------------------------Going for key " +key);

            var connectLayer = new L.Graph(schoolData, {
                recordsField: null,
                locationMode: L.LocationModes.CUSTOM,
                fromField: 'label',
                toField: 'label',
                codeField: null,
                getLocation: getLocation,
                getEdge: L.Graph.EDGESTYLE.ARC,
                includeLayer: function (record) {
                    return record.label != key;
                },
                setHighlight: function (style) {
                    style.opacity = 1.0;

                    return style;
                },
                unsetHighlight: function (style) {
                    style.opacity = 0.8;

                    return style;
                },
                layerOptions: {
                    fill: false,
                    opacity: 0.8,
                    weight: 0.5,
                    fillOpacity: 1.0,
                    distanceToHeight: new L.LinearFunction([0, 5], [1000, 200])
                },
                legendOptions: {
                    width: 200,
                    numSegments: 5,
                    className: 'legend-line'
                },
                tooltipOptions: {
                    iconSize: new L.Point(80, 64),
                    iconAnchor: new L.Point(-5, 64),
                    className: 'leaflet-div-icon line-legend'
               },
                displayOptions: {
                    cnt: {
                        weight: new L.LinearFunction([0, 1], [schoolData.length, 14]),
                        color: new L.HSLHueFunction([0, 200], [schoolData.length, 330], {
                            outputLuminosity: '60%'
                        }), displayname: schoolData[i].kratk_name,
                    displaytext: schoolData[i].kratk_name}
//
 //
 //               },
 //               onEachRecord: function (layer, record) {
 //                   layer.bindPopup($(L.HTMLUtils.buildTable(record)).wrap('<div/>').parent().html());
                }
            });

*/

});

<|endoftext|>


<commit_before>const {app, globalShortcut, BrowserWindow} = require('electron')
const WebSocket = require('ws')

const WS_ADDRESS = "ws://localhost:8025/ws/echo"

// Local connection to Cytoscape app
let ws

let isDevEnabled = false;

let mainWindow

function createWindow () {
  // Establish WS connection
  try {
    // Try Connection to server...
    ws = new WebSocket(WS_ADDRESS)

    ws.onopen = function() {
      app.on('browser-window-focus', function() {
        var msg = {
          from: "ndex",
          type: "focus",
          body: "Ndex focused "
        };

        ws.send(JSON.stringify(msg));
      });
    };

    //Listen for messages
    ws.onmessage = function(event) {
      var msg = JSON.parse(event.data)
      switch(msg.type) {
        case "focus":
          //Bring NDEx Valet into focus
          if(msg.from === "cy3") {
            mainWindow.show();
          }
          break;
      }
    };

    ws.onclose = function() {
      app.quit()
    };

  } catch (e) {
    console.log(e);
  }

  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1100, height: 870,
    minHeight: 870, minWidth: 500,
    frame: true
  })
  mainWindow.loadURL(`file://${__dirname}/ndex/index.html`)

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

function addShortcuts() {
  globalShortcut.register('CommandOrControl+w', function() {
    console.log('Close (w) is pressed');
    app.quit()
  });

  // For dev tool
  globalShortcut.register('CommandOrControl+d', function() {
    console.log('Devtool');
    if(isDevEnabled) {
      mainWindow.webContents.closeDevTools();
      isDevEnabled = false;
    } else {
      mainWindow.webContents.openDevTools();
      isDevEnabled = true;
    }
  });
}

app.on('ready', () => {
  createWindow()
  addShortcuts()
});

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
})
<commit_msg>Updated focus<commit_after>const {app, globalShortcut, BrowserWindow} = require('electron')
const WebSocket = require('ws')

const WS_ADDRESS = "ws://localhost:8025/ws/echo"

// Local connection to Cytoscape app
let ws

let isDevEnabled = false;

let mainWindow

function createWindow () {
  // Establish WS connection
  try {
    // Try Connection to server...
    ws = new WebSocket(WS_ADDRESS)

    ws.onopen = function() {
      app.on('browser-window-focus', function() {
        var msg = {
          from: "ndex",
          type: "focus",
          body: "Ndex focused "
        };

        ws.send(JSON.stringify(msg));
      });
    };

    //Listen for messages
    ws.onmessage = function(event) {
      var msg = JSON.parse(event.data)
      switch(msg.type) {
        case "focus-success":
          //Bring NDEx Valet into focus
          if(msg.from === "cy3") {
              mainWindow.setAlwaysOnTop(true);
              mainWindow.show();
              // mainWindow.focus();
              mainWindow.setAlwaysOnTop(false);
          }
          break;
      }
    };

    ws.onclose = function() {
      app.quit()
    };

  } catch (e) {
    console.log(e);
  }

  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1100, height: 870,
    minHeight: 870, minWidth: 500,
    frame: true
  })
  mainWindow.loadURL(`file://${__dirname}/ndex/index.html`)

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

function addShortcuts() {
  globalShortcut.register('CommandOrControl+w', function() {
    console.log('Close (w) is pressed');
    app.quit()
  });

  // For dev tool
  globalShortcut.register('CommandOrControl+d', function() {
    console.log('Devtool');
    if(isDevEnabled) {
      mainWindow.webContents.closeDevTools();
      isDevEnabled = false;
    } else {
      mainWindow.webContents.openDevTools();
      isDevEnabled = true;
    }
  });
}

app.on('ready', () => {
  createWindow()
  addShortcuts()
});

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
})
<|endoftext|>


<commit_before>var game = new Phaser.Game(window.innerWidth-8, window.innerHeight-17, Phaser.AUTO, 'test', null, false, true);

var BasicGame = function (game) { };

BasicGame.Boot = function (game) { };

var isoGroup,
  groundGroup,
  wallGroup,
  player;

BasicGame.Boot.prototype ={
  preload: function () {
    game.load.image('cube_', 'assets/cube.png');
    game.load.image('ground', 'assets/ground_tile.png');
    game.load.image('wall', 'assets/wall.png');
    game.load.image('wall2', 'assets/wall2.png');

    game.time.advancedTiming = true;
    // Add and enable the plug-in.
    game.plugins.add(new Phaser.Plugin.Isometric(game));

    // In order to have the camera move, we need to increase the size of our world bounds.
    game.world.setBounds(0, 0, 2048, 1024);

    // Start the IsoArcade physics system.
    game.physics.startSystem(Phaser.Plugin.Isometric.ISOARCADE);
    game.world.setBounds(0, 0, 2048, 1024);

    // This is used to set a game canvas-based offset for the 0, 0, 0 isometric coordinate - by default
    // this point would be at screen coordinates 0, 0 (top left) which is usually undesirable.
    game.iso.anchor.setTo(0.3, 0.1);
  },
  create: function () {

    // Make the camera follow the player.
    game.camera.follow(player);

    game.stage.background = 0xB91717;

    groundGroup = game.add.group();
    wallGroup = game.add.group();

    game.physics.isoArcade.gravity.setTo(0, 0, -500);

    var a2 = game.add.isoSprite(45, 24, 0, 'wall', 0, wallGroup);
    var a3 = game.add.isoSprite(85, 24, 0, 'wall', 0, wallGroup);
    var a4 = game.add.isoSprite(125, 24, 0, 'wall', 0, wallGroup);
    var a1;
    for(var i = 0; i < 4; ++i) {
      a1 = game.add.isoSprite(5+(i*40), 24, 0, 'wall', 0, wallGroup);
      game.physics.isoArcade.enable(a1);
      a1.body.collideWorldBounds = true;
      a1.body.immovable = true;
    }

    var a5 = game.add.isoSprite(125, 24, 0, 'wall2', 0, wallGroup);
    var a6 = game.add.isoSprite(-25, 60, 0, 'wall2', 0, wallGroup);
    var a7 = game.add.isoSprite(-25, 100, 0, 'wall2', 0, wallGroup);
    var a8 = game.add.isoSprite(-25, 140, 0, 'wall2', 0, wallGroup);
    var a9 = game.add.isoSprite(-25, 180, 0, 'wall2', 0, wallGroup);
    var a10 = game.add.isoSprite(-25, 220, 0, 'wall2', 0, wallGroup);
    var a11 = game.add.isoSprite(50, 60, 0, 'wall2', 0, wallGroup);
    var a12 = game.add.isoSprite(50, 100, 0, 'wall2', 0, wallGroup);
    var a13 = game.add.isoSprite(50, 140, 0, 'wall2', 0, wallGroup);
    var a14 = game.add.isoSprite(50, 180, 0, 'wall2', 0, wallGroup);
    var a15 = game.add.isoSprite(50, 220, 0, 'wall2', 0, wallGroup);
    var a16 = game.add.isoSprite(150, 60, 0, 'wall2', 0, wallGroup);
    var a17 = game.add.isoSprite(150, 100, 0, 'wall2', 0, wallGroup);
    var a18 = game.add.isoSprite(150, 140, 0, 'wall2', 0, wallGroup);
    var a19 = game.add.isoSprite(150, 180, 0, 'wall2', 0, wallGroup);
    var a20 = game.add.isoSprite(150, 220, 0, 'wall2', 0, wallGroup);

    isoGroup = game.add.group();
    var floorTile;
    for (var xt = 1024; xt > 0; xt -= 35) {
      for (var yt = 1024; yt > 0; yt -= 35) {
        floorTile = game.add.isoSprite(xt, yt, 0, 'ground', 0, groundGroup);
        floorTile.anchor.set(0.5);
      }
    }

    // Create another cube as our 'player', and set it up just like the cubes above.
    player = game.add.isoSprite(328, 328, 0, 'cube_', 0, wallGroup);
    player.tint = 0x00ff00;
    player.anchor.set(0.5);
    game.physics.isoArcade.enable(player);
    player.body.collideWorldBounds = true;

    // Set up our controls.
    this.cursors = game.input.keyboard.createCursorKeys();

    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.LEFT,
      Phaser.Keyboard.RIGHT,
      Phaser.Keyboard.UP,
      Phaser.Keyboard.DOWN,
      Phaser.Keyboard.SPACEBAR
    ]);

    var space = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    space.onDown.add(function () {
      player.body.velocity.z = 300;
    }, this);
  },
  update: function () {
    // Move the player at this speed.
    var speed = 100;

    if (this.cursors.up.isDown) {
      player.body.velocity.y = -speed;
    }
    else if (this.cursors.down.isDown) {
      player.body.velocity.y = speed;
    }
    else {
      player.body.velocity.y = 0;
    }

    if (this.cursors.left.isDown) {
      player.body.velocity.x = -speed;
    }
    else if (this.cursors.right.isDown) {
      player.body.velocity.x = speed;
    }
    else {
      player.body.velocity.x = 0;
    }

    // Our collision and sorting code again.
    game.physics.isoArcade.collide(wallGroup);
    game.iso.topologicalSort(wallGroup);
  },
  render: function () {
    game.debug.text("Move with cursors, jump with space!", 2, 36, "#ffffff");
    game.debug.text(game.time.fps || '--', 2, 14, "#a7aebe");
  }
};

game.state.add('Boot', BasicGame.Boot);
game.state.start('Boot');
<commit_msg>camara following the player.., now it works :P<commit_after>var game = new Phaser.Game(window.innerWidth-8, window.innerHeight-17, Phaser.AUTO, 'test', null, false, true);

var BasicGame = function (game) { };

BasicGame.Boot = function (game) { };

var isoGroup,
  groundGroup,
  wallGroup,
  player;

BasicGame.Boot.prototype ={
  preload: function () {
    game.load.image('cube_', 'assets/cube.png');
    game.load.image('ground', 'assets/ground_tile.png');
    game.load.image('wall', 'assets/wall.png');
    game.load.image('wall2', 'assets/wall2.png');

    game.time.advancedTiming = true;
    // Add and enable the plug-in.
    game.plugins.add(new Phaser.Plugin.Isometric(game));

    // In order to have the camera move, we need to increase the size of our world bounds.
    game.world.setBounds(0, 0, 2048, 1024);

    // Start the IsoArcade physics system.
    game.physics.startSystem(Phaser.Plugin.Isometric.ISOARCADE);
    game.world.setBounds(0, 0, 2048, 1024);

    // This is used to set a game canvas-based offset for the 0, 0, 0 isometric coordinate - by default
    // this point would be at screen coordinates 0, 0 (top left) which is usually undesirable.
    game.iso.anchor.setTo(0.3, 0.1);
  },
  create: function () {
    game.stage.background = 0xB91717;

    groundGroup = game.add.group();
    wallGroup = game.add.group();

    game.physics.isoArcade.gravity.setTo(0, 0, -500);

    var a2 = game.add.isoSprite(45, 24, 0, 'wall', 0, wallGroup);
    var a3 = game.add.isoSprite(85, 24, 0, 'wall', 0, wallGroup);
    var a4 = game.add.isoSprite(125, 24, 0, 'wall', 0, wallGroup);
    var a1;
    for(var i = 0; i < 4; ++i) {
      a1 = game.add.isoSprite(5+(i*40), 24, 0, 'wall', 0, wallGroup);
      game.physics.isoArcade.enable(a1);
      a1.body.collideWorldBounds = true;
      a1.body.immovable = true;
    }

    var a5 = game.add.isoSprite(125, 24, 0, 'wall2', 0, wallGroup);
    var a6 = game.add.isoSprite(-25, 60, 0, 'wall2', 0, wallGroup);
    var a7 = game.add.isoSprite(-25, 100, 0, 'wall2', 0, wallGroup);
    var a8 = game.add.isoSprite(-25, 140, 0, 'wall2', 0, wallGroup);
    var a9 = game.add.isoSprite(-25, 180, 0, 'wall2', 0, wallGroup);
    var a10 = game.add.isoSprite(-25, 220, 0, 'wall2', 0, wallGroup);
    var a11 = game.add.isoSprite(50, 60, 0, 'wall2', 0, wallGroup);
    var a12 = game.add.isoSprite(50, 100, 0, 'wall2', 0, wallGroup);
    var a13 = game.add.isoSprite(50, 140, 0, 'wall2', 0, wallGroup);
    var a14 = game.add.isoSprite(50, 180, 0, 'wall2', 0, wallGroup);
    var a15 = game.add.isoSprite(50, 220, 0, 'wall2', 0, wallGroup);
    var a16 = game.add.isoSprite(150, 60, 0, 'wall2', 0, wallGroup);
    var a17 = game.add.isoSprite(150, 100, 0, 'wall2', 0, wallGroup);
    var a18 = game.add.isoSprite(150, 140, 0, 'wall2', 0, wallGroup);
    var a19 = game.add.isoSprite(150, 180, 0, 'wall2', 0, wallGroup);
    var a20 = game.add.isoSprite(150, 220, 0, 'wall2', 0, wallGroup);

    isoGroup = game.add.group();
    var floorTile;
    for (var xt = 1024; xt > 0; xt -= 35) {
      for (var yt = 1024; yt > 0; yt -= 35) {
        floorTile = game.add.isoSprite(xt, yt, 0, 'ground', 0, groundGroup);
        floorTile.anchor.set(0.5);
      }
    }

    // Create another cube as our 'player', and set it up just like the cubes above.
    player = game.add.isoSprite(328, 328, 0, 'cube_', 0, wallGroup);
    player.tint = 0x00ff00;
    player.anchor.set(0.5);
    game.physics.isoArcade.enable(player);
    player.body.collideWorldBounds = true;

    // Make the camera follow the player.
    game.camera.follow(player);

    // Set up our controls.
    this.cursors = game.input.keyboard.createCursorKeys();

    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.LEFT,
      Phaser.Keyboard.RIGHT,
      Phaser.Keyboard.UP,
      Phaser.Keyboard.DOWN,
      Phaser.Keyboard.SPACEBAR
    ]);

    var space = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    space.onDown.add(function () {
      player.body.velocity.z = 300;
    }, this);
  },
  update: function () {
    // Move the player at this speed.
    var speed = 100;

    if (this.cursors.up.isDown) {
      player.body.velocity.y = -speed;
    }
    else if (this.cursors.down.isDown) {
      player.body.velocity.y = speed;
    }
    else {
      player.body.velocity.y = 0;
    }

    if (this.cursors.left.isDown) {
      player.body.velocity.x = -speed;
    }
    else if (this.cursors.right.isDown) {
      player.body.velocity.x = speed;
    }
    else {
      player.body.velocity.x = 0;
    }

    // Our collision and sorting code again.
    game.physics.isoArcade.collide(wallGroup);
    game.iso.topologicalSort(wallGroup);
  },
  render: function () {
    game.debug.text("Move with cursors, jump with space!", 2, 36, "#ffffff");
    game.debug.text(game.time.fps || '--', 2, 14, "#a7aebe");
  }
};

game.state.add('Boot', BasicGame.Boot);
game.state.start('Boot');
<|endoftext|>


<commit_before>/*
NOTICE
The code herein was taken and modified in part from the Twitter open source portal - https://github.com/twitter/twitter.github.com
Modifications were made to include multiple organization accounts and display them differently
 */

(function () {

  // Put custom repo descriptions in this object, keyed by repo name.
  var repoDescriptions = {
    eas : "The Enterprise Addressing System (EAS) is an open source, web-based application that allows employees of government agencies to query, update, and retire street addresses.",
    CycleTracksWebsite : "Simple db and php code to catch data from iOS and Android CycleTracks apps."
  };

  // readOrgs() populates these three data structures from index.html.
  // Putting the raw data in index.html is more SEO-friendly since the
  // links are available in the original HTML as opposed to being
  // "injected" by the javascript at render-time.
  var orgs = [];
  var orgNameMap = {};
  var orgUrls = {};

  var repoUrls = {};

  // Extract the organization username from the URL.
  function urlToOrg(url) {
    // Remove the trailing slash, if present.
    if (url[url.length - 1] == "/") {
      url = url.slice(0, -1);
    }
    var index = url.lastIndexOf("/") + 1;
    var org = url.slice(index);

    return org;
  }

  // Read the organization data from index.html.
  function readOrgs() {
    var anchors = $("#orgs li a");
    for (var i = 0; i < anchors.length; i++) {
      var anchor = $(anchors[i]);
      var orgName = anchor.text();
      var url = anchor.attr("href");
      var org = urlToOrg(url).toLowerCase();

      orgs.push(org);
      orgNameMap[org] = orgName;
      orgUrls[org] = url;
    }
  }

  function repoUrl(repo) {
    return repoUrls[repo.name] || repo.html_url;
  }

  function repoDescription(repo) {
    return repoDescriptions[repo.name] || repo.description;
  }

  function repoToOrgName(repo) {
    return orgNameMap[repo.owner.login.toLowerCase()] || repo.name;
  }

  function addRepo(repo) {
    var description = repoDescription(repo);
    var $item = $("<div>").addClass("col-sm-4 repo");
    var $link = $("<a>").attr("href", repoUrl(repo)).attr("id",repo.id).appendTo($item);
    var $panel = $("<div>").addClass("panel panel-default " + (repo.language || '').toLowerCase()).appendTo($link);
    var $heading = $("<div>").addClass("panel-heading").appendTo($panel);
    $heading.append($("<h3>").addClass("panel-title").text(repo.name));
    $heading.append($("<small>").text(repo.language || ''));
    var $body = $("<div>").addClass("panel-body").appendTo($panel);
    var $para = $("<p>");
    if (description) {
      $para.text(description);
    } else {
      $para.append($("<em>").text("No description provided."));
    }
    $body.append($para);
    $panel.append($("<div>").addClass("panel-footer " + (repo.owner.login || '').toLowerCase()).text(repoToOrgName(repo)));
    $item.appendTo("#repos");
  }

  function mapBitbucket(result) {
    // Map required values from Bitbucket API to GitHub equivalent for easier processing
    $.each(result.values, function(i,repo){
      repo.pushed_at = repo.updated_on;
      repo.created_at = repo.created_on;
      repo.id = repo.full_name;
      repo.owner.login = repo.owner.username;
      repo.html_url = repo.links.html.href;
      $.getJSON(repo.links.watchers.href + "?callback=?", function(result){
        repo.watchers = result.values.length;
      });
    });
    return result;
  }

  function addRepos(orgIdx, repos, page, bitbucket) {
    orgIdx = orgIdx || 0;
    repos = repos || [];
    page = page || 1;
    bitbucket = bitbucket || false;

    var org = orgs[orgIdx];

    if (!bitbucket) {
      var uri = "https://api.github.com/orgs/" + org + "/repos?callback=?"
          + "&per_page=100"
          + "&page=" + page;
    } else {
      var uri = "https://bitbucket.org/api/2.0/repositories/" + org + "?callback=?";
    }

    $.getJSON(uri, function (result) {
      if ((result.values && result.values.length > 0) || (result.data && result.data.length > 0)) {
        if(bitbucket) {
          result = mapBitbucket(result);
          repos = repos.concat(result.values);
          addRepos(orgIdx + 1, repos);
        } else {
          repos = repos.concat(result.data);
          addRepos(orgIdx, repos, page + 1);
        }
      }
      else if (!bitbucket && result.data.message == "Not Found") {
        addRepos(orgIdx, repos, 1, true);
      }
      else if (orgs.length > orgIdx + 1) {
        addRepos(orgIdx + 1, repos);
      }
      else {
        $(function () {
         // $("#num-repos").text(repos.length);

          // Convert pushed_at to Date.
          $.each(repos, function (i, repo) {
            repo.pushed_at = new Date(repo.pushed_at);

            var weekHalfLife = 1.146 * Math.pow(10, -9);

            var pushDelta = (new Date) - Date.parse(repo.pushed_at);
            var createdDelta = (new Date) - Date.parse(repo.created_at);

            var weightForPush = 1;
            var weightForWatchers = 1.314 * Math.pow(10, 7);

            repo.hotness = weightForPush * Math.pow(Math.E, -1 * weekHalfLife * pushDelta);
            repo.hotness += weightForWatchers * repo.watchers / createdDelta;
          });

          // Sort by highest # of watchers.
          repos.sort(function (a, b) {
            if (a.hotness < b.hotness) return 1;
            if (b.hotness < a.hotness) return -1;
            return 0;
          });

          $.each(repos, function (i, repo) {
            addRepo(repo);
          });

          // Sort by most-recently pushed to.
          repos.sort(function (a, b) {
            if (a.pushed_at < b.pushed_at) return 1;
            if (b.pushed_at < a.pushed_at) return -1;
            return 0;
          });
          /*
          $.each(repos.slice(0, 3), function (i, repo) {
            addRecentlyUpdatedRepo(repo);
          });
          */
        });
      }
    });
  }

  readOrgs();
  addRepos();
})();
<commit_msg>Compute the bitbucket variable instead of passing it.<commit_after>/*
NOTICE
The code herein was taken and modified in part from the Twitter open source portal - https://github.com/twitter/twitter.github.com
Modifications were made to include multiple organization accounts and display them differently
 */

(function () {

  // Put custom repo descriptions in this object, keyed by repo name.
  var repoDescriptions = {
    eas : "The Enterprise Addressing System (EAS) is an open source, web-based application that allows employees of government agencies to query, update, and retire street addresses.",
    CycleTracksWebsite : "Simple db and php code to catch data from iOS and Android CycleTracks apps."
  };

  // readOrgs() populates these three data structures from index.html.
  // Putting the raw data in index.html is more SEO-friendly since the
  // links are available in the original HTML as opposed to being
  // "injected" by the javascript at render-time.
  var orgs = [];
  var orgNameMap = {};
  var orgUrls = {};

  var repoUrls = {};

  // Extract the organization username from the URL.
  function urlToOrg(url) {
    // Remove the trailing slash, if present.
    if (url[url.length - 1] == "/") {
      url = url.slice(0, -1);
    }
    var index = url.lastIndexOf("/") + 1;
    var org = url.slice(index);

    return org;
  }

  // Read the organization data from index.html.
  function readOrgs() {
    var anchors = $("#orgs li a");
    for (var i = 0; i < anchors.length; i++) {
      var anchor = $(anchors[i]);
      var orgName = anchor.text();
      var url = anchor.attr("href");
      var org = urlToOrg(url).toLowerCase();

      orgs.push(org);
      orgNameMap[org] = orgName;
      orgUrls[org] = url;
    }
  }

  function repoUrl(repo) {
    return repoUrls[repo.name] || repo.html_url;
  }

  function repoDescription(repo) {
    return repoDescriptions[repo.name] || repo.description;
  }

  function repoToOrgName(repo) {
    return orgNameMap[repo.owner.login.toLowerCase()] || repo.name;
  }

  function addRepo(repo) {
    var description = repoDescription(repo);
    var $item = $("<div>").addClass("col-sm-4 repo");
    var $link = $("<a>").attr("href", repoUrl(repo)).attr("id",repo.id).appendTo($item);
    var $panel = $("<div>").addClass("panel panel-default " + (repo.language || '').toLowerCase()).appendTo($link);
    var $heading = $("<div>").addClass("panel-heading").appendTo($panel);
    $heading.append($("<h3>").addClass("panel-title").text(repo.name));
    $heading.append($("<small>").text(repo.language || ''));
    var $body = $("<div>").addClass("panel-body").appendTo($panel);
    var $para = $("<p>");
    if (description) {
      $para.text(description);
    } else {
      $para.append($("<em>").text("No description provided."));
    }
    $body.append($para);
    $panel.append($("<div>").addClass("panel-footer " + (repo.owner.login || '').toLowerCase()).text(repoToOrgName(repo)));
    $item.appendTo("#repos");
  }

  function mapBitbucket(result) {
    // Map required values from Bitbucket API to GitHub equivalent for easier processing
    $.each(result.values, function(i,repo){
      repo.pushed_at = repo.updated_on;
      repo.created_at = repo.created_on;
      repo.id = repo.full_name;
      repo.owner.login = repo.owner.username;
      repo.html_url = repo.links.html.href;
      $.getJSON(repo.links.watchers.href + "?callback=?", function(result){
        repo.watchers = result.values.length;
      });
    });
    return result;
  }

  function addRepos(orgIdx, repos, page) {
    orgIdx = orgIdx || 0;
    repos = repos || [];
    page = page || 1;

    var org = orgs[orgIdx];
    var orgUrl = orgUrls[org];
    var urlPrefix = orgUrl.slice(0, 21);
    var bitbucket = (urlPrefix == "https://bitbucket.org");

    if (!bitbucket) {
      var uri = "https://api.github.com/orgs/" + org + "/repos?callback=?"
          + "&per_page=100"
          + "&page=" + page;
    } else {
      var uri = "https://bitbucket.org/api/2.0/repositories/" + org + "?callback=?";
    }

    $.getJSON(uri, function (result) {
      if ((result.values && result.values.length > 0) || (result.data && result.data.length > 0)) {
        if (bitbucket) {
          result = mapBitbucket(result);
          repos = repos.concat(result.values);
          addRepos(orgIdx + 1, repos);
        } else {
          repos = repos.concat(result.data);
          addRepos(orgIdx, repos, page + 1);
        }
      }
      else if (orgs.length > orgIdx + 1) {
        addRepos(orgIdx + 1, repos);
      }
      else {
        $(function () {
         // $("#num-repos").text(repos.length);

          // Convert pushed_at to Date.
          $.each(repos, function (i, repo) {
            repo.pushed_at = new Date(repo.pushed_at);

            var weekHalfLife = 1.146 * Math.pow(10, -9);

            var pushDelta = (new Date) - Date.parse(repo.pushed_at);
            var createdDelta = (new Date) - Date.parse(repo.created_at);

            var weightForPush = 1;
            var weightForWatchers = 1.314 * Math.pow(10, 7);

            repo.hotness = weightForPush * Math.pow(Math.E, -1 * weekHalfLife * pushDelta);
            repo.hotness += weightForWatchers * repo.watchers / createdDelta;
          });

          // Sort by highest # of watchers.
          repos.sort(function (a, b) {
            if (a.hotness < b.hotness) return 1;
            if (b.hotness < a.hotness) return -1;
            return 0;
          });

          $.each(repos, function (i, repo) {
            addRepo(repo);
          });

          // Sort by most-recently pushed to.
          repos.sort(function (a, b) {
            if (a.pushed_at < b.pushed_at) return 1;
            if (b.pushed_at < a.pushed_at) return -1;
            return 0;
          });
          /*
          $.each(repos.slice(0, 3), function (i, repo) {
            addRecentlyUpdatedRepo(repo);
          });
          */
        });
      }
    });
  }

  readOrgs();
  addRepos();
})();
<|endoftext|>


<commit_before>(function(){

    function load_config(callback){
        var config={};
        $.getJSON("config.json", function(json) {
            config=json;

            config.params=load_params();

            //If tiles_path in params, overrides tiles_path in config.json
            if (config.params.tiles_path) config.tiles_path = config.params.tiles_path;

            if (typeof callback==='function') callback(config);
        });
    }

    function load_metadata(config,callback){
        config.template={};
        $.getJSON(config.tiles_path+"/metadata.json", function(json) {

            //config.json title key overrides mbtiles title
            config.title = config.title || json.name;

            document.title=config.title;

            // Overrides config.json data if present in metadata.json and there are no params
            if (!config.params || !config.params.coords){
                if (json.center) {
                    var p = json.center.split(',');
                    config.view.zoom=parseInt(p[2]);
                    config.view.center.lat=parseFloat(p[1]);
                    config.view.center.lon=parseFloat(p[0]);
                }

                if (json.bounds) {
                    var b=json.bounds.split(',');
                    config.view.bounds=[[parseFloat(b[1]),parseFloat(b[0])],[parseFloat(b[3]),parseFloat(b[2])]];
                }

            } else if (config.params.coords){
                config.view.zoom=config.params.coords.z;
                config.view.center.lat=config.params.coords.lat;
                config.view.center.lon=config.params.coords.lon;
            }

            if (json.minzoom) {
                config.view.min_zoom=parseInt(json.minzoom);
            }

            if (json.maxzoom) {
                config.view.max_zoom=parseInt(json.maxzoom);
            }

            var metadata_template=json.template;
            config.template.location = metadata_template.match("{{#__location__}}(.*){{/__location__}}")[1];
            config.template.teaser = metadata_template.match("{{#__teaser__}}(.*){{/__teaser__}}")[1];
            config.template.full = metadata_template.match("{{#__full__}}(.*){{/__full__}}")[1];

            if (config.use_mbtiles_legend && json.legend) $(".legend").html(json.legend);

            if (typeof callback==='function') callback(config);
        });
    }

    $(document).ready(function() {
        load_config(function(config){
            load_metadata(config,function(extended_config){
                var app=new MapClass(extended_config);
            });
        });
    });

})();
<commit_msg>not null metadata check<commit_after>(function(){

    function load_config(callback){
        var config={};
        $.getJSON("config.json", function(json) {
            config=json;

            config.params=load_params();

            //If tiles_path in params, overrides tiles_path in config.json
            if (config.params.tiles_path) config.tiles_path = config.params.tiles_path;

            if (typeof callback==='function') callback(config);
        });
    }

    function load_metadata(config,callback){
        config.template={};
        $.getJSON(config.tiles_path+"/metadata.json", function(json) {

            //config.json title key overrides mbtiles title
            config.title = config.title || json.name;

            document.title=config.title;

            // Overrides config.json data if present in metadata.json and there are no params
            if (!config.params || !config.params.coords){
                if (json.center) {
                    var p = json.center.split(',');
                    config.view.zoom=parseInt(p[2]);
                    config.view.center.lat=parseFloat(p[1]);
                    config.view.center.lon=parseFloat(p[0]);
                }

                if (json.bounds) {
                    var b=json.bounds.split(',');
                    config.view.bounds=[[parseFloat(b[1]),parseFloat(b[0])],[parseFloat(b[3]),parseFloat(b[2])]];
                }

            } else if (config.params.coords){
                config.view.zoom=config.params.coords.z;
                config.view.center.lat=config.params.coords.lat;
                config.view.center.lon=config.params.coords.lon;
            }

            if (json.minzoom) {
                config.view.min_zoom=parseInt(json.minzoom);
            }

            if (json.maxzoom) {
                config.view.max_zoom=parseInt(json.maxzoom);
            }

            var metadata_template=json.template;
            config.template.location = (metadata_template.match("{{#__location__}}(.*){{/__location__}}"))? metadata_template.match("{{#__location__}}(.*){{/__location__}}")[1] : '';
            config.template.teaser = (metadata_template.match("{{#__teaser__}}(.*){{/__teaser__}}"))? metadata_template.match("{{#__teaser__}}(.*){{/__teaser__}}")[1] : '' ;
            config.template.full = (metadata_template.match("{{#__full__}}(.*){{/__full__}}"))? metadata_template.match("{{#__full__}}(.*){{/__full__}}")[1] : '';

            if (config.use_mbtiles_legend && json.legend) $(".legend").html(json.legend);

            if (typeof callback==='function') callback(config);
        });
    }

    $(document).ready(function() {
        load_config(function(config){
            load_metadata(config,function(extended_config){
                var app=new MapClass(extended_config);
            });
        });
    });

})();
<|endoftext|>


<commit_before>var context = new (window.AudioContext || window.webkitAudioContext)();
var analyser = context.createAnalyser();

var buf = new Float32Array( 1024 );
var MIN_SAMPLES = 0; // To be initailzed when context is set
var mediaStreamSource = null;
var analyser = null;

var alphabet = "^\n abcdefghijklmnopqrstuvwxyz$";
var emoticons = ["^", "smile", "cry", "cool", "sleep", "sob", "uneasy", "$"];
var start = '^';
var end = '$';

var supersonic = false;
var freqMin = 440;
var freqMax = 1760;

var range = freqMax - freqMin;
var processing = false;
var listening = false;

var message = "";
var emoji = "";
var capturing = false;
var finished_capturing = false;

function submit() {
  if(processing)
    return;
  var message = document.getElementById('message').value;
  if(message.length === 0)
    return;
  processing = true;
  document.getElementById('submit').disabled = true;
  process(message.toLowerCase());
}

function listen() {
  if(!document.getElementById('emoji_box').checked) {
    var message = document.getElementById('message');
    message.value = "";

    var listen_text = document.getElementById('listen').innerText;
    if(listen_text == "Cancel") {
      listening = false;
      processing = false;
      document.getElementById('message_listen').innerText = "Listen";
      document.getElementById('submit').disabled = false;
      message.placeholder = "Type Message";
    } else {
      listening = true;
      processing = true;
      document.getElementById('message_listen').innerText = "Cancel";
      document.getElementById('submit').disabled = true;
      message.placeholder = "Listening...";
      liveInput();
    }
  } else {
    if(listening) {
      listening = false;
      processing = false;
      document.getElementById('emoji_listen').innerText = "Listen";
    } else {
      listening = true;
      processing = true;
      document.getElementById('emoji_listen').innerText = "Cancel";
      liveInput();
    }
  }
}

window.onload = function() {
  document.getElementById("emoji_wrapper").style.display = "none";
}

document.getElementById('supersonic').onclick = function() {
  if(supersonic) {
    supersonic = false;
    freqMin = 440;
    freqMax = 1760;
  } else {
    supersonic = true;
    freqMin = 18500;
    freqMax = 19500;
  }
}

document.getElementById('emoji_box').onclick = function() {
  if(document.getElementById('emoji_box').checked) {
    document.getElementById("message_wrapper").style.display = "none";
    document.getElementById("emoji_wrapper").style.display = "block";
  }
  else {
    document.getElementById("message_wrapper").style.display = "block";
    document.getElementById("emoji_wrapper").style.display = "none";
  }
}

function selected(emoji) {
  processEmoji(emoji.name);
}

function stopListening() {
  listening = false;
  processing = false;
  if(document.getElementById('emoji_box').checked) {
    document.getElementById('emoji_listen').innerText = "Listen";
    emoji = "";
  } else {
    document.getElementById('listen').innerText = "Listen";
    document.getElementById('submit').disabled = false;
    message.placeholder = "Type Message";
    message = "";
  }
  capturing = false;
  finished_capturing = false;
}

function error() {
  alert('Stream generation failed.');
}

function getUserMedia(dictionary, callback) {
  try {
    navigator.getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia;
      navigator.getUserMedia(dictionary, callback, error);
  } catch (e) {
      alert('getUserMedia threw exception :' + e);
  }
}

function gotStream(stream) {
  // Create an AudioNode from the stream.
  mediaStreamSource = context.createMediaStreamSource(stream);

  // Connect it to the destination.
  analyser = context.createAnalyser();
  analyser.fftSize = 2048;
  mediaStreamSource.connect(analyser);
  if(document.getElementById('emoji_box').checked) {
    updateEmoji();
  } else {
    updatePitch();
  }
}

function output() {
  if(typeof arguments !== undefined && arguments.length > 0) {
    var result = arguments.join("");
    var message = document.getElementById('message');
    message.value = result;
  }
}

function liveInput() {
  getUserMedia(
    {
      "audio": {
        "mandatory": {
          "googEchoCancellation": "false",
          "googAutoGainControl": "false",
          "googNoiseSuppression": "false",
          "googHighpassFilter": "false"
        },
        "optional": []
      },
    }, gotStream);
}

function autoCorrelate(buf, sampleRate) {
  var SIZE = buf.length;
  var MAX_SAMPLES = Math.floor(SIZE/2);
  var best_offset = -1;
  var best_correlation = 0;
  var rms = 0;
  var foundGoodCorrelation = false;
  var correlations = new Array(MAX_SAMPLES);

  for(var i = 0; i < SIZE; i++) {
    var val = buf[i];
    rms += Math.pow(val, 2);
  }

  rms = Math.sqrt(rms/SIZE);
  if(rms < 0.01) {
    //Not enough signal
    return -1;
  }

  var lastCorrelation = 1;
  for(var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) {
    var correlation = 0;

    for(var i = 0; i < MAX_SAMPLES; i++) {
      correlation += Math.abs((buf[i]) - (buf[i + offset]));
    }
    correlation = 1 - (correlation/MAX_SAMPLES);
    correlations[offset] = correlation; // Store for later

    if((correlation > 0.9) && (correlation > lastCorrelation)) {
      foundGoodCorrelation = true;
      if(correlation > best_correlation) {
        best_correlation = correlation;
        best_offset = offset;
      }
    } else if (foundGoodCorrelation) {
      var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset];
      return sampleRate/(best_offset + (8 * shift));
    }
    lastCorrelation = correlation;
  }

  if(best_correlation > 0.01) {
    return sampleRate/best_offset;
  }
  return -1;
}

function updateEmoji() {
  var cycles = new Array;
  analyser.getFloatTimeDomainData(buf);
  var ac = autoCorrelate(buf, context.sampleRate);

  var freq = null;

  if(ac !== -1 && ac < freqMax && ac > freqMin) {
    freq = ac;
    var note = toEmoji(freq);
    if(note === "^") {
      capturing = true;
    }
    if(note === "$") {
      capturing = false;
      finished_capturing = true;
    }
    if(capturing && note != "^") {
      emoji = note;
    }
    console.log(note);
  }
  if(finished_capturing) {
    selectEmoji(emoji);
    stopListening();
  }
  if(listening) {
    setTimeout(function() {
      window.requestAnimationFrame(updateEmoji);
    }, 190);
  }
}

function updatePitch() {
  var cycles = new Array;
  analyser.getFloatTimeDomainData(buf);
  var ac = autoCorrelate(buf, context.sampleRate);

  var freq = null;

  // console.log(freq);

  if(ac !== -1 && ac < freqMax && ac > freqMin) {
    freq = ac;
    var note = toChar(freq);
    if(note === "^") {
      capturing = true;
    }
    if(note === "$") {
      capturing = false;
      finished_capturing = true;
    }
    if(capturing && note != "^") {
      message += note;
    }
    console.log(note);
  } else {
    //console.log("ac is -1");
  }
  if(finished_capturing) {
    output("Received: \"", message, "\""   );
    stopListening();
  }
  if(listening) {
    setTimeout(function() {
      window.requestAnimationFrame(updatePitch);
    }, 190)
  }
}

function selectEmoji(emoji) {
  var placeholder = document.getElementById("result_area");
  var path = "images/" + emoji + ".png";
  placeholder.src = path;
}

function process(message) {
  var message = start + message + end;

  var i = 0;
  for(i; i < message.length; i++) {
    var tone;
    var char = message[i];
    var time = context.currentTime + 0.2*i;
    if(char === start) {
      tone = freqMin;
    }
    else if(char === end) {
      tone = freqMax;
    }
    else {
      tone = toFreq(char);
    }
    emit(tone, time);
  }
  setTimeout(function() {
    processing = false;
    document.getElementById('submit').disabled = false;
  }, 200 * message.length);
}

function processEmoji(emoji) {

  emit(freqMin, context.currentTime);
  emit(toEmojiFreq(emoji), context.currentTime + 0.2);
  emit(freqMax, context.currentTime + 0.4);

}

function toFreq(char) {
  var index = alphabet.indexOf(char);
  if(index === -1) {
    console.error('Invalid character: ', char);
    index = alphabet.length - 1;
  }
  var percent = index / alphabet.length;
  var offset = Math.round(range * percent);
  return freqMin + offset;
}

function toEmojiFreq(emoji) {
  var index = emoticons.indexOf(emoji);
  if(index === -1) {
    console.error("Invalid emoji: ", emoji);
    index = emoticons.length - 1;
  }
  var percent = index / emoticons.length;
  var offset = Math.round(range * percent);
  return freqMin + offset;
}

function toChar(freq, emoji) {
  if(!(freqMin < freq && freq < freqMax)) {
    if(freqMin - freq < 50) {
      freq = freqMin;
    } else if (freq - freqMax < 50) {
      freq = freqMax;
    } else {
      console.error("Invalid frequency: ", freq);
      return;
    }
  }

  var percent = (freq - freqMin) / range;
  var index = Math.round(alphabet.length * percent);
  if(index == alphabet.length)
    return alphabet[index-1];
  return alphabet[index];
}

function toEmoji(freq) {
  if(!(freqMin < freq && freq < freqMax)) {
    if(freqMin - freq < 50) {
      freq = freqMin;
    } else if (freq - freqMax < 50) {
      freq = freqMax;
    } else {
      console.error("Invalid frequency: ", freq);
      return;
    }
  }

  var percent = (freq - freqMin) / range;
  var index = Math.round(emoticons.length * percent);
  if(index == emoticons.length)
    return emoticons[index-1];
  return emoticons[index];
}

function emit(tone, time) {
  // GainNode
  var gainNode = context.createGain();
  gainNode.gain.value = 0;
  gainNode.gain.setValueAtTime(0, time);
  gainNode.gain.linearRampToValueAtTime(1, time + 0.001);
  gainNode.gain.setValueAtTime(1, time + 0.2 - 0.001);
  gainNode.gain.linearRampToValueAtTime(0, time + 0.2);
  gainNode.connect(context.destination);

  // Oscillator
  var oscillator = context.createOscillator();
  oscillator.frequency.value = tone;
  oscillator.connect(gainNode);
  oscillator.start();
}

function restart() {
  window.location.reload();
}<commit_msg>Not breaking placeholder if path is empty<commit_after>var context = new (window.AudioContext || window.webkitAudioContext)();
var analyser = context.createAnalyser();

var buf = new Float32Array( 1024 );
var MIN_SAMPLES = 0; // To be initailzed when context is set
var mediaStreamSource = null;
var analyser = null;

var alphabet = "^\n abcdefghijklmnopqrstuvwxyz$";
var emoticons = ["^", "smile", "cry", "cool", "sleep", "sob", "uneasy", "$"];
var start = '^';
var end = '$';

var supersonic = false;
var freqMin = 440;
var freqMax = 1760;

var range = freqMax - freqMin;
var processing = false;
var listening = false;

var message = "";
var emoji = "";
var capturing = false;
var finished_capturing = false;

function submit() {
  if(processing)
    return;
  var message = document.getElementById('message').value;
  if(message.length === 0)
    return;
  processing = true;
  document.getElementById('submit').disabled = true;
  process(message.toLowerCase());
}

function listen() {
  if(!document.getElementById('emoji_box').checked) {
    var message = document.getElementById('message');
    message.value = "";

    var listen_text = document.getElementById('listen').innerText;
    if(listen_text == "Cancel") {
      listening = false;
      processing = false;
      document.getElementById('message_listen').innerText = "Listen";
      document.getElementById('submit').disabled = false;
      message.placeholder = "Type Message";
    } else {
      listening = true;
      processing = true;
      document.getElementById('message_listen').innerText = "Cancel";
      document.getElementById('submit').disabled = true;
      message.placeholder = "Listening...";
      liveInput();
    }
  } else {
    if(listening) {
      listening = false;
      processing = false;
      document.getElementById('emoji_listen').innerText = "Listen";
    } else {
      listening = true;
      processing = true;
      document.getElementById('emoji_listen').innerText = "Cancel";
      liveInput();
    }
  }
}

window.onload = function() {
  document.getElementById("emoji_wrapper").style.display = "none";
}

document.getElementById('supersonic').onclick = function() {
  if(supersonic) {
    supersonic = false;
    freqMin = 440;
    freqMax = 1760;
  } else {
    supersonic = true;
    freqMin = 18500;
    freqMax = 19500;
  }
}

document.getElementById('emoji_box').onclick = function() {
  if(document.getElementById('emoji_box').checked) {
    document.getElementById("message_wrapper").style.display = "none";
    document.getElementById("emoji_wrapper").style.display = "block";
  }
  else {
    document.getElementById("message_wrapper").style.display = "block";
    document.getElementById("emoji_wrapper").style.display = "none";
  }
}

function selected(emoji) {
  processEmoji(emoji.name);
}

function stopListening() {
  listening = false;
  processing = false;
  if(document.getElementById('emoji_box').checked) {
    document.getElementById('emoji_listen').innerText = "Listen";
    emoji = "";
  } else {
    document.getElementById('listen').innerText = "Listen";
    document.getElementById('submit').disabled = false;
    message.placeholder = "Type Message";
    message = "";
  }
  capturing = false;
  finished_capturing = false;
}

function error() {
  alert('Stream generation failed.');
}

function getUserMedia(dictionary, callback) {
  try {
    navigator.getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia;
      navigator.getUserMedia(dictionary, callback, error);
  } catch (e) {
      alert('getUserMedia threw exception :' + e);
  }
}

function gotStream(stream) {
  // Create an AudioNode from the stream.
  mediaStreamSource = context.createMediaStreamSource(stream);

  // Connect it to the destination.
  analyser = context.createAnalyser();
  analyser.fftSize = 2048;
  mediaStreamSource.connect(analyser);
  if(document.getElementById('emoji_box').checked) {
    updateEmoji();
  } else {
    updatePitch();
  }
}

function output() {
  if(typeof arguments !== undefined && arguments.length > 0) {
    var result = arguments.join("");
    var message = document.getElementById('message');
    message.value = result;
  }
}

function liveInput() {
  getUserMedia(
    {
      "audio": {
        "mandatory": {
          "googEchoCancellation": "false",
          "googAutoGainControl": "false",
          "googNoiseSuppression": "false",
          "googHighpassFilter": "false"
        },
        "optional": []
      },
    }, gotStream);
}

function autoCorrelate(buf, sampleRate) {
  var SIZE = buf.length;
  var MAX_SAMPLES = Math.floor(SIZE/2);
  var best_offset = -1;
  var best_correlation = 0;
  var rms = 0;
  var foundGoodCorrelation = false;
  var correlations = new Array(MAX_SAMPLES);

  for(var i = 0; i < SIZE; i++) {
    var val = buf[i];
    rms += Math.pow(val, 2);
  }

  rms = Math.sqrt(rms/SIZE);
  if(rms < 0.01) {
    //Not enough signal
    return -1;
  }

  var lastCorrelation = 1;
  for(var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) {
    var correlation = 0;

    for(var i = 0; i < MAX_SAMPLES; i++) {
      correlation += Math.abs((buf[i]) - (buf[i + offset]));
    }
    correlation = 1 - (correlation/MAX_SAMPLES);
    correlations[offset] = correlation; // Store for later

    if((correlation > 0.9) && (correlation > lastCorrelation)) {
      foundGoodCorrelation = true;
      if(correlation > best_correlation) {
        best_correlation = correlation;
        best_offset = offset;
      }
    } else if (foundGoodCorrelation) {
      var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset];
      return sampleRate/(best_offset + (8 * shift));
    }
    lastCorrelation = correlation;
  }

  if(best_correlation > 0.01) {
    return sampleRate/best_offset;
  }
  return -1;
}

function updateEmoji() {
  var cycles = new Array;
  analyser.getFloatTimeDomainData(buf);
  var ac = autoCorrelate(buf, context.sampleRate);

  var freq = null;

  if(ac !== -1 && ac < freqMax && ac > freqMin) {
    freq = ac;
    var note = toEmoji(freq);
    if(note === "^") {
      capturing = true;
    }
    if(note === "$") {
      capturing = false;
      finished_capturing = true;
    }
    if(capturing && note != "^") {
      emoji = note;
    }
    console.log(note);
  }
  if(finished_capturing) {
    selectEmoji(emoji);
    stopListening();
  }
  if(listening) {
    setTimeout(function() {
      window.requestAnimationFrame(updateEmoji);
    }, 190);
  }
}

function updatePitch() {
  var cycles = new Array;
  analyser.getFloatTimeDomainData(buf);
  var ac = autoCorrelate(buf, context.sampleRate);

  var freq = null;

  // console.log(freq);

  if(ac !== -1 && ac < freqMax && ac > freqMin) {
    freq = ac;
    var note = toChar(freq);
    if(note === "^") {
      capturing = true;
    }
    if(note === "$") {
      capturing = false;
      finished_capturing = true;
    }
    if(capturing && note != "^") {
      message += note;
    }
    console.log(note);
  } else {
    //console.log("ac is -1");
  }
  if(finished_capturing) {
    output("Received: \"", message, "\""   );
    stopListening();
  }
  if(listening) {
    setTimeout(function() {
      window.requestAnimationFrame(updatePitch);
    }, 190)
  }
}

function selectEmoji(emoji) {
  if(emoji === "" || typeof emoji === undefined || !emoji) {
    console.error("Unable to read emoji");
  } else {
    var placeholder = document.getElementById("result_area");
    var path = "images/" + emoji + ".png";
    placeholder.src = path;
  }
}

function process(message) {
  var message = start + message + end;

  var i = 0;
  for(i; i < message.length; i++) {
    var tone;
    var char = message[i];
    var time = context.currentTime + 0.2*i;
    if(char === start) {
      tone = freqMin;
    }
    else if(char === end) {
      tone = freqMax;
    }
    else {
      tone = toFreq(char);
    }
    emit(tone, time);
  }
  setTimeout(function() {
    processing = false;
    document.getElementById('submit').disabled = false;
  }, 200 * message.length);
}

function processEmoji(emoji) {

  emit(freqMin, context.currentTime);
  emit(toEmojiFreq(emoji), context.currentTime + 0.2);
  emit(freqMax, context.currentTime + 0.4);

}

function toFreq(char) {
  var index = alphabet.indexOf(char);
  if(index === -1) {
    console.error('Invalid character: ', char);
    index = alphabet.length - 1;
  }
  var percent = index / alphabet.length;
  var offset = Math.round(range * percent);
  return freqMin + offset;
}

function toEmojiFreq(emoji) {
  var index = emoticons.indexOf(emoji);
  if(index === -1) {
    console.error("Invalid emoji: ", emoji);
    index = emoticons.length - 1;
  }
  var percent = index / emoticons.length;
  var offset = Math.round(range * percent);
  return freqMin + offset;
}

function toChar(freq, emoji) {
  if(!(freqMin < freq && freq < freqMax)) {
    if(freqMin - freq < 50) {
      freq = freqMin;
    } else if (freq - freqMax < 50) {
      freq = freqMax;
    } else {
      console.error("Invalid frequency: ", freq);
      return;
    }
  }

  var percent = (freq - freqMin) / range;
  var index = Math.round(alphabet.length * percent);
  if(index == alphabet.length)
    return alphabet[index-1];
  return alphabet[index];
}

function toEmoji(freq) {
  if(!(freqMin < freq && freq < freqMax)) {
    if(freqMin - freq < 50) {
      freq = freqMin;
    } else if (freq - freqMax < 50) {
      freq = freqMax;
    } else {
      console.error("Invalid frequency: ", freq);
      return;
    }
  }

  var percent = (freq - freqMin) / range;
  var index = Math.round(emoticons.length * percent);
  if(index == emoticons.length)
    return emoticons[index-1];
  return emoticons[index];
}

function emit(tone, time) {
  // GainNode
  var gainNode = context.createGain();
  gainNode.gain.value = 0;
  gainNode.gain.setValueAtTime(0, time);
  gainNode.gain.linearRampToValueAtTime(1, time + 0.001);
  gainNode.gain.setValueAtTime(1, time + 0.2 - 0.001);
  gainNode.gain.linearRampToValueAtTime(0, time + 0.2);
  gainNode.connect(context.destination);

  // Oscillator
  var oscillator = context.createOscillator();
  oscillator.frequency.value = tone;
  oscillator.connect(gainNode);
  oscillator.start();
}

function restart() {
  window.location.reload();
}<|endoftext|>


<commit_before>/*!
 * Brackets Git Extension
 *
 * @author Martin Zagora
 * @license http://opensource.org/licenses/MIT
 */

/*jslint plusplus: true, vars: true, nomen: true */
/*global define, brackets */

define(function (require, exports, module) {
    "use strict";

    // Get module dependencies.
    var AppInit                    = brackets.getModule("utils/AppInit"),
        CommandManager             = brackets.getModule("command/CommandManager"),
        Commands                   = brackets.getModule("command/Commands"),
        ExtensionUtils             = brackets.getModule("utils/ExtensionUtils"),
        Menus                      = brackets.getModule("command/Menus");

    var ExtensionInfo              = require("src/ExtensionInfo"),
        Preferences                = require("src/Preferences"),
        ExtensionMain              = require("src/Main"),
        ChangelogDialog            = require("src/ChangelogDialog"),
        SettingsDialog             = require("src/SettingsDialog"),
        Strings                    = require("strings");

    // Load extension modules that are not included by core
    var modules = ["src/Remotes"];
    if (Preferences.get("useGitFtp")) {
        modules.push("src/Ftp/Ftp");
    }
    require(modules);

    // Load CSS
    ExtensionUtils.loadStyleSheet(module, "styles/brackets-git.less");
    ExtensionUtils.loadStyleSheet(module, "styles/fonts/octicon.less");

    // Handle settings dialog
    function openSettingsPanel() {
        SettingsDialog.show();
    }

    // Display settings panel on first start / changelog dialog on version change
    ExtensionInfo.get().then(function (packageJson) {
        var lastVersion    = Preferences.get("lastVersion"),
            currentVersion = packageJson.version;

        if (lastVersion === null) {
            Preferences.persist("lastVersion", "firstStart");
            openSettingsPanel();
        } else if (lastVersion !== currentVersion) {
            Preferences.persist("lastVersion", currentVersion);
            ChangelogDialog.show();
        }
    });

    // Register command and add it to the menu.
    var SETTINGS_COMMAND_ID = "brackets-git.settings";
    CommandManager.register(Strings.GIT_SETTINGS, SETTINGS_COMMAND_ID, openSettingsPanel);
    Menus.getMenu(Menus.AppMenuBar.FILE_MENU).addMenuItem(SETTINGS_COMMAND_ID, "", Menus.AFTER, Commands.FILE_PROJECT_SETTINGS);

    AppInit.appReady(function () {
        ExtensionMain.init();
    });

});
<commit_msg>rewrite main.js<commit_after>/*!
 * Brackets Git Extension
 *
 * @author Martin Zagora
 * @license http://opensource.org/licenses/MIT
 */

define(function (require, exports, module) {

    // Brackets modules
    var AppInit         = brackets.getModule("utils/AppInit"),
        CommandManager  = brackets.getModule("command/CommandManager"),
        Commands        = brackets.getModule("command/Commands"),
        ExtensionUtils  = brackets.getModule("utils/ExtensionUtils"),
        Menus           = brackets.getModule("command/Menus");

    // Local modules
    var ChangelogDialog = require("src/ChangelogDialog"),
        ExtensionInfo   = require("src/ExtensionInfo"),
        Main            = require("src/Main"),
        Preferences     = require("src/Preferences"),
        SettingsDialog  = require("src/SettingsDialog"),
        Strings         = require("strings");

    // Load extension modules that are not included by core
    var modules = ["src/Remotes"];
    if (Preferences.get("useGitFtp")) { modules.push("src/Ftp/Ftp"); }
    require(modules);

    // Load CSS
    ExtensionUtils.loadStyleSheet(module, "styles/brackets-git.less");
    ExtensionUtils.loadStyleSheet(module, "styles/fonts/octicon.less");
    // TODO: load ftp.less on demand after Sprint 38

    // Display settings panel on first start / changelog dialog on version change
    ExtensionInfo.get().then(function (packageJson) {
        var lastVersion    = Preferences.get("lastVersion"),
            currentVersion = packageJson.version;

        if (lastVersion === null) {
            Preferences.persist("lastVersion", "firstStart");
            SettingsDialog.show();
        } else if (lastVersion !== currentVersion) {
            Preferences.persist("lastVersion", currentVersion);
            ChangelogDialog.show();
        }
    });

    // Register command and add it to the menu.
    var SETTINGS_COMMAND_ID = "brackets-git.settings";
    CommandManager.register(Strings.GIT_SETTINGS, SETTINGS_COMMAND_ID, SettingsDialog.show);
    Menus.getMenu(Menus.AppMenuBar.FILE_MENU).addMenuItem(SETTINGS_COMMAND_ID, "", Menus.AFTER, Commands.FILE_PROJECT_SETTINGS);

    AppInit.appReady(function () {
        Main.init();
    });
});
<|endoftext|>


<commit_before>'use babel';

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

// Report crashes to the Electron project
electron.crashReporter.start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  // We're a single pane app for the moment, so we'll just close
  // instead of conditional closure on process.platform !== 'darwin'
  app.quit();
});

app.on('ready', function () {
  mainWindow = new BrowserWindow({width: 800, height: 600});

  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});
<commit_msg>Fat arrow.<commit_after>'use babel';

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

// Report crashes to the Electron project
electron.crashReporter.start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  // We're a single pane app for the moment, so we'll just close
  // instead of conditional closure on process.platform !== 'darwin'
  app.quit();
});

app.on('ready', () => {
  mainWindow = new BrowserWindow({width: 800, height: 600});

  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});
<|endoftext|>


<commit_before>
// x axis for may-2017 dataset
var mayx = ["Apr-11","May-11","Jun-11","Jul-11","Aug-11","Sep-11","Oct-11","Nov-11","Dec-11","Jan-12","Feb-12","Mar-12","Apr-12","May-12","Jun-12","Jul-12","Aug-12","Sep-12","Oct-12","Nov-12","Dec-12","Jan-13","Feb-13","Mar-13","Apr-13","May-13","Jun-13","Jul-13","Aug-13","Sep-13","Oct-13","Nov-13","Dec-13","Jan-14","Feb-14","Mar-14","Apr-14","May-14","Jun-14","Jul-14","Aug-14","Sep-14","Oct-14","Nov-14","Dec-14","Jan-15","Feb-15","Mar-15","Apr-15","May-15","Jun-15","Jul-15","Aug-15","Sep-15","Oct-15","Nov-15","Dec-15","Jan-16","Feb-16","Mar-16","Apr-16","May-16","Jun-16","Jul-16","Aug-16","Sep-16","Oct-16","Nov-16","Dec-16","Jan-17","Feb-17","Mar-17","Apr-17","May-17"];

var obj = new Object();
	obj.labs = mayx; //labels
	obj.name = "All commodities";
	obj.data = [97.1,97.7,98.2,98.6,99.2,100.1,100.5,100.8,100.9,101.6,102.1,103.4,104.7,105.3,105.3,106.2,106.9,107.6,107.4,107.3,107.1,108.0,108.4,108.6,108.6,108.6,110.1,111.2,112.9,114.3,114.6,114.3,113.4,113.6,113.6,114.3,114.1,114.8,115.2,116.7,117.2,116.4,115.6,114.1,112.1,110.8,109.6,109.9,110.2,111.4,111.8,111.1,110.0,109.9,110.1,109.9,109.4,108.0,107.1,107.7,109.0,110.4,111.7,111.8,111.2,111.4,111.5,111.9,111.7,112.6,113.0,113.2,113.2,112.8];

function loadChart(o)
{
	var ctx = document.getElementById("myChart").getContext('2d');
	var myChart = new Chart(ctx, {
		type: 'line',
		data: {
			labels: o.labs,
			datasets: [{
				label: o.name,
				data: o.data,
				backgroundColor: [
					'rgba(255,255,255,0)'
				],
				borderColor: [
					'rgba(255,99,132,1)',
					'rgba(54, 162, 235, 1)',
					'rgba(255, 206, 86, 1)',
					'rgba(75, 192, 192, 1)',
					'rgba(153, 102, 255, 1)',
					'rgba(255, 159, 64, 1)'
				],
				borderWidth: 1
			}]
		},
		options: {
			scales: {
				yAxes: [{
					ticks: {

					}
				}]
			}
		}
	});
}

//loadChart(obj);
var commodities = null;
function loadDatasets()
{
	var datasets = JSON.parse(may);
	commodities = datasets.commodities;

	for(var i = 0; i < commodities.length; i++)
	{
		createLI(commodities[i].name);
	}
}
loadDatasets();
function createLI(name)
{
	var abc = document.getElementById("menu-ul").innerHTML;
	abc += "
" + name + "
";
	document.getElementById("menu-ul").innerHTML = abc;
}

// show/hide menu--------
var menuHidden = true;
function showHideMenu()
{

	if(menuHidden)
	{
		//show menu;
		document.getElementById("menu-id").style.marginLeft = "0px";
		menuHidden = false;
	}
	else
	{
		//hide menu;
		document.getElementById("menu-id").style.marginLeft = "-200px";
		menuHidden = true;
	}
}
//------------

function grabData(t)
{
	var i = 0;
	for(i = 0; i < commodities.length; i++)
	{
		if(commodities[i].name == t.innerHTML)
		{ break; }
	}
	obj.name = commodities[i].name;
	obj.data = commodities[i].data;

	loadChart(obj);

}<commit_msg>Delete main.js<commit_after><|endoftext|>