<commit_before>define(['backbone', 'backbone.pageable.collection', 'config', 'communicator', 'plugin/geojson_features/models/feature', 'erfgeoviewer.common'],
  function(Backbone, PageableCollection, Config, Communicator, ResultModel, App) {

    var ResultModel = ResultModel.extend({
      parse: function(fields) {

        var f = {
          title: fields['dc:title'],
          description: fields['dc:description'],
          creator: fields['dc:creator'],
          __id__: fields['@id'],
          subject: fields['subject'],
          source: fields['edm:dataProvider'],
          externalUrl: fields['edm:isShownAt'],
          isShownBy: fields['edm:isShownBy'],
          spatial: this.parseDctermsSpatial(fields)
        };

        if (_.isArray(f.title)) f.title = f.title.join(', ');

        // Image
        var img, ext;
        if (_.isArray(fields['edm:object'])) {
          ext = fields['edm:object'][0].match(/\.[0-9a-z]+$/i);
          if (ext && _.contains(['.jpg', '.jpeg', '.png', '.gif'], ext[0]) || fields['edm:type'][0] == "IMAGE")
            img = fields['edm:object'][0];
        }
        if (img) f.image = img;

        // Title defaults to a shortened description if need be
        if (!fields['dc:title'] && fields['dc:description']) {
          var words = fields['dc:description'][0].split(/\s+/);
          var max = 250;
          var newtitle;
          for (var i = words.length; i >= 0; i--) {
            newtitle = words.slice([0, i]).join(" ");
            if (newtitle.length < max) break;
          }
          f.title = newtitle;
        }

        return f;
      },

      parseDctermsSpatial: function(fields) {
        var geoJSONStrings = [],
          dcTermsSpatial,
          geosHasGeometry,
          geosAsWKT,
          lat,
          long;

        if ( _.isArray(dcTermsSpatial = _.property('dcterms:spatial')(fields)) ) {
          _.each(dcTermsSpatial, function(term) {
            if ( _.isArray(geosHasGeometry = _.property('geos:hasGeometry')(term)) ) {
              _.each(geosHasGeometry, function(geometry) {
                if ( _.isArray(geosAsWKT = _.property('geos:asWKT')(geometry)) ) {
                  _.each(geosAsWKT, function(wkt) {
                    geoJSONStrings.push(wkt);
                  });
                }
              });
            }
            else if ( (lat = _.property('geo:lat')(term)) && (long = _.property('geo:long')(term)) ) {
              geoJSONStrings.push('POINT(' + long + ' ' + lat + ')');
            }
          });
        }

        return geoJSONStrings;
      }
    });

    var MODE_ADVANCED = 'advanced',
      MODE_SIMPLE = 'simple';

    return PageableCollection.extend({

      model: ResultModel,

      searchMode: 'simple',

      queryParams: {
        currentPage: null,
        pageSize: null,
        totalPages: null,
        totalRecords: null,
        facets: function() {
          return _.isArray(Config.zoek_en_vind.requestedFacets) ?
            Config.zoek_en_vind.requestedFacets.join(',') : 'dc:subject,edm:dataProvider,dc:date.year';
        },
        maximumRecords: function() {
          return this.state.maxRecords;
        },
        startRecord: function() {
          return (this.state.currentPage -1) * this.state.pageSize +1;
        },
        query: function() {
          var query = {
            type: 'AND',
            values: [
              this.state.terms
            ]
          };

          if (_.isEmpty(this.state.facets) && _.isObject(Config.zoek_en_vind.facets)) {
            query.values.push(Config.zoek_en_vind.facets);
          }
          else if (!_.isEmpty(this.state.facets) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: this.state.facets
            });
          }

          if (!_.isEmpty(this.state.date.from) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year >= ' + this.state.date.from]
            });
          }

          if (!_.isEmpty(this.state.date.to) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year <= ' + this.state.date.to]
            });
          }

          if (App.mode == 'mapmaker' && _.isEmpty(this.state.geoFence)) {
            // Add filter to only return items with geo info #8899
            query.values.push({
              type: 'AND',
              values: [
                'minGeoLat=-90',
                'minGeoLong=-180',
                'maxGeoLat=90',
                'maxGeoLong=180'
              ]
            });
          }

          if (!_.isEmpty(this.state.geoFence)) {
            query.values.push(this.state.geoFence);
          }

          return this.renderQuery(query);
        }
      },
      state: {
        d: 100,
        firstPage: 1,
        pageSize: 30,
        maxRecords: 30,
        terms: "*",
        date: {
          from: '',
          to: ''
        },
        facets: [], // Always AND
        facetConfig: null,
        geoFence: null
      },
      url: Config.zoek_en_vind.uri + '/search',

      initialize: function() {
        Communicator.mediator.on('search:toggleAdvancedSearch', this.toggleSearchMode, this);
      },

      toggleSearchMode: function() {
        this.searchMode = this.searchMode == MODE_SIMPLE ? MODE_ADVANCED : MODE_SIMPLE;
      },

      renderQuery: function(query) {
        var self = this;

        _.each(query.values, function(value, key) {
          if (_.isObject(value)) {
            query.values[key] = '(' + self.renderQuery(value) + ')';
          }
        });

        return query.values.join(' ' + query.type + ' ');
      },
      getFacetConfig: function() {
        return new Backbone.Collection(this.state.facetConfig);
      },
      getFacetState: function(resp) {
        var facetConfig = [];
        var facetName, facetKey;

        _.each(resp.result.facets, function(options, name) {
          if (!_.isUndefined(Config.zoek_en_vind.facetLabels)
          && !_.isUndefined(Config.zoek_en_vind.facetLabels[name])) {
            facetKey = name;
            facetName = Config.zoek_en_vind.facetLabels[name];
          } else {
            facetKey = name;
            facetName = name;
          }
          facetConfig.push({
            name: facetName,
            key: facetKey,
            options: options
          });
        });

        return facetConfig;
      },
      hasNext: function() {
        return this.hasNextPage();
      },
      hasPrevious: function() {
        return this.hasPreviousPage();
      },
      parseRecords: function(resp) {
        return resp.result.items;
      },
      parseState: function(resp) {
        return {
          facetConfig: this.getFacetState(resp),
          totalRecords: resp.result.total
        }
      }

    });

  });<commit_msg>added quotation marks around search query for multiple search terms. refs #8764<commit_after>define(['backbone', 'backbone.pageable.collection', 'config', 'communicator', 'plugin/geojson_features/models/feature', 'erfgeoviewer.common'],
  function(Backbone, PageableCollection, Config, Communicator, ResultModel, App) {

    var ResultModel = ResultModel.extend({
      parse: function(fields) {

        var f = {
          title: fields['dc:title'],
          description: fields['dc:description'],
          creator: fields['dc:creator'],
          __id__: fields['@id'],
          subject: fields['subject'],
          source: fields['edm:dataProvider'],
          externalUrl: fields['edm:isShownAt'],
          isShownBy: fields['edm:isShownBy'],
          spatial: this.parseDctermsSpatial(fields)
        };

        if (_.isArray(f.title)) f.title = f.title.join(', ');

        // Image
        var img, ext;
        if (_.isArray(fields['edm:object'])) {
          ext = fields['edm:object'][0].match(/\.[0-9a-z]+$/i);
          if (ext && _.contains(['.jpg', '.jpeg', '.png', '.gif'], ext[0]) || fields['edm:type'][0] == "IMAGE")
            img = fields['edm:object'][0];
        }
        if (img) f.image = img;

        // Title defaults to a shortened description if need be
        if (!fields['dc:title'] && fields['dc:description']) {
          var words = fields['dc:description'][0].split(/\s+/);
          var max = 250;
          var newtitle;
          for (var i = words.length; i >= 0; i--) {
            newtitle = words.slice([0, i]).join(" ");
            if (newtitle.length < max) break;
          }
          f.title = newtitle;
        }

        return f;
      },

      parseDctermsSpatial: function(fields) {
        var geoJSONStrings = [],
          dcTermsSpatial,
          geosHasGeometry,
          geosAsWKT,
          lat,
          long;

        if ( _.isArray(dcTermsSpatial = _.property('dcterms:spatial')(fields)) ) {
          _.each(dcTermsSpatial, function(term) {
            if ( _.isArray(geosHasGeometry = _.property('geos:hasGeometry')(term)) ) {
              _.each(geosHasGeometry, function(geometry) {
                if ( _.isArray(geosAsWKT = _.property('geos:asWKT')(geometry)) ) {
                  _.each(geosAsWKT, function(wkt) {
                    geoJSONStrings.push(wkt);
                  });
                }
              });
            }
            else if ( (lat = _.property('geo:lat')(term)) && (long = _.property('geo:long')(term)) ) {
              geoJSONStrings.push('POINT(' + long + ' ' + lat + ')');
            }
          });
        }

        return geoJSONStrings;
      }
    });

    var MODE_ADVANCED = 'advanced',
      MODE_SIMPLE = 'simple';

    return PageableCollection.extend({

      model: ResultModel,

      searchMode: 'simple',

      queryParams: {
        currentPage: null,
        pageSize: null,
        totalPages: null,
        totalRecords: null,
        facets: function() {
          return _.isArray(Config.zoek_en_vind.requestedFacets) ?
            Config.zoek_en_vind.requestedFacets.join(',') : 'dc:subject,edm:dataProvider,dc:date.year';
        },
        maximumRecords: function() {
          return this.state.maxRecords;
        },
        startRecord: function() {
          return (this.state.currentPage -1) * this.state.pageSize +1;
        },
        query: function() {
          var query = {
            type: 'AND',
            values: [
              '"' + this.state.terms + '"'
            ]
          };

          if (_.isEmpty(this.state.facets) && _.isObject(Config.zoek_en_vind.facets)) {
            query.values.push(Config.zoek_en_vind.facets);
          }
          else if (!_.isEmpty(this.state.facets) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: this.state.facets
            });
          }

          if (!_.isEmpty(this.state.date.from) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year >= ' + this.state.date.from]
            });
          }

          if (!_.isEmpty(this.state.date.to) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year <= ' + this.state.date.to]
            });
          }

          if (App.mode == 'mapmaker' && _.isEmpty(this.state.geoFence)) {
            // Add filter to only return items with geo info #8899
            query.values.push({
              type: 'AND',
              values: [
                'minGeoLat=-90',
                'minGeoLong=-180',
                'maxGeoLat=90',
                'maxGeoLong=180'
              ]
            });
          }

          if (!_.isEmpty(this.state.geoFence)) {
            query.values.push(this.state.geoFence);
          }

          return this.renderQuery(query);
        }
      },
      state: {
        d: 100,
        firstPage: 1,
        pageSize: 30,
        maxRecords: 30,
        terms: "*",
        date: {
          from: '',
          to: ''
        },
        facets: [], // Always AND
        facetConfig: null,
        geoFence: null
      },
      url: Config.zoek_en_vind.uri + '/search',

      initialize: function() {
        Communicator.mediator.on('search:toggleAdvancedSearch', this.toggleSearchMode, this);
      },

      toggleSearchMode: function() {
        this.searchMode = this.searchMode == MODE_SIMPLE ? MODE_ADVANCED : MODE_SIMPLE;
      },

      renderQuery: function(query) {
        var self = this;

        _.each(query.values, function(value, key) {
          if (_.isObject(value)) {
            query.values[key] = '(' + self.renderQuery(value) + ')';
          }
        });

        return query.values.join(' ' + query.type + ' ');
      },
      getFacetConfig: function() {
        return new Backbone.Collection(this.state.facetConfig);
      },
      getFacetState: function(resp) {
        var facetConfig = [];
        var facetName, facetKey;

        _.each(resp.result.facets, function(options, name) {
          if (!_.isUndefined(Config.zoek_en_vind.facetLabels)
          && !_.isUndefined(Config.zoek_en_vind.facetLabels[name])) {
            facetKey = name;
            facetName = Config.zoek_en_vind.facetLabels[name];
          } else {
            facetKey = name;
            facetName = name;
          }
          facetConfig.push({
            name: facetName,
            key: facetKey,
            options: options
          });
        });

        return facetConfig;
      },
      hasNext: function() {
        return this.hasNextPage();
      },
      hasPrevious: function() {
        return this.hasPreviousPage();
      },
      parseRecords: function(resp) {
        return resp.result.items;
      },
      parseState: function(resp) {
        return {
          facetConfig: this.getFacetState(resp),
          totalRecords: resp.result.total
        }
      }

    });

  });<|endoftext|>


<commit_before>'use strict';

angular.module('emuwebApp')
	.service('Ssffparserservice', function Ssffparserservice(viewState) {

		// shared service object
		var sServObj = {};

		sServObj.vs = viewState;

		sServObj.ssffData = {};

		sServObj.headID = 'SSFF -- (c) SHLRC\n';
		sServObj.machineID = 'Machine IBM-PC\n';
		sServObj.sepString = '-----------------\n';

		sServObj.ssffData.ssffTrackName = '';
		sServObj.ssffData.sampleRate = -1;
		sServObj.ssffData.startTime = -1;
		sServObj.ssffData.origFreq = -1;
		sServObj.ssffData.Columns = [];

		/**
		 * convert arraybuffer containing a ssff file
		 * to a javascript object
		 * @param buf arraybuffer containing ssff file
		 * @param name is ssffTrackName
		 * @returns ssff javascript object
		 */
		sServObj.ssff2jso = function (buf, name) {
			var my = this;
			sServObj.ssffData.ssffTrackName = name;
			sServObj.ssffData.Columns = [];
			// console.log('SSFF loaded');

			var uIntBuffView = new Uint8Array(buf);

			// Causes "RangeError: Maximum call stack size exceeded"
			// with some browsers (?)(Chrome/Chromium on Ubuntu)
			//var buffStr = String.fromCharCode.apply(null, uIntBuffView);
			var buffStr = '';
			var i;
			for (i = 0; i < uIntBuffView.length; i++) {
				buffStr = buffStr + String.fromCharCode(uIntBuffView[i]);
			}
			// console.log(buffStr);

			var newLsep = buffStr.split(/^/m);

			//check if header has headID and machineID
			if (newLsep[0] !== my.headID) {
				alert('SSFF parse error: first line != SSFF -- (c) SHLRC');
				return;
			}
			if (newLsep[1] !== my.machineID) {
				alert('SSFF parse error: machineID != Machine IBM-PC');
				return;
			}

			// check if Record_Freq+Start_Time is there
			if (newLsep[2].split(/[ ,]+/)[0] !== 'Record_Freq ' || newLsep[3].split(/[ ,]+/)[0] !== 'Start_Time ') {
				this.ssffData.sampleRate = parseFloat(newLsep[2].split(/[ ,]+/)[1].replace(/(\r\n|\n|\r)/gm, ''));
				this.ssffData.startTime = parseFloat(newLsep[3].split(/[ ,]+/)[1].replace(/(\r\n|\n|\r)/gm, ''));
			} else {
				alert('SSFF parse error: Required fields Record_Freq or Start_Time not set!');
			}

			for (var i = 4; i < newLsep.length; i++) {
				if (newLsep[i].split(/[ ,]+/)[0] === 'Original_Freq') {
					this.ssffData.origFreq = parseFloat(newLsep[i].split(/[ ,]+/)[2].replace(/(\r\n|\n|\r)/gm, ''));
				}
				if (newLsep[i] === this.sepString) {
					break;
				}
				var lSpl = newLsep[i].split(/[ ]+/);

				if (lSpl[0] === 'Column') {
					this.ssffData.Columns.push({
						'name': lSpl[1],
						'ssffdatatype': lSpl[2],
						'length': parseInt(lSpl[3].replace(/(\r\n|\n|\r)/gm, ''), 10),
						'values': []
					});
				}
			}

			var curBinIdx = newLsep.slice(0, i + 1).join('').length;

			var curBufferView, curBuffer, curLen;

			while (curBinIdx <= uIntBuffView.length) {

				for (i = 0; i < this.ssffData.Columns.length; i++) {
					//console.log(this.ssffData.Columns[i].length);
					if (this.ssffData.Columns[i].ssffdatatype === 'DOUBLE') {
						curLen = 8 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Float64Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;

					} else if (this.ssffData.Columns[i].ssffdatatype === 'FLOAT') {
						curLen = 4 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Float32Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;

					} else if (this.ssffData.Columns[i].ssffdatatype === 'SHORT') {
						curLen = 2 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Uint16Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;

					} else if (this.ssffData.Columns[i].ssffdatatype === 'BYTE') {
						curLen = 1 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Uint8Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;
					} else {
						alert('not supported... only doubles, floats, short  column types and for now');
						return;
					}

				} //for
			} //while
			// console.log(this.ssffData);
			// console.log(JSON.stringify(this.ssffData, undefined, 2));
			return this.ssffData;

		};

		/**
		 * convert javascript object of label file to
		 * array buffer containing
		 * @param ssff javascipt object
		 * @returns ssff arraybuffer
		 */
		sServObj.jso2ssff = function (jso) {
			var my = this;
			// create header
			var headerStr = this.headID + this.machineID;
			headerStr += 'Record_Freq ' + this.vs.round(jso.sampleRate, 1) + '\n';
			headerStr += 'Start_Time ' + jso.startTime + '\n';

			jso.Columns.forEach(function (col) {
				// console.log(col.name)
				headerStr += 'Column ' + col.name + ' ' + col.ssffdatatype + ' ' + col.length + '\n';
			});

			headerStr += 'Original_Freq DOUBLE ' + this.vs.round(jso.origFreq, 1) + '\n';
			headerStr += this.sepString;

			// convert buffer to header
			var ssffBufView = new Uint8Array(this.stringToUint(headerStr));

			var curBufferView, curArray;

			curBufferView = new Uint16Array(jso.Columns[0].length);
			curArray = jso.Columns[0].values[0];

			// loop through vals and append array of each column to ssffBufView
			jso.Columns[0].values.forEach(function (curArray, curArrayIDX) {
				jso.Columns.forEach(function (curCol) {
					if (curCol.ssffdatatype === 'SHORT') {
						curBufferView = new Uint16Array(curCol.length);
						curCol.values[curArrayIDX].forEach(function (val, valIDX) {
							curBufferView[valIDX] = val;
						});
						var tmp = new Uint8Array(curBufferView.buffer);
						ssffBufView = my.Uint8Concat(ssffBufView, tmp);
					} else {
						alert('Only SHORT columns supported for now!!!');
						return;
					}
				});
			});

			// console.log(String.fromCharCode.apply(null, ssffBufView));
			return ssffBufView.buffer;
		};

		/**
		 * helper function to convert string to Uint8Array
		 * @param string
		 */
		sServObj.stringToUint = function (string) {
			// var string = btoa(unescape(encodeURIComponent(string)));
			var charList = string.split('');
			var uintArray = [];
			for (var i = 0; i < charList.length; i++) {
				uintArray.push(charList[i].charCodeAt(0));
			}
			return new Uint8Array(uintArray);
		};

		/**
		 *
		 */
		sServObj.Uint8Concat = function (first, second) {
			var firstLength = first.length;
			var result = new Uint8Array(firstLength + second.length);

			result.set(first);
			result.set(second, firstLength);

			return result;
		};

		return sServObj;

	});<commit_msg>now searching all of header for reqfreq and st<commit_after>'use strict';

angular.module('emuwebApp')
	.service('Ssffparserservice', function Ssffparserservice(viewState) {

		// shared service object
		var sServObj = {};

		sServObj.vs = viewState;

		sServObj.ssffData = {};

		sServObj.headID = 'SSFF -- (c) SHLRC\n';
		sServObj.machineID = 'Machine IBM-PC\n';
		sServObj.sepString = '-----------------\n';

		sServObj.ssffData.ssffTrackName = '';
		sServObj.ssffData.sampleRate = -1;
		sServObj.ssffData.startTime = -1;
		sServObj.ssffData.origFreq = -1;
		sServObj.ssffData.Columns = [];

		/**
		 * convert arraybuffer containing a ssff file
		 * to a javascript object
		 * @param buf arraybuffer containing ssff file
		 * @param name is ssffTrackName
		 * @returns ssff javascript object
		 */
		sServObj.ssff2jso = function (buf, name) {
			var my = this;
			sServObj.ssffData.ssffTrackName = name;
			sServObj.ssffData.Columns = [];
			// console.log('SSFF loaded');

			var uIntBuffView = new Uint8Array(buf);

			// Causes "RangeError: Maximum call stack size exceeded"
			// with some browsers (?)(Chrome/Chromium on Ubuntu)
			//var buffStr = String.fromCharCode.apply(null, uIntBuffView);
			var buffStr = '';
			var i;
			for (i = 0; i < uIntBuffView.length; i++) {
				buffStr = buffStr + String.fromCharCode(uIntBuffView[i]);
			}

			var newLsep = buffStr.split(/^/m);

			//check if header has headID and machineID
			if (newLsep[0] !== my.headID) {
				alert('SSFF parse error: first line != SSFF -- (c) SHLRC');
				return;
			}
			if (newLsep[1] !== my.machineID) {
				alert('SSFF parse error: machineID != Machine IBM-PC');
				return;
			}

			// search header for Record_Freq and Start_Time
			this.ssffData.sampleRate = undefined;
			this.ssffData.startTime = undefined;
			var counter = 0;
			while(newLsep[counter] !== this.sepString){
				if (newLsep[counter].split(/[ ,]+/)[0] === 'Record_Freq'){
					// console.log("FOUND Record_Freq")
					this.ssffData.sampleRate = parseFloat(newLsep[counter].split(/[ ,]+/)[1].replace(/(\r\n|\n|\r)/gm, ''));
				}
				if (newLsep[counter].split(/[ ,]+/)[0] === 'Start_Time'){
					// console.log("FOUND Start_Time")
					this.ssffData.startTime = parseFloat(newLsep[counter].split(/[ ,]+/)[1].replace(/(\r\n|\n|\r)/gm, ''));
				}
				counter += 1;
			}

			// check if found Record_Freq and Start_Time
			if(this.ssffData.sampleRate === undefined || this.ssffData.startTime === undefined){
				alert('SSFF parse error: Required fields Record_Freq or Start_Time not set!');
			}

			for (var i = 4; i < newLsep.length; i++) {
				if (newLsep[i].split(/[ ,]+/)[0] === 'Original_Freq') {
					this.ssffData.origFreq = parseFloat(newLsep[i].split(/[ ,]+/)[2].replace(/(\r\n|\n|\r)/gm, ''));
				}
				if (newLsep[i] === this.sepString) {
					break;
				}
				var lSpl = newLsep[i].split(/[ ]+/);

				if (lSpl[0] === 'Column') {
					this.ssffData.Columns.push({
						'name': lSpl[1],
						'ssffdatatype': lSpl[2],
						'length': parseInt(lSpl[3].replace(/(\r\n|\n|\r)/gm, ''), 10),
						'values': []
					});
				}
			}

			var curBinIdx = newLsep.slice(0, i + 1).join('').length;

			var curBufferView, curBuffer, curLen;

			while (curBinIdx <= uIntBuffView.length) {

				for (i = 0; i < this.ssffData.Columns.length; i++) {
					//console.log(this.ssffData.Columns[i].length);
					if (this.ssffData.Columns[i].ssffdatatype === 'DOUBLE') {
						curLen = 8 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Float64Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;

					} else if (this.ssffData.Columns[i].ssffdatatype === 'FLOAT') {
						curLen = 4 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Float32Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;

					} else if (this.ssffData.Columns[i].ssffdatatype === 'SHORT') {
						curLen = 2 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Uint16Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;

					} else if (this.ssffData.Columns[i].ssffdatatype === 'BYTE') {
						curLen = 1 * this.ssffData.Columns[i].length;
						curBuffer = buf.subarray(curBinIdx, curLen);
						curBufferView = new Uint8Array(curBuffer);
						this.ssffData.Columns[i].values.push(Array.prototype.slice.call(curBufferView));
						curBinIdx += curLen;
					} else {
						alert('not supported... only doubles, floats, short  column types and for now');
						return;
					}

				} //for
			} //while
			// console.log(this.ssffData);
			// console.log(JSON.stringify(this.ssffData, undefined, 2));
			return this.ssffData;

		};

		/**
		 * convert javascript object of label file to
		 * array buffer containing
		 * @param ssff javascipt object
		 * @returns ssff arraybuffer
		 */
		sServObj.jso2ssff = function (jso) {
			var my = this;
			// create header
			var headerStr = this.headID + this.machineID;
			headerStr += 'Record_Freq ' + this.vs.round(jso.sampleRate, 1) + '\n';
			headerStr += 'Start_Time ' + jso.startTime + '\n';

			jso.Columns.forEach(function (col) {
				// console.log(col.name)
				headerStr += 'Column ' + col.name + ' ' + col.ssffdatatype + ' ' + col.length + '\n';
			});

			headerStr += 'Original_Freq DOUBLE ' + this.vs.round(jso.origFreq, 1) + '\n';
			headerStr += this.sepString;

			// convert buffer to header
			var ssffBufView = new Uint8Array(this.stringToUint(headerStr));

			var curBufferView, curArray;

			curBufferView = new Uint16Array(jso.Columns[0].length);
			curArray = jso.Columns[0].values[0];

			// loop through vals and append array of each column to ssffBufView
			jso.Columns[0].values.forEach(function (curArray, curArrayIDX) {
				jso.Columns.forEach(function (curCol) {
					if (curCol.ssffdatatype === 'SHORT') {
						curBufferView = new Uint16Array(curCol.length);
						curCol.values[curArrayIDX].forEach(function (val, valIDX) {
							curBufferView[valIDX] = val;
						});
						var tmp = new Uint8Array(curBufferView.buffer);
						ssffBufView = my.Uint8Concat(ssffBufView, tmp);
					} else {
						alert('Only SHORT columns supported for now!!!');
						return;
					}
				});
			});

			// console.log(String.fromCharCode.apply(null, ssffBufView));
			return ssffBufView.buffer;
		};

		/**
		 * helper function to convert string to Uint8Array
		 * @param string
		 */
		sServObj.stringToUint = function (string) {
			// var string = btoa(unescape(encodeURIComponent(string)));
			var charList = string.split('');
			var uintArray = [];
			for (var i = 0; i < charList.length; i++) {
				uintArray.push(charList[i].charCodeAt(0));
			}
			return new Uint8Array(uintArray);
		};

		/**
		 *
		 */
		sServObj.Uint8Concat = function (first, second) {
			var firstLength = first.length;
			var result = new Uint8Array(firstLength + second.length);

			result.set(first);
			result.set(second, firstLength);

			return result;
		};

		return sServObj;

	});<|endoftext|>


<commit_before>$(function() {

"use strict";
var Match = Backbone.Model.extend({
  url: function() {
    return "https://github.com/torvalds/linux/blob/" + shorten(this.ref) +
      "/" + this.get('path').path + "#L" + this.get('context').lno;
  }
});

function shorten(ref) {
  var match = /^refs\/(tags|branches)\/(.*)/.exec(ref);
  if (match)
    return match[2];
  return ref;
}

var MatchView = Backbone.View.extend({
  tagName: 'div',
  render: function() {
    var div = this._render();
    this.$el.empty();
    this.$el.append(div);
    return this;
  },
  _render: function() {
    var h = new HTMLFactory();
    var ctx = this.model.get('context');
    var i;
    var ctx_before = [], ctx_after = [];
    for (i = 0; i < ctx.context_before.length; i ++) {
      ctx_before.unshift(h.div([
                                 h.span({cls: 'lno'}, [ctx.lno - i - 1, ":"]),
                                 ctx.context_before[i]
                               ]));
    }
    for (i = 0; i < ctx.context_after.length; i ++) {
      ctx_after.push(h.div([
                             h.span({cls: 'lno'}, [ctx.lno + i + 1, ":"]),
                             ctx.context_after[i]
                           ]));
    }
    var line = this.model.get('line');
    var bounds = this.model.get('bounds');
    var pieces = [line.substring(0, bounds[0]),
                  line.substring(bounds[0], bounds[1]),
                  line.substring(bounds[1])];

    return h.div({cls: 'match'},
                 [
                   h.div({},
                         [h.span({cls: 'label'},
                                 [
                                   h.a({
                                         href: this.model.url()
                                       },
                                   [ shorten(this.model.get('path').ref), ":",
                                     this.model.get('path').path])])
                         ]),
                   h.div({cls: 'contents'},
                         [
                           ctx_before,
                           h.div({cls: 'matchline'},
                                 [
                                   h.span({cls: 'lno'}, [ctx.lno + ":"]),
                                   pieces[0],
                                   h.span({cls: 'matchstr'}, [pieces[1]]),
                                   pieces[2]
                                 ]),
                           ctx_after])]);
  }
});

var MatchSet = Backbone.Collection.extend({
  model: Match
});

var SearchState = Backbone.Model.extend({
  defaults: function() {
    return {
      displaying: null,
      error: null,
      time: null,
      why: null
    };
  },

  initialize: function() {
    this.search_map = {};
    this.matches = new MatchSet();
    this.search_id = 0;
    this.on('change:displaying', this.new_search, this);
  },

  new_search: function() {
    this.set({
        error: null,
        time: null,
        why: null
    });
    this.matches.reset();
    for (var k in this.search_map) {
      if (k < this.get('displaying'))
        delete this.search_map[k];
    }
  },

  next_id: function() {
    return ++this.search_id;
  },

  dispatch: function (q, file) {
    var id = this.next_id();
    this.search_map[id] = {q: q, file: file};
    if (!q.length)
      this.set('displaying', id);
    return id;
  },

  url: function() {
    var q = {};
    var current = this.search_map[this.get('displaying')];
    if (!current)
      return '/search';

    if (current.q)    q.q = current.q;
    if (current.file) q.file = current.file;
    return '/search?' + $.param(q);
  },

  handle_error: function (search, error) {
    if (search === this.search_id) {
      this.set('displaying', search);
      this.set('error', error);
    }
  },

  handle_match: function (search, match) {
    if (search < this.get('displaying'))
      return false;
    this.set('displaying', search);
    this.matches.add({
                       line: match.line,
                       bounds: match.bounds,
                       context: match.contexts[0],
                       path: match.contexts[0].paths[0],
                     });
  },
  handle_done: function (search, time, why) {
    this.set('displaying', search);
    this.set({time: time, why: why});
  }
});

var MatchesView = Backbone.View.extend({
  el: $('#results'),
  initialize: function() {
    this.model.matches.bind('add', this.add_one, this);
    this.model.matches.bind('reset', this.add_all, this);
  },
  add_one: function(model) {
    var view = new MatchView({model: model});
    this.$el.append(view.render().el);
  },
  add_all: function() {
    this.$el.empty();
    this.model.matches.each(this.add_one);
  }
});

var ResultView = Backbone.View.extend({
  el: $('#resultarea'),
  initialize: function() {
    this.matches_view = new MatchesView({model: this.model});
    this.permalink = this.$('#permalink');
    this.results   = this.$('#numresults');
    this.errorbox  = $('#regex-error');
    this.time      = this.$('#searchtime');

    this.model.on('all', this.render, this);
    this.model.matches.on('all', this.render, this);
  },

  render: function() {
    if (this.model.get('error')) {
      this.errorbox.find('#errortext').text(this.model.get('error'));
      this.errorbox.show();
    } else {
      this.errorbox.hide()
    }

    var url = this.model.url();
    this.permalink.attr('href', url);
    if (history.replaceState) {
      history.replaceState(null, '', url);
    }

    if (this.model.search_map[this.model.get('displaying')].q === '' ||
       this.model.get('error')) {
      this.$el.hide();
      return this;
    }

    this.$el.show();

    if (this.model.get('time')) {
      this.$('#searchtimebox').show();
      var time = this.model.get('time');
      this.time.text((time/1000) + "s")
    } else {
      this.$('#searchtimebox').hide();
    }

    var results = '' + this.model.matches.size();
    if (this.model.get('why') === 'limit')
      results = results + '+';
    this.results.text(results);

    return this;
  }
});

var CodesearchUI = function() {
  return {
    state: new SearchState(),
    view: null,
    onload: function() {
      if (CodesearchUI.input)
        return;

      CodesearchUI.view = new ResultView({model: CodesearchUI.state});

      CodesearchUI.input      = $('#searchbox');
      CodesearchUI.input_file = $('#filebox');
      var parms = CodesearchUI.parse_query_params();
      if (parms.q)
        CodesearchUI.input.val(parms.q);
      if (parms.file)
        CodesearchUI.input_file.val(parms.file);

      CodesearchUI.input.keydown(CodesearchUI.keypress);
      CodesearchUI.input_file.keydown(CodesearchUI.keypress);
      CodesearchUI.input.bind('paste', CodesearchUI.keypress);
      CodesearchUI.input_file.bind('paste', CodesearchUI.keypress);
      CodesearchUI.input.focus();

      Codesearch.connect(CodesearchUI);
    },
    parse_query_params: function() {
      var urlParams = {};
      var e,
          a = /\+/g,
          r = /([^&=]+)=?([^&]*)/g,
          d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
          q = window.location.search.substring(1);

      while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
      return urlParams;
    },
    on_connect: function() {
      CodesearchUI.newsearch();
    },
    keypress: function() {
      setTimeout(CodesearchUI.newsearch, 0);
    },
    newsearch: function() {
      var id = CodesearchUI.state.dispatch(CodesearchUI.input.val(),
                                           CodesearchUI.input_file.val());
      Codesearch.new_search(
        CodesearchUI.input.val(),
        CodesearchUI.input_file.val(),
        id);
    },
    error: function(search, error) {
      CodesearchUI.state.handle_error(search, error);
    },
    match: function(search, match) {
      CodesearchUI.state.handle_match(search, match);
    },
    search_done: function(search, time, why) {
      CodesearchUI.state.handle_done(search, time, why);
    },
  };
}();
CodesearchUI.onload();
window.CodesearchUI = CodesearchUI;
});
<commit_msg>Only call history.replaceState() if the value has changed.<commit_after>$(function() {

"use strict";
var Match = Backbone.Model.extend({
  url: function() {
    return "https://github.com/torvalds/linux/blob/" + shorten(this.ref) +
      "/" + this.get('path').path + "#L" + this.get('context').lno;
  }
});

function shorten(ref) {
  var match = /^refs\/(tags|branches)\/(.*)/.exec(ref);
  if (match)
    return match[2];
  return ref;
}

var MatchView = Backbone.View.extend({
  tagName: 'div',
  render: function() {
    var div = this._render();
    this.$el.empty();
    this.$el.append(div);
    return this;
  },
  _render: function() {
    var h = new HTMLFactory();
    var ctx = this.model.get('context');
    var i;
    var ctx_before = [], ctx_after = [];
    for (i = 0; i < ctx.context_before.length; i ++) {
      ctx_before.unshift(h.div([
                                 h.span({cls: 'lno'}, [ctx.lno - i - 1, ":"]),
                                 ctx.context_before[i]
                               ]));
    }
    for (i = 0; i < ctx.context_after.length; i ++) {
      ctx_after.push(h.div([
                             h.span({cls: 'lno'}, [ctx.lno + i + 1, ":"]),
                             ctx.context_after[i]
                           ]));
    }
    var line = this.model.get('line');
    var bounds = this.model.get('bounds');
    var pieces = [line.substring(0, bounds[0]),
                  line.substring(bounds[0], bounds[1]),
                  line.substring(bounds[1])];

    return h.div({cls: 'match'},
                 [
                   h.div({},
                         [h.span({cls: 'label'},
                                 [
                                   h.a({
                                         href: this.model.url()
                                       },
                                   [ shorten(this.model.get('path').ref), ":",
                                     this.model.get('path').path])])
                         ]),
                   h.div({cls: 'contents'},
                         [
                           ctx_before,
                           h.div({cls: 'matchline'},
                                 [
                                   h.span({cls: 'lno'}, [ctx.lno + ":"]),
                                   pieces[0],
                                   h.span({cls: 'matchstr'}, [pieces[1]]),
                                   pieces[2]
                                 ]),
                           ctx_after])]);
  }
});

var MatchSet = Backbone.Collection.extend({
  model: Match
});

var SearchState = Backbone.Model.extend({
  defaults: function() {
    return {
      displaying: null,
      error: null,
      time: null,
      why: null
    };
  },

  initialize: function() {
    this.search_map = {};
    this.matches = new MatchSet();
    this.search_id = 0;
    this.on('change:displaying', this.new_search, this);
  },

  new_search: function() {
    this.set({
        error: null,
        time: null,
        why: null
    });
    this.matches.reset();
    for (var k in this.search_map) {
      if (k < this.get('displaying'))
        delete this.search_map[k];
    }
  },

  next_id: function() {
    return ++this.search_id;
  },

  dispatch: function (q, file) {
    var id = this.next_id();
    this.search_map[id] = {q: q, file: file};
    if (!q.length)
      this.set('displaying', id);
    return id;
  },

  url: function() {
    var q = {};
    var current = this.search_map[this.get('displaying')];
    if (!current)
      return '/search';

    if (current.q)    q.q = current.q;
    if (current.file) q.file = current.file;
    return '/search?' + $.param(q);
  },

  handle_error: function (search, error) {
    if (search === this.search_id) {
      this.set('displaying', search);
      this.set('error', error);
    }
  },

  handle_match: function (search, match) {
    if (search < this.get('displaying'))
      return false;
    this.set('displaying', search);
    this.matches.add({
                       line: match.line,
                       bounds: match.bounds,
                       context: match.contexts[0],
                       path: match.contexts[0].paths[0],
                     });
  },
  handle_done: function (search, time, why) {
    this.set('displaying', search);
    this.set({time: time, why: why});
  }
});

var MatchesView = Backbone.View.extend({
  el: $('#results'),
  initialize: function() {
    this.model.matches.bind('add', this.add_one, this);
    this.model.matches.bind('reset', this.add_all, this);
  },
  add_one: function(model) {
    var view = new MatchView({model: model});
    this.$el.append(view.render().el);
  },
  add_all: function() {
    this.$el.empty();
    this.model.matches.each(this.add_one);
  }
});

var ResultView = Backbone.View.extend({
  el: $('#resultarea'),
  initialize: function() {
    this.matches_view = new MatchesView({model: this.model});
    this.permalink = this.$('#permalink');
    this.results   = this.$('#numresults');
    this.errorbox  = $('#regex-error');
    this.time      = this.$('#searchtime');
    this.last_url  = null;

    this.model.on('all', this.render, this);
    this.model.matches.on('all', this.render, this);
  },

  render: function() {
    if (this.model.get('error')) {
      this.errorbox.find('#errortext').text(this.model.get('error'));
      this.errorbox.show();
    } else {
      this.errorbox.hide()
    }

    var url = this.model.url();
    if (this.last_url !== url ) {
      this.permalink.attr('href', url);
      if (history.replaceState) {
        history.replaceState(null, '', url);
      }
      this.last_url = url;
    }

    if (this.model.search_map[this.model.get('displaying')].q === '' ||
       this.model.get('error')) {
      this.$el.hide();
      return this;
    }

    this.$el.show();

    if (this.model.get('time')) {
      this.$('#searchtimebox').show();
      var time = this.model.get('time');
      this.time.text((time/1000) + "s")
    } else {
      this.$('#searchtimebox').hide();
    }

    var results = '' + this.model.matches.size();
    if (this.model.get('why') === 'limit')
      results = results + '+';
    this.results.text(results);

    return this;
  }
});

var CodesearchUI = function() {
  return {
    state: new SearchState(),
    view: null,
    onload: function() {
      if (CodesearchUI.input)
        return;

      CodesearchUI.view = new ResultView({model: CodesearchUI.state});

      CodesearchUI.input      = $('#searchbox');
      CodesearchUI.input_file = $('#filebox');
      var parms = CodesearchUI.parse_query_params();
      if (parms.q)
        CodesearchUI.input.val(parms.q);
      if (parms.file)
        CodesearchUI.input_file.val(parms.file);

      CodesearchUI.input.keydown(CodesearchUI.keypress);
      CodesearchUI.input_file.keydown(CodesearchUI.keypress);
      CodesearchUI.input.bind('paste', CodesearchUI.keypress);
      CodesearchUI.input_file.bind('paste', CodesearchUI.keypress);
      CodesearchUI.input.focus();

      Codesearch.connect(CodesearchUI);
    },
    parse_query_params: function() {
      var urlParams = {};
      var e,
          a = /\+/g,
          r = /([^&=]+)=?([^&]*)/g,
          d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
          q = window.location.search.substring(1);

      while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
      return urlParams;
    },
    on_connect: function() {
      CodesearchUI.newsearch();
    },
    keypress: function() {
      setTimeout(CodesearchUI.newsearch, 0);
    },
    newsearch: function() {
      var id = CodesearchUI.state.dispatch(CodesearchUI.input.val(),
                                           CodesearchUI.input_file.val());
      Codesearch.new_search(
        CodesearchUI.input.val(),
        CodesearchUI.input_file.val(),
        id);
    },
    error: function(search, error) {
      CodesearchUI.state.handle_error(search, error);
    },
    match: function(search, match) {
      CodesearchUI.state.handle_match(search, match);
    },
    search_done: function(search, time, why) {
      CodesearchUI.state.handle_done(search, time, why);
    },
  };
}();
CodesearchUI.onload();
window.CodesearchUI = CodesearchUI;
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { Callout } from 'react-foundation';
import { MdWarning } from 'react-icons/lib/md';

const Styles = {
  hidden: {
    display: 'none'
  },
  notHidden: {
    display: ''
  }
};

const ErrorPanel = ({
  errors,
  isVisible
}) => (
  <Callout
    color={'alert'}
    size={'large'}
    className="error-panel"
    style={isVisible ? Styles.hidden : Styles.notHidden}
  >
    <MdWarning />

Errors

      {errors.map((err) =>
{err}
)}

  </Callout>
);

ErrorPanel.propTypes = {
  errors: PropTypes.array.isRequired,
  isVisible: PropTypes.bool.isRequired
};

export default ErrorPanel;
<commit_msg>Fix: add defaultProps for error pane<commit_after>import React, { PropTypes } from 'react';
import { Callout } from 'react-foundation';
import { MdWarning } from 'react-icons/lib/md';

const Styles = {
  hidden: {
    display: 'none'
  },
  notHidden: {
    display: ''
  }
};

const ErrorPanel = ({
  errors,
  isVisible
}) => (
  <Callout
    color={'alert'}
    size={'large'}
    className="error-panel"
    style={isVisible ? Styles.hidden : Styles.notHidden}
  >
    <MdWarning />

Errors

      {errors != null && errors.length > 0 &&
        errors.map((err) =>

{err}

        )}

  </Callout>
);

ErrorPanel.propTypes = {
  errors: PropTypes.array.isRequired,
  isVisible: PropTypes.bool.isRequired
};

ErrorPanel.defaultProps = {
  isVisible: false
};

export default ErrorPanel;
<|endoftext|>


<commit_before>import {search}  from './search/search'

export function jfCodeMirror() {
    return {
        restrict: 'E',
        scope: {
            mimeType: '@',
            mode: '@',
            model: '=',
            allowEdit: '=',
            noCursor: '=',
            height: '@?',
            apiAccess: '=',
            autofocus: '@',
	        matchBrackets: '<',
	        autoFormat: '<',
            autoIndent: '<',
	        enableCopyToClipboard: '<?',
	        clipboardCopyModel: '<?',
	        clipboardCopyEntityName: '@?',
	        clipboardKeepTooltipLetterCase: '<?'
        },
        controller: jfCodeController,
        controllerAs: 'jfCodeMirror',
        bindToController: true,
	    templateUrl: 'directives/jf_codemirror/jf_codemirror.html'
    }
}

class jfCodeController {
	/* @ngInject */
    constructor($scope, $element, $timeout,JFrogUIUtils) {
        this.JFrogUIUtils = JFrogUIUtils;
        this.$element = $element;
        this.$scope = $scope;
        this.$timeout = $timeout;
	    this.defineExtensions();
    }

    $onInit() {
	    this._formatModel();
	    this.autofocus = this.autofocus === 'true';
        let readOnlyParam = !this.allowEdit;

        if(!_.isUndefined(this.noCursor) && this.noCursor) {
            readOnlyParam = 'nocursor';
        }

        this.editorOptions = {
            lineNumbers: true,
            readOnly: readOnlyParam, // enables nocursor usage if provided in the params for mobile layout
            lineWrapping: true,
            mode: this.mode || 'links',
            viewportMargin: 65,
            autofocus: this.autofocus,
            mimeType: this.mimeType,
            matchBrackets: this.matchBrackets,
            onLoad: this._codeMirrorLoaded.bind(this)
        };
        // Hide cursor in readonly mode
        if (!this.allowEdit) {
            this.editorOptions.cursorBlinkRate = -1;
        }
    }

    // register click handlers on code mirror links
    _codeMirrorLoaded(_editor) {
        this.cmApi = _editor;
        if (this.height) {
            let codeMirrorElement = $(this.$element).find('.CodeMirror');
            if (this.height === 'flexible') {
                codeMirrorElement.css('top', 0);
                codeMirrorElement.css('bottom', 0);
                codeMirrorElement.css('left', 0);
                codeMirrorElement.css('right', 0);
                codeMirrorElement.css('position', 'absolute');
            }
            else {
                codeMirrorElement.css('height', this.height);
            }
        }
        $(_editor.display.wrapper).on('click', '.cm-link', (e) => {
            let url = $(this).text();
            if (url) {
                window.open(url, '_blank');
            }
        });
        this.$scope.$on('$destroy', () => {
            this.$destroyed = true;
            $(_editor.display.wrapper).off('click')
        });
        if (this.apiAccess) {
            this.apiAccess.api = this.cmApi;
            if (this.apiAccess.onLoad) {
                this.apiAccess.onLoad();
            }
        }
    }

    autoFormatText(indent) {
	    let last = this.cmApi.lineCount();
	    let start = {line:0,ch:0},
		    end = {line:last};
	    if(indent) {
	        this.cmApi.autoIndentRange(start,end);
	    } else {
		    this.cmApi.autoFormatRange(start,end);
        }
	    this.cmApi.setCursor(start);
    }

    _isJSON(str) {
        try {
            JSON.parse(str);
        }
        catch(e) {
            return false;
        }
        return true;
    }

    _formatModel() {
        let format = (content) => {
	        if (this.autoFormat && (this.mode === 'javascript' || this.mode === 'htmlmixed')) {
		        this.$timeout(() => {
			        if(this.cmApi && this.cmApi.getValue().length > 0) {
				        this.autoFormatText();
				        this.formattedModel = this.cmApi.getValue();
				        this.cmApi.refresh();
			        }
		        });
	        }
	        if (this._isJSON(content)) {
                this.formattedModel = require('js-beautify').js_beautify(content);
            }
            else {
                this.formattedModel = content;
            }
            this.expectChange();
            this.refreshUntilVisible();
        }

        if (!this.allowEdit) {
            format(this.model);
            this.$scope.$watch('jfCodeMirror.model',v=>{
                format(v);
            })
        }
        else {
            this.formattedModel = this.model;
            this.$scope.$watch('jfCodeMirror.model',v=>{
                if (this.formattedModel !== this.model) {
                    this.formattedModel = this.model;
                    this.expectChange();
                    this.refreshUntilVisible();
                }
            });
            this.$scope.$watch('jfCodeMirror.formattedModel',v=>{
                this.model = v;
            });
            this.expectChange();
            this.refreshUntilVisible();
        }
    }

    refreshUntilVisible() {
        if (this.cmApi) this.cmApi.refresh();
        if (this.allowEdit) return;
        this.$timeout(()=>{
            let cmText = $(this.$element).find('.CodeMirror-code').find('pre').text().replace(/\u200B/g,'');
            if (this.expectingChange && cmText === this.lastVal) {
                if (this.cmApi) {
                    this.cmApi.refresh();
                }
                if (!this.$destroyed) this.refreshUntilVisible();
            }
            else if (this.expectingChange) {
                this.expectingChange = false;
                delete this.lastVal;
            }
        },100)
    }

    expectChange() {
        let cmText = $(this.$element).find('.CodeMirror-code').find('pre').text().replace(/\u200B/g,'');
        this.expectingChange = true;
        this.lastVal = cmText;
    }

    defineExtensions() {
	    CodeMirror.defineExtension("autoFormatRange", (from, to) => {
		    let cm = this.cmApi;
		    let outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
		    let state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
		    let tabSize = cm.getOption("tabSize");

		    let out = "", lines = 0, atSol = from.ch == 0;
		    let newline = () => {
			    out += "\n";
			    atSol = true;
			    ++lines;
		    };

		    for (let i = 0; i < text.length; ++i) {
			    let stream = new CodeMirror.StringStream(text[i], tabSize);
			    while (!stream.eol()) {
				    let inner = CodeMirror.innerMode(outer, state);
				    let style = outer.token(stream, state), cur = stream.current();
				    stream.start = stream.pos;
				    if (!atSol || /\S/.test(cur)) {
					    out += cur;
					    atSol = false;
				    }
				    if (!atSol && inner.mode.newlineAfterToken &&
					    inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
					    newline();
			    }
			    if (!stream.pos && outer.blankLine) outer.blankLine(state);
			    if (!atSol) newline();
		    }

		    cm.operation(() => {
			    cm.replaceRange(out, from, to);
			    for (let cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
				    cm.indentLine(cur, "smart");
		    });
	    });

	    // Applies automatic mode-aware indentation to the specified range
	    CodeMirror.defineExtension("autoIndentRange", (from, to) => {
		    let cmInstance = this.cmApi;
		    this.cmApi.operation(() => {
			    for (let i = from.line; i <= to.line; i++) {
				    cmInstance.indentLine(i, "smart");
			    }
		    });
	    });
    }

	codeMirrorIsWithScroll() {
		let codemirrorScrollBar = this.$element.find('.CodeMirror .CodeMirror-vscrollbar:not(:hidden)');
		return codemirrorScrollBar && codemirrorScrollBar.length > 0;
	}
}<commit_msg>code review updates<commit_after>import {search}  from './search/search'

export function jfCodeMirror() {
    return {
        restrict: 'E',
        scope: {
            mimeType: '@',
            mode: '@',
            model: '=',
            allowEdit: '=',
            noCursor: '=',
            height: '@?',
            apiAccess: '=',
            autofocus: '@',
	        matchBrackets: '<',
	        autoFormat: '<',
            autoIndent: '<',
	        enableCopyToClipboard: '<?',
	        clipboardCopyModel: '<?',
	        clipboardCopyEntityName: '@?',
	        clipboardKeepTooltipLetterCase: '<?'
        },
        controller: jfCodeController,
        controllerAs: 'jfCodeMirror',
        bindToController: true,
	    templateUrl: 'directives/jf_codemirror/jf_codemirror.html'
    }
}

class jfCodeController {
	/* @ngInject */
    constructor($scope, $element, $timeout,JFrogUIUtils) {
        this.JFrogUIUtils = JFrogUIUtils;
        this.$element = $element;
        this.$scope = $scope;
        this.$timeout = $timeout;
	    this.defineExtensions();
    }

    $onInit() {
	    this._formatModel();
	    this.autofocus = this.autofocus === 'true';
        let isReadOnlyMode = !this.allowEdit;

        // enables nocursor usage if provided in the params for mobile layout
        if(!_.isUndefined(this.noCursor) && this.noCursor) {
            isReadOnlyMode = 'nocursor';
        }

        this.editorOptions = {
            lineNumbers: true,
            readOnly: isReadOnlyMode,
            lineWrapping: true,
            mode: this.mode || 'links',
            viewportMargin: 65,
            autofocus: this.autofocus,
            mimeType: this.mimeType,
            matchBrackets: this.matchBrackets,
            onLoad: this._codeMirrorLoaded.bind(this)
        };
        // Hide cursor in readonly mode
        if (!this.allowEdit) {
            this.editorOptions.cursorBlinkRate = -1;
        }
    }

    // register click handlers on code mirror links
    _codeMirrorLoaded(_editor) {
        this.cmApi = _editor;
        if (this.height) {
            let codeMirrorElement = $(this.$element).find('.CodeMirror');
            if (this.height === 'flexible') {
                codeMirrorElement.css('top', 0);
                codeMirrorElement.css('bottom', 0);
                codeMirrorElement.css('left', 0);
                codeMirrorElement.css('right', 0);
                codeMirrorElement.css('position', 'absolute');
            }
            else {
                codeMirrorElement.css('height', this.height);
            }
        }
        $(_editor.display.wrapper).on('click', '.cm-link', (e) => {
            let url = $(this).text();
            if (url) {
                window.open(url, '_blank');
            }
        });
        this.$scope.$on('$destroy', () => {
            this.$destroyed = true;
            $(_editor.display.wrapper).off('click')
        });
        if (this.apiAccess) {
            this.apiAccess.api = this.cmApi;
            if (this.apiAccess.onLoad) {
                this.apiAccess.onLoad();
            }
        }
    }

    autoFormatText(indent) {
	    let last = this.cmApi.lineCount();
	    let start = {line:0,ch:0},
		    end = {line:last};
	    if(indent) {
	        this.cmApi.autoIndentRange(start,end);
	    } else {
		    this.cmApi.autoFormatRange(start,end);
        }
	    this.cmApi.setCursor(start);
    }

    _isJSON(str) {
        try {
            JSON.parse(str);
        }
        catch(e) {
            return false;
        }
        return true;
    }

    _formatModel() {
        let format = (content) => {
	        if (this.autoFormat && (this.mode === 'javascript' || this.mode === 'htmlmixed')) {
		        this.$timeout(() => {
			        if(this.cmApi && this.cmApi.getValue().length > 0) {
				        this.autoFormatText();
				        this.formattedModel = this.cmApi.getValue();
				        this.cmApi.refresh();
			        }
		        });
	        }
	        if (this._isJSON(content)) {
                this.formattedModel = require('js-beautify').js_beautify(content);
            }
            else {
                this.formattedModel = content;
            }
            this.expectChange();
            this.refreshUntilVisible();
        }

        if (!this.allowEdit) {
            format(this.model);
            this.$scope.$watch('jfCodeMirror.model',v=>{
                format(v);
            })
        }
        else {
            this.formattedModel = this.model;
            this.$scope.$watch('jfCodeMirror.model',v=>{
                if (this.formattedModel !== this.model) {
                    this.formattedModel = this.model;
                    this.expectChange();
                    this.refreshUntilVisible();
                }
            });
            this.$scope.$watch('jfCodeMirror.formattedModel',v=>{
                this.model = v;
            });
            this.expectChange();
            this.refreshUntilVisible();
        }
    }

    refreshUntilVisible() {
        if (this.cmApi) this.cmApi.refresh();
        if (this.allowEdit) return;
        this.$timeout(()=>{
            let cmText = $(this.$element).find('.CodeMirror-code').find('pre').text().replace(/\u200B/g,'');
            if (this.expectingChange && cmText === this.lastVal) {
                if (this.cmApi) {
                    this.cmApi.refresh();
                }
                if (!this.$destroyed) this.refreshUntilVisible();
            }
            else if (this.expectingChange) {
                this.expectingChange = false;
                delete this.lastVal;
            }
        },100)
    }

    expectChange() {
        let cmText = $(this.$element).find('.CodeMirror-code').find('pre').text().replace(/\u200B/g,'');
        this.expectingChange = true;
        this.lastVal = cmText;
    }

    defineExtensions() {
	    CodeMirror.defineExtension("autoFormatRange", (from, to) => {
		    let cm = this.cmApi;
		    let outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
		    let state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
		    let tabSize = cm.getOption("tabSize");

		    let out = "", lines = 0, atSol = from.ch == 0;
		    let newline = () => {
			    out += "\n";
			    atSol = true;
			    ++lines;
		    };

		    for (let i = 0; i < text.length; ++i) {
			    let stream = new CodeMirror.StringStream(text[i], tabSize);
			    while (!stream.eol()) {
				    let inner = CodeMirror.innerMode(outer, state);
				    let style = outer.token(stream, state), cur = stream.current();
				    stream.start = stream.pos;
				    if (!atSol || /\S/.test(cur)) {
					    out += cur;
					    atSol = false;
				    }
				    if (!atSol && inner.mode.newlineAfterToken &&
					    inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
					    newline();
			    }
			    if (!stream.pos && outer.blankLine) outer.blankLine(state);
			    if (!atSol) newline();
		    }

		    cm.operation(() => {
			    cm.replaceRange(out, from, to);
			    for (let cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
				    cm.indentLine(cur, "smart");
		    });
	    });

	    // Applies automatic mode-aware indentation to the specified range
	    CodeMirror.defineExtension("autoIndentRange", (from, to) => {
		    let cmInstance = this.cmApi;
		    this.cmApi.operation(() => {
			    for (let i = from.line; i <= to.line; i++) {
				    cmInstance.indentLine(i, "smart");
			    }
		    });
	    });
    }

	codeMirrorIsWithScroll() {
		let codemirrorScrollBar = this.$element.find('.CodeMirror .CodeMirror-vscrollbar:not(:hidden)');
		return codemirrorScrollBar && codemirrorScrollBar.length > 0;
	}
}<|endoftext|>


<commit_before>// Dependencies
const Eris = require('eris')
const fs = require('fs')
const path = require('path')

// Setting up objects & vars
const config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json')))
let pf = config.prefix
let cooldown = false
let spamblockMessage = false
let spamblockNotifyMessage
let bot = new Eris.CommandClient(config.bot_token, {}, {
  'name': 'ModBot',
  'owner': 'CF12',
  'prefix': pf,
  'description': 'A moderation bot designed by CF12'
})

// Attempts to connect the bot
bot.connect()

// Class: Logger
class Logger {
  // Log to console
  logConsole (log, type) {
    if (type === 'info') {
      console.log('INFO > ' + log)
    } else if (type === 'err') {
      console.log('ERROR > ' + log)
    } else if (type === 'debug') {
      console.log('DEBUG > ' + log)
    } else {
      console.log('ERROR > Invalid console log')
    }
  }

  // Log to channel
  logChannel (log, type) {
    if (type === 'info') {
      return '```> INFO: ' + log + '```'
    } else if (type === 'err') {
      return '```> ERROR: ' + log + '```'
    } else {
      console.log('ERROR > Invalid channel log')
    }
  }
}

// Function: Kills message after duration in seconds
function timeoutMsg (promise, timeout) {
  return promise.then((msg) => {
    setTimeout(() => {
      msg.delete()
    }, timeout * 1000)
  })
}

// Function: Analyzes 2 messages for similarities, and returns a percentage of similarities
function analyzeMessage (msg1, msg2) {
  if (msg1.attachments.length >= 1 || msg2.attachments.length >= 1) {
    if (msg1.content === msg2.content) return 100
    return 0
  }

  msg1 = msg1.content.toUpperCase()
  msg2 = msg2.content.toUpperCase()
  let simchar = 0

  for (var i = 0; i < msg1.length; i++) {
    if (msg2.indexOf(msg1[i]) !== -1) simchar = simchar + 1
  }

  return simchar / msg2.length * 100
}

// Def Logger
const logger = new Logger()

// On: Bot Ready
bot.on('ready', () => {
  console.log('INFO > Bot activated')
  bot.editStatus('online', {
    'name': 'v0.1.1 - by CF12'
  })
})

/*
  Commands
*/

// Simple Ping Command
bot.registerCommand('ping', (msg, args) => {
  msg.channel.createMessage('Pong!')
}, {
  'description': 'Pings the bot',
  'fullDescription': 'Throws a ping pong ball at the bot'
})

// Text similarities db command
bot.registerCommand('compare', (msg, args) => {
  msg.channel.createMessage(analyzeMessage(args[0], args[1]))
}, {
  'description': 'DB Compares 2 strings',
  'fullDescription': ''
})

// Purge Command
bot.registerCommand('purge', (msg, args) => {
  if (args.length > 1) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('Invalid usage! Correct syntax: ' + pf + 'purge [1-100]', 'err')), 5)
    return
  } else if (args.length === 0) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('Purges messages: ' + pf + 'purge [1-100]', 'info')), 5)
    return
  } else if (!msg.member.permission.has('manageMessages')) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('User does not have the manageMessages permission!', 'err')), 5)
    return
  } else if (cooldown) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('Please wait a few seconds before trying again.', 'err')), 5)
    return
  }

  let arg = args[0]

  if (arg % 1 === 0 && arg >= 1 && arg <= 100) {
    cooldown = true
    msg.channel.purge(arg).then(() => {
      msg.channel.createMessage(logger.logChannel('Successfully purged ' + arg + ' message(s).', 'info')).then(msg => {
        setTimeout(() => {
          cooldown = false
          msg.delete()
        }, 3000)
      })
    })
  } else {
    return logger.logChannel('Invalid arguments! Use an integer from 1 to 100 for your parameter.', 'err')
  }
}, {
  'description': 'Purge messages in the current channel',
  'fullDescription': 'Purges a number of messages from channel the command is called in.',
  'usage': '<1-100>'
})

// Debug Command
bot.registerCommand('db', (msg, args) => {
  logger.logConsole(msg.member.permission.has('manageMessages'), 'debug')
}, {
  'description': 'Debug command',
  'fullDescription': 'Debug command. \'nouf said.'
})

bot.on('messageCreate', (msg) => {
  if (msg.author.bot) return

  if (spamblockMessage === false) {
    spamblockNotifyMessage = msg
  }

  msg.channel.getMessages(2, spamblockNotifyMessage.id)
  .then((msgs) => {
    if ((analyzeMessage(msgs[0], msg) >= 90 && msg.author.id === msgs[0].author.id) && (analyzeMessage(msgs[1], msg) >= 90) && msg.author.id === msgs[1].author.id) {
      msg.channel.unsendMessage(msg.id)
      if (spamblockMessage === false) {
        spamblockMessage = true
        msg.channel.createMessage('```SPAMBLOCK™: Spam detected. Please don\'t spam.```')
        .then((nmsg) => {
          spamblockNotifyMessage = nmsg
          setTimeout(() => {
            spamblockMessage = false
            nmsg.delete()
          }, 3000)
        })
      }
    }
  }, (err) => {
    logger.logConsole(err, 'err')
  })
})

// On: Bot Error
bot.on('error', (err, id) => {
  if (err) {
    logger.logConsole('Unknown error has occured to shard ' + id + '. Please see stack trace', 'err')
    throw err
  }
})
<commit_msg>Stuff<commit_after>// Dependencies
const Eris = require('eris')
const fs = require('fs')
const path = require('path')

// Setting up objects & vars
const config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json')))
let pf = config.prefix
let cooldown = false
let spamblockMessage = false
let spamblockNotifyMessage
let bot = new Eris.CommandClient(config.bot_token, {}, {
  'name': 'ModBot',
  'owner': 'CF12',
  'prefix': pf,
  'description': 'A moderation bot designed by CF12'
})

// Attempts to connect the bot
bot.connect()

// Class: Logger
class Logger {
  // Log to console
  logConsole (log, type) {
    if (type === 'info') {
      console.log('INFO > ' + log)
    } else if (type === 'err') {
      console.log('ERROR > ' + log)
    } else if (type === 'debug') {
      console.log('DEBUG > ' + log)
    } else {
      console.log('ERROR > Invalid console log')
    }
  }

  // Log to channel
  logChannel (log, type) {
    if (type === 'info') {
      return '```> INFO: ' + log + '```'
    } else if (type === 'err') {
      return '```> ERROR: ' + log + '```'
    } else {
      console.log('ERROR > Invalid channel log')
    }
  }
}

// Function: Kills message after duration in seconds
function timeoutMsg (promise, timeout) {
  return promise.then((msg) => {
    setTimeout(() => {
      msg.delete()
    }, timeout * 1000)
  })
}

// Function: Analyzes 2 messages for similarities, and returns a percentage of similarities
function analyzeMessage (msg1, msg2) {
  if (msg1.attachments.length > 0 && msg2.attachments.length > 0) {
    if (msg1.attachments[0].size === msg2.attachments[0].size) {
      if (msg1.attachments[0].width === msg2.attachments[0].width) {
        if (msg1.attachments[0].height === msg2.attachments[0].height) {
          return true
        }
      }
    }
    return false
  }

  msg1 = msg1.content.toUpperCase()
  msg2 = msg2.content.toUpperCase()
  let simchar = 0

  for (var i = 0; i < msg1.length; i++) {
    if (msg2.indexOf(msg1[i]) !== -1) simchar = simchar + 1
  }

  if ((simchar / msg2.length * 100) >= 90) return true
  return false
}

// Def Logger
const logger = new Logger()

// On: Bot Ready
bot.on('ready', () => {
  console.log('INFO > Bot activated')
  bot.editStatus('online', {
    'name': 'v0.1.1 - by CF12'
  })
})

/*
  Commands
*/

// Simple Ping Command
bot.registerCommand('ping', (msg, args) => {
  msg.channel.createMessage('Pong!')
}, {
  'description': 'Pings the bot',
  'fullDescription': 'Throws a ping pong ball at the bot'
})

// Text similarities db command
bot.registerCommand('compare', (msg, args) => {
  msg.channel.createMessage(analyzeMessage(args[0], args[1]))
}, {
  'description': 'DB Compares 2 strings',
  'fullDescription': ''
})

// Purge Command
bot.registerCommand('purge', (msg, args) => {
  if (args.length > 1) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('Invalid usage! Correct syntax: ' + pf + 'purge [1-100]', 'err')), 5)
    return
  } else if (args.length === 0) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('Purges messages: ' + pf + 'purge [1-100]', 'info')), 5)
    return
  } else if (!msg.member.permission.has('manageMessages')) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('User does not have the manageMessages permission!', 'err')), 5)
    return
  } else if (cooldown) {
    timeoutMsg(msg.channel.createMessage(logger.logChannel('Please wait a few seconds before trying again.', 'err')), 5)
    return
  }

  let arg = args[0]

  if (arg % 1 === 0 && arg >= 1 && arg <= 100) {
    cooldown = true
    msg.channel.purge(arg).then(() => {
      msg.channel.createMessage(logger.logChannel('Successfully purged ' + arg + ' message(s).', 'info')).then(msg => {
        setTimeout(() => {
          cooldown = false
          msg.delete()
        }, 3000)
      })
    })
  } else {
    return logger.logChannel('Invalid arguments! Use an integer from 1 to 100 for your parameter.', 'err')
  }
}, {
  'description': 'Purge messages in the current channel',
  'fullDescription': 'Purges a number of messages from channel the command is called in.',
  'usage': '<1-100>'
})

// Debug Command
bot.registerCommand('db', (msg, args) => {
  logger.logConsole(msg.member.permission.has('manageMessages'), 'debug')
}, {
  'description': 'Debug command',
  'fullDescription': 'Debug command. \'nouf said.'
})

bot.on('messageCreate', (msg) => {
  if (msg.author.bot) return

  if (spamblockMessage === false) {
    spamblockNotifyMessage = msg
  }

  msg.channel.getMessages(2, spamblockNotifyMessage.id)
  .then((msgs) => {
    if ((analyzeMessage(msgs[0], msg) && msg.author.id === msgs[0].author.id) && (analyzeMessage(msgs[1], msg)) && msg.author.id === msgs[1].author.id) {
      msg.channel.unsendMessage(msg.id)
      if (spamblockMessage === false) {
        spamblockMessage = true
        msg.channel.createMessage('```SPAMBLOCK™: Spam detected. Please don\'t spam.```')
        .then((nmsg) => {
          spamblockNotifyMessage = nmsg
          setTimeout(() => {
            spamblockMessage = false
            nmsg.delete()
          }, 3000)
        })
      }
    }
  }, (err) => {
    logger.logConsole(err, 'err')
  })
})

// On: Bot Error
bot.on('error', (err, id) => {
  if (err) {
    logger.logConsole('Unknown error has occured to shard ' + id + '. Please see stack trace', 'err')
    throw err
  }
})
<|endoftext|>


<commit_before>/**
  * @file the main file the makes everything work
  * @author Capuccino
  * @author Ovyerus
  * @copyright Copyright (c) 2018 Capuccino, Ovyerus and the repository contributors.
  * @license MIT
  */

// Imports
const Clara = require(`${__dirname}/lib/Clara`);
const fs = require('fs');
let config;

try {
    config = require(`${__dirname}/config.json`);
} catch(_) {
    config = {
        /** @see {Link} https://github.com/ClarityMoe/Clara/issues/133 */

        token: process.env.DISCORD_TOKEN,
        debug: process.env.DEBUG,
        promiseWarnings: process.env.ENABLE_PROMISE_WARNS || false,
        ibKey: process.env.IB_TOKEN,
        mainPrefix: process.env.DEFAULT_PREFIX,
        osuApiKey: process.env.OSU_API_TOKEN,
        sauceKey: process.env.SAUCENAO_TOKEN,
        soundCloudKey: process.env.SOUNDCLOUD_TOKEN,
        gameName: process.env.GAME_NAME,
        gameURL: process.env.GAME_URL,
        ownerID: process.env.BOT_OWNER_ID,
        maxShards: process.env.INSTANCES,
        ytSearchKey: process.env.YOUTUBE_TOKEN,
        discordBotsPWKey: process.env.DISCORD_PW_TOKEN,
        discordBotsOrgKey: process.env.DISCORD_ORG_TOKEN,
        twitchKey: process.env.TWITCH_TOKEN,
        nasaKey: process.env.NASA_KEY,
        redisURL: process.env.REDIS_URL || 'redis://127.0.0.1/0'
    };
}

// Globals
global.mainDir = __dirname;
global.utils = require(`${__dirname}/lib/modules/utils`);
global.logger = require(`${__dirname}/lib/modules/Logger`);
global.Promise = require('bluebird');
global.got = require('got');

// Bot stuff
const bot = new Clara(config, {
    seedVoiceConnections: true,
    maxShards: config.maxShards || 1,
    latencyThreshold: 420000000,
    defaultImageFormat: 'webp',
    defaultImageSize: 512,
    disableEvents: {
        TYPING_START: true
    }
});

bot.commandsDir = `${__dirname}/cmd`;
bot.unloadedPath = `${__dirname}/data/unloadedCommands.json`;

//Promise configuration
Promise.config({
    warnings: {wForgottenReturn: config.promiseWarnings || false},
    longStackTraces: config.promiseWarnings || false
});

if (!fs.existsSync(`${__dirname}/cache`)) fs.mkdirSync(`${__dirname}/cache/`);
if (fs.readdirSync(`${__dirname}/cache`).length) {
    // Clears out anything in the cache directory if it has something.
    fs.readdirSync(`${__dirname}/cache`).forEach(f => fs.unlinkSync(`${__dirname}/cache/${f}`));
}

require(`${__dirname}/lib/events`)(bot);
bot.connect();

exports.bot = bot;<commit_msg>handle nulls on some things<commit_after>/**
  * @file the main file the makes everything work
  * @author Capuccino
  * @author Ovyerus
  * @copyright Copyright (c) 2018 Capuccino, Ovyerus and the repository contributors.
  * @license MIT
  */

// Imports
const Clara = require(`${__dirname}/lib/Clara`);
const fs = require('fs');
let config;

try {
    config = require(`${__dirname}/config.json`);
} catch(_) {
    config = {
        /** @see {Link} https://github.com/ClarityMoe/Clara/issues/133 */

        token: process.env.DISCORD_TOKEN,
        debug: process.env.DEBUG,
        promiseWarnings: process.env.ENABLE_PROMISE_WARNS || false,
        ibKey: process.env.IB_TOKEN,
        mainPrefix: process.env.DEFAULT_PREFIX,
        osuApiKey: process.env.OSU_API_TOKEN,
        sauceKey: process.env.SAUCENAO_TOKEN,
        soundCloudKey: process.env.SOUNDCLOUD_TOKEN,
        gameName: process.env.GAME_NAME || null,
        gameURL: process.env.GAME_URL || null,
        ownerID: process.env.BOT_OWNER_ID,
        maxShards: process.env.INSTANCES || 1,
        ytSearchKey: process.env.YOUTUBE_TOKEN,
        discordBotsPWKey: process.env.DISCORD_PW_TOKEN,
        discordBotsOrgKey: process.env.DISCORD_ORG_TOKEN,
        twitchKey: process.env.TWITCH_TOKEN,
        nasaKey: process.env.NASA_KEY,
        redisURL: process.env.REDIS_URL || 'redis://127.0.0.1/0'
    };
}

// Globals
global.mainDir = __dirname;
global.utils = require(`${__dirname}/lib/modules/utils`);
global.logger = require(`${__dirname}/lib/modules/Logger`);
global.Promise = require('bluebird');
global.got = require('got');

// Bot stuff
const bot = new Clara(config, {
    seedVoiceConnections: true,
    maxShards: config.maxShards || 1,
    latencyThreshold: 420000000,
    defaultImageFormat: 'webp',
    defaultImageSize: 512,
    disableEvents: {
        TYPING_START: true
    }
});

bot.commandsDir = `${__dirname}/cmd`;
bot.unloadedPath = `${__dirname}/data/unloadedCommands.json`;

//Promise configuration
Promise.config({
    warnings: {wForgottenReturn: config.promiseWarnings || false},
    longStackTraces: config.promiseWarnings || false
});

if (!fs.existsSync(`${__dirname}/cache`)) fs.mkdirSync(`${__dirname}/cache/`);
if (fs.readdirSync(`${__dirname}/cache`).length) {
    // Clears out anything in the cache directory if it has something.
    fs.readdirSync(`${__dirname}/cache`).forEach(f => fs.unlinkSync(`${__dirname}/cache/${f}`));
}

require(`${__dirname}/lib/events`)(bot);
bot.connect();

exports.bot = bot;<|endoftext|>


<commit_before>var os = require('os');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
describe('nw in memory after quiting',function(){
	it('nw.exe should not be in memory after gui.App.quit is called on windows',function(done){
		this.timeout(0);
		if(os.platform() == "win32") {
			var app = spawn(process.execPath, [path.join(global.tests_dir,'nw-in-mem/package')])
			app.on('close',function(){
				var nwname = "nw.exe";
				var nwcount = 0;
				exec("tasklist", function(err, stdout, stderr) {
					if(err){ return console.log(err); }
					stdout.split('\n').filter(function(line){
		        var p=line.trim().split(/\s+/),pname=p[0];
		        if(pname.toLowerCase().indexOf(nwname)>=0)
		            nwcount++;
	    		});

		  		if(nwcount == 2)
		  			done();
		  		else if(nwcount > 2)
		  			done('nw.exe is still in memory after the quit of app');
				})
			});
		}
		else
			done();
	})
})<commit_msg>revise the timeout of nw-in-mem test<commit_after>var os = require('os');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
describe('nw in memory after quiting',function(){
  it('nw.exe should not be in memory after gui.App.quit is called on windows',function(done){
    this.timeout(0);
    if(os.platform() == "win32") {
      var app = spawn(process.execPath, [path.join(global.tests_dir,'nw-in-mem/package')])
      app.on('close',function(){
        var nwname = "nw.exe";
        var nwcount = 0;
        setTimeout(function() {
          exec("tasklist", function(err, stdout, stderr) {
            if(err){ return console.log(err); }
            stdout.split('\n').filter(function(line){
              var p=line.trim().split(/\s+/),pname=p[0];
              if(pname.toLowerCase().indexOf(nwname)>=0)
                  nwcount++;
            });

            if(nwcount == 2)
              done();
            else if(nwcount > 2)
              done('nw.exe is still in memory after the quit of app');
          })
        }, 500);
      });
    }
    else
      done();
  })
})<|endoftext|>


<commit_before>const $ = require('jquery');
const marked = require('marked');
const renderer = require('./renderer.js');
const page = require('./page.js');

$(document).ready(function(){
    mermaid.initialize({startOnLoad:true});

    var target = $("#view_wrapper");

    window.render_markdown = function(mdtext, filepath){
        renderer.init_number();
        renderer.filepath = filepath;

        //markdownをhtmlに
        var md = marked(mdtext, {renderer: renderer});
        var viewer = document.getElementById('view');
        viewer.innerHTML = md;

        //数式を描画
        MathJax.Hub.config.TeX.equationNumbers.chapterNum = '1';
        MathJax.Hub.config.TeX.equationNumbers.eqNum = 0;
        MathJax.Hub.Queue(['Typeset', MathJax.Hub, 'view']);
        MathJax.Hub.Queue(function () {
            //図を描画
            mermaid.init();
            //リンクの処理
            page.set_link_number();
            //改ページを計算
            page.calculate_pages();

            //改ページ部分の余白を設定
            //この余白は本文の余白ではないため
            //改ページの計算に含めてはいけない
            //そのため、calculate_pagesの後に設定し
            //PDFを書き出す直前に消す
            var $page_num = $('.page-num');
            $page_num.css({
               'border-bottom': '1px solid #000',
                'margin-bottom': '20mm',
            });
        });
    };

    $.ajax({
        url: target[0].attributes["src"].value,
    }).done(function(data){
        render_markdown(data, '');
    }).fail(function(data){
        console.log("This content failed to load.");
    });
});<commit_msg>#5 式番号をリセットする処理を追加<commit_after>const $ = require('jquery');
const marked = require('marked');
const renderer = require('./renderer.js');
const page = require('./page.js');

$(document).ready(function(){
    mermaid.initialize({startOnLoad:true});

    var target = $("#view_wrapper");

    window.render_markdown = function(mdtext, filepath){
        renderer.init_number();
        renderer.filepath = filepath;

        //markdownをhtmlに
        var md = marked(mdtext, {renderer: renderer});
        var viewer = document.getElementById('view');
        viewer.innerHTML = md;

        //式番号をリセット
        MathJax.Hub.config.TeX.equationNumbers.chapterNum = '1';
        MathJax.Hub.config.TeX.equationNumbers.eqNum = 0;
        MathJax.Hub.Queue(
          ["resetEquationNumbers",MathJax.InputJax.TeX],
          ["PreProcess",MathJax.Hub],
          ["Reprocess",MathJax.Hub]
        );
        //数式を描画
        MathJax.Hub.Queue(['Typeset', MathJax.Hub, 'view']);
        MathJax.Hub.Queue(function () {
            //図を描画
            mermaid.init();
            //リンクの処理
            page.set_link_number();
            //改ページを計算
            page.calculate_pages();

            //改ページ部分の余白を設定
            //この余白は本文の余白ではないため
            //改ページの計算に含めてはいけない
            //そのため、calculate_pagesの後に設定し
            //PDFを書き出す直前に消す
            var $page_num = $('.page-num');
            $page_num.css({
               'border-bottom': '1px solid #000',
                'margin-bottom': '20mm',
            });
        });
    };

    $.ajax({
        url: target[0].attributes["src"].value,
    }).done(function(data){
        render_markdown(data, '');
    }).fail(function(data){
        console.log("This content failed to load.");
    });
});<|endoftext|>


<commit_before>/*jslint node: true */
/*jslint newcap: true */
/*global before, beforeEach, afterEach, after, describe, it */
/*jslint nomen: true */
"use strict";

var assert = require('assert');
var English = require('yadda').localisation.English;
var dbhelpers = require('./common/DbHelpers');
var tms;
var clubname;
var squadname;
var agelimit;
var cityname;
var email;
var season;

module.exports = (function () {

    return English.library()

        // Background
        .given("The user $firstname $lastname is logged into the site and is an administrator for the club $club in $city playing at $field in $suburb for the current season.",
            function (firstname, lastname, club, city, field, suburb, next) {
                clubname = club;
                cityname = city;
                tms = this.interpreter_context.tms;
                var today = new Date(),
                    createdUsers = this.interpreter_context.createdUsers,
                    createdClubs = this.interpreter_context.createdClubs,
                    usersDb = this.interpreter_context.usersDb,
                    clubsDb = this.interpreter_context.clubsDb,
                    dbh = new dbhelpers();
                season = today.getFullYear().toString();
                // create the sample user, making up the password and email address as being declarative in the feature makes it a bit easier to manage. Email is the key
                email = firstname + '.' + lastname + '@' + 'gmail.com';
                // create the sample club name
                dbh.CreateClub(clubsDb, createdClubs, club, city, field, suburb, email, next, false);
                dbh.CreateUser(usersDb, createdUsers, firstname, lastname, 'SomePassword', email, '', true, next);
            })

        // Scenario 1
        .given("User gives the squad name $squadname and an age limit of $agelimit", function (squad, age, next) {
            squadname = squad;
            agelimit = age;
            next();
        })

        .when("the squad is saved", function (next) {
            var createdSquads = this.interpreter_context.createdSquads,
                club = clubname,
                city = cityname,
                squad = squadname,
                s = season;
            tms.CreateSquad(clubname, cityname, squadname, season, agelimit, email,
                function (err) {
                    assert.ifError(err, "Error in CreateSquad");
                    //saving the created club for cleaning up later on
                    createdSquads.push({ squad: squad, season: s });
                    next();
                });
        })

        .then("the user will also be marked as the creator of the squad", function (next) {
            var dbh = new dbhelpers();
            dbh.GetSquad(this.interpreter_context.squadsDb, clubname, cityname, squadname, season, function (err, res) {
                assert.ifError(err, "Error in getting the squad back");
                assert.equal(res.admin, email, 'creator should have been set to ' + email + ' instead it was ' + res.admin);
                assert.equal(res.agelimit, agelimit, 'fieldname should have been set to ' + agelimit + ' instead it was ' + res.agelimit);
                next();
            });
        });
}());
<commit_msg>repairs to test<commit_after>/*jslint node: true */
/*jslint newcap: true */
/*global before, beforeEach, afterEach, after, describe, it */
/*jslint nomen: true */
"use strict";

var assert = require('assert');
var English = require('yadda').localisation.English;
var dbhelpers = require('./common/DbHelpers');
var tms;
var clubname;
var squadname;
var agelimit;
var cityname;
var email;
var season;

module.exports = (function () {

    return English.library()

        // Background
        .given("The user $firstname $lastname is logged into the site and is an administrator for the club $club in $city playing at $field in $suburb for the current season.",
            function (firstname, lastname, club, city, field, suburb, next) {
                clubname = club;
                cityname = city;
                tms = this.interpreter_context.tms;
                var today = new Date(),
                    createdUsers = this.interpreter_context.createdUsers,
                    createdClubs = this.interpreter_context.createdClubs,
                    usersDb = this.interpreter_context.usersDb,
                    clubsDb = this.interpreter_context.clubsDb,
                    dbh = new dbhelpers();
                season = today.getFullYear().toString();
                // create the sample user, making up the password and email address as being declarative in the feature makes it a bit easier to manage. Email is the key
                email = firstname + '.' + lastname + '@' + 'gmail.com';
                // create the sample club name
                dbh.CreateClub(clubsDb, createdClubs, club, city, field, suburb, email, next, false);
                dbh.CreateUser(usersDb, createdUsers, firstname, lastname, 'SomePassword', email, '', true, next);
            })

        // Scenario 1
        .given("User gives the squad name $squadname and an age limit of $agelimit", function (squad, age, next) {
            squadname = squad;
            agelimit = age;
            next();
        })

        .when("the squad is saved", function (next) {
            var createdSquads = this.interpreter_context.createdSquads;
            tms.CreateSquad(clubname, cityname, squadname, season, agelimit, email,
                function (err) {
                    assert.ifError(err, "Error in CreateSquad");
                    //saving the created club for cleaning up later on
                    createdSquads.push({ squad: squadname, season: season });
                    next();
                });
        })

        .then("the user will also be marked as the creator of the squad", function (next) {
            var dbh = new dbhelpers();
            dbh.GetSquad(this.interpreter_context.squadsDb, clubname, cityname, squadname, season, function (err, res) {
                assert.ifError(err, "Error in getting the squad back");
                assert.equal(res.admin, email, 'creator should have been set to ' + email + ' instead it was ' + res.admin);
                assert.equal(res.agelimit, agelimit, 'fieldname should have been set to ' + agelimit + ' instead it was ' + res.agelimit);
                next();
            });
        });
}());
<|endoftext|>