<commit_before>/*jslint indent: 2 */
/*global window: false, XMLHttpRequest: false, chrome: false, btoa: false */
"use strict";

var TogglButton = {
  $user: null,
  $apiUrl: "https://www.toggl.com/api/v7",
  $newApiUrl: "https://new.toggl.com/api/v8",
  $sites: new RegExp([
    'asana\\.com',
    'podio\\.com',
    'trello\\.com',
    'github\\.com',
    'bitbucket\\.org',
    'gitlab\\.com',
    'redbooth\\.com',
    'teamweek\\.com',
    'basecamp\\.com',
    'unfuddle\\.com',
    'worksection\\.com',
    'pivotaltracker\\.com',
    'producteev\\.com',
    'redmine\\.org'].join('|')),
  $curEntryId: null,

  checkUrl: function (tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete') {
      if (TogglButton.$sites.test(tab.url)) {
        TogglButton.setPageAction(tabId);
      } else if (/toggl\.com\/track/.test(tab.url)) {
        TogglButton.fetchUser(TogglButton.$apiUrl);
      } else if (/toggl\.com\/app/.test(tab.url)) {
        TogglButton.fetchUser(TogglButton.$newApiUrl);
      }
    }
  },

  fetchUser: function (apiUrl) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", apiUrl + "/me?with_related_data=true", true);
    xhr.onload = function () {
      if (xhr.status === 200) {
        var projectMap = {}, resp = JSON.parse(xhr.responseText);
        if (resp.data.projects) {
          resp.data.projects.forEach(function (project) {
            projectMap[project.name] = project.id;
          });
        }
        TogglButton.$user = resp.data;
        TogglButton.$user.projectMap = projectMap;
      } else if (apiUrl === TogglButton.$apiUrl) {
        TogglButton.fetchUser(TogglButton.$newApiUrl);
      }
    };
    xhr.send();
  },

  createTimeEntry: function (timeEntry) {
    var start = new Date(),
      xhr = new XMLHttpRequest(),
      entry = {
        time_entry: {
          start: start.toISOString(),
          description: timeEntry.description,
          wid: TogglButton.$user.default_wid,
          pid: timeEntry.projectId || null,
          billable: timeEntry.billable || false,
          duration: -(start.getTime() / 1000),
          created_with: timeEntry.createdWith || 'TogglButton'
        }
      };
    if (timeEntry.projectName !== undefined) {
      entry.time_entry.pid = TogglButton.$user.projectMap[timeEntry.projectName];
    }
    xhr.open("POST", TogglButton.$newApiUrl + "/time_entries", true);
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token'));
    // handle response
    xhr.addEventListener('load', function (e) {
      var responseData, entryId;
      responseData = JSON.parse(xhr.responseText);
      entryId = responseData && responseData.data && responseData.data.id;
      TogglButton.$curEntryId = entryId;
    });
    xhr.send(JSON.stringify(entry));
  },

  stopTimeEntry: function (entryId) {
    entryId = entryId || TogglButton.$curEntryId;
    if (!entryId) {
      return;
    }
    var xhr = new XMLHttpRequest();

    // PUT https://www.toggl.com/api/v8/time_entries/{time_entry_id}/stop
    xhr.open("PUT", TogglButton.$newApiUrl + "/time_entries/" + entryId + "/stop", true);
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token'));
    xhr.send();
  },

  setPageAction: function (tabId) {
    var imagePath = 'images/inactive-19.png';
    if (TogglButton.$user !== null) {
      imagePath = 'images/active-19.png';
    }
    chrome.pageAction.setIcon({
      tabId: tabId,
      path: imagePath
    });
    chrome.pageAction.show(tabId);
  },

  newMessage: function (request, sender, sendResponse) {
    if (request.type === 'activate') {
      TogglButton.setPageAction(sender.tab.id);
      sendResponse({success: TogglButton.$user !== null, user: TogglButton.$user});
    } else if (request.type === 'timeEntry') {
      TogglButton.createTimeEntry(request);
    } else if (request.type === 'stop') {
      TogglButton.stopTimeEntry();
    }
  }

};

chrome.pageAction.onClicked.addListener(function (tab) {
  if (TogglButton.$user === null) {
    chrome.tabs.create({url: 'https://new.toggl.com/#login'});
  }
});

TogglButton.fetchUser(TogglButton.$apiUrl);
chrome.tabs.onUpdated.addListener(TogglButton.checkUrl);
chrome.extension.onMessage.addListener(TogglButton.newMessage);
<commit_msg>added sifter to background<commit_after>/*jslint indent: 2 */
/*global window: false, XMLHttpRequest: false, chrome: false, btoa: false */
"use strict";

var TogglButton = {
  $user: null,
  $apiUrl: "https://www.toggl.com/api/v7",
  $newApiUrl: "https://new.toggl.com/api/v8",
  $sites: new RegExp([
    'asana\\.com',
    'podio\\.com',
    'trello\\.com',
    'github\\.com',
    'bitbucket\\.org',
    'gitlab\\.com',
    'redbooth\\.com',
    'teamweek\\.com',
    'basecamp\\.com',
    'unfuddle\\.com',
    'worksection\\.com',
    'pivotaltracker\\.com',
    'producteev\\.com',
    'sifterapp\\.com'].join('|')),
  $curEntryId: null,

  checkUrl: function (tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete') {
      if (TogglButton.$sites.test(tab.url)) {
        TogglButton.setPageAction(tabId);
      } else if (/toggl\.com\/track/.test(tab.url)) {
        TogglButton.fetchUser(TogglButton.$apiUrl);
      } else if (/toggl\.com\/app/.test(tab.url)) {
        TogglButton.fetchUser(TogglButton.$newApiUrl);
      }
    }
  },

  fetchUser: function (apiUrl) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", apiUrl + "/me?with_related_data=true", true);
    xhr.onload = function () {
      if (xhr.status === 200) {
        var projectMap = {}, resp = JSON.parse(xhr.responseText);
        if (resp.data.projects) {
          resp.data.projects.forEach(function (project) {
            projectMap[project.name] = project.id;
          });
        }
        TogglButton.$user = resp.data;
        TogglButton.$user.projectMap = projectMap;
      } else if (apiUrl === TogglButton.$apiUrl) {
        TogglButton.fetchUser(TogglButton.$newApiUrl);
      }
    };
    xhr.send();
  },

  createTimeEntry: function (timeEntry) {
    var start = new Date(),
      xhr = new XMLHttpRequest(),
      entry = {
        time_entry: {
          start: start.toISOString(),
          description: timeEntry.description,
          wid: TogglButton.$user.default_wid,
          pid: timeEntry.projectId || null,
          billable: timeEntry.billable || false,
          duration: -(start.getTime() / 1000),
          created_with: timeEntry.createdWith || 'TogglButton'
        }
      };
    if (timeEntry.projectName !== undefined) {
      entry.time_entry.pid = TogglButton.$user.projectMap[timeEntry.projectName];
    }
    xhr.open("POST", TogglButton.$newApiUrl + "/time_entries", true);
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token'));
    // handle response
    xhr.addEventListener('load', function (e) {
      var responseData, entryId;
      responseData = JSON.parse(xhr.responseText);
      entryId = responseData && responseData.data && responseData.data.id;
      TogglButton.$curEntryId = entryId;
    });
    xhr.send(JSON.stringify(entry));
  },

  stopTimeEntry: function (entryId) {
    entryId = entryId || TogglButton.$curEntryId;
    if (!entryId) {
      return;
    }
    var xhr = new XMLHttpRequest();

    // PUT https://www.toggl.com/api/v8/time_entries/{time_entry_id}/stop
    xhr.open("PUT", TogglButton.$newApiUrl + "/time_entries/" + entryId + "/stop", true);
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token'));
    xhr.send();
  },

  setPageAction: function (tabId) {
    var imagePath = 'images/inactive-19.png';
    if (TogglButton.$user !== null) {
      imagePath = 'images/active-19.png';
    }
    chrome.pageAction.setIcon({
      tabId: tabId,
      path: imagePath
    });
    chrome.pageAction.show(tabId);
  },

  newMessage: function (request, sender, sendResponse) {
    if (request.type === 'activate') {
      TogglButton.setPageAction(sender.tab.id);
      sendResponse({success: TogglButton.$user !== null, user: TogglButton.$user});
    } else if (request.type === 'timeEntry') {
      TogglButton.createTimeEntry(request);
    } else if (request.type === 'stop') {
      TogglButton.stopTimeEntry();
    }
  }

};

chrome.pageAction.onClicked.addListener(function (tab) {
  if (TogglButton.$user === null) {
    chrome.tabs.create({url: 'https://new.toggl.com/#login'});
  }
});

TogglButton.fetchUser(TogglButton.$apiUrl);
chrome.tabs.onUpdated.addListener(TogglButton.checkUrl);
chrome.extension.onMessage.addListener(TogglButton.newMessage);
<|endoftext|>


<commit_before>/*eslint-env node */

var m = require("mithril");

var tabs = require("./polythene_tabs");
tabs.onClick(function(newIndex, oldIndex) {
    var h = require("./headers")[newIndex];
    grid.setRef(require("./firebase_ref").child(h.field), h.columns);
});

var t = document.createElement("div");
m.mount(t, tabs.view);

var grid = require("./w2ui_grid");
grid.view.style.height = "calc(100% - 48px)";

var wrapper = document.createElement("div");
wrapper.appendChild(t);
wrapper.appendChild(grid.view);
module.exports = wrapper;
<commit_msg>Define "grid" variable before it's used.<commit_after>/*eslint-env node */

var m = require("mithril");

var grid = require("./w2ui_grid");
grid.view.style.height = "calc(100% - 48px)";

var tabs = require("./polythene_tabs");
tabs.onClick(function(newIndex, oldIndex) {
    var h = require("./headers")[newIndex];
    grid.setRef(require("./firebase_ref").child(h.field), h.columns);
});

var t = document.createElement("div");
m.mount(t, tabs.view);

var wrapper = document.createElement("div");
wrapper.appendChild(t);
wrapper.appendChild(grid.view);
module.exports = wrapper;
<|endoftext|>


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

    angular
        .module('documents')
        .component('profileSummary', {
            templateUrl: 'partials/profile-summary.html',
            controller: ProfileSummaryComponent,
            controllerAs: 'vm'
        });

    ProfileSummaryComponent.$inject = [
        'context',
        'DocumentTypesService'
    ];

    function ProfileSummaryComponent(context, DocumentTypesService) {
        const vm = this;
        vm.researchEntity = context.getResearchEntity();
        vm.changeChart = changeChart;

        vm.documentsByYear = {};
        vm.documentsByType = {};
        vm.invitedTalksByYear = {};

        const previewDefaultOptions = {
            chart: {
                showLabels: false,
                showLegend: false,
                showControls: false,
                width: undefined,
                height: 250,
                duration: 300,
                reduceXTicks: true,
                xAxis: {
                    axisLabel: ''
                },
                yAxis: {
                    axisLabel: ''
                }
            }
        };
        const mainChartDefaultOptions = {
            chart: {
                showLabels: true,
                showLegend: true,
                showControls: true,
                width: undefined,
                height: 420,
                margin: {
                    top: 40,
                    right: 20,
                    bottom: 65,
                    left: 50
                },
                duration: 300,
                reduceXTicks: false
            }
        };

        vm.documentsByYear.title = 'Documents by year';
        vm.documentsByYear.data = [];
        vm.documentsByYear.baseOptions = {
            chart: {
                type: 'multiBarChart',
                x: d => d.year,
                y: d => d.count,
                showValues: true,
                stacked: true,
                xAxis: {
                    axisLabel: 'Year',
                    rotateLabels: 50,
                    showMaxMin: false
                },
                yAxis: {
                    axisLabel: '# documents',
                    axisLabelDistance: -10
                }
            }
        };

        vm.invitedTalksByYear.title = 'Invited talks by year';
        vm.invitedTalksByYear.data = [];
        vm.invitedTalksByYear.baseOptions = {
            chart: {
                type: 'multiBarChart',
                x: d => d.year,
                y: d => d.count,
                showValues: true,
                xAxis: {
                    axisLabel: 'Year',
                    rotateLabels: 50,
                    showMaxMin: false
                },
                yAxis: {
                    axisLabel: '# invited talks',
                    axisLabelDistance: -10
                }
            }
        };

        vm.documentsByType.title = 'Documents by Type';
        vm.documentsByType.data = [];
        vm.documentsByType.baseOptions = {
            chart: {
                type: 'pieChart',
                x: function (d) {
                    return d.type;
                },
                y: function (d) {
                    return d.count;
                },
                labelThreshold: 0.02,
                labelSunbeamLayout: true,
                legend: {
                    margin: {
                        top: 5,
                        right: 35,
                        bottom: 5,
                        left: 0
                    }
                }
            }
        };

        /* jshint ignore:start */
        vm.$onInit = async () => {
            const charts = ['ConferencesByYear', 'ArticlesByYear', 'BooksByYear', 'BookChaptersByYear', 'InvitedTalksByYear', 'DocumentsByType'];
            const chartsData = await vm.researchEntity.all('charts').getList({charts: charts});

            const yearRange = getYearRange(chartsData);

            vm.documentsByYear.data.push({
                key: 'Journal',
                values: getDocumentsByYear(chartsData[1], yearRange)
            });
            vm.documentsByYear.data.push({
                key: 'Conference',
                values: getDocumentsByYear(chartsData[1], yearRange)
            });
            vm.documentsByYear.data.push({
                key: "Book",
                values: getDocumentsByYear(chartsData[2], yearRange)
            });
            vm.documentsByYear.data.push({
                key: 'Book Chapter',
                values: getDocumentsByYear(chartsData[3], yearRange)
            });

            vm.documentsByYear.options = getDefaultOptions(vm.documentsByYear.baseOptions, previewDefaultOptions);

            vm.invitedTalksByYear.data.push({
                key: 'Invited talk',
                values: getDocumentsByYear(chartsData[4], yearRange)
            });
            vm.invitedTalksByYear.options = getDefaultOptions(vm.invitedTalksByYear.baseOptions, previewDefaultOptions);

            vm.documentsByType.data = chartsData[5].map(d => ({
                type: DocumentTypesService.getDocumentTypeLabel(d.type),
                count: parseInt(d.count)
            }));
            vm.documentsByType.options = getDefaultOptions(vm.documentsByType.baseOptions, previewDefaultOptions);

            changeChart(vm.documentsByYear);

        };

        /* jshint ignore:end */

        function getYearRange(chartsData) {
            const years = _.flatten(chartsData).map(v => parseInt(v.year, 10));

            return {
                min: _.isEmpty(years) ? 0 : _.min(years),
                max: _.isEmpty(years) ? 0 : _.max(years)
            };
        }

        function getDocumentsByYear(data, yearRange) {
            const newData = data.map(d => ({
                year: parseInt(d.year, 10),
                count: parseInt(d.count, 10)
            }));
            for (let y = yearRange.min; y <= yearRange.max; y++) {
                if (!_.find(newData, {year: y}))
                    newData.push({count: 0, year: y});
            }

            newData.sort((a, b) => a.year < b.year ? -1 : a.year > b.year ? 1 : 0);

            return newData;
        }

        function changeChart(chart) {
            vm.mainChart = _.cloneDeep(chart);
            vm.mainChart.options = getDefaultOptions(vm.mainChart.baseOptions, mainChartDefaultOptions);
        }

        function getDefaultOptions(options, defaults) {
            const newOptions = {};
            newOptions.chart = Object.assign({}, options.chart, _.cloneDeep(defaults.chart));
            return newOptions;

        }
    }
})();<commit_msg>Changed axis labels<commit_after>(function () {
    "use strict";

    angular
        .module('documents')
        .component('profileSummary', {
            templateUrl: 'partials/profile-summary.html',
            controller: ProfileSummaryComponent,
            controllerAs: 'vm'
        });

    ProfileSummaryComponent.$inject = [
        'context',
        'DocumentTypesService'
    ];

    function ProfileSummaryComponent(context, DocumentTypesService) {
        const vm = this;
        vm.researchEntity = context.getResearchEntity();
        vm.changeChart = changeChart;

        vm.documentsByYear = {};
        vm.documentsByType = {};
        vm.invitedTalksByYear = {};

        const previewDefaultOptions = {
            chart: {
                showLabels: false,
                showLegend: false,
                showControls: false,
                width: undefined,
                height: 250,
                duration: 300,
                reduceXTicks: true,
                xAxis: {
                    axisLabel: '',
                    tickFormat: d => d3.format('')(d)
                },
                yAxis: {
                    axisLabel: '',
                    tickFormat: d => d3.format('')(d)
                },
                valueFormat: d => d3.format('')(d)
            }
        };
        const mainChartDefaultOptions = {
            chart: {
                showLabels: true,
                showLegend: true,
                showControls: true,
                width: undefined,
                height: 420,
                margin: {
                    top: 40,
                    right: 20,
                    bottom: 65,
                    left: 50
                },
                duration: 300,
                reduceXTicks: false,
                xAxis: {
                    tickFormat: d => d3.format('')(d)
                },
                yAxis: {
                    tickFormat: d => d3.format('')(d)
                },
                valueFormat: d => d3.format('')(d)
            }
        };

        vm.documentsByYear.title = 'Documents by year';
        vm.documentsByYear.data = [];
        vm.documentsByYear.baseOptions = {
            chart: {
                type: 'multiBarChart',
                x: d => d.year,
                y: d => d.count,
                showValues: true,
                stacked: true,
                xAxis: {
                    axisLabel: '',
                    rotateLabels: 50,
                    showMaxMin: false
                },
                yAxis: {
                    axisLabel: '',
                    axisLabelDistance: -10
                }
            }
        };

        vm.invitedTalksByYear.title = 'Invited talks by year';
        vm.invitedTalksByYear.data = [];
        vm.invitedTalksByYear.baseOptions = {
            chart: {
                type: 'multiBarChart',
                x: d => d.year,
                y: d => d.count,
                showValues: true,
                xAxis: {
                    axisLabel: '',
                    rotateLabels: 50,
                    showMaxMin: false
                },
                yAxis: {
                    axisLabel: '',
                    axisLabelDistance: -10
                }
            }
        };

        vm.documentsByType.title = 'Documents by Type';
        vm.documentsByType.data = [];
        vm.documentsByType.baseOptions = {
            chart: {
                type: 'pieChart',
                x: function (d) {
                    return d.type;
                },
                y: function (d) {
                    return d.count;
                },
                labelThreshold: 0.02,
                labelSunbeamLayout: true,
                legend: {
                    margin: {
                        top: 5,
                        right: 35,
                        bottom: 5,
                        left: 0
                    }
                }
            }
        };

        /* jshint ignore:start */
        vm.$onInit = async () => {
            const charts = ['ConferencesByYear', 'ArticlesByYear', 'BooksByYear', 'BookChaptersByYear', 'InvitedTalksByYear', 'DocumentsByType'];
            const chartsData = await vm.researchEntity.all('charts').getList({charts: charts});

            const yearRange = getYearRange(chartsData);

            vm.documentsByYear.data.push({
                key: 'Journal',
                values: getDocumentsByYear(chartsData[1], yearRange)
            });
            vm.documentsByYear.data.push({
                key: 'Conference',
                values: getDocumentsByYear(chartsData[1], yearRange)
            });
            vm.documentsByYear.data.push({
                key: "Book",
                values: getDocumentsByYear(chartsData[2], yearRange)
            });
            vm.documentsByYear.data.push({
                key: 'Book Chapter',
                values: getDocumentsByYear(chartsData[3], yearRange)
            });

            vm.documentsByYear.options = getDefaultOptions(vm.documentsByYear.baseOptions, previewDefaultOptions);

            vm.invitedTalksByYear.data.push({
                key: 'Invited talk',
                values: getDocumentsByYear(chartsData[4], yearRange)
            });
            vm.invitedTalksByYear.options = getDefaultOptions(vm.invitedTalksByYear.baseOptions, previewDefaultOptions);

            vm.documentsByType.data = chartsData[5].map(d => ({
                type: DocumentTypesService.getDocumentTypeLabel(d.type),
                count: parseInt(d.count)
            }));
            vm.documentsByType.options = getDefaultOptions(vm.documentsByType.baseOptions, previewDefaultOptions);

            changeChart(vm.documentsByYear);

        };

        /* jshint ignore:end */

        function getYearRange(chartsData) {
            const years = _.flatten(chartsData).map(v => parseInt(v.year, 10));

            return {
                min: _.isEmpty(years) ? 0 : _.min(years),
                max: _.isEmpty(years) ? 0 : _.max(years)
            };
        }

        function getDocumentsByYear(data, yearRange) {
            const newData = data.map(d => ({
                year: parseInt(d.year, 10),
                count: parseInt(d.count, 10)
            }));
            for (let y = yearRange.min; y <= yearRange.max; y++) {
                if (!_.find(newData, {year: y}))
                    newData.push({count: 0, year: y});
            }

            newData.sort((a, b) => a.year < b.year ? -1 : a.year > b.year ? 1 : 0);

            return newData;
        }

        function changeChart(chart) {
            vm.mainChart = _.cloneDeep(chart);
            vm.mainChart.options = getDefaultOptions(vm.mainChart.baseOptions, mainChartDefaultOptions);
        }

        function getDefaultOptions(options, defaults) {
            const newOptions = {};
            newOptions.chart = Object.assign({}, options.chart, _.cloneDeep(defaults.chart));
            newOptions.chart.margin = Object.assign({}, options.chart.margin, _.cloneDeep(defaults.chart.margin));
            newOptions.chart.xAxis = Object.assign({}, options.chart.xAxis, _.cloneDeep(defaults.chart.xAxis));
            newOptions.chart.yAxis = Object.assign({}, options.chart.yAxis, _.cloneDeep(defaults.chart.yAxis));
            return newOptions;

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


<commit_before>mini.Module(
	"engine/map/entity"
)
.requires(
	"engine/map/entityrepository",
	"engine/rendering/animation",
	"engine/time/tween",
	"behaviour/trait"
)
.defines(function(
	EntityRepository,
	Animation,
	Tween,
	Trait
) {
	var Entity = mini.Class.subclass({
		initialize: function(x, y, settings) {
			this.stateAnimations = {};

			this.aabb = new Jello.AABB(
				new Jello.Vector2(x, y),
				new Jello.Vector2(x + 4, y + 4)
			);

			this.pos = Vector2.Zero.copy();
			this.offset = Vector2.Zero.copy();

			// Process settings.
			settings = settings || {};
			for( var s in settings ) {
				this[s] = settings[s];
			}
		},
		state: function(name) {
			if(typeof name === "undefined") return this.__state__;
			if(typeof name === "string") {
				this.__state__ = name;
			} else if(typeof name === "function") {
				this.__state__ = name(this);
			} else {
				throw "incompatible state data type";
			};

			if(typeof this.stateAnimations[name] !== "undefined")
				this.animation = this.stateAnimations[name];
		},
		addStateAnimation: function(name, sheet, frameTime, order) {
			this.stateAnimations[name] = new Animation(sheet, frameTime, order);
		},

		// Updating.
		update: function(timePassed) {
			if(typeof this.animation !== "undefined")
				this.animation.update(timePassed);
		},
		draw: function() {

		},
		debugDraw: function(debugDraw) {
			if(typeof this.animation !== "undefined")
				this.animation.draw(this.aabb);
		},

		// Utilities.
		contains: function(point) {
			return this.aabb.contains(point);
		}

	});

	EntityRepository.addClass("Entity", Entity);

	return Entity;
});
<commit_msg>added additional getter and setter in Entity<commit_after>mini.Module(
	"engine/map/entity"
)
.requires(
	"engine/map/entityrepository",
	"engine/rendering/animation",
	"engine/time/tween",
	"behaviour/trait"
)
.defines(function(
	EntityRepository,
	Animation,
	Tween,
	Trait
) {
	var Entity = mini.Class.subclass({
		initialize: function(x, y, settings) {
			this.stateAnimations = {};

			this.aabb = new Jello.AABB(
				new Jello.Vector2(x, y),
				new Jello.Vector2(x + 4, y + 4)
			);

			this.pos = Vector2.Zero.copy();
			this.offset = Vector2.Zero.copy();

			// Process settings.
			settings = settings || {};
			for( var s in settings ) {
				this[s] = settings[s];
			}
		},
		state: function(name) {
			if(typeof name === "undefined") return this.__state__;
			if(typeof name === "string") {
				this.__state__ = name;
			} else if(typeof name === "function") {
				this.__state__ = name(this);
			} else {
				throw "incompatible state data type";
			};

			if(typeof this.stateAnimations[name] !== "undefined")
				this.animation = this.stateAnimations[name];
		},

		/*
		 * Rendering/Animation
		 */
		addStateAnimation: function(name, sheet, frameTime, order) {
			this.stateAnimations[name] = new Animation(sheet, frameTime, order);
		},

		/*
		 * Physics
		 */
		setBody: function(body) {
			this.body = body;
		},

		getBody: function() {
			return this.body;
		},

		/*
		 * Behavior
		 */
		setTrait: function(trait) {
			this.trait = trait;
		},

		getTrait: function() {
			return this.trait;
		},

		// Updating.
		update: function(timePassed) {
			var trait = this.getTrait();
			if(typeof trait !== "undefined")
				trait.update(timePassed);

			if(typeof this.animation !== "undefined")
				this.animation.update(timePassed);
		},
		draw: function() {

		},
		debugDraw: function(debugDraw) {
			if(typeof this.animation !== "undefined")
				this.animation.draw(this.aabb);
		},

		// Utilities.
		contains: function(point) {
			return this.aabb.contains(point);
		}

	});

	EntityRepository.addClass("Entity", Entity);

	return Entity;
});
<|endoftext|>


<commit_before>function Endpoint(name) {
  this.name = name
  this.description = ''
  this.summary = ''
  this.request = {}
  this.request.bodies = []
  this.request.headers = '{}'
  this.responses = []
}

Endpoint.prototype = {
    set ItemId(id) {
      this.itemId = id
    },

    get Path() {
      return this.request.path
    },
    set Path(path) {
      this.request.path = path
    },
    get Method() {
      return this.request.method
    },
    set Method(requestMethod) {
      this.request.method = requestMethod.toLowerCase()
    },
    get Name() {
      return this.name
    },
    get Headers() {
      return JSON.parse(this.request.headers)
    },
    set Headers(headers) {
      this.request.headers = JSON.stringify(headers)
    },
    get QueryString() {
      return this.request.queryString
    },
    set QueryString(queryString) {
      this.request.queryString = JSON.stringify(queryString)
    },
    get Before() {
      return this.middlewareBefore
    },
    set Before(before) {
      this.middlewareBefore = before
    },
    set Body(body) {
      body.body = JSON.stringify(body.body)
      this.request.bodies.push(body)
    },
    get Body() {
      if (this.request.bodies.length > 0) {
        return this.request.bodies[0]
      }
      return []
    },
    set QueryString(queryString) {
      queryString = JSON.stringify(queryString)
      this.request.queryString = queryString
    },
    get QueryString() {
      if (!this.request.queryString) {
        this.request.queryString = '{}'
      }
      return JSON.parse(this.request.queryString)
    },
    set PathParams(uriParams) {
      //uriParams = JSON.stringify(uriParams)
      this.request.pathParams = uriParams
    },
    get PathParams() {
      return this.request.pathParams
    },
    set Responses(res) {
      this.responses = res
    },
    get Responses() {
      return this.responses
    },

    set SLData(data) {
      for(var key in data) {
        this[key] = data[key]
      }
    },

    set Description(desc) {
      this.description = desc
    },
    get Description() {
      return this.description || ''
    },

    set Summary(summary) {
      if (summary.length > 120) {
        this.summary = summary.substring(0, 119)
      }
      else {
        this.summary = summary
      }
    },

    get Summary() {
      return this.summary || ''
    }
}

module.exports = Endpoint
<commit_msg>remove redundant set/get for query string<commit_after>function Endpoint(name) {
  this.name = name
  this.description = ''
  this.summary = ''
  this.request = {}
  this.request.bodies = []
  this.request.headers = '{}'
  this.responses = []
}

Endpoint.prototype = {
    set ItemId(id) {
      this.itemId = id
    },

    get Path() {
      return this.request.path
    },
    set Path(path) {
      this.request.path = path
    },
    get Method() {
      return this.request.method
    },
    set Method(requestMethod) {
      this.request.method = requestMethod.toLowerCase()
    },
    get Name() {
      return this.name
    },
    get Headers() {
      return JSON.parse(this.request.headers)
    },
    set Headers(headers) {
      this.request.headers = JSON.stringify(headers)
    },
    get Before() {
      return this.middlewareBefore
    },
    set Before(before) {
      this.middlewareBefore = before
    },
    set Body(body) {
      body.body = JSON.stringify(body.body)
      this.request.bodies.push(body)
    },
    get Body() {
      if (this.request.bodies.length > 0) {
        return this.request.bodies[0]
      }
      return []
    },
    set QueryString(queryString) {
      queryString = JSON.stringify(queryString)
      this.request.queryString = queryString
    },
    get QueryString() {
      if (!this.request.queryString) {
        this.request.queryString = '{}'
      }
      return JSON.parse(this.request.queryString)
    },
    set PathParams(uriParams) {
      //uriParams = JSON.stringify(uriParams)
      this.request.pathParams = uriParams
    },
    get PathParams() {
      return this.request.pathParams
    },
    set Responses(res) {
      this.responses = res
    },
    get Responses() {
      return this.responses
    },

    set SLData(data) {
      for(var key in data) {
        this[key] = data[key]
      }
    },

    set Description(desc) {
      this.description = desc
    },
    get Description() {
      return this.description || ''
    },

    set Summary(summary) {
      if (summary.length > 120) {
        this.summary = summary.substring(0, 119)
      }
      else {
        this.summary = summary
      }
    },

    get Summary() {
      return this.summary || ''
    }
}

module.exports = Endpoint
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, doReplace */
/*unittests: FindReplace*/

/*
 * Adds Find and Replace commands
 *
 * Originally based on the code in CodeMirror2/lib/util/search.js.
 */
define(function (require, exports, module) {
    "use strict";

    var CommandManager      = require("command/CommandManager"),
        Commands            = require("command/Commands"),
        Strings             = require("strings"),
        StringUtils         = require("utils/StringUtils"),
        Editor              = require("editor/Editor"),
        EditorManager       = require("editor/EditorManager"),
        ModalBar            = require("widgets/ModalBar").ModalBar,
        ViewUtils           = require("utils/ViewUtils");

    var modalBar,
        isFindFirst = false;

    function SearchState() {
        this.posFrom = this.posTo = this.query = null;
        this.marked = [];
    }

    function getSearchState(cm) {
        if (!cm._searchState) {
            cm._searchState = new SearchState();
        }
        return cm._searchState;
    }

    function getSearchCursor(cm, query, pos) {
        // Heuristic: if the query string is all lowercase, do a case insensitive search.
        return cm.getSearchCursor(query, pos, typeof query === "string" && query === query.toLowerCase());
    }

    function getDialogTextField() {
        return $("input[type='text']", modalBar.getRoot());
    }

    function parseQuery(query) {
        var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
        $(".modal-bar .message").css("display", "inline-block");
        $(".modal-bar .error").css("display", "none");
        try {
            if (isRE && isRE[1]) {  // non-empty regexp
                return new RegExp(isRE[1], isRE[2].indexOf("i") === -1 ? "" : "i");
            } else {
                return query;
            }
        } catch (e) {
            $(".modal-bar .message").css("display", "none");
            $(".modal-bar .error")
                .css("display", "inline-block")
                .html("
" + e.message + "
");
            return "";
        }
    }

    function findNext(editor, rev) {
        var cm = editor._codeMirror;
        var found = true;
        cm.operation(function () {
            var state = getSearchState(cm);
            var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);

            if (!cursor.find(rev)) {
                // If no result found before hitting edge of file, try wrapping around
                cursor = getSearchCursor(cm, state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});

                // No result found, period: clear selection & bail
                if (!cursor.find(rev)) {
                    cm.setCursor(cm.getCursor());  // collapses selection, keeping cursor in place to avoid scrolling
                    found = false;
                    return;
                }
            }

            var centerOptions = (isFindFirst) ? Editor.BOUNDARY_IGNORE_TOP : Editor.BOUNDARY_CHECK_NORMAL;
            editor.setSelection(cursor.from(), cursor.to(), true, centerOptions);
            state.posFrom = cursor.from();
            state.posTo = cursor.to();
            state.findNextCalled = true;
        });
        return found;
    }

    function clearHighlights(cm, state) {
        cm.operation(function () {
            state.marked.forEach(function (markedRange) {
                markedRange.clear();
            });
        });
        state.marked.length = 0;
    }

    function clearSearch(cm) {
        cm.operation(function () {
            var state = getSearchState(cm);
            if (!state.query) {
                return;
            }
            state.query = null;

            clearHighlights(cm, state);
        });
    }

    function createModalBar(template, autoClose) {
        // Normally, creating a new modal bar will simply cause the old one to close
        // automatically. This can cause timing issues because the focus change might
        // cause the new one to think it should close, too. The old CodeMirror version
        // of this handled it by adding a timeout within which a blur wouldn't cause
        // the modal bar to close. Rather than reinstate that hack, we simply explicitly
        // close the old modal bar before creating a new one.
        if (modalBar) {
            modalBar.close();
        }
        modalBar = new ModalBar(template, autoClose);
        $(modalBar).on("closeOk closeBlur closeCancel", function () {
            modalBar = null;
        });
    }

    var queryDialog = Strings.CMD_FIND +
            ": <input type='text' style='width: 10em'/>
 " +
            "(" + Strings.SEARCH_REGEXP_INFO  + ")

";

    /**
     * If no search pending, opens the search dialog. If search is already open, moves to
     * next/prev result (depending on 'rev')
     */
    function doSearch(editor, rev, initialQuery) {
        var cm = editor._codeMirror;
        var state = getSearchState(cm);
        if (state.query) {
            findNext(editor, rev);
            return;
        }

        // Use the selection start as the searchStartPos. This way if you
        // start with a pre-populated search and enter an additional character,
        // it will extend the initial selection instead of jumping to the next
        // occurrence.
        var searchStartPos = cm.getCursor(true);

        // Called each time the search query changes while being typed. Jumps to the first matching
        // result, starting from the original cursor position
        function findFirst(query) {
            isFindFirst = true;
            cm.operation(function () {
                if (state.query) {
                    clearHighlights(cm, state);
                }
                state.query = parseQuery(query);
                if (!state.query) {
                    // Search field is empty - no results
                    $("#find-counter").text("");
                    cm.setCursor(searchStartPos);
                    if (modalBar) {
                        getDialogTextField().removeClass("no-results");
                    }
                    return;
                }

                // Highlight all matches
                // (Except on huge documents, where this is too expensive)
                if (cm.getValue().length < 500000) {
                    // Temporarily change selection color to improve highlighting - see LESS code for details
                    $(cm.getWrapperElement()).addClass("find-highlighting");

                    // FUTURE: if last query was prefix of this one, could optimize by filtering existing result set
                    var resultCount = 0;
                    var cursor = getSearchCursor(cm, state.query);
                    while (cursor.findNext()) {
                        state.marked.push(cm.markText(cursor.from(), cursor.to(), { className: "CodeMirror-searching" }));
                        resultCount++;

                        //Remove this section when https://github.com/marijnh/CodeMirror/issues/1155 will be fixed
                        if (cursor.pos.match && cursor.pos.match[0] === "") {
                            if (cursor.to().line + 1 === cm.lineCount()) {
                                break;
                            }
                            cursor = getSearchCursor(cm, state.query, {line: cursor.to().line + 1, ch: 0});
                        }
                    }
                    $("#find-counter").text(StringUtils.format(Strings.FIND_RESULT_COUNT, resultCount));
                } else {
                    $("#find-counter").text("");
                }

                state.posFrom = state.posTo = searchStartPos;
                var foundAny = findNext(editor, rev);

                if (modalBar) {
                    ViewUtils.toggleClass(getDialogTextField(), "no-results", !foundAny);
                }
            });
            isFindFirst = false;
        }

        if (modalBar) {
            // The modalBar was already up. When creating the new modalBar, copy the
            // current query instead of using the passed-in selected text.
            initialQuery = getDialogTextField().attr("value");
        }

        createModalBar(queryDialog, true);
        $(modalBar).on("closeOk", function (e, query) {
            if (!state.findNextCalled) {
                // If findNextCalled is false, this means the user has *not*
                // entered any search text *or* pressed Cmd-G/F3 to find the
                // next occurrence. In this case we want to start searching
                // *after* the current selection so we find the next occurrence.
                searchStartPos = cm.getCursor(false);
                findFirst(query);
            }
        });
        $(modalBar).on("closeOk closeCancel closeBlur", function (e, query) {
            // Clear highlights but leave search state in place so Find Next/Previous work after closing
            clearHighlights(cm, state);

            // As soon as focus goes back to the editor, restore normal selection color
            $(cm.getWrapperElement()).removeClass("find-highlighting");
        });

        var $input = getDialogTextField();
        $input.on("input", function () {
            findFirst($input.attr("value"));
        });

        // Prepopulate the search field with the current selection, if any.
        if (initialQuery !== undefined) {
            // Eliminate newlines since we don't generally support searching across line boundaries (#2960)
            var newline = initialQuery.indexOf("\n");
            if (newline !== -1) {
                initialQuery = initialQuery.substr(0, newline);
            }

            $input
                .attr("value", initialQuery)
                .get(0).select();
            findFirst(initialQuery);
            // Clear the "findNextCalled" flag here so we have a clean start
            state.findNextCalled = false;
        }
    }

    var replaceQueryDialog = Strings.CMD_REPLACE +
            ': <input type="text" style="width: 10em"/>
(' +
            Strings.SEARCH_REGEXP_INFO  + ')

';
    var replacementQueryDialog = Strings.WITH +
            ': <input type="text" style="width: 10em"/>';
    // style buttons to match height/margins/border-radius of text input boxes
    var style = ' style="padding:5px 15px;border:1px #999 solid;border-radius:3px;margin:2px 2px 5px;"';
    var doReplaceConfirm = Strings.CMD_REPLACE +
            '? <button id="replace-yes"' + style + '>' + Strings.BUTTON_YES +
            '</button> <button id="replace-no"' + style + '>' + Strings.BUTTON_NO +
            '</button> <button' + style + '>' + Strings.BUTTON_STOP + '</button>';

    function replace(editor, all) {
        var cm = editor._codeMirror;
        createModalBar(replaceQueryDialog, true);
        $(modalBar).on("closeOk", function (e, query) {
            if (!query) {
                return;
            }

            query = parseQuery(query);
            createModalBar(replacementQueryDialog, true);
            $(modalBar).on("closeOk", function (e, text) {
                text = text || "";
                var match,
                    fnMatch = function (w, i) { return match[i]; };
                if (all) {
                    cm.compoundChange(function () {
                        cm.operation(function () {
                            var cursor = getSearchCursor(cm, query);
                            while (cursor.findNext()) {
                                if (typeof query !== "string") {
                                    match = cm.getRange(cursor.from(), cursor.to()).match(query);
                                    cursor.replace(text.replace(/\$(\d)/, fnMatch));
                                } else {
                                    cursor.replace(text);
                                }
                            }
                        });
                    });
                } else {
                    clearSearch(cm);
                    var cursor = getSearchCursor(cm, query, cm.getCursor(true));
                    var advance = function () {
                        var start = cursor.from(),
                            match = cursor.findNext();
                        if (!match) {
                            cursor = getSearchCursor(cm, query);
                            match = cursor.findNext();
                            if (!match ||
                                    (start && cursor.from().line === start.line && cursor.from().ch === start.ch)) {
                                // No more matches, so destroy modalBar
                                modalBar = null;
                                return;
                            }
                        }
                        editor.setSelection(cursor.from(), cursor.to(), true, Editor.BOUNDARY_CHECK_NORMAL);
                        createModalBar(doReplaceConfirm, true);
                        modalBar.getRoot().on("click", function (e) {
                            modalBar.close();
                            if (e.target.id === "replace-yes") {
                                doReplace(match);
                            } else if (e.target.id === "replace-no") {
                                advance();
                            }
                        });
                    };
                    var doReplace = function (match) {
                        cursor.replace(typeof query === "string" ? text :
                                            text.replace(/\$(\d)/, fnMatch));
                        advance();
                    };
                    advance();
                }
            });
        });

        // Prepopulate the replace field with the current selection, if any
        getDialogTextField()
            .attr("value", cm.getSelection())
            .get(0).select();
    }

    function _launchFind() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            var codeMirror = editor._codeMirror;

            // Create a new instance of the search bar UI
            clearSearch(codeMirror);
            doSearch(editor, false, codeMirror.getSelection());
        }
    }

    function _findNext() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            doSearch(editor);
        }
    }

    function _findPrevious() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            doSearch(editor, true);
        }
    }

    function _replace() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            replace(editor);
        }
    }

    CommandManager.register(Strings.CMD_FIND,           Commands.EDIT_FIND,          _launchFind);
    CommandManager.register(Strings.CMD_FIND_NEXT,      Commands.EDIT_FIND_NEXT,     _findNext);
    CommandManager.register(Strings.CMD_REPLACE,        Commands.EDIT_REPLACE,       _replace);
    CommandManager.register(Strings.CMD_FIND_PREVIOUS,  Commands.EDIT_FIND_PREVIOUS, _findPrevious);
});
<commit_msg>Applied default button styling to the unstyled buttons for consistency.<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, doReplace */
/*unittests: FindReplace*/

/*
 * Adds Find and Replace commands
 *
 * Originally based on the code in CodeMirror2/lib/util/search.js.
 */
define(function (require, exports, module) {
    "use strict";

    var CommandManager      = require("command/CommandManager"),
        Commands            = require("command/Commands"),
        Strings             = require("strings"),
        StringUtils         = require("utils/StringUtils"),
        Editor              = require("editor/Editor"),
        EditorManager       = require("editor/EditorManager"),
        ModalBar            = require("widgets/ModalBar").ModalBar,
        ViewUtils           = require("utils/ViewUtils");

    var modalBar,
        isFindFirst = false;

    function SearchState() {
        this.posFrom = this.posTo = this.query = null;
        this.marked = [];
    }

    function getSearchState(cm) {
        if (!cm._searchState) {
            cm._searchState = new SearchState();
        }
        return cm._searchState;
    }

    function getSearchCursor(cm, query, pos) {
        // Heuristic: if the query string is all lowercase, do a case insensitive search.
        return cm.getSearchCursor(query, pos, typeof query === "string" && query === query.toLowerCase());
    }

    function getDialogTextField() {
        return $("input[type='text']", modalBar.getRoot());
    }

    function parseQuery(query) {
        var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
        $(".modal-bar .message").css("display", "inline-block");
        $(".modal-bar .error").css("display", "none");
        try {
            if (isRE && isRE[1]) {  // non-empty regexp
                return new RegExp(isRE[1], isRE[2].indexOf("i") === -1 ? "" : "i");
            } else {
                return query;
            }
        } catch (e) {
            $(".modal-bar .message").css("display", "none");
            $(".modal-bar .error")
                .css("display", "inline-block")
                .html("
" + e.message + "
");
            return "";
        }
    }

    function findNext(editor, rev) {
        var cm = editor._codeMirror;
        var found = true;
        cm.operation(function () {
            var state = getSearchState(cm);
            var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);

            if (!cursor.find(rev)) {
                // If no result found before hitting edge of file, try wrapping around
                cursor = getSearchCursor(cm, state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});

                // No result found, period: clear selection & bail
                if (!cursor.find(rev)) {
                    cm.setCursor(cm.getCursor());  // collapses selection, keeping cursor in place to avoid scrolling
                    found = false;
                    return;
                }
            }

            var centerOptions = (isFindFirst) ? Editor.BOUNDARY_IGNORE_TOP : Editor.BOUNDARY_CHECK_NORMAL;
            editor.setSelection(cursor.from(), cursor.to(), true, centerOptions);
            state.posFrom = cursor.from();
            state.posTo = cursor.to();
            state.findNextCalled = true;
        });
        return found;
    }

    function clearHighlights(cm, state) {
        cm.operation(function () {
            state.marked.forEach(function (markedRange) {
                markedRange.clear();
            });
        });
        state.marked.length = 0;
    }

    function clearSearch(cm) {
        cm.operation(function () {
            var state = getSearchState(cm);
            if (!state.query) {
                return;
            }
            state.query = null;

            clearHighlights(cm, state);
        });
    }

    function createModalBar(template, autoClose) {
        // Normally, creating a new modal bar will simply cause the old one to close
        // automatically. This can cause timing issues because the focus change might
        // cause the new one to think it should close, too. The old CodeMirror version
        // of this handled it by adding a timeout within which a blur wouldn't cause
        // the modal bar to close. Rather than reinstate that hack, we simply explicitly
        // close the old modal bar before creating a new one.
        if (modalBar) {
            modalBar.close();
        }
        modalBar = new ModalBar(template, autoClose);
        $(modalBar).on("closeOk closeBlur closeCancel", function () {
            modalBar = null;
        });
    }

    var queryDialog = Strings.CMD_FIND +
            ": <input type='text' style='width: 10em'/>
 " +
            "(" + Strings.SEARCH_REGEXP_INFO  + ")

";

    /**
     * If no search pending, opens the search dialog. If search is already open, moves to
     * next/prev result (depending on 'rev')
     */
    function doSearch(editor, rev, initialQuery) {
        var cm = editor._codeMirror;
        var state = getSearchState(cm);
        if (state.query) {
            findNext(editor, rev);
            return;
        }

        // Use the selection start as the searchStartPos. This way if you
        // start with a pre-populated search and enter an additional character,
        // it will extend the initial selection instead of jumping to the next
        // occurrence.
        var searchStartPos = cm.getCursor(true);

        // Called each time the search query changes while being typed. Jumps to the first matching
        // result, starting from the original cursor position
        function findFirst(query) {
            isFindFirst = true;
            cm.operation(function () {
                if (state.query) {
                    clearHighlights(cm, state);
                }
                state.query = parseQuery(query);
                if (!state.query) {
                    // Search field is empty - no results
                    $("#find-counter").text("");
                    cm.setCursor(searchStartPos);
                    if (modalBar) {
                        getDialogTextField().removeClass("no-results");
                    }
                    return;
                }

                // Highlight all matches
                // (Except on huge documents, where this is too expensive)
                if (cm.getValue().length < 500000) {
                    // Temporarily change selection color to improve highlighting - see LESS code for details
                    $(cm.getWrapperElement()).addClass("find-highlighting");

                    // FUTURE: if last query was prefix of this one, could optimize by filtering existing result set
                    var resultCount = 0;
                    var cursor = getSearchCursor(cm, state.query);
                    while (cursor.findNext()) {
                        state.marked.push(cm.markText(cursor.from(), cursor.to(), { className: "CodeMirror-searching" }));
                        resultCount++;

                        //Remove this section when https://github.com/marijnh/CodeMirror/issues/1155 will be fixed
                        if (cursor.pos.match && cursor.pos.match[0] === "") {
                            if (cursor.to().line + 1 === cm.lineCount()) {
                                break;
                            }
                            cursor = getSearchCursor(cm, state.query, {line: cursor.to().line + 1, ch: 0});
                        }
                    }
                    $("#find-counter").text(StringUtils.format(Strings.FIND_RESULT_COUNT, resultCount));
                } else {
                    $("#find-counter").text("");
                }

                state.posFrom = state.posTo = searchStartPos;
                var foundAny = findNext(editor, rev);

                if (modalBar) {
                    ViewUtils.toggleClass(getDialogTextField(), "no-results", !foundAny);
                }
            });
            isFindFirst = false;
        }

        if (modalBar) {
            // The modalBar was already up. When creating the new modalBar, copy the
            // current query instead of using the passed-in selected text.
            initialQuery = getDialogTextField().attr("value");
        }

        createModalBar(queryDialog, true);
        $(modalBar).on("closeOk", function (e, query) {
            if (!state.findNextCalled) {
                // If findNextCalled is false, this means the user has *not*
                // entered any search text *or* pressed Cmd-G/F3 to find the
                // next occurrence. In this case we want to start searching
                // *after* the current selection so we find the next occurrence.
                searchStartPos = cm.getCursor(false);
                findFirst(query);
            }
        });
        $(modalBar).on("closeOk closeCancel closeBlur", function (e, query) {
            // Clear highlights but leave search state in place so Find Next/Previous work after closing
            clearHighlights(cm, state);

            // As soon as focus goes back to the editor, restore normal selection color
            $(cm.getWrapperElement()).removeClass("find-highlighting");
        });

        var $input = getDialogTextField();
        $input.on("input", function () {
            findFirst($input.attr("value"));
        });

        // Prepopulate the search field with the current selection, if any.
        if (initialQuery !== undefined) {
            // Eliminate newlines since we don't generally support searching across line boundaries (#2960)
            var newline = initialQuery.indexOf("\n");
            if (newline !== -1) {
                initialQuery = initialQuery.substr(0, newline);
            }

            $input
                .attr("value", initialQuery)
                .get(0).select();
            findFirst(initialQuery);
            // Clear the "findNextCalled" flag here so we have a clean start
            state.findNextCalled = false;
        }
    }

    var replaceQueryDialog = Strings.CMD_REPLACE +
            ': <input type="text" style="width: 10em"/>
(' +
            Strings.SEARCH_REGEXP_INFO  + ')

';
    var replacementQueryDialog = Strings.WITH +
            ': <input type="text" style="width: 10em"/>';
    var doReplaceConfirm = Strings.CMD_REPLACE +
            '? <button id="replace-yes" class="btn">' + Strings.BUTTON_YES +
            '</button> <button id="replace-no" class="btn">' + Strings.BUTTON_NO +
            '</button> <button class="btn">' + Strings.BUTTON_STOP + '</button>';

    function replace(editor, all) {
        var cm = editor._codeMirror;
        createModalBar(replaceQueryDialog, true);
        $(modalBar).on("closeOk", function (e, query) {
            if (!query) {
                return;
            }

            query = parseQuery(query);
            createModalBar(replacementQueryDialog, true);
            $(modalBar).on("closeOk", function (e, text) {
                text = text || "";
                var match,
                    fnMatch = function (w, i) { return match[i]; };
                if (all) {
                    cm.compoundChange(function () {
                        cm.operation(function () {
                            var cursor = getSearchCursor(cm, query);
                            while (cursor.findNext()) {
                                if (typeof query !== "string") {
                                    match = cm.getRange(cursor.from(), cursor.to()).match(query);
                                    cursor.replace(text.replace(/\$(\d)/, fnMatch));
                                } else {
                                    cursor.replace(text);
                                }
                            }
                        });
                    });
                } else {
                    clearSearch(cm);
                    var cursor = getSearchCursor(cm, query, cm.getCursor(true));
                    var advance = function () {
                        var start = cursor.from(),
                            match = cursor.findNext();
                        if (!match) {
                            cursor = getSearchCursor(cm, query);
                            match = cursor.findNext();
                            if (!match ||
                                    (start && cursor.from().line === start.line && cursor.from().ch === start.ch)) {
                                // No more matches, so destroy modalBar
                                modalBar = null;
                                return;
                            }
                        }
                        editor.setSelection(cursor.from(), cursor.to(), true, Editor.BOUNDARY_CHECK_NORMAL);
                        createModalBar(doReplaceConfirm, true);
                        modalBar.getRoot().on("click", function (e) {
                            modalBar.close();
                            if (e.target.id === "replace-yes") {
                                doReplace(match);
                            } else if (e.target.id === "replace-no") {
                                advance();
                            }
                        });
                    };
                    var doReplace = function (match) {
                        cursor.replace(typeof query === "string" ? text :
                                            text.replace(/\$(\d)/, fnMatch));
                        advance();
                    };
                    advance();
                }
            });
        });

        // Prepopulate the replace field with the current selection, if any
        getDialogTextField()
            .attr("value", cm.getSelection())
            .get(0).select();
    }

    function _launchFind() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            var codeMirror = editor._codeMirror;

            // Create a new instance of the search bar UI
            clearSearch(codeMirror);
            doSearch(editor, false, codeMirror.getSelection());
        }
    }

    function _findNext() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            doSearch(editor);
        }
    }

    function _findPrevious() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            doSearch(editor, true);
        }
    }

    function _replace() {
        var editor = EditorManager.getActiveEditor();
        if (editor) {
            replace(editor);
        }
    }

    CommandManager.register(Strings.CMD_FIND,           Commands.EDIT_FIND,          _launchFind);
    CommandManager.register(Strings.CMD_FIND_NEXT,      Commands.EDIT_FIND_NEXT,     _findNext);
    CommandManager.register(Strings.CMD_REPLACE,        Commands.EDIT_REPLACE,       _replace);
    CommandManager.register(Strings.CMD_FIND_PREVIOUS,  Commands.EDIT_FIND_PREVIOUS, _findPrevious);
});
<|endoftext|>


<commit_before>'use babel';

import ExemplatorPluginView from './exemplator-plugin-view';
import {CompositeDisposable} from 'atom';

const FUNCTION = 0;
const TYPE = 1;
const OTHER = 2;

var getCursorIndex = function () {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var currentPosition = editor.getCursorBufferPosition();

    var row = 0;
    var col = 0;
    var index;
    // translate row and column into an index for text
    for (index = 0; index < text.length; index++) {
        if (row == currentPosition.row && col == currentPosition.column)
            break;

        if (text.charAt(index) == '\n') {
            row++;
            col = 0;
        } else {
            col++;
        }
    }

    return index;
}

var getCurrentSegment = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // is cursor on method or type/variable name?
    var currentSegmentStart;
    var currentSegmentEnd;

    for (var currentSegmentStart = Math.max(0, index - 1); currentSegmentStart >= 0; currentSegmentStart--) {
        var c = text.charAt(currentSegmentStart);

        if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentStart++;
            break;
        }
    }

    var type;

    for (var currentSegmentEnd = index; currentSegmentEnd < text.length; currentSegmentEnd++) {
        var c = text.charAt(currentSegmentEnd);

        if (c == '(') {
            type = FUNCTION;
            currentSegmentEnd--;
            break;
        } else if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentEnd--;
            break;
        }
    }

    if (type != FUNCTION) {
        // type declaration if capitalized
        if (text.charAt(currentSegmentStart) >= 'A' && text.charAt(currentSegmentStart) <= 'Z')
            type = TYPE;
        else
            type = OTHER;
    }

    return {
        "type": type,
        "str": text.substr(currentSegmentStart, (currentSegmentEnd - currentSegmentStart) + 1),
        "start": currentSegmentStart,
        "end": currentSegmentEnd
    };
}

var getPackage = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index)
    var type = segment["type"]
    var str = segment["str"]

    if (type == OTHER)
        return null;
    else if (type == TYPE) {
        lines = text.split('\n');
        var simpleTypeName = str;
        // find package name
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].startsWith('import')) {
                var packageName = getPackageName(lines[i], simpleTypeName)
                if (packageName != null)
                    return {"package": packageName, "name": simpleTypeName};
            }
        }
    }

    return {"name": str};
}

String.prototype.regexIndexOf = function (regex, startpos) {
    var indexOf = this.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

String.prototype.regexLastIndexOf = function (regex, startpos) {
    regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
    if (typeof (startpos) == "undefined") {
        startpos = this.length;
    } else if (startpos < 0) {
        startpos = 0;
    }
    var stringToWorkWith = this.substring(0, startpos + 1);
    var lastIndexOf = -1;
    var nextStop = 0;
    while ((result = regex.exec(stringToWorkWith)) != null) {
        lastIndexOf = result.index;
        regex.lastIndex = ++nextStop;
    }
    return lastIndexOf;
}

var getFullClassNameForVariable = function (index) {
    var segment = getCurrentSegment(index)

    if (segment["str"].length == 0)
        return null;

    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // go to declaration

    var regex = new RegExp("[A-Z][a-zA-Z]* " + segment["str"]);
    var declarationPos = text.regexLastIndexOf(regex, index);
    if (declarationPos == -1)
        return null;

    var fullClassName = getPackage(declarationPos);

    return fullClassName;
}

var getFullClassNameForFunction = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index);
    var type = segment["type"];
    var str = segment["str"];

    if (type != FUNCTION)
        return null;

    if (text.charAt(segment["start"] - 1) != ".")
        return null;

    return getFullClassNameForVariable(segment["start"] - 2);
}

var getPackageName = function (importLine, typeName) {
    // only return if it matches typeName
    var packageStart = importLine.indexOf(' ');
    var p = importLine.substr(packageStart);
    var comps = p.split('.');
    var packageWithClass = comps[comps.length - 1];
    packageWithClass = packageWithClass.substr(0, packageWithClass.length - 1)
    if (packageWithClass !== typeName)
        return null;
    else {
        var packageWithClass = p.substr(0, p.length - 1);
        return packageWithClass.replace("." + typeName, "")
    }
}

var sendRequest = function (exemplatorPluginView, request, page = 0) {
    console.log("hi 1")
    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
    xmlhttp.open("POST", "http://localhost:4567/search");
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    var dict = {}

    if (request.class != null && request.class.package != null)
        dict["package"] = request.class.package.trim();
    if (request.class != null && request.class.name != null)
        dict["class"] = request.class.name.trim();
    if (request.method != null)
        dict["method"] = request.method.trim();
    if (request.token != null)
        dict["token"] = request.token.trim();
    dict["page"] = page;

    console.log("Dict to be sent: ");
    console.log(dict);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                handleResponse(exemplatorPluginView, xmlhttp.responseText);
            }
            else if (xmlhttp.status == 400) {
                console.log("Error 400 returned from server");
            }
            else {
                console.log("Error returned from server",xmlhttp.status);
            }
        }
    };

    var dict = {
    'class': 'List',
    'method': 'add',
    'page': 0
    }

    xmlhttp.send(JSON.stringify(dict));
}

var splitCode = function (codeString, startRow, endRow) {
    var array = codeString.match(/[^\r\n]+/g);

    var startString = "";
    var highlightedString = "";
    var endString = "";
    for (var i = 0; i < array.length; i++) {
        if (i < startRow) {
            startString += array[i];
        } else if (i < endRow) {
            highlightedString += array[i];
        } else {
            endString += array[i];
        }
    }

    return [startString, highlightedString, endString];
}

var handleResponse = function (exemplatorPluginView, responseText) {
    var response = JSON.parse(responseText);
    console.log("Response from server: ");
    console.log(response);

    var responseArray = response.occurrences;
    console.log(responseArray)

    var data = {
        examples: []
    }

    responseArray.forEach(item => {
        item.selections.forEach(selection => {
            let code = splitCode(item.code, 1, 2);
            if (selection.start.line != -1) {
                var element = {
                    user: 'bill',
                    score: item.userUrl,
                    userurl: item.userUrl,
                    rawUrl: item.rawUrl,
                    codeTop: code[0],
                    highlightedCode: code[1],
                    codeBottom:  code[2]
                }
                data.examples.push(element)
            }
        })
    })

    exemplatorPluginView.setData(data);
}

export default {

    exemplatorPluginView: null,
    modalPanel: null,
    subscriptions: null,

    activate(state) {
        this.exemplatorPluginView = new ExemplatorPluginView(state.exemplatorPluginViewState);
        this.modalPanel = atom.workspace.addRightPanel({
            item: this.exemplatorPluginView.getElement(),
            visible: true
        });

        // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
        this.subscriptions = new CompositeDisposable();

        // Register command that toggles this view
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:toggle': () => this.toggle()
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:showExamples': () => this.showExamples()
        }));
    },

    deactivate() {
        this.modalPanel.destroy();
        this.subscriptions.dispose();
        this.exemplatorPluginView.destroy();
    },

    serialize() {
        return {
            exemplatorPluginViewState: this.exemplatorPluginView.serialize()
        };
    },

    toggle() {
        console.log('ExemplatorPlugin was toggled!');
        return (
            this.modalPanel.isVisible() ?
                this.modalPanel.hide() :
                this.modalPanel.show()
        );
    },

    showExamples() {
        editor = atom.workspace.getActiveTextEditor();

        var request = {

        };

        // text selected? then search for plain string
        if (editor.getSelectedText().length > 0) {
            var plainStr = editor.getSelectedText();
            console.log("Found plain str: " + plainStr);
            request.token = plainStr;
        } else {
            var index = getCursorIndex();
            // function?
            var classNameForFunction = getFullClassNameForFunction(index);
            if (classNameForFunction != null) {
                var functionName = getCurrentSegment(index)["str"];
                console.log("found " + classNameForFunction + "." + functionName);
                request.class = classNameForFunction;
                request.method = functionName;
            } else {
                var classNameForVariable = getFullClassNameForVariable(index);
                if (classNameForVariable != null) {
                    console.log("found " + classNameForVariable);
                    request.class = classNameForVariable;
                } else {
                    // type?
                    var classNameForType = getPackage(index);
                    if (classNameForType != null) {
                        console.log("found " + classNameForType);
                        request.class = classNameForType;
                    } else {
                        console.log("Nothing found");
                    }
                }
            }
        }

        console.log(request)
        //this.exemplatorPluginView.setData();
        sendRequest(this.exemplatorPluginView, 'test');
    }
};
<commit_msg>Package is omitted in request<commit_after>'use babel';

import ExemplatorPluginView from './exemplator-plugin-view';
import {CompositeDisposable} from 'atom';

const FUNCTION = 0;
const TYPE = 1;
const OTHER = 2;

var getCursorIndex = function () {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var currentPosition = editor.getCursorBufferPosition();

    var row = 0;
    var col = 0;
    var index;
    // translate row and column into an index for text
    for (index = 0; index < text.length; index++) {
        if (row == currentPosition.row && col == currentPosition.column)
            break;

        if (text.charAt(index) == '\n') {
            row++;
            col = 0;
        } else {
            col++;
        }
    }

    return index;
}

var getCurrentSegment = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // is cursor on method or type/variable name?
    var currentSegmentStart;
    var currentSegmentEnd;

    for (var currentSegmentStart = Math.max(0, index - 1); currentSegmentStart >= 0; currentSegmentStart--) {
        var c = text.charAt(currentSegmentStart);

        if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentStart++;
            break;
        }
    }

    var type;

    for (var currentSegmentEnd = index; currentSegmentEnd < text.length; currentSegmentEnd++) {
        var c = text.charAt(currentSegmentEnd);

        if (c == '(') {
            type = FUNCTION;
            currentSegmentEnd--;
            break;
        } else if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
            currentSegmentEnd--;
            break;
        }
    }

    if (type != FUNCTION) {
        // type declaration if capitalized
        if (text.charAt(currentSegmentStart) >= 'A' && text.charAt(currentSegmentStart) <= 'Z')
            type = TYPE;
        else
            type = OTHER;
    }

    return {
        "type": type,
        "str": text.substr(currentSegmentStart, (currentSegmentEnd - currentSegmentStart) + 1),
        "start": currentSegmentStart,
        "end": currentSegmentEnd
    };
}

var getPackage = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index)
    var type = segment["type"]
    var str = segment["str"]

    if (type == OTHER)
        return null;
    else if (type == TYPE) {
        lines = text.split('\n');
        var simpleTypeName = str;
        // find package name
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].startsWith('import')) {
                var packageName = getPackageName(lines[i], simpleTypeName)
                if (packageName != null)
                    return {"package": packageName, "name": simpleTypeName};
            }
        }
    }

    return {"name": str};
}

String.prototype.regexIndexOf = function (regex, startpos) {
    var indexOf = this.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

String.prototype.regexLastIndexOf = function (regex, startpos) {
    regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
    if (typeof (startpos) == "undefined") {
        startpos = this.length;
    } else if (startpos < 0) {
        startpos = 0;
    }
    var stringToWorkWith = this.substring(0, startpos + 1);
    var lastIndexOf = -1;
    var nextStop = 0;
    while ((result = regex.exec(stringToWorkWith)) != null) {
        lastIndexOf = result.index;
        regex.lastIndex = ++nextStop;
    }
    return lastIndexOf;
}

var getFullClassNameForVariable = function (index) {
    var segment = getCurrentSegment(index)

    if (segment["str"].length == 0)
        return null;

    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    // go to declaration

    var regex = new RegExp("[A-Z][a-zA-Z]* " + segment["str"]);
    var declarationPos = text.regexLastIndexOf(regex, index);
    if (declarationPos == -1)
        return null;

    var fullClassName = getPackage(declarationPos);

    return fullClassName;
}

var getFullClassNameForFunction = function (index) {
    var editor = atom.workspace.getActiveTextEditor();
    var text = editor.getText();

    var segment = getCurrentSegment(index);
    var type = segment["type"];
    var str = segment["str"];

    if (type != FUNCTION)
        return null;

    if (text.charAt(segment["start"] - 1) != ".")
        return null;

    return getFullClassNameForVariable(segment["start"] - 2);
}

var getPackageName = function (importLine, typeName) {
    // only return if it matches typeName
    var packageStart = importLine.indexOf(' ');
    var p = importLine.substr(packageStart);
    var comps = p.split('.');
    var packageWithClass = comps[comps.length - 1];
    packageWithClass = packageWithClass.substr(0, packageWithClass.length - 1)
    if (packageWithClass !== typeName)
        return null;
    else {
        var packageWithClass = p.substr(0, p.length - 1);
        return packageWithClass.replace("." + typeName, "")
    }
}

var sendRequest = function (exemplatorPluginView, request, page = 0) {
    console.log("hi 1")
    var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
    xmlhttp.open("POST", "http://localhost:4567/search");
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    var dict = {}

    if (false)//request.class != null && request.class.package != null)
        dict["package"] = request.class.package.trim();
    if (request.class != null && request.class.name != null)
        dict["class"] = request.class.name.trim();
    if (request.method != null)
        dict["method"] = request.method.trim();
    if (request.token != null)
        dict["token"] = request.token.trim();
    dict["page"] = page;

    console.log("Dict to be sent: ");
    console.log(dict);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                handleResponse(exemplatorPluginView, xmlhttp.responseText);
            }
            else if (xmlhttp.status == 400) {
                console.log("Error 400 returned from server");
            }
            else {
                console.log("Error returned from server",xmlhttp.status);
            }
        }
    };

    var dict = {
    'class': 'List',
    'method': 'add',
    'page': 0
    }

    xmlhttp.send(JSON.stringify(dict));
}

var splitCode = function (codeString, startRow, endRow) {
    var array = codeString.match(/[^\r\n]+/g);

    var startString = "";
    var highlightedString = "";
    var endString = "";
    for (var i = 0; i < array.length; i++) {
        if (i < startRow) {
            startString += array[i];
        } else if (i < endRow) {
            highlightedString += array[i];
        } else {
            endString += array[i];
        }
    }

    return [startString, highlightedString, endString];
}

var handleResponse = function (exemplatorPluginView, responseText) {
    var response = JSON.parse(responseText);
    console.log("Response from server: ");
    console.log(response);

    var responseArray = response.occurrences;
    console.log(responseArray)

    var data = {
        examples: []
    }

    responseArray.forEach(item => {
        item.selections.forEach(selection => {
            let code = splitCode(item.code, 1, 2);
            if (selection.start.line != -1) {
                var element = {
                    user: 'bill',
                    score: item.userUrl,
                    userurl: item.userUrl,
                    rawUrl: item.rawUrl,
                    codeTop: code[0],
                    highlightedCode: code[1],
                    codeBottom:  code[2]
                }
                data.examples.push(element)
            }
        })
    })

    exemplatorPluginView.setData(data);
}

export default {

    exemplatorPluginView: null,
    modalPanel: null,
    subscriptions: null,

    activate(state) {
        this.exemplatorPluginView = new ExemplatorPluginView(state.exemplatorPluginViewState);
        this.modalPanel = atom.workspace.addRightPanel({
            item: this.exemplatorPluginView.getElement(),
            visible: true
        });

        // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
        this.subscriptions = new CompositeDisposable();

        // Register command that toggles this view
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:toggle': () => this.toggle()
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'Exemplator:showExamples': () => this.showExamples()
        }));
    },

    deactivate() {
        this.modalPanel.destroy();
        this.subscriptions.dispose();
        this.exemplatorPluginView.destroy();
    },

    serialize() {
        return {
            exemplatorPluginViewState: this.exemplatorPluginView.serialize()
        };
    },

    toggle() {
        console.log('ExemplatorPlugin was toggled!');
        return (
            this.modalPanel.isVisible() ?
                this.modalPanel.hide() :
                this.modalPanel.show()
        );
    },

    showExamples() {
        editor = atom.workspace.getActiveTextEditor();

        var request = {

        };

        // text selected? then search for plain string
        if (editor.getSelectedText().length > 0) {
            var plainStr = editor.getSelectedText();
            console.log("Found plain str: " + plainStr);
            request.token = plainStr;
        } else {
            var index = getCursorIndex();
            // function?
            var classNameForFunction = getFullClassNameForFunction(index);
            if (classNameForFunction != null) {
                var functionName = getCurrentSegment(index)["str"];
                console.log("found " + classNameForFunction + "." + functionName);
                request.class = classNameForFunction;
                request.method = functionName;
            } else {
                var classNameForVariable = getFullClassNameForVariable(index);
                if (classNameForVariable != null) {
                    console.log("found " + classNameForVariable);
                    request.class = classNameForVariable;
                } else {
                    // type?
                    var classNameForType = getPackage(index);
                    if (classNameForType != null) {
                        console.log("found " + classNameForType);
                        request.class = classNameForType;
                    } else {
                        console.log("Nothing found");
                    }
                }
            }
        }

        console.log(request)
        //this.exemplatorPluginView.setData();
        sendRequest(this.exemplatorPluginView, 'test');
    }
};
<|endoftext|>