<commit_before>define([
	"dojo/_base/declare", "dijit/layout/BorderContainer", "dojo/on",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"../PageGrid", "../formatter", "../../WorkspaceManager", "dojo/_base/lang",
	"dojo/dom-attr", "../WorkspaceExplorerView", "dijit/Dialog"
], function(declare, BorderContainer, on,
			domClass, ContentPane, domConstruct,
			Grid, formatter, WorkspaceManager, lang,
			domAttr, WorkspaceExplorerView, Dialog){
	return declare([BorderContainer], {
		"baseClass": "ExperimentViewer",
		"disabled": false,
		"query": null,
		data: null,
		containerType: "job_result",
		_resultType: null,
		_jobOut: {
			"id": {"label": "Job ID"},
			"start_time": {"label": "Start time", "format": formatter.epochDate},
			"end_time": {"label": "End time", "format": formatter.epochDate},
			"elapsed_time": {"label": "Run time", "format": formatter.runTime},
			"parameters": {"label": "Parameters", "format": function(d){
				if(d.hasOwnProperty('ustring')){
				    d['ustring'] = JSON.parse(d['ustring'])
				}
				return '
' + JSON.stringify(d,null,2) + "
"
			}}
		},
		_jobOrder: ["id", "start_time", "end_time", "elapsed_time", "parameters"],
		_appLabel: "",
		_resultMetaTypes: {},
		_autoLabels: {},
		_setDataAttr: function(data){
			this.data = data;
			//console.log("[JobResult] data: ", data);
			this._hiddenPath = data.path + "." + data.name;
			// console.log("[JobResult] Output Files: ", this.data.autoMeta.output_files);
			var _self = this;

			// check to see if there's a hidden .folder with the actual data
			WorkspaceManager.getObject(this._hiddenPath, true).otherwise(function(err) {
				new Dialog({
					content: "No output from this job was found in the '."+_self.data.name+"' folder. "
								  +"If you moved the job result file from another location, please ensure you "
									+"have also moved the accomanying folder to this location.",
					title: "Error Loading Job Result",
					style: "width: 300px !important;"
				}).show();
			});

			// get the contents directly from the hidden folder, since metadata may be stale after a move
			WorkspaceManager.getFolderContents(this._hiddenPath, true, true)
				.then(function(objs){
					//console.log("[JobResult] objects: ", objs);
						_self._resultObjects = objs;
						_self.setupResultType();
						_self.refresh();
				});

		},
		isSummaryView: function(){
			return false;
		},
		setupResultType: function(){
			// console.log("[JobResult] setupResultType()");
			if(this.data.autoMeta.app.id){
				this._resultType = this.data.autoMeta.app.id;
				// console.log("[JobResult] _resultType:",this._resultType);
			}
			if(this._resultType == "GenomeAssembly"){
				this._appLabel = "Genome Assembly";
			}
			else{
				this._appLabel = this._resultType;
			}
		},
		getExtraMetaDataForHeader: function(job_output){
			return job_output;
		},
		refresh: function(){
			// console.log("[JobResult] refresh()");
			if(this.data){
				var jobHeader = '

';
				if(this.data.autoMeta && this.data.autoMeta.app){
					jobHeader = jobHeader + this._appLabel + " ";
				}
				jobHeader = jobHeader + "Job Result" + '
';
				//this.viewer.set('content',jobHeader);

				var output = [];
				output.push(jobHeader + '

');
				var job_output = [];

				// add extra metadata header lines
				job_output = this.getExtraMetaDataForHeader(job_output)

				this._jobOrder.forEach(function(prop){
					/*if (prop=="output_files") { return; }
					if (prop=="app") { return; }
					if (prop=="job_output") { return; }
					if (prop=="hostname") { return; }*/
					if(!this.data.autoMeta[prop]){
						return;
					}

					if(this._jobOut.hasOwnProperty(prop)){
						//this._jobOut[prop]["value"]=this.data.autoMeta[prop];
						var tableLabel = this._jobOut[prop].hasOwnProperty("label") ? this._jobOut[prop]["label"] : prop;
						var tableValue = this._jobOut[prop].hasOwnProperty("format") ? this._jobOut[prop]["format"](this.data.autoMeta[prop]) : this.data.autoMeta[prop];
						if(prop == 'parameters') {
							job_output.push('

'+tableValue+'

');
						} else {
							job_output.push('
' + this._jobOut[prop]["label"] + '	' + tableValue + "
");
						}
					}
				}, this);
			}

			output.push.apply(output, job_output);
			output.push("

");

			if(this.data.userMeta){
				Object.keys(this.data.userMeta).forEach(function(prop){
					output.push("
" + prop + ": " + this.data.userMeta[prop] + "
");
				}, this);
			}

			output.push("
");
			this.viewHeader.set("content", output.join(""));
			this.resize();
		},
		startup: function(){
			if(this._started){
				return;
			}
			this.inherited(arguments);
			this.viewHeader = new ContentPane({content: "Loading data from "+this.data.name+" job file.  If you have moved your job result, please ensure you have also moved the ."+this.data.name+" folder to this directory as well.", region: "top", style:"width:90%;height:40%;", splitter: true});
			//this.viewer= new ContentPane({content: "", region: "center"});
			this.viewer = new WorkspaceExplorerView({region: "center", path: this._hiddenPath});
			// console.log("[JobResult] WSV: ", this.viewer);
			this.addChild(this.viewHeader);
			this.addChild(this.viewer);

			this.on("i:click", function(evt){
				var rel = domAttr.get(evt.target, 'rel');
				if(rel){
					WorkspaceManager.downloadFile(rel);
				}else{
					console.warn("link not found: ", rel);
				}
			});
		}
	});
});
<commit_msg>adjusted default split of the job results page<commit_after>define([
	"dojo/_base/declare", "dijit/layout/BorderContainer", "dojo/on",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"../PageGrid", "../formatter", "../../WorkspaceManager", "dojo/_base/lang",
	"dojo/dom-attr", "../WorkspaceExplorerView", "dijit/Dialog"
], function(declare, BorderContainer, on,
			domClass, ContentPane, domConstruct,
			Grid, formatter, WorkspaceManager, lang,
			domAttr, WorkspaceExplorerView, Dialog){
	return declare([BorderContainer], {
		"baseClass": "ExperimentViewer",
		"disabled": false,
		"query": null,
		data: null,
		containerType: "job_result",
		_resultType: null,
		_jobOut: {
			"id": {"label": "Job ID"},
			"start_time": {"label": "Start time", "format": formatter.epochDate},
			"end_time": {"label": "End time", "format": formatter.epochDate},
			"elapsed_time": {"label": "Run time", "format": formatter.runTime},
			"parameters": {"label": "Parameters", "format": function(d){
				if(d.hasOwnProperty('ustring')){
				    d['ustring'] = JSON.parse(d['ustring'])
				}
				return '
' + JSON.stringify(d,null,2) + "
"
			}}
		},
		_jobOrder: ["id", "start_time", "end_time", "elapsed_time", "parameters"],
		_appLabel: "",
		_resultMetaTypes: {},
		_autoLabels: {},
		_setDataAttr: function(data){
			this.data = data;
			//console.log("[JobResult] data: ", data);
			this._hiddenPath = data.path + "." + data.name;
			// console.log("[JobResult] Output Files: ", this.data.autoMeta.output_files);
			var _self = this;

			// check to see if there's a hidden .folder with the actual data
			WorkspaceManager.getObject(this._hiddenPath, true).otherwise(function(err) {
				new Dialog({
					content: "No output from this job was found in the '."+_self.data.name+"' folder. "
								  +"If you moved the job result file from another location, please ensure you "
									+"have also moved the accomanying folder to this location.",
					title: "Error Loading Job Result",
					style: "width: 300px !important;"
				}).show();
			});

			// get the contents directly from the hidden folder, since metadata may be stale after a move
			WorkspaceManager.getFolderContents(this._hiddenPath, true, true)
				.then(function(objs){
					//console.log("[JobResult] objects: ", objs);
						_self._resultObjects = objs;
						_self.setupResultType();
						_self.refresh();
				});

		},
		isSummaryView: function(){
			return false;
		},
		setupResultType: function(){
			// console.log("[JobResult] setupResultType()");
			if(this.data.autoMeta.app.id){
				this._resultType = this.data.autoMeta.app.id;
				// console.log("[JobResult] _resultType:",this._resultType);
			}
			if(this._resultType == "GenomeAssembly"){
				this._appLabel = "Genome Assembly";
			}
			else{
				this._appLabel = this._resultType;
			}
		},
		getExtraMetaDataForHeader: function(job_output){
			return job_output;
		},
		refresh: function(){
			// console.log("[JobResult] refresh()");
			if(this.data){
				var jobHeader = '

';
				if(this.data.autoMeta && this.data.autoMeta.app){
					jobHeader = jobHeader + this._appLabel + " ";
				}
				jobHeader = jobHeader + "Job Result" + '
';
				//this.viewer.set('content',jobHeader);

				var output = [];
				output.push(jobHeader + '

');
				var job_output = [];

				// add extra metadata header lines
				job_output = this.getExtraMetaDataForHeader(job_output)

				this._jobOrder.forEach(function(prop){
					/*if (prop=="output_files") { return; }
					if (prop=="app") { return; }
					if (prop=="job_output") { return; }
					if (prop=="hostname") { return; }*/
					if(!this.data.autoMeta[prop]){
						return;
					}

					if(this._jobOut.hasOwnProperty(prop)){
						//this._jobOut[prop]["value"]=this.data.autoMeta[prop];
						var tableLabel = this._jobOut[prop].hasOwnProperty("label") ? this._jobOut[prop]["label"] : prop;
						var tableValue = this._jobOut[prop].hasOwnProperty("format") ? this._jobOut[prop]["format"](this.data.autoMeta[prop]) : this.data.autoMeta[prop];
						if(prop == 'parameters') {
							job_output.push('

'+tableValue+'

');
						} else {
							job_output.push('
' + this._jobOut[prop]["label"] + '	' + tableValue + "
");
						}
					}
				}, this);
			}

			output.push.apply(output, job_output);
			output.push("

");

			if(this.data.userMeta){
				Object.keys(this.data.userMeta).forEach(function(prop){
					output.push("
" + prop + ": " + this.data.userMeta[prop] + "
");
				}, this);
			}

			output.push("
");
			this.viewHeader.set("content", output.join(""));
			this.resize();
		},
		startup: function(){
			if(this._started){
				return;
			}
			this.inherited(arguments);
			this.viewHeader = new ContentPane({content: "Loading data from "+this.data.name+" job file.  If you have moved your job result, please ensure you have also moved the ."+this.data.name+" folder to this directory as well.", region: "top", style:"width:90%;height:35%;", splitter: true});
			//this.viewer= new ContentPane({content: "", region: "center"});
			this.viewer = new WorkspaceExplorerView({region: "center", path: this._hiddenPath});
			// console.log("[JobResult] WSV: ", this.viewer);
			this.addChild(this.viewHeader);
			this.addChild(this.viewer);

			this.on("i:click", function(evt){
				var rel = domAttr.get(evt.target, 'rel');
				if(rel){
					WorkspaceManager.downloadFile(rel);
				}else{
					console.warn("link not found: ", rel);
				}
			});
		}
	});
});
<|endoftext|>


<commit_before>new Vue({
    el: 'body',
    data: {
        show: false,
        submit: false,
        error: false,
        finals: false,
        select: ['String', 'date', 'longText', 'integer', 'biginteger', 'boolean', 'float'],
        selected: '0',
        baseUrl: baseUrl,
        OneToMany: scaffoldList,
        attributes: {},
        OneToManyRows: 0,
        rows: 0,
    },
    methods: {
        increment: function() {
            this.error = false;
            this.rows += 1;
        },
        decrement: function() {
            if (this.rows == 0) {
                this.error = true;
            } else {
                this.rows -= 1;
            }
        },
        addOneToMany: function() {
            this.OneToManyRows += 1;
        },
        deleteOneToMany: function() {
            this.OneToManyRows -= 1;
        },
        getAttr: function() {
            var E = this.OneToManyRows;
            E -= 1;
            console.log('#tbl' + E);
            this.selected = $('#tbl' + E).val();
            console.log(this.baseUrl + '/scaffold/getAttributes/' + this.selected);
            $.ajax({
                method: 'get',
                url: this.baseUrl + '/scaffold/getAttributes/' + this.selected,
                success: function(response) {
                    this.attributes = response
                    console.log(this.attributes)
                }
            })
        }
    }
})<commit_msg>update test script<commit_after>new Vue({
    el: 'body',
    data: {
        show: false,
        submit: false,
        error: false,
        finals: false,
        select: ['String', 'date', 'longText', 'integer', 'biginteger', 'boolean', 'float'],
        selected: '0',
        baseUrl: baseUrl,
        OneToMany: scaffoldList,
        attributes: {},
        OneToManyRows: 0,
        rows: 0,
    },
    methods: {
        increment: function() {
            this.error = false;
            this.rows += 1;
        },
        decrement: function() {
            if (this.rows == 0) {
                if (this.OneToManyRows != 0) {
                    this.OneToManyRows -= 1;
                    return;
                }
                this.error = true;
            } else {
                this.rows -= 1;
            }
        },
        addOneToMany: function() {
            this.OneToManyRows += 1;
        },

        getAttr: function() {
            var E = this.OneToManyRows;
            E -= 1;
            console.log('#tbl' + E);
            this.selected = $('#tbl' + E).val();
            console.log(this.baseUrl + '/scaffold/getAttributes/' + this.selected);
            $.ajax({
                method: 'get',
                url: this.baseUrl + '/scaffold/getAttributes/' + this.selected,
                success: function(response) {
                    this.attributes = response
                    console.log(this.attributes)
                }
            })
        }
    }
})<|endoftext|>


<commit_before>angular.module('directives')
.directive('storySubmit', function () {
  return {
    restrict: 'EA',
    replace: true,
    controller: function($scope, storiesService, inputService, userService, $routeParams, $q, analyticService, $location){
      //  For WYSIWY
      $scope.tinymceOptions = {
        plugins: 'link image code',
        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code',
        image_dimensions: false
      };

      $scope.handleSuccess = function(id){
        $location.path('/success/save-story').search({d:id || $routeParams.storyId});
      };

      const storyPromise = $q(function(resolve, reject){
        if($routeParams.storyId === 'example'){
          $scope.exampleStory = true;
          resolve(storiesService.exampleStory)
        } else if ($routeParams.storyId) {
          // handle empty response, mis-match ids, and success
          storiesService.searchStories({_id:$routeParams.storyId}).then(function(res){
            if(res.data){
              const story = res.data;
              if(!userService.user._id === story.authorId){ $scope.pageErrorMessage = 'You do not have permission to edit this story.  Please try logging in under the account that authored this story.' }
              resolve(story);
            } else {
              $scope.pageErrorMessage = `Story not found.  Check the id in the URL and contact support if you continue to have problems`;
            }
          })
        } else {
          // default values
          resolve({
            inputs: {},
            html: 'Write your story here.  Include your interactive keywords with curly brackets like such: {keyword}'
          })
        }
      }).then(function(story) {
        story.html = inputService.bindTextKeywords(story.html, false);
        story.html = inputService.bindToggleKeywords(story.html, false);
        $scope.story = story;
      })

      $scope.submitStory = function(story){
        story = story || $scope.story;
        if(story.tags && !(typeof(story.tags) === 'object')){
          var tagArray = story.tags.split(/[,]+/).filter(Boolean);
          story.tags = tagArray.map(function(x){ return x.trim(); })
        }
        let inputs = story.inputs || {};
        if(Object.keys(inputs).length){
          let index = 0;
          for (var k in inputs){
            // TEMPORARY - get legacy up to date
            // for re-ordering legacy stories
            if (!inputs[k].index) { inputs[k].index = index; index++; }
            // for adding type of input
            if (!inputs[k].type){ inputs[k].type = 'text'}
            // end of temporary

            let input = inputs[k];
            // if changed / updated
            if (input.keyword != k){ inputs[input.keyword] = input; delete inputs[k]; }
            // if empty
            if (!input.keyword){ delete inputs[k] }
            // if added new
            if (inputs.hasOwnProperty(k) && input.hasOwnProperty('temporary') ) {
              delete input.temporary;
              inputs[input.keyword] = input;
              delete inputs[k];
            }
          }

          story.html = inputService.bindTextKeywords(story.html, true);
          story.html = inputService.bindToggleKeywords(story.html, true);
        }

        story.authorName = userService.isLoggedIn() ? 'Guest Author' : userService.user.profile.name;
        story.authorId = userService.user._id;

        storiesService.postStory(story).then(function(res){
          if(!res.data || res.data.error){
            $scope.globalErrorMessage = res.data.error || 'An error occured.  If problems continue contact support';
            console.error(res || 'error occured');
            analyticService.error('Post Story', 'storySubmit.js')
          } else {
            $scope.handleSuccess(res.data.savedStoryId);
          }
        });
      }

      $scope.add = function (type) {
        const length = Object.keys($scope.story.inputs).length;
        $scope.story.inputs[length] = {
          index: length,
          temporary: true,
          type: type
        };
      }
    },
    templateUrl: '/pages/storySubmit/storySubmit.html',
    scope: {}
  }
});
<commit_msg>adds some analytics calls<commit_after>angular.module('directives')
.directive('storySubmit', function () {
  return {
    restrict: 'EA',
    replace: true,
    controller: function($scope, storiesService, inputService, userService, $routeParams, $q, analyticService, $location){
      //  For WYSIWY
      $scope.tinymceOptions = {
        plugins: 'link image code',
        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code',
        image_dimensions: false
      };

      $scope.handleSuccess = function(id){
        $location.path('/success/save-story').search({d:id || $routeParams.storyId});
      };

      const storyPromise = $q(function(resolve, reject){
        if($routeParams.storyId === 'example'){
          $scope.exampleStory = true;
          resolve(storiesService.exampleStory)
        } else if ($routeParams.storyId) {
          // handle empty response, mis-match ids, and success
          storiesService.searchStories({_id:$routeParams.storyId}).then(function(res){
            if(res.data){
              const story = res.data;
              if(!userService.user._id === story.authorId){ $scope.pageErrorMessage = 'You do not have permission to edit this story.  Please try logging in under the account that authored this story.' }
              resolve(story);
            } else {
              $scope.pageErrorMessage = `Story not found.  Check the id in the URL and contact support if you continue to have problems`;
            }
          })
        } else {
          // default values
          resolve({
            inputs: {},
            html: 'Write your story here.  Include your interactive keywords with curly brackets like such: {keyword}'
          })
        }
      }).then(function(story) {
        story.html = inputService.bindTextKeywords(story.html, false);
        story.html = inputService.bindToggleKeywords(story.html, false);
        $scope.story = story;
      })

      $scope.submitStory = function(story){
        story = story || $scope.story;
        if(story.tags && !(typeof(story.tags) === 'object')){
          var tagArray = story.tags.split(/[,]+/).filter(Boolean);
          story.tags = tagArray.map(function(x){ return x.trim(); })
        }
        let inputs = story.inputs || {};
        if(Object.keys(inputs).length){
          let index = 0;
          for (var k in inputs){
            // TEMPORARY - get legacy up to date
            // for re-ordering legacy stories
            if (!inputs[k].index) { inputs[k].index = index; index++; }
            // for adding type of input
            if (!inputs[k].type){ inputs[k].type = 'text'}
            // end of temporary

            let input = inputs[k];
            // if changed / updated
            if (input.keyword != k){ inputs[input.keyword] = input; delete inputs[k]; }
            // if empty
            if (!input.keyword){ delete inputs[k] }
            // if added new
            if (inputs.hasOwnProperty(k) && input.hasOwnProperty('temporary') ) {
              delete input.temporary;
              inputs[input.keyword] = input;
              delete inputs[k];
            }
          }

          story.html = inputService.bindTextKeywords(story.html, true);
          story.html = inputService.bindToggleKeywords(story.html, true);
        }

        story.authorName = userService.isLoggedIn() ? 'Guest Author' : userService.user.profile.name;
        story.authorId = userService.user._id;

        storiesService.postStory(story).then(function(res){
          if(!res.data || res.data.error){
            $scope.globalErrorMessage = res.data.error || 'An error occured.  If problems continue contact support';
            console.error(res || 'error occured');
            analyticService.error('error posting story' , $scope.globalErrorMessage)
          } else {
            analyticService.event('Post Story', 'success posting story', res.data.savedStoryId )
            $scope.handleSuccess(res.data.savedStoryId);
          }
        });
      }

      $scope.add = function (type) {
        const length = Object.keys($scope.story.inputs).length;
        $scope.story.inputs[length] = {
          index: length,
          temporary: true,
          type: type
        };
      }
    },
    templateUrl: '/pages/storySubmit/storySubmit.html',
    scope: {}
  }
});
<|endoftext|>


<commit_before>'use strict';

if (!MODULE) { var MODULE = {}; }

MODULE.LevelScreen = (function() {
    var LevelScreen = function() {
        var self = this;

        this.screen = document.getElementById('screen-level');

        this.level_el = this.screen.getElementsByClassName('level-container')[0];
        this.grid_el = this.screen.getElementsByClassName('grid-container')[0];

        this.footer = this.screen.getElementsByTagName('footer')[0];
        this.header = this.screen.getElementsByTagName('header')[0];

        this.playcontrols = this.footer.getElementsByClassName('play-controls')[0];
        this.stopcontrols = this.footer.getElementsByClassName('stop-controls')[0];

        this.generation = this.header.getElementsByClassName('generation')[0];
        this.played = this.header.getElementsByClassName('played')[0];

        this.title = this.header.getElementsByClassName('title')[0];

        this.autowin = this.header.getElementsByClassName('autowin')[0];
        this.autowin_goal = this.autowin.getElementsByClassName('autowin-gen')[0];

        this.maxplay = this.header.getElementsByClassName('maxplay')[0];
        this.maxplayval = this.maxplay.getElementsByClassName('maxplay-val')[0];

        this.segment_generation = this.header.getElementsByClassName('segment-gen')[0];
        this.segment_played = this.header.getElementsByClassName('segment-played')[0];
        this.segment_red = this.header.getElementsByClassName('segment-red')[0];
        this.segment_green = this.header.getElementsByClassName('segment-green')[0];

        this.maxred_current = this.segment_red.getElementsByClassName('current')[0];
        this.maxred_limit = this.segment_red.getElementsByClassName('limit')[0];

        this.mingreen_current = this.segment_green.getElementsByClassName('current')[0];
        this.mingreen_limit = this.segment_green.getElementsByClassName('limit')[0];

        this.buttons = {
            play: this.footer.getElementsByClassName('play')[0],
            stop: this.footer.getElementsByClassName('stop')[0],
            clear: this.footer.getElementsByClassName('clear')[0],
            help: this.footer.getElementsByClassName('help')[0],
            library: this.footer.getElementsByClassName('library')[0],
            exit: this.footer.getElementsByClassName('exit')[0]
        };

        this.level = null;
        this.grid = null;
        this.level_id = null;
        this.library = null;

        this.buttons.play.onclick = this.onPlay.bind(this);
        this.buttons.stop.onclick = this.onStop.bind(this);
        this.buttons.clear.onclick = this.onClear.bind(this);
        this.buttons.help.onclick = this.onHelp.bind(this);
        this.buttons.library.onclick = this.onLibrary.bind(this);
        this.buttons.exit.onclick = this.onExit.bind(this);
    };

    LevelScreen.HEADER_HEIGHT = 50;
    LevelScreen.FOOTER_HEIGHT = 50;

    LevelScreen.prototype.display = function(level_id) {
        var self = this;

        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');
        this.header.className = '';
        this.footer.className = '';

        this.level_id = level_id;

        var campaign = app.content.data.campaign[level_id];
        this.title.innerHTML = campaign.name;

        var constraints = {
            width: app.device.viewport.width,
            height: app.device.viewport.height - (LevelScreen.HEADER_HEIGHT + LevelScreen.FOOTER_HEIGHT)
        };

        console.log('constraints', constraints);

        this.level = new MODULE.Level(campaign, this.level_el, constraints);

        this.grid = new MODULE.Grid(
            this.level.dimensions.width,
            this.level.dimensions.height,
            this.level.size,
            this.grid_el
        );

        this.level
        .on('generation', function(generation) {
            self.generation.textContent = generation;
        })
        .on('play-count', function(played) {
            self.played.textContent = played;
        })
        .on('status', function(status) {
            if (status === MODULE.Level.STATUS.DONE) {
                self.win();
            } else if (status === MODULE.Level.STATUS.LOSE) {
                self.lose();
            }
        })
        .on('win', function(data) {
            var my_level = app.storage.get('level', 0);
            var max_level = Object.keys(app.content.data.campaign).length;
            var levelup = false;

            if (data.level === max_level) {
                // TODO: Congratulate user on winning
                console.log("Beat the final level... Now what?");
            }

            if (data.level === my_level + 1) {
                levelup = true;
                app.storage.set('level', data.level);
                self.displayAdIfNeeded(data.level);
            }

            var rank = app.rank.get(data.level, data.generation, data.played);

            var rank_up = app.rank.report(data.level, rank.id);

            console.log('Rank up?', rank_up, rank);

            var content = LevelScreen.resultModal(rank, campaign.win, data.generation, data.played);

            if (levelup || rank_up) {
                app.modal.show(
                    content, [{
                        text: "Watch"
                    },{
                        text: "Next Level",
                        callback: function() {
                            app.screen.display('level', self.level_id + 1);
                        }
                    }], true
                );
            }

            app.analytics.track('LEVEL-WIN', {
                level: data.level,
                generation: data.generation,
                played: data.played,
                levelup: levelup
            });
        })
        .on('lose', function(data) {
            var rank = app.rank.getFailure();

            var content = LevelScreen.resultModal(rank, campaign.lose, data.generation, data.played);

            app.modal.show(
                content, [{
                    text: "Watch"
                },{
                    text: "Try Again",
                    callback: function() {
                        self.onStop();
                    }
                }], true
            );
        })
        .on('green-count', function(count) {
            self.mingreen_current.textContent = count;
        })
        .on('red-count', function(count) {
            self.maxred_current.textContent = count;
        });

        this.level.initialize();

        if (level_id > app.storage.get('level')) {
            this.incomplete();
            this.intro();
        } else {
            this.complete();
        }

        this.setGenerationGoal(this.level.autowin);
        this.setMaxPlay(this.level.maxplay);
        this.togglePlayedSegment(!!this.level.playables.length);
        this.toggleRedSegment(this.level.maxred);
        this.toggleGreenSegment(this.level.mingreen);

        var gamefield = this.level.gamefield;
        var finger = new Hammer(gamefield);
        finger.get('pinch').set({enable: true});

        /*
        finger.add(new Hammer.Pan({
            direction: Hammer.DIRECTION_ALL,
            threshold: 0
        }));
        */

        finger.on('pinchstart', function() {
            self.level.scaleStart();
        });

        finger.on('pinch', function(event) {
            self.level.scale(event.scale);
            self.grid.scale(self.level.size);
        });

        finger.on('pinchend', function() {
            self.level.scaleEnd();
        });

        // finger.on('pan', function(event) {});

        gamefield.onclick = function(event) {
            console.log('click');
            self.level.onTap(event);
        };

        // But hammer, I don't want you to stop my panning!
        gamefield.setAttribute('style', '');

        app.audio.playMusic('chapter-' + this.level.chapter);

        this.screen.style.display = 'block';

        this.library = null;

        app.analytics.track('SCREEN-LEVEL', {
            level: level_id
        });
    };

    LevelScreen.prototype.hide = function() {
        this.level.onStop();
        this.level = null;
        this.setGenerationGoal(0);
        this.setMaxPlay(0);
        this.screen.style.display = 'none';
    };

    LevelScreen.prototype.displayAdIfNeeded = function(level) {
        var min = app.content.data.dictionary.ad_min_level;
        var mod = app.content.data.dictionary.ad_mod_level;

        if (level >= min && level % mod === 0) {
            app.interstitial.show();
        }
    };

    LevelScreen.resultModal = function(rank, flavor, gen, played) {
        var html = "
\n";
            html += "

\n";
            html += "
\n";
                html += "
" + rank.name + "
\n";
                html += "
Gen: " + gen + " Played: " + played + "
\n";
            html += "
\n";
        html += "
\n";
        html += "
\n" + flavor + "
\n";

        return html;
    };

    LevelScreen.prototype.setGenerationGoal = function(generation) {
        this.autowin_goal.textContent = generation;

        this.autowin.classList.toggle('hide', !generation);
    };

    LevelScreen.prototype.setMaxPlay = function(maxplay) {
        this.maxplayval.textContent = maxplay;

        this.maxplay.classList.toggle('hide', !maxplay);
    };

    LevelScreen.prototype.togglePlayedSegment = function(count) {
        this.segment_played.classList.toggle('hide', !count);
        this.buttons.clear.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleRedSegment = function(count) {
        this.maxred_limit.textContent = count;
        this.segment_red.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleGreenSegment = function(count) {
        this.mingreen_limit.textContent = count;
        this.segment_green.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.complete = function() {
        this.header.classList.add('done');
        this.footer.classList.add('done');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.win = function() {
        this.header.classList.add('win');
        this.footer.classList.add('win');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.lose = function() {
        this.header.classList.add('lose');
        this.footer.classList.add('lose');
    };

    LevelScreen.prototype.incomplete = function() {
        this.header.classList.remove('done');
        this.footer.classList.remove('done');
        this.buttons.exit.classList.remove('cycle');
    };

    LevelScreen.prototype.intro = function() {
        app.modal.show("
" + this.level.name + "
" + this.level.description, [{
            text: "Ok"
        }]);
    };

    LevelScreen.prototype.getLibrary = function() {
        if (this.library) {
            return this.library;
        }

        var self = this;

        var library = '
';

        Object.keys(app.content.data.library).forEach(function(lib) {
            var item = app.content.data.library[lib];

            if (item.id > self.level.library) {
                return;
            }

            library +=
                '
' +
                    '' + item.name + '
' +
                    '' +
                '
';
        });

        library += '
';

        this.library = library;

        return this.library;
    };

    LevelScreen.prototype.onPlay = function() {
        app.audio.playSound('play');
        this.playcontrols.classList.remove('hide');
        this.stopcontrols.classList.add('hide');

        this.header.classList.add('playing');
        this.footer.classList.add('playing');

        app.analytics.track('LEVEL-START', {
            level: this.level_id
        });

        this.level.onPlay();
    };

    LevelScreen.prototype.onStop = function() {
        app.audio.playSound('stop');
        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');

        this.header.classList.remove('playing');
        this.footer.classList.remove('playing');
        //this.header.classList.add('win');
        //this.footer.classList.add('win');

        app.analytics.track('LEVEL-STOP', {
            level: this.level_id,
            generation: this.level.generation
        });

        this.unLose();
        this.level.onStop();
    };

    LevelScreen.prototype.unLose = function() {
        this.header.classList.remove('lose');
        this.footer.classList.remove('lose');
    };

    LevelScreen.prototype.onClear = function() {
        app.audio.playSound('clear');

        app.analytics.track('LEVEL-CLEAR', {
            level: this.level_id
        });

        this.level.onClear();
    };

    LevelScreen.prototype.onHelp = function() {
        this.intro();

        app.analytics.track('LEVEL-HELP', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onLibrary = function() {
        app.modal.show(this.getLibrary(), [{
            text: 'Ok'
        }]);

        app.analytics.track('LEVEL-LIBRARY', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onExit = function() {
        app.audio.playSound('back');
        app.screen.display('campaign');
    };

    return LevelScreen;
}());
<commit_msg>broken ios<commit_after>'use strict';

if (!MODULE) { var MODULE = {}; }

MODULE.LevelScreen = (function() {
    var LevelScreen = function() {
        var self = this;

        this.screen = document.getElementById('screen-level');

        this.level_el = this.screen.getElementsByClassName('level-container')[0];
        this.grid_el = this.screen.getElementsByClassName('grid-container')[0];

        this.footer = this.screen.getElementsByTagName('footer')[0];
        this.header = this.screen.getElementsByTagName('header')[0];

        this.playcontrols = this.footer.getElementsByClassName('play-controls')[0];
        this.stopcontrols = this.footer.getElementsByClassName('stop-controls')[0];

        this.generation = this.header.getElementsByClassName('generation')[0];
        this.played = this.header.getElementsByClassName('played')[0];

        this.title = this.header.getElementsByClassName('title')[0];

        this.autowin = this.header.getElementsByClassName('autowin')[0];
        this.autowin_goal = this.autowin.getElementsByClassName('autowin-gen')[0];

        this.maxplay = this.header.getElementsByClassName('maxplay')[0];
        this.maxplayval = this.maxplay.getElementsByClassName('maxplay-val')[0];

        this.segment_generation = this.header.getElementsByClassName('segment-gen')[0];
        this.segment_played = this.header.getElementsByClassName('segment-played')[0];
        this.segment_red = this.header.getElementsByClassName('segment-red')[0];
        this.segment_green = this.header.getElementsByClassName('segment-green')[0];

        this.maxred_current = this.segment_red.getElementsByClassName('current')[0];
        this.maxred_limit = this.segment_red.getElementsByClassName('limit')[0];

        this.mingreen_current = this.segment_green.getElementsByClassName('current')[0];
        this.mingreen_limit = this.segment_green.getElementsByClassName('limit')[0];

        this.buttons = {
            play: this.footer.getElementsByClassName('play')[0],
            stop: this.footer.getElementsByClassName('stop')[0],
            clear: this.footer.getElementsByClassName('clear')[0],
            help: this.footer.getElementsByClassName('help')[0],
            library: this.footer.getElementsByClassName('library')[0],
            exit: this.footer.getElementsByClassName('exit')[0]
        };

        this.level = null;
        this.grid = null;
        this.level_id = null;
        this.library = null;

        this.buttons.play.onclick = this.onPlay.bind(this);
        this.buttons.stop.onclick = this.onStop.bind(this);
        this.buttons.clear.onclick = this.onClear.bind(this);
        this.buttons.help.onclick = this.onHelp.bind(this);
        this.buttons.library.onclick = this.onLibrary.bind(this);
        this.buttons.exit.onclick = this.onExit.bind(this);
    };

    LevelScreen.HEADER_HEIGHT = 50;
    LevelScreen.FOOTER_HEIGHT = 50;

    LevelScreen.prototype.display = function(level_id) {
        var self = this;

        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');
        this.header.className = '';
        this.footer.className = '';

        this.level_id = level_id;

        var campaign = app.content.data.campaign[level_id];
        this.title.innerHTML = campaign.name;

        var constraints = {
            width: app.device.viewport.width,
            height: app.device.viewport.height - (LevelScreen.HEADER_HEIGHT + LevelScreen.FOOTER_HEIGHT)
        };

        console.log('constraints', constraints);

        this.level = new MODULE.Level(campaign, this.level_el, constraints);

        this.grid = new MODULE.Grid(
            this.level.dimensions.width,
            this.level.dimensions.height,
            this.level.size,
            this.grid_el
        );

        this.level
        .on('generation', function(generation) {
            self.generation.textContent = generation;
        })
        .on('play-count', function(played) {
            self.played.textContent = played;
        })
        .on('status', function(status) {
            if (status === MODULE.Level.STATUS.DONE) {
                self.win();
            } else if (status === MODULE.Level.STATUS.LOSE) {
                self.lose();
            }
        })
        .on('win', function(data) {
            var my_level = app.storage.get('level', 0);
            var max_level = Object.keys(app.content.data.campaign).length;
            var levelup = false;

            if (data.level === max_level) {
                // TODO: Congratulate user on winning
                console.log("Beat the final level... Now what?");
            }

            if (data.level === my_level + 1) {
                levelup = true;
                app.storage.set('level', data.level);
                self.displayAdIfNeeded(data.level);
            }

            var rank = app.rank.get(data.level, data.generation, data.played);

            var rank_up = app.rank.report(data.level, rank.id);

            console.log('Rank up?', rank_up, rank);

            var content = LevelScreen.resultModal(rank, campaign.win, data.generation, data.played);

            if (levelup || rank_up) {
                app.modal.show(
                    content, [{
                        text: "Watch"
                    },{
                        text: "Next Level",
                        callback: function() {
                            app.screen.display('level', self.level_id + 1);
                        }
                    }], true
                );
            }

            app.analytics.track('LEVEL-WIN', {
                level: data.level,
                generation: data.generation,
                played: data.played,
                levelup: levelup
            });
        })
        .on('lose', function(data) {
            var rank = app.rank.getFailure();

            var content = LevelScreen.resultModal(rank, campaign.lose, data.generation, data.played);

            app.modal.show(
                content, [{
                    text: "Watch"
                },{
                    text: "Try Again",
                    callback: function() {
                        self.onStop();
                    }
                }], true
            );
        })
        .on('green-count', function(count) {
            self.mingreen_current.textContent = count;
        })
        .on('red-count', function(count) {
            self.maxred_current.textContent = count;
        });

        this.level.initialize();

        if (level_id > app.storage.get('level')) {
            this.incomplete();
            this.intro();
        } else {
            this.complete();
        }

        this.setGenerationGoal(this.level.autowin);
        this.setMaxPlay(this.level.maxplay);
        this.togglePlayedSegment(!!this.level.playables.length);
        this.toggleRedSegment(this.level.maxred);
        this.toggleGreenSegment(this.level.mingreen);

        var gamefield = this.level.gamefield;
        var finger = new Hammer(gamefield);
        finger.get('pinch').set({enable: true});

        /*
        finger.add(new Hammer.Pan({
            direction: Hammer.DIRECTION_ALL,
            threshold: 0
        }));
        */

        finger.on('pinchstart', function() {
            self.level.scaleStart();
        });

        finger.on('pinch', function(event) {
            self.level.scale(event.scale);
            self.grid.scale(self.level.size);
        });

        finger.on('pinchend', function() {
            self.level.scaleEnd();
        });

        // finger.on('pan', function(event) {});

        gamefield.onclick = function(event) {
            alert('click');
            self.level.onTap(event);
        };

        // But hammer, I don't want you to stop my panning!
        gamefield.setAttribute('style', '');

        app.audio.playMusic('chapter-' + this.level.chapter);

        this.screen.style.display = 'block';

        this.library = null;

        app.analytics.track('SCREEN-LEVEL', {
            level: level_id
        });
    };

    LevelScreen.prototype.hide = function() {
        this.level.onStop();
        this.level = null;
        this.setGenerationGoal(0);
        this.setMaxPlay(0);
        this.screen.style.display = 'none';
    };

    LevelScreen.prototype.displayAdIfNeeded = function(level) {
        var min = app.content.data.dictionary.ad_min_level;
        var mod = app.content.data.dictionary.ad_mod_level;

        if (level >= min && level % mod === 0) {
            app.interstitial.show();
        }
    };

    LevelScreen.resultModal = function(rank, flavor, gen, played) {
        var html = "
\n";
            html += "

\n";
            html += "
\n";
                html += "
" + rank.name + "
\n";
                html += "
Gen: " + gen + " Played: " + played + "
\n";
            html += "
\n";
        html += "
\n";
        html += "
\n" + flavor + "
\n";

        return html;
    };

    LevelScreen.prototype.setGenerationGoal = function(generation) {
        this.autowin_goal.textContent = generation;

        this.autowin.classList.toggle('hide', !generation);
    };

    LevelScreen.prototype.setMaxPlay = function(maxplay) {
        this.maxplayval.textContent = maxplay;

        this.maxplay.classList.toggle('hide', !maxplay);
    };

    LevelScreen.prototype.togglePlayedSegment = function(count) {
        this.segment_played.classList.toggle('hide', !count);
        this.buttons.clear.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleRedSegment = function(count) {
        this.maxred_limit.textContent = count;
        this.segment_red.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.toggleGreenSegment = function(count) {
        this.mingreen_limit.textContent = count;
        this.segment_green.classList.toggle('hide', !count);
    };

    LevelScreen.prototype.complete = function() {
        this.header.classList.add('done');
        this.footer.classList.add('done');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.win = function() {
        this.header.classList.add('win');
        this.footer.classList.add('win');
        this.buttons.exit.classList.add('cycle');
    };

    LevelScreen.prototype.lose = function() {
        this.header.classList.add('lose');
        this.footer.classList.add('lose');
    };

    LevelScreen.prototype.incomplete = function() {
        this.header.classList.remove('done');
        this.footer.classList.remove('done');
        this.buttons.exit.classList.remove('cycle');
    };

    LevelScreen.prototype.intro = function() {
        app.modal.show("
" + this.level.name + "
" + this.level.description, [{
            text: "Ok"
        }]);
    };

    LevelScreen.prototype.getLibrary = function() {
        if (this.library) {
            return this.library;
        }

        var self = this;

        var library = '
';

        Object.keys(app.content.data.library).forEach(function(lib) {
            var item = app.content.data.library[lib];

            if (item.id > self.level.library) {
                return;
            }

            library +=
                '
' +
                    '' + item.name + '
' +
                    '' +
                '
';
        });

        library += '
';

        this.library = library;

        return this.library;
    };

    LevelScreen.prototype.onPlay = function() {
        app.audio.playSound('play');
        this.playcontrols.classList.remove('hide');
        this.stopcontrols.classList.add('hide');

        this.header.classList.add('playing');
        this.footer.classList.add('playing');

        app.analytics.track('LEVEL-START', {
            level: this.level_id
        });

        this.level.onPlay();
    };

    LevelScreen.prototype.onStop = function() {
        app.audio.playSound('stop');
        this.playcontrols.classList.add('hide');
        this.stopcontrols.classList.remove('hide');

        this.header.classList.remove('playing');
        this.footer.classList.remove('playing');
        //this.header.classList.add('win');
        //this.footer.classList.add('win');

        app.analytics.track('LEVEL-STOP', {
            level: this.level_id,
            generation: this.level.generation
        });

        this.unLose();
        this.level.onStop();
    };

    LevelScreen.prototype.unLose = function() {
        this.header.classList.remove('lose');
        this.footer.classList.remove('lose');
    };

    LevelScreen.prototype.onClear = function() {
        app.audio.playSound('clear');

        app.analytics.track('LEVEL-CLEAR', {
            level: this.level_id
        });

        this.level.onClear();
    };

    LevelScreen.prototype.onHelp = function() {
        this.intro();

        app.analytics.track('LEVEL-HELP', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onLibrary = function() {
        app.modal.show(this.getLibrary(), [{
            text: 'Ok'
        }]);

        app.analytics.track('LEVEL-LIBRARY', {
            level: this.level_id
        });
    };

    LevelScreen.prototype.onExit = function() {
        app.audio.playSound('back');
        app.screen.display('campaign');
    };

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


<commit_before>angular.module('bp').directive('bpNavbarConfig', function($state) {
  return {
    restrict: 'E',
    require: '^bpNavigation',
    transclude: true,
    compile: function(elem, attrs, transcludeFn) {
      return function(scope, element, attrs, ctrl) {
        transcludeFn(scope, function(clone) {
          ctrl.registerNavbar(attrs,clone,$state.current,scope)
          element.remove()
        })
      }
    }
  }
})
<commit_msg>docs(navbar-config): initial docs<commit_after>/**
@ngdoc directive
@name bp.directive:bpNavbarConfig
@restrict E
@requires bp.directive:bpNavigation
@description `bpNavbarConfig` is a way to configure navbars injected by the {@link bp.bpNavigation `bpNavigation`} directive.
It offers exactly the {@link bp.directive:bpNavbar#usage_parameters same attributes} for configuration as the original navbar, and forwards them to it.
If you put `bpAction`s into the directive they will be moved to the original navbar.
@example
<pre>
<bp-navbar-config bp-navbar-no-up>
  <bp-action class="icon-checkmark">
    Done
  </bp-action>
</bp-navbar-config>
</pre>
*/

angular.module('bp').directive('bpNavbarConfig', function($state) {
  return {
    restrict: 'E',
    require: '^bpNavigation',
    transclude: true,
    compile: function(elem, attrs, transcludeFn) {
      return function(scope, element, attrs, ctrl) {
        transcludeFn(scope, function(clone) {
          ctrl.registerNavbar(attrs,clone,$state.current,scope)
          element.remove()
        })
      }
    }
  }
})
<|endoftext|>


<commit_before>// need to set start end dates.

from = ISODate("2020-01-30T21:00:00Z");
to = ISODate("2020-06-30T21:00:00Z");

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

function setUsageData(old_count,final_left,new_total,final_usagev){

    new_updated_service = {
                          "count": old_count,
                          "left" : final_left,
                          "total" : new_total,
                          "usagev": final_usagev
                        };
    return new_updated_service;
}

function setTotal(new_cost,new_count,totals_object){
    totals_object['cost'] = new_cost;
    totals_object['count'] = new_count;
    return totals_object;
}

function checkService(service_name,from,to,sid){
//check if service non-custom
var service_non_custom = db.services.find({name:service_name,balance_period:{$exists:0}}).toArray()[0];

if(!isEmpty(service_non_custom)){
    //check if not connected to subs plan
    var sub_service_check = db.subscribers.find({sid: sid, services:{$exists:1,$ne: []}},{services:1}).toArray()[0];
    if(!isEmpty(sub_service_check)&&(sub_service_check!=="undefined")){
    for (var i = 0; i < sub_service_check['services'].length; i++) {

    if((sub_service_check['services'][i]['name'] === service_name)&&(from >=sub_service_check['services'][i]['from'])&&
            (to <=sub_service_check['services'][i]['to'])){
        return true;
    }
    }
}
}
    return false;

}

function checkIfBalanceExists(service_name){

    location = 'balance.groups.'+[service_name]+'.left';
    service_exists = db.balances.find({from:{$gte:from},to:{$lte:to}, service_name:service_name,
    [location]:{$gt:0}}).toArray()[0];

    // case all service usage is full, but server exists
     if (typeof service_exists === "undefined"){
    service_exists = db.balances.find({from:{$gte:from},to:{$lte:to}, service_name:service_name,
    [location]:{$eq:0}}).toArray()[0];
     }

    return service_exists;

}

old_balances = db.balances.find({from:{$gte:from},to:{$lte:to}, priority:{$eq:0},service_name:{$exists:0}});

if(old_balances.balance!=="undefined"){

old_balances.forEach(function (current_balance){

    id = current_balance._id;
    sid = current_balance.sid;
    data = current_balance['balance']['groups'];

          for ( var service_name in data) {
            is_valid = checkService(service_name,from,to,sid);
            if(is_valid){

               new_balance_found = checkIfBalanceExists(service_name);

               if(!isEmpty(new_balance_found)){
                   print("this service name exists, updating...");
                // old service data
                    old_group_data = current_balance['balance']['groups'][service_name];
                    new_group_data = new_balance_found['balance']['groups'][service_name];

                    call_or_data = null;
                //check if service is data or calls
                    if (typeof (new_group_data['usage_types']) === "undefined") {
                        call_or_data = "call";
                    } else {
                        call_or_data = "data";
                    }

                    old_count = old_group_data.count;
                    old_left = old_group_data.left;
                    old_total = old_group_data.total;
                    old_usagev =  old_group_data.usagev;
                    old_cost = current_balance['balance']['totals'][call_or_data].cost;

                //new serivce data
                    new_left = new_group_data.left;
                    new_total = new_group_data.total;
                    new_usagev = new_group_data.usagev;
                    new_cost = old_cost + new_balance_found['balance']['totals'][call_or_data].cost;
                    new_count = old_count+new_group_data.count;

                //final service data
                    final_usagev = old_usagev + new_usagev;

                    //set service usage data
                    final_left = new_total - final_usagev;
                    if(final_left<0){
                        final_left = 0;
                    }
                    new_updated_service = setUsageData(old_count,final_left,new_total,final_usagev);
                    //set total object
                    new_total_object = setTotal(new_cost,new_count,new_balance_found['balance']['totals'][call_or_data]);
                    new_balance_found['balance']['groups'][service_name] = new_updated_service;
                    new_balance_found['balance']['totals'][call_or_data] = new_total_object;
                    new_balance_found['service_updated'] = true;
                    db.balances.save(new_balance_found);

                unset_old_values = 'balance.'+'groups.'+service_name;
                print(unset_old_values);
                db.balances.update(
                        { _id: id },
                        { $unset: { [unset_old_values]: "" } }
                        )
               }
                else{
                    //service doesn't exist
                    print("no aligned services found");
                }
            }

            }
});
}
<commit_msg>BRCD-2556: split monthly balances that has aligned to cycle add-ons to monthly balance + add-on balance<commit_after>const time = ISODate();
const services = getServices();

services.forEach(function (service) {
	const groups = getServiceGroups(service);
	groups.forEach(function (group) {
		const balances = getBalances(group);
		balances.forEach(function (balance) {
			// update/create add-on specific balance
			db.balances.update(
							{
								aid: balance['aid'],
								sid: balance['sid'],
								from: balance['from'],
								to: balance['to'],
								period: balance['period'],
								service_name: service['name'],
								connection_type: 'postpaid',
								priority: {
									$exists: true,
									$ne: 0
								}
							},
							{
								$setOnInsert: {
									aid: balance['aid'],
									sid: balance['sid'],
									from: balance['from'],
									to: balance['to'],
									period: balance['period'],
									start_period: balance['start_period'],
									connection_type: balance['connection_type'],
									current_plan: balance['current_plan'],
									plan_description: balance['plan_description'],
									priority: service['service_id'] || Math.floor(Math.random() * 10000000000000000) + 1,
									service_name: service['name'],
									added_by_script: ISODate(),
									['balance.groups.' + group['name'] + '.total']: balance['balance']['groups'][group['name']]['total'],
									['balance.totals.' + group['usaget'] + '.cost']: 0
								},
								$inc: {
									['balance.groups.' + group['name'] + '.count']: balance['balance']['groups'][group['name']]['count'],
									['balance.groups.' + group['name'] + '.usagev']: balance['balance']['groups'][group['name']]['usagev'],
									['balance.totals.' + group['usaget'] + '.usagev']: balance['balance']['groups'][group['name']]['usagev'],
									['balance.totals.' + group['usaget'] + '.count']: balance['balance']['groups'][group['name']]['count']
								},
								$set: {
									['balance.groups.' + group['name'] + '.left']: balance['balance']['groups'][group['name']]['left']
								}
							},
							{
								upsert: true
							}
			);

			// update balance totals
			balance['balance']['totals'][group['usaget']]['usagev'] -= balance['balance']['groups'][group['name']]['usagev'];
			balance['balance']['totals'][group['usaget']]['count'] -= balance['balance']['groups'][group['name']]['count'];

			// remove group from monthly balance
			delete balance['balance']['groups'][group['name']];
			if (typeof Object.keys(balance['balance']['groups'])[0] == 'undefined') {
				delete balance['balance']['groups'];
			}
			balance['updated_by_script'] = ISODate();
			db.balances.save(balance);
		});
	});

});

// get services aligned to cycle that are not included in any plan
function getServices() {
	const ret = [];
	const alignedToCycleServices = db.services.find({
		from: {$lte: time},
		to: {$gt: time},
		$or: [
			{balance_period: {$exists: false}},
			{balance_period: 'default'}
		]
	});
	var servicesIncludedInPlans = db.plans.aggregate([
		{
			$match: {
				from: {$lte: time},
				to: {$gt: time},
				'include.services': {$exists: true}
			}
		},
		{
			$unwind: '$include.services'
		},
		{
			$project: {
				_id: 0,
				service: '$include.services'
			}
		}
	]);

	const servicesIncludedInPlansNames = servicesIncludedInPlans.map(x => x['service']);
	alignedToCycleServices.forEach(function (service) {
		if (servicesIncludedInPlansNames.indexOf(service['name']) == -1) {
			ret.push(service);
		}
	});

	return ret;
}

// get monthly balances with existing group
function getBalances(group) {
	const ret = db.balances.find({
		from: {$lte: time},
		to: {$gt: time},
		['balance.groups.' + group['name']]: {$exists: true},
		priority: 0
	});

	return ret;
}

function getServiceGroups(service) {
	const ret = [];
	if (typeof service['include'] == 'undefined' || typeof service['include']['groups'] == 'undefined') {
		return ret;
	}

	for (var group in service['include']['groups']) {
		ret.push({
			name: group,
			usaget: Object.keys(service['include']['groups'][group]['usage_types'])[0],
			value: service['include']['groups'][group]['value'],
		});
	}

	return ret;
}<|endoftext|>


<commit_before>// ==UserScript==
// @name        Basecamp Classic hours in person days
// @namespace   soultank.ch
// @include     https://*.basecamphq.com/*
// @version     1
// @grant       none
// ==/UserScript==

//configuration: how many hours does a person day have?
var hoursInPersonDay = 8;

var hoursWorkedCell = document.getElementById('hours_subtotal')
var hoursWorkedString = hoursWorkedCell.innerHTML.replace(',', '.');
console.log("hoursWorkedString: "+ hoursWorkedString);
var hoursWorked = parseFloat(hoursWorkedString);

console.log("hoursworked: "+ hoursWorked);

var daysWorked = hoursWorked / hoursInPersonDay;

console.log("daysWorked: "+ daysWorked);

var daysWorkedTwoDecimals = daysWorked.toFixed(2);

console.log("daysWorkedTwoDecimals: "+ daysWorkedTwoDecimals);

var daysWorkedCell = document.createElement('td');

var textDaysTotal = daysWorkedTwoDecimals.toString() +  " (Tage)";

console.log("textDaysTotal: " + textDaysTotal);

daysWorkedCell.innerHTML = textDaysTotal;

daysWorkedCell.setAttribute("class","hours");

var nextSiblingOfHoursWorkedCell = hoursWorkedCell.nextSibling;

hoursWorkedCell.parentNode.insertBefore(daysWorkedCell, nextSiblingOfHoursWorkedCell);

<commit_msg>Display-Text geändert<commit_after>// ==UserScript==
// @name        Basecamp Classic hours in person days
// @namespace   soultank.ch
// @include     https://*.basecamphq.com/*
// @version     1
// @grant       none
// ==/UserScript==

//configuration: how many hours does a person day have?
var hoursInPersonDay = 8;

var hoursWorkedCell = document.getElementById('hours_subtotal')
var hoursWorkedString = hoursWorkedCell.innerHTML.replace(',', '.');
console.log("hoursWorkedString: "+ hoursWorkedString);
var hoursWorked = parseFloat(hoursWorkedString);

console.log("hoursworked: "+ hoursWorked);

var daysWorked = hoursWorked / hoursInPersonDay;

console.log("daysWorked: "+ daysWorked);

var daysWorkedTwoDecimals = daysWorked.toFixed(2);

console.log("daysWorkedTwoDecimals: "+ daysWorkedTwoDecimals);

var daysWorkedCell = document.createElement('td');

var textDaysTotal = "(" + daysWorkedTwoDecimals.toString() +  " Tage)";

console.log("textDaysTotal: " + textDaysTotal);

daysWorkedCell.innerHTML = textDaysTotal;

daysWorkedCell.setAttribute("class","hours");

var nextSiblingOfHoursWorkedCell = hoursWorkedCell.nextSibling;

hoursWorkedCell.parentNode.insertBefore(daysWorkedCell, nextSiblingOfHoursWorkedCell);

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2015 Netforce Co. Ltd.
 *
 * 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.
 */

var FieldText=NFView.extend({
    _name: "field_text",
    className: "form-group nf-field",
    events: {
        "change textarea": "onchange",
        "blur textarea": "blur",
        "keyup textarea": "keyup",
        "focus textarea": "on_focus",
        "click .view-source": "view_source",
        "keydown textarea": "keydown"
    },

    initialize: function(options) {
        NFView.prototype.initialize.call(this,options);
        var name=this.options.name;
        var model=this.context.model;
        model.on("change:"+name,this.render,this);
        if (this.options.inner) {
            this.template=this.options.inner;
        }
        this.listen_attrs();
    },

    render: function() {
        log("field_text.render",this);
        var name=this.options.name;
        var model=this.context.model;
        this.data.value=model.get(name);
        var field=model.get_field(name);
        this.data.string=this.options.string||field.string;
        this.data.readonly=field.readonly||this.options.readonly||this.context.readonly;
        var has_focus=this.$el.find("textarea").is(":focus");
        this.disable_blur=true;
        var form_layout=this.options.form_layout||"stacked";
        this.data.horizontal=this.options.form_layout=="horizontal";
        NFView.prototype.render.call(this);
        this.disable_blur=false;
        if (has_focus) this.$el.find("textarea").focus();
        var attrs=this.eval_attrs();
        if (this.options.invisible || attrs.invisible) {
            this.$el.hide();
        } else {
            this.$el.show();
        }
        var required=false;
        if (field.required!=null) required=field.required;
        if (this.options.required!=null) required=this.options.required;
        if (attrs.required!=null) required=attrs.required;
        if (required && !this.data.readonly) {
            this.$el.addClass("nf-required-field");
        }
        if (required) {
            model.set_required(name);
        } else {
            model.set_not_required(name);
        }
        var err=model.get_field_error(name);
        if (err) {
            this.$el.addClass("error");
        } else {
            this.$el.removeClass("error");
        }
        if (this.options.span && !this.options.span_input_only) {
            this.$el.addClass("col-sm-"+this.options.span);
            this.$el.find("textarea").addClass("col-sm-"+this.options.span);
        }
        if (this.options.width) {
            this.$el.find("textarea").css("width",this.options.width+"px");
        }
        this.$el.find("textarea").css("height",(this.options.height||70)+"px");
        if (this.options.nomargin) {
            this.$el.find("textarea").css({margin: 0});
            this.$el.css({margin: 0});
        }
        if (this.options.autoresize) {
            this.$el.find("textarea").css({resize:"none"});
            var width=this.$el.find("textarea").width();
            var height=this.$el.find("textarea").height();
            var text=this.$el.find("textarea").val();
            this.$mirror=$("<div/>").css({whiteSpace:"pre-wrap",wordWrap:"break-word",padding:"2px 4px",fontSize:"12px",visibility:"hidden"});
            this.$mirror.text(text);
            this.$mirror.width(width);
            this.$el.find("textarea").css({position:"absolute"});
            this.$el.find(".mirror-cont").append(this.$mirror);
            this.$el.find("textarea").height(height+20);
        }
        var that=this;
        if (this.options.wysi) {
            var el=that.$el.find("textarea")[0];
            var editor=CKEDITOR.replace(el,{
                width: this.options.width||300,
                height: this.options.height||70,
                filebrowserUploadUrl:  '/ck_upload',
                allowedContent: true // XXX
            });
            if (editor) {
                editor.on("change",function(e) {
                    var val=editor.getData();
                    log("ckeditor change");
                    var name=that.options.name;
                    var model=that.context.model;
                    model.set(name,val,{silent:true});
                });
            } else {
                log("ERROR! can't create ckeditor!");
            }
        }
    },

    onchange: function() {
        log("field_text.onchange");
        var val=this.$el.find("textarea").val();
        var name=this.options.name;
        var model=this.context.model;
        model.set(name,val,{silent:true});
    },

    focus: function() {
        log("field_text.focus");
        this.$el.find("textarea").focus();
    },

    blur: function(e) {
        log("field_text.blur");
        if (this.disable_blur) return; // because chrome fires blur event when element is removed (during rerender for ex)
        this.trigger("blur");
    },

    keyup: function(e) {
        log("field_text.keyup",e.keyCode);
        if (!this.$mirror) return;
        var v=this.$el.find("textarea").val();
        this.$mirror.text(v);
        var h=this.$mirror.height();
        log("TTTTTTTTTTTTTT",v,h);
        this.$el.find("textarea").height(h+20);
    },

    on_focus: function(e) {
        log("field_text.on_focus",this);
        var that=this;
        register_focus(e.target);
        if (this.options.onfocus) {
            var name=this.options.name;
            var model=this.context.model;
            var path=model.get_path(name);
            var form=this.context.form;
            form.do_onfocus(that.options.onfocus,path);
        }
    },

    view_source: function(e) {
        log("view_source");
        e.preventDefault();
        e.stopPropagation();
        if (this.$el.find(".editor").is(":visible")) {
            var val=this.$el.find(".editor").html();
            this.$el.find("textarea").text(val);
            this.$el.find(".editor").hide();
            this.$el.find("textarea").show();
        } else {
            var val=this.$el.find("textarea").val();
            this.$el.find(".editor").html(val);
            this.$el.find("textarea").hide();
            this.$el.find(".editor").show();
        }
    },

    eval_attrs: function() {
        var str=this.options.attrs;
        //log("eval_attrs",this,str);
        if (!str) return {};
        var expr=JSON.parse(str);
        var model=this.context.model;
        var attrs={};
        for (var attr in expr) {
            var conds=expr[attr];
            var attr_val=true;
            for (var i in conds) {
                var clause=conds[i];
                var n=clause[0];
                var op=clause[1];
                var cons=clause[2];
                var v=model.get(n);
                var clause_v;
                if (op=="=") {
                    clause_v=v==cons;
                } else if (op=="!=") {
                    clause_v=v!=cons;
                } else if (op=="in") {
                    clause_v=_.contains(cons,v);
                } else if (op=="not in") {
                    clause_v=!_.contains(cons,v);
                } else {
                    throw "Invalid operator: "+op;
                }
                if (!clause_v) {
                    attr_val=false;
                    break;
                }
            }
            attrs[attr]=attr_val;
        }
        //log("==>",attrs);
        return attrs;
    },

    listen_attrs: function() {
        var str=this.options.attrs;
        //log("listen_attrs",this,str);
        if (!str) return;
        var expr=JSON.parse(str);
        var attrs={};
        var depends=[];
        for (var attr in expr) {
            var conds=expr[attr];
            for (var i in conds) {
                var clause=conds[i];
                var n=clause[0];
                depends.push(n);
            }
        }
        //log("==> depends",depends);
        var model=this.context.model;
        for (var i in depends) {
            var n=depends[i];
            //log("...listen "+n);
            model.on("change:"+n,this.render,this);
        }
    },

    keydown: function (e) {
        log("field_text.keydown",e.keyCode);
        if (e.keyCode==9) {
            e.preventDefault();
            if (e.shiftKey) {
                this.trigger("focus_prev");
                if (!this.options.disable_focus_change) {
                    focus_prev();
                }
            } else {
                this.trigger("focus_next");
                if (!this.options.disable_focus_change) {
                    focus_next();
                }
            }
        }
    }
});

FieldText.register();
<commit_msg>ADD : onchange on field text<commit_after>/*
 * Copyright (c) 2012-2015 Netforce Co. Ltd.
 *
 * 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.
 */

var FieldText=NFView.extend({
    _name: "field_text",
    className: "form-group nf-field",
    events: {
        "change textarea": "onchange",
        "blur textarea": "blur",
        "keyup textarea": "keyup",
        "focus textarea": "on_focus",
        "click .view-source": "view_source",
        "keydown textarea": "keydown"
    },

    initialize: function(options) {
        NFView.prototype.initialize.call(this,options);
        var name=this.options.name;
        var model=this.context.model;
        model.on("change:"+name,this.render,this);
        if (this.options.inner) {
            this.template=this.options.inner;
        }
        this.listen_attrs();
    },

    render: function() {
        log("field_text.render",this);
        var name=this.options.name;
        var model=this.context.model;
        this.data.value=model.get(name);
        var field=model.get_field(name);
        this.data.string=this.options.string||field.string;
        this.data.readonly=field.readonly||this.options.readonly||this.context.readonly;
        var has_focus=this.$el.find("textarea").is(":focus");
        this.disable_blur=true;
        var form_layout=this.options.form_layout||"stacked";
        this.data.horizontal=this.options.form_layout=="horizontal";
        NFView.prototype.render.call(this);
        this.disable_blur=false;
        if (has_focus) this.$el.find("textarea").focus();
        var attrs=this.eval_attrs();
        if (this.options.invisible || attrs.invisible) {
            this.$el.hide();
        } else {
            this.$el.show();
        }
        var required=false;
        if (field.required!=null) required=field.required;
        if (this.options.required!=null) required=this.options.required;
        if (attrs.required!=null) required=attrs.required;
        if (required && !this.data.readonly) {
            this.$el.addClass("nf-required-field");
        }
        if (required) {
            model.set_required(name);
        } else {
            model.set_not_required(name);
        }
        var err=model.get_field_error(name);
        if (err) {
            this.$el.addClass("error");
        } else {
            this.$el.removeClass("error");
        }
        if (this.options.span && !this.options.span_input_only) {
            this.$el.addClass("col-sm-"+this.options.span);
            this.$el.find("textarea").addClass("col-sm-"+this.options.span);
        }
        if (this.options.width) {
            this.$el.find("textarea").css("width",this.options.width+"px");
        }
        this.$el.find("textarea").css("height",(this.options.height||70)+"px");
        if (this.options.nomargin) {
            this.$el.find("textarea").css({margin: 0});
            this.$el.css({margin: 0});
        }
        if (this.options.autoresize) {
            this.$el.find("textarea").css({resize:"none"});
            var width=this.$el.find("textarea").width();
            var height=this.$el.find("textarea").height();
            var text=this.$el.find("textarea").val();
            this.$mirror=$("<div/>").css({whiteSpace:"pre-wrap",wordWrap:"break-word",padding:"2px 4px",fontSize:"12px",visibility:"hidden"});
            this.$mirror.text(text);
            this.$mirror.width(width);
            this.$el.find("textarea").css({position:"absolute"});
            this.$el.find(".mirror-cont").append(this.$mirror);
            this.$el.find("textarea").height(height+20);
        }
        var that=this;
        if (this.options.wysi) {
            var el=that.$el.find("textarea")[0];
            var editor=CKEDITOR.replace(el,{
                width: this.options.width||300,
                height: this.options.height||70,
                filebrowserUploadUrl:  '/ck_upload',
                allowedContent: true // XXX
            });
            if (editor) {
                editor.on("change",function(e) {
                    var val=editor.getData();
                    log("ckeditor change");
                    var name=that.options.name;
                    var model=that.context.model;
                    model.set(name,val,{silent:true});
                });
            } else {
                log("ERROR! can't create ckeditor!");
            }
        }
    },

    onchange: function() {
        log("field_text.onchange");
        var val=this.$el.find("textarea").val();
        var name=this.options.name;
        var model=this.context.model;
        model.set(name,val,{silent:true});
        if (this.options.onchange) {
            var path=model.get_path(name);
            var form=this.context.form;
            form.do_onchange(this.options.onchange,path);
        }
    },

    focus: function() {
        log("field_text.focus");
        this.$el.find("textarea").focus();
    },

    blur: function(e) {
        log("field_text.blur");
        if (this.disable_blur) return; // because chrome fires blur event when element is removed (during rerender for ex)
        this.trigger("blur");
    },

    keyup: function(e) {
        log("field_text.keyup",e.keyCode);
        if (!this.$mirror) return;
        var v=this.$el.find("textarea").val();
        this.$mirror.text(v);
        var h=this.$mirror.height();
        log("TTTTTTTTTTTTTT",v,h);
        this.$el.find("textarea").height(h+20);
    },

    on_focus: function(e) {
        log("field_text.on_focus",this);
        var that=this;
        register_focus(e.target);
        if (this.options.onfocus) {
            var name=this.options.name;
            var model=this.context.model;
            var path=model.get_path(name);
            var form=this.context.form;
            form.do_onfocus(that.options.onfocus,path);
        }
    },

    view_source: function(e) {
        log("view_source");
        e.preventDefault();
        e.stopPropagation();
        if (this.$el.find(".editor").is(":visible")) {
            var val=this.$el.find(".editor").html();
            this.$el.find("textarea").text(val);
            this.$el.find(".editor").hide();
            this.$el.find("textarea").show();
        } else {
            var val=this.$el.find("textarea").val();
            this.$el.find(".editor").html(val);
            this.$el.find("textarea").hide();
            this.$el.find(".editor").show();
        }
    },

    eval_attrs: function() {
        var str=this.options.attrs;
        //log("eval_attrs",this,str);
        if (!str) return {};
        var expr=JSON.parse(str);
        var model=this.context.model;
        var attrs={};
        for (var attr in expr) {
            var conds=expr[attr];
            var attr_val=true;
            for (var i in conds) {
                var clause=conds[i];
                var n=clause[0];
                var op=clause[1];
                var cons=clause[2];
                var v=model.get(n);
                var clause_v;
                if (op=="=") {
                    clause_v=v==cons;
                } else if (op=="!=") {
                    clause_v=v!=cons;
                } else if (op=="in") {
                    clause_v=_.contains(cons,v);
                } else if (op=="not in") {
                    clause_v=!_.contains(cons,v);
                } else {
                    throw "Invalid operator: "+op;
                }
                if (!clause_v) {
                    attr_val=false;
                    break;
                }
            }
            attrs[attr]=attr_val;
        }
        //log("==>",attrs);
        return attrs;
    },

    listen_attrs: function() {
        var str=this.options.attrs;
        //log("listen_attrs",this,str);
        if (!str) return;
        var expr=JSON.parse(str);
        var attrs={};
        var depends=[];
        for (var attr in expr) {
            var conds=expr[attr];
            for (var i in conds) {
                var clause=conds[i];
                var n=clause[0];
                depends.push(n);
            }
        }
        //log("==> depends",depends);
        var model=this.context.model;
        for (var i in depends) {
            var n=depends[i];
            //log("...listen "+n);
            model.on("change:"+n,this.render,this);
        }
    },

    keydown: function (e) {
        log("field_text.keydown",e.keyCode);
        if (e.keyCode==9) {
            e.preventDefault();
            if (e.shiftKey) {
                this.trigger("focus_prev");
                if (!this.options.disable_focus_change) {
                    focus_prev();
                }
            } else {
                this.trigger("focus_next");
                if (!this.options.disable_focus_change) {
                    focus_next();
                }
            }
        }
    }
});

FieldText.register();
<|endoftext|>


<commit_before>require('angular');
Howl = require('howler');    // for sounds (if you need them)
Nodule = require('nodule');  // for nodule helpers

var app = angular.module('asteroid-mining', []);

app.directive("asteroidMining", function() {
    return {
        restrict: 'E',
        templateUrl: "/ng-modules/asteroidMining/asteroidMining.html"
    };
});

app.controller("asteroidMiningController", ['data', '$scope', '$rootScope', function(data, $scope, $rootScope) {
    var vm = this;
    vm.nodule = new Nodule($rootScope, 'asteroid-mining', function(){
      vm.game = new Phaser.Game(800, 600, Phaser.CANVAS, 'asteroid-mining-content', {
        preload: vm.preload,
        create: vm.create,
        update: vm.update,
        render: vm.render
      });
    });

    vm.preload = function() {

      vm.game.load.image('a1', 'http://examples.phaser.io/assets/games/asteroids/asteroid1.jpg');
      vm.game.load.image('a2', 'http://examples.phaser.io/assets/games/asteroids/asteroid2.jpg');
      vm.game.load.image('a3', 'http://examples.phaser.io/assets/games/asteroids/asteroid3.jpg');
      vm.game.load.image('space', 'http://examples.phaser.io/assets/skies/deep-space.jpg');
      vm.game.load.image('bullet', 'http://examples.phaser.io/assets/games/asteroids/bullets.png');
      vm.game.load.image('ship', 'http://examples.phaser.io/assets/games/asteroids/ship.png');

    }

    vm.create = function() {
      //  This will run in Canvas mode, so let's gain a little speed and display
      vm.game.renderer.clearBeforeRender = false;
      vm.game.renderer.roundPixels = true;

      //  We need arcade physics
      vm.game.physics.startSystem(Phaser.Physics.ARCADE);

      //  A spacey background
      vm.game.add.tileSprite(0, 0, game.width, game.height, 'space');
    }

    vm.update = function() {

    }

    vm.render = function() {

    }
}]);

module.exports = angular.module('asteroid-mining').name;
<commit_msg>simple asteroid like implementation for #67<commit_after>require('angular');
Howl = require('howler');    // for sounds (if you need them)
Nodule = require('nodule');  // for nodule helpers

var app = angular.module('asteroid-mining', []);

app.directive("asteroidMining", function() {
    return {
        restrict: 'E',
        templateUrl: "/ng-modules/asteroidMining/asteroidMining.html"
    };
});

app.controller("asteroidMiningController", ['data', '$scope', '$rootScope', function(data, $scope, $rootScope) {
    var vm = this;
    vm.nodule = new Nodule($rootScope, 'asteroid-mining', function(){
      vm.game = new Phaser.Game(800, 600, Phaser.CANVAS, 'asteroid-mining-content', {
        preload: vm.preload,
        create: vm.create,
        update: vm.update,
        render: vm.render
      });
    });

    vm.bulletTime = 0;

    vm.preload = function() {

      vm.game.load.image('a1', 'http://examples.phaser.io/assets/games/asteroids/asteroid1.jpg');
      vm.game.load.image('a2', 'http://examples.phaser.io/assets/games/asteroids/asteroid2.jpg');
      vm.game.load.image('a3', 'http://examples.phaser.io/assets/games/asteroids/asteroid3.jpg');
      vm.game.load.image('space', 'http://examples.phaser.io/assets/skies/deep-space.jpg');
      vm.game.load.image('bullet', 'http://examples.phaser.io/assets/games/asteroids/bullets.png');
      vm.game.load.image('ship', 'http://examples.phaser.io/assets/games/asteroids/ship.png');

    }

    vm.create = function() {
      //  This will run in Canvas mode, so let's gain a little speed and display
      vm.game.renderer.clearBeforeRender = true;
      vm.game.renderer.roundPixels = true;

      //  We need arcade physics
      vm.game.physics.startSystem(Phaser.Physics.ARCADE);

      //  A spacey background
      vm.game.add.tileSprite(0, 0, vm.game.width, vm.game.height, 'space');

      //  Our ships bullets
      vm.bullets = vm.game.add.group();
      vm.bullets.enableBody = true;
      vm.bullets.physicsBodyType = Phaser.Physics.ARCADE;

      //  All 40 of them
      vm.bullets.createMultiple(40, 'bullet');
      vm.bullets.setAll('anchor.x', 0.5);
      vm.bullets.setAll('anchor.y', 0.5);

      //  Our player ship
      vm.sprite = vm.game.add.sprite(300, 300, 'ship');
      vm.sprite.anchor.set(0.5);

      //  and its physics settings
      vm.game.physics.enable(vm.sprite, Phaser.Physics.ARCADE);

      vm.sprite.body.drag.set(0);
      vm.sprite.body.maxVelocity.set(200);

      // asteroids
      vm.asteroids = vm.game.add.group();
      vm.asteroids.enableBody = true;
      vm.asteroids.physicsBodyType = Phaser.Physics.ARCADE;

      vm.asteroids.createMultiple(3, 'a1');
      vm.asteroids.createMultiple(3, 'a2');
      vm.asteroids.createMultiple(3, 'a3');
      vm.createAsteroids();

      //  Game input
      vm.cursors = vm.game.input.keyboard.createCursorKeys();
      vm.game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]);
    }

    vm.update = function() {
      if (vm.cursors.up.isDown)
      {
          vm.game.physics.arcade.accelerationFromRotation(vm.sprite.rotation, 200, vm.sprite.body.acceleration);
      }
      else
      {
          vm.sprite.body.acceleration.set(0);
      }

      if (vm.cursors.left.isDown)
      {
          vm.sprite.body.angularVelocity = -300;
      }
      else if (vm.cursors.right.isDown)
      {
          vm.sprite.body.angularVelocity = 300;
      }
      else
      {
          vm.sprite.body.angularVelocity = 0;
      }

      if (vm.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR))
      {
          vm.fireBullet();
      }

      vm.screenWrap(vm.sprite);

      vm.bullets.forEachExists(vm.screenWrap, this);

      vm.asteroids.forEachExists(function (item) {
              item.x += item.moveX;
              item.y += item.moveY;
              item.angle += item.rotateAngle;
              vm.screenWrap(item);
          });

      vm.game.physics.arcade.overlap(vm.bullets, vm.asteroids, null, function(bullet, asteroid){
          if (!bullet.alive || !asteroid.alive) return;
          bullet.kill();
          asteroid.kill();
      });
    }

    vm.createAsteroids = function() {
        for (var enemyIndex = 0; enemyIndex < 9; enemyIndex++) {
            var indexEntry = vm.game.rnd.integerInRange(0, 3),
                x, y;
            switch (indexEntry) {
                case 0:
                {
                    x = vm.game.world.randomX;
                    y = 0;
                }
                    break;
                case 1:
                {
                    x = vm.game.width;
                    y = vm.game.world.randomY;
                }
                    break;
                case 2:
                {
                    x = vm.game.world.randomX;
                    y = vm.game.height;
                }
                    break;
                case 3:
                {
                    x = 0;
                    y = vm.game.world.randomY;
                }
                    break;
            }

            var enemy = vm.asteroids.create(x, y, "a" + vm.game.rnd.integerInRange(1, 3));
            enemy.moveX = vm.game.rnd.integerInRange(-2, 2);
            while (enemy.moveX == 0) {
                enemy.moveX = vm.game.rnd.integerInRange(-2, 2);
            }
            enemy.moveY = vm.game.rnd.integerInRange(-2, 2);
            while (enemy.moveY == 0) {
                enemy.moveY = vm.game.rnd.integerInRange(-2, 2);
            }
            enemy.rotateAngle = vm.game.rnd.integerInRange(-2, 2);
            while (enemy.rotateAngle == 0) {
                enemy.rotateAngle = vm.game.rnd.integerInRange(-2, 2);
            }
            enemy.asteroidSize = 2;

            vm.asteroids.add(enemy);
            vm.game.physics.enable(enemy, Phaser.Physics.ARCADE);
        }

        vm.asteroids.setAll("anchor.x", 0.5);
        vm.asteroids.setAll("anchor.y", 0.5);
    }

    vm.fireBullet = function() {

        if (vm.game.time.now > vm.bulletTime)
        {
            var bullet = vm.bullets.getFirstExists(false);

            if (bullet)
            {
                bullet.reset(vm.sprite.body.x + 16, vm.sprite.body.y + 16);
                bullet.lifespan = 2000;
                bullet.rotation = vm.sprite.rotation;
                vm.game.physics.arcade.velocityFromRotation(vm.sprite.rotation, 400, bullet.body.velocity);
                bulletTime = vm.game.time.now + 50;
            }
        }

    }

    vm.screenWrap = function(sprite) {

        if (sprite.x < 0)
        {
            sprite.x = vm.game.width;
        }
        else if (sprite.x > vm.game.width)
        {
            sprite.x = 0;
        }

        if (sprite.y < 0)
        {
            sprite.y = vm.game.height;
        }
        else if (sprite.y > vm.game.height)
        {
            sprite.y = 0;
        }

    }

    vm.render = function() {

    }
}]);

module.exports = angular.module('asteroid-mining').name;
<|endoftext|>


<commit_before>var
	serialport = require('serialport')
	, through = require('through')
	, stream = require('stream')
	, net = require('net')
	, fs = require('fs')
;

module.exports = deviceStream;

function deviceStream(platform) {

	platform.prototype.createStream = function createStream(opts) {

		var opts = opts || this.opts;
		if(opts.deviceHost) {

			return str = this.createNetStream(

				opts.deviceHost
				, opts.devicePort
			);
		}
		else {

			return str = this.createSerialStream(opts.devicePath);
		}
		return false;
	};

	platform.prototype.createNetStream = function createNetStream(host, port) {

		var mod = this;

		if(!host) { return false; }
		if(!port) { port = 9000; } // default!
		mod.opts.devicePath = undefined;
		mod.opts.deviceHost = host;
		mod.opts.devicePort = port;
		mod.device = net.connect(port, host, this.onOpen.bind(this));
		mod.bindStream(mod.device);

		mod.log.debug(

			"platform: Opening net connection (%s:%s)"
			, mod.opts.deviceHost
			, mod.opts.devicePort
		);
		return mod.device;
	};

	platform.prototype.createSerialStream = function createSerialStream(path) {

		var mod = this;

		if(!fs.existsSync(mod.opts.devicePath)) {

			mod.log.error(

				"platform: Serial device path unavailable (%s)"
				, path
			);
		}
		if(!path) { return false; }
		mod.opts.deviceHost = undefined;
		mod.opts.devicePath = path;
		mod.device = new serialport.SerialPort(mod.opts.devicePath, {

			parser : serialport.parsers.readline("\n")
			, baudrate : 115200
		});
		mod.device.on('open', this.onOpen.bind(this));

		mod.log.debug(

			"platform: Opening serial connection (%s)"
			, mod.opts.devicePath
		);
		return mod.device;
	};

	platform.prototype.bindStream = function bindStream(str) {

		var mod = this;
		if(!(str instanceof stream)) { return false; }
		str.on('error', mod.onError.bind(mod));
		str.on('close', mod.onClose.bind(mod));
		mod.channel = new through(mod.onData.bind(mod));
		str.pipe(mod.channel).pipe(str);
		return true;
	};
};
<commit_msg>Fixed baud rate. Added bindings for serial devices.<commit_after>var
	serialport = require('serialport')
	, through = require('through')
	, stream = require('stream')
	, net = require('net')
	, fs = require('fs')
;

module.exports = deviceStream;

function deviceStream(platform) {

	platform.prototype.createStream = function createStream(opts) {

		var opts = opts || this.opts;
		if(opts.deviceHost) {

			return str = this.createNetStream(

				opts.deviceHost
				, opts.devicePort
			);
		}
		else {

			return str = this.createSerialStream(opts.devicePath);
		}
		return false;
	};

	platform.prototype.createNetStream = function createNetStream(host, port) {

		var mod = this;

		if(!host) { return false; }
		if(!port) { port = 9000; } // default!
		mod.opts.devicePath = undefined;
		mod.opts.deviceHost = host;
		mod.opts.devicePort = port;
		mod.device = net.connect(port, host, this.onOpen.bind(this));
		mod.bindStream(mod.device);

		mod.log.debug(

			"platform: Opening net connection (%s:%s)"
			, mod.opts.deviceHost
			, mod.opts.devicePort
		);
		return mod.device;
	};

	platform.prototype.createSerialStream = function createSerialStream(path) {

		var mod = this;

		if(!fs.existsSync(mod.opts.devicePath)) {

			mod.log.error(

				"platform: Serial device path unavailable (%s)"
				, path
			);
		}
		if(!path) { return false; }
		mod.opts.deviceHost = undefined;
		mod.opts.devicePath = path;
		mod.device = new serialport.SerialPort(mod.opts.devicePath, {

			parser : serialport.parsers.readline("\n")
		});
		mod.device.on('open', this.onOpen.bind(this));
		mod.bindStream(mod.device);

		mod.log.debug(

			"platform: Opening serial connection (%s)"
			, mod.opts.devicePath
		);
		return mod.device;
	};

	platform.prototype.bindStream = function bindStream(str) {

		var mod = this;
		if(!(str instanceof stream)) { return false; }
		str.on('error', mod.onError.bind(mod));
		str.on('close', mod.onClose.bind(mod));
		mod.channel = new through(mod.onData.bind(mod));
		str.pipe(mod.channel).pipe(str);
		return true;
	};
};
<|endoftext|>