<commit_before>/**
 *
 */

VK.init({
	apiId : 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray;
var manpos = [];
var sexCountArray = [0,0,0];
var wompos = [];
var onopos = [];
var wArray = [];
var mArray = [];
var m = 0;
var w = 0;

function getGroupInfo(groupId) {// ??? 2nd main funtion

	VK.api("groups.getById", {
		'group_id' : Math.abs(groupId),
		'fields' : 'members_count,photo_100'
	}, function(data) {
		if (data.error) {
			errorMSG('Error in data. Wrong group data.')
		} else {
			for (var i = 0; i < data.response.length; i++) {
				grp = data.response[i].name;
				us = data.response[i].members_count;
				grpAvatar = data.response[i].photo_100;

				obj[0] = grp;
				obj[1] = us;
				obj[2] = grpAvatar;

			}
			groupViewChanges(getGroupData());
			//UI changes
			getGroupMembers(getParsedInfo(),0);
		}
	});

}

function getGroupMembers(objTargets, offset) {
	var aboutPost = objTargets;
	// 0-group, 1-item_post
	var code = '';
	code = 'var c=0;var co=100;var p=[];var i=0;var o=' + offset + ';var u=[];' + 'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":' + aboutPost[0] + ',"item_id":' + aboutPost[1] + ',"filter":"likes","friends_only":0,"offset":o,"count":co});'
	+ 'c=li.count;u=u+API.users.get({"user_ids":li.users,"fields":"sex"})@.sex;i=i+1;o=o+co;}'
	+ 'return {"count":c,"sex":u};';

	VK.api('execute', {'code' : code,}, function(data) {
		if (data.response.error) {
			errorMSG('Wrong: Group Member');
			console.log("error");
		} else {

			document.getElementById("m_members").innerHTML = 'Count: ' + data.response.count + ' members.' + " L: " + data.response.sex.length;

			var dtd = data.response.sex;
			var cM = data.response.count;
			sexArray = dtd;//JSON.parse("["+data.response.sex+"]");
			document.getElementById("pCaption").innerHTML = '

'+data.response.sex;
			//put different in array.
			for (var i = 0; i < sexArray.length; i++) {// 1 man 2 woman
				if (sexArray[i] == 1) {
					sexCountArray[1]++;
					manpos.push(i);
				}
				if (sexArray[i] == 2){
					sexCountArray[2]++;
					wompos.push(i);
				}
				if (sexArray[i] == 0){
					sexCountArray[0]++;
					onopos.push(i);
				}
			}

			console.log("0: "+sexCountArray[0]);
			console.log("1: "+sexCountArray[1]);
			console.log("2: "+sexCountArray[2]);

			console.log("sArray: "+sexArray.length);
		}
	});
}

function getGroupData() {//data for groupName,groupMembersCount, avatar.
	return obj;
}

function getParsedInfo() {//getting obj {groupID, postID}
	return parsed;
}

function waiting() {//maybe wait some time
	var se = 0;
	var t = setTimeout(function() {
		if (se > 1) {
			waiting();
			console.log('waits ----------------------------------');
			se = 0;
		}
		se++;
	}, 500);
}

function groupViewChanges(obj) {//changes UI view
	var a = obj;
	document.getElementById('groupName').innerHTML = 'Name: ' + a[0];
	document.getElementById('members_count').innerHTML = 'Count: ' + a[1];
	document.getElementById('av').src = a[2];
}

function parseLink() {// main function for parse link from text area.
	var link = String(document.getElementById('post').value);

	if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

		if (link.indexOf('=wall') != -1) {
			var adr = link.substring(link.indexOf('=wall') + 5, link.length);
			var p = adr.split('_');
			if ((p[0] === undefined) && (p[1] === undefined)) {
				errorMSG('Wrong: group or post or both');
			} else {
				if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
					parsed[0] = p[0];
					parsed[1] = p[1];
					getGroupInfo(parsed[0]);
				}

			}
		} else {
			errorMSG('Wrong: not wall post');
		}
	} else {
		errorMSG('Wrong: not vk.com');
	}
}

function clearadress() {// clear text area
	document.getElementById('post').value = '';
}

function errorMSG(msg) {// shows error messages in main text area
	document.getElementById('post').value = msg;
	var t = setTimeout(clearadress, 1000);
}<commit_msg>ans fix<commit_after>/**
 *
 */

VK.init({
	apiId : 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray;
var manpos = [];
var sexCountArray = [0,0,0];
var wompos = [];
var onopos = [];
var wArray = [];
var mArray = [];
var m = 0;
var w = 0;

function getGroupInfo(groupId) {// ??? 2nd main funtion

	VK.api("groups.getById", {
		'group_id' : Math.abs(groupId),
		'fields' : 'members_count,photo_100'
	}, function(data) {
		if (data.error) {
			errorMSG('Error in data. Wrong group data.')
		} else {
			for (var i = 0; i < data.response.length; i++) {
				grp = data.response[i].name;
				us = data.response[i].members_count;
				grpAvatar = data.response[i].photo_100;

				obj[0] = grp;
				obj[1] = us;
				obj[2] = grpAvatar;

			}
			groupViewChanges(getGroupData());
			//UI changes
			getGroupMembers(getParsedInfo(),0);
		}
	});

}

function getGroupMembers(objTargets, offset) {
	var aboutPost = objTargets;
	// 0-group, 1-item_post
	var code = '';
	code = 'var c=0;var co=100;var p=[];var i=0;var o=' + offset
	+ ';var u=[];' + 'while(i!=2)'
	+ '{var li=API.likes.getList({"type":"post","owner_id":' + aboutPost[0] + ',"item_id":' + aboutPost[1]
	+ ',"filter":"likes","friends_only":0,"offset":o,"count":co});'
	+ 'c=li.count;u.push(API.users.get({"user_ids":li.users,"fields":"sex"})@.sex);i=i+1;o=o+co;}'
	+ 'return {"count":c,"sex":u};';

	VK.api('execute', {'code' : code,}, function(data) {
		if (data.response.error) {
			errorMSG('Wrong: Group Member');
			console.log("error");
		} else {

			document.getElementById("m_members").innerHTML = 'Count: ' + data.response.count + ' members.' + " L: " + data.response.sex.length;

			var dtd = data.response.sex;
			var cM = data.response.count;
			sexArray = dtd;//JSON.parse("["+data.response.sex+"]");
			document.getElementById("pCaption").innerHTML = '

'+data.response.sex;
			//put different in array.
			for (var i = 0; i < sexArray.length; i++) {// 1 man 2 woman
				if (sexArray[i] == 1) {
					sexCountArray[1]++;
					manpos.push(i);
				}
				if (sexArray[i] == 2){
					sexCountArray[2]++;
					wompos.push(i);
				}
				if (sexArray[i] == 0){
					sexCountArray[0]++;
					onopos.push(i);
				}
			}

			console.log("0: "+sexCountArray[0]);
			console.log("1: "+sexCountArray[1]);
			console.log("2: "+sexCountArray[2]);

			console.log("sArray: "+sexArray.length);
		}
	});
}

function getGroupData() {//data for groupName,groupMembersCount, avatar.
	return obj;
}

function getParsedInfo() {//getting obj {groupID, postID}
	return parsed;
}

function waiting() {//maybe wait some time
	var se = 0;
	var t = setTimeout(function() {
		if (se > 1) {
			waiting();
			console.log('waits ----------------------------------');
			se = 0;
		}
		se++;
	}, 500);
}

function groupViewChanges(obj) {//changes UI view
	var a = obj;
	document.getElementById('groupName').innerHTML = 'Name: ' + a[0];
	document.getElementById('members_count').innerHTML = 'Count: ' + a[1];
	document.getElementById('av').src = a[2];
}

function parseLink() {// main function for parse link from text area.
	var link = String(document.getElementById('post').value);

	if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

		if (link.indexOf('=wall') != -1) {
			var adr = link.substring(link.indexOf('=wall') + 5, link.length);
			var p = adr.split('_');
			if ((p[0] === undefined) && (p[1] === undefined)) {
				errorMSG('Wrong: group or post or both');
			} else {
				if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
					parsed[0] = p[0];
					parsed[1] = p[1];
					getGroupInfo(parsed[0]);
				}

			}
		} else {
			errorMSG('Wrong: not wall post');
		}
	} else {
		errorMSG('Wrong: not vk.com');
	}
}

function clearadress() {// clear text area
	document.getElementById('post').value = '';
}

function errorMSG(msg) {// shows error messages in main text area
	document.getElementById('post').value = msg;
	var t = setTimeout(clearadress, 1000);
}<|endoftext|>


<commit_before>import Router from '@ember/routing/router';

export function initialize() {
  const isEmbedded = window !== window.top;

  let stylesheet = null;

  if (isEmbedded) {
    Router.reopen({
      notifyTopFrame: function() {
        window.top.postMessage({
          action: 'did-transition',
          url:    this.currentURL
        })
      }.on('didTransition'),

      willTranstionNotify: function(transition) {
        window.top.postMessage({
          action: 'before-navigation',
          target: transition.targetName,
        })
      }.on('willTransition')
    });

    // Add listener for post messages to change the route in the application
    window.addEventListener('message', (event) => {
      const msg = event.data || {};

      // Navigate when asked to
      if (msg.action === 'navigate') {
        const router = window.ls('router');

        // If the route being asked for is already loaded, send a did-transition event
        if (router.currentRouteName === msg.name) {
          window.top.postMessage({
            action: 'did-transition',
            url:    router.urlFor(msg.name)
          })
        }

        router.transitionTo(msg.name);
      } else if (msg.action === 'set-theme') {
        const userTheme = window.ls('userTheme');

        if (userTheme) {
          userTheme.setTheme( msg.name, false);
        }
      } else if (msg.action === 'colors') {
        const head = document.getElementsByTagName('head')[0];

        // Inject stylesheet to customize some colors
        if (stylesheet) {
          head.removeChild(stylesheet);
        }

        let css = `.bg-primary { background-color: ${ msg.primary }; color: ${ msg.primaryText } }\n `;

        css += `.ember-basic-dropdown-content > li > a:hover {background-color: ${ msg.primary }; color: ${ msg.primaryText } }\n `;
        css += `.ember-basic-dropdown-content > li > a:focus {background-color: ${ msg.primary }; color: ${ msg.primaryText } }\n `;

        stylesheet = document.createElement('style');
        stylesheet.setAttribute('type', 'text/css');
        stylesheet.appendChild(document.createTextNode(css));
        head.appendChild(stylesheet);
      }
    });
  }
}

export default {
  name: 'route-spy',
  initialize,

};
<commit_msg>Update comment<commit_after>import Router from '@ember/routing/router';

export function initialize() {
  const isEmbedded = window !== window.top;

  let stylesheet = null;

  if (isEmbedded) {
    Router.reopen({
      notifyTopFrame: function() {
        window.top.postMessage({
          action: 'did-transition',
          url:    this.currentURL
        })
      }.on('didTransition'),

      willTranstionNotify: function(transition) {
        window.top.postMessage({
          action: 'before-navigation',
          target: transition.targetName,
        })
      }.on('willTransition')
    });

    // Add listener for post messages to change the route in the application
    window.addEventListener('message', (event) => {
      const msg = event.data || {};

      // Navigate when asked to
      if (msg.action === 'navigate') {
        const router = window.ls('router');

        // If the route being asked for is already loaded, send a did-transition event
        if (router.currentRouteName === msg.name) {
          window.top.postMessage({
            action: 'did-transition',
            url:    router.urlFor(msg.name)
          })
        }

        router.transitionTo(msg.name);
      } else if (msg.action === 'set-theme') {
        const userTheme = window.ls('userTheme');

        if (userTheme) {
          userTheme.setTheme( msg.name, false);
        }
      } else if (msg.action === 'colors') {
        const head = document.getElementsByTagName('head')[0];

        // Inject stylesheet to customize some styles to reflect the primary color
        if (stylesheet) {
          head.removeChild(stylesheet);
        }

        let css = `.bg-primary { background-color: ${ msg.primary }; color: ${ msg.primaryText } }\n `;

        css += `.ember-basic-dropdown-content > li > a:hover {background-color: ${ msg.primary }; color: ${ msg.primaryText } }\n `;
        css += `.ember-basic-dropdown-content > li > a:focus {background-color: ${ msg.primary }; color: ${ msg.primaryText } }\n `;

        stylesheet = document.createElement('style');
        stylesheet.setAttribute('type', 'text/css');
        stylesheet.appendChild(document.createTextNode(css));
        head.appendChild(stylesheet);
      }
    });
  }
}

export default {
  name: 'route-spy',
  initialize,

};
<|endoftext|>


<commit_before>/**
 *
 */

VK.init({
	apiId : 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray;
var manpos = [];
var sexCountArray = [0,0,0];
var wompos = [];
var onopos = [];
var wArray = [];
var mArray = [];
var m = 0;
var w = 0;

function getGroupInfo(groupId) {// ??? 2nd main funtion

	VK.api("groups.getById", {
		'group_id' : Math.abs(groupId),
		'fields' : 'members_count,photo_100'
	}, function(data) {
		if (data.error) {
			errorMSG('Error in data. Wrong group data.')
		} else {
			for (var i = 0; i < data.response.length; i++) {
				grp = data.response[i].name;
				us = data.response[i].members_count;
				grpAvatar = data.response[i].photo_100;

				obj[0] = grp;
				obj[1] = us;
				obj[2] = grpAvatar;

			}
			groupViewChanges(getGroupData());
			//UI changes
			getGroupMembers(getParsedInfo(),0);
		}
	});

}

function getGroupMembers(objTargets, offset) {
	var aboutPost = objTargets;
	// 0-group, 1-item_post
	var code = '';
	code = 'var c=0;var co=1000;var p=[];var i=0;var o=' + offset + ';var u=[];' + 'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":' + aboutPost[0] + ',"item_id":' + aboutPost[1] + ',"filter":"likes","friends_only":0,"offset":o,"count":co});'
	+ 'c=li.count;u=u+API.users.get({"user_ids":li.users,"fields":"sex"})@.sex;i=i+1;o=o+co;}'
	+ 'return {"count":c,"sex":u};';

	VK.api('execute', {'code' : code,}, function(data) {
		if (data.response.error) {
			errorMSG('Wrong: Group Member');
			console.log("error");
		} else {

			document.getElementById("m_members").innerHTML = 'Count: ' + data.response.count + ' members.';
			var dtd = data.response.sex;
			var cM = data.response.count;
			sexArray = dtd.split(",");//JSON.parse("["+data.response.sex+"]");
			//put different in array.
			for (var i = 0; i < sexArray.length; i++) {// 1 man 2 woman
				if (sexArray[i] == 1) {
					sexCountArray[1]++;
					manpos.push(i);
				}
				if (sexArray[i] == 2){
					sexCountArray[2]++;
					wompos.push(i);
				}
				if (sexArray[i] == 0){
					sexCountArray[0]++;
					onopos.push(i);
				}
			}

			console.log("0: "+sexCountArray[0]);
			console.log("1: "+sexCountArray[1]);
			console.log("2: "+sexCountArray[2]);

			console.log("sArray: "+sexArray.length);
		}
	});
}

function getGroupData() {//data for groupName,groupMembersCount, avatar.
	return obj;
}

function getParsedInfo() {//getting obj {groupID, postID}
	return parsed;
}

function waiting() {//maybe wait some time
	var se = 0;
	var t = setTimeout(function() {
		if (se > 1) {
			waiting();
			console.log('waits ----------------------------------');
			se = 0;
		}
		se++;
	}, 500);
}

function groupViewChanges(obj) {//changes UI view
	var a = obj;
	document.getElementById('groupName').innerHTML = 'Name: ' + a[0];
	document.getElementById('members_count').innerHTML = 'Count: ' + a[1];
	document.getElementById('av').src = a[2];
}

function parseLink() {// main function for parse link from text area.
	var link = String(document.getElementById('post').value);

	if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

		if (link.indexOf('=wall') != -1) {
			var adr = link.substring(link.indexOf('=wall') + 5, link.length);
			var p = adr.split('_');
			if ((p[0] === undefined) && (p[1] === undefined)) {
				errorMSG('Wrong: group or post or both');
			} else {
				if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
					parsed[0] = p[0];
					parsed[1] = p[1];
					getGroupInfo(parsed[0]);
				}

			}
		} else {
			errorMSG('Wrong: not wall post');
		}
	} else {
		errorMSG('Wrong: not vk.com');
	}
}

function clearadress() {// clear text area
	document.getElementById('post').value = '';
}

function errorMSG(msg) {// shows error messages in main text area
	document.getElementById('post').value = msg;
	var t = setTimeout(clearadress, 1000);
}<commit_msg>ans fix<commit_after>/**
 *
 */

VK.init({
	apiId : 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray;
var manpos = [];
var sexCountArray = [0,0,0];
var wompos = [];
var onopos = [];
var wArray = [];
var mArray = [];
var m = 0;
var w = 0;

function getGroupInfo(groupId) {// ??? 2nd main funtion

	VK.api("groups.getById", {
		'group_id' : Math.abs(groupId),
		'fields' : 'members_count,photo_100'
	}, function(data) {
		if (data.error) {
			errorMSG('Error in data. Wrong group data.')
		} else {
			for (var i = 0; i < data.response.length; i++) {
				grp = data.response[i].name;
				us = data.response[i].members_count;
				grpAvatar = data.response[i].photo_100;

				obj[0] = grp;
				obj[1] = us;
				obj[2] = grpAvatar;

			}
			groupViewChanges(getGroupData());
			//UI changes
			getGroupMembers(getParsedInfo(),0);
		}
	});

}

function getGroupMembers(objTargets, offset) {
	var aboutPost = objTargets;
	// 0-group, 1-item_post
	var code = '';
	code = 'var c=0;var co=1000;var p=[];var i=0;var o=' + offset + ';var u=[];' + 'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":' + aboutPost[0] + ',"item_id":' + aboutPost[1] + ',"filter":"likes","friends_only":0,"offset":o,"count":co});'
	+ 'c=li.count;u=u+API.users.get({"user_ids":li.users,"fields":"sex"})@.sex;i=i+1;o=o+co;}'
	+ 'return {"count":c,"sex":u};';

	VK.api('execute', {'code' : code,}, function(data) {
		if (data.response.error) {
			errorMSG('Wrong: Group Member');
			console.log("error");
		} else {

			document.getElementById("m_members").innerHTML = 'Count: ' + data.response.count + ' members.';
			var dtd = data.response.sex;
			var cM = data.response.count;
			sexArray = String(dtd.split(","));//JSON.parse("["+data.response.sex+"]");
			//put different in array.
			for (var i = 0; i < sexArray.length; i++) {// 1 man 2 woman
				if (sexArray[i] == 1) {
					sexCountArray[1]++;
					manpos.push(i);
				}
				if (sexArray[i] == 2){
					sexCountArray[2]++;
					wompos.push(i);
				}
				if (sexArray[i] == 0){
					sexCountArray[0]++;
					onopos.push(i);
				}
			}

			console.log("0: "+sexCountArray[0]);
			console.log("1: "+sexCountArray[1]);
			console.log("2: "+sexCountArray[2]);

			console.log("sArray: "+sexArray.length);
		}
	});
}

function getGroupData() {//data for groupName,groupMembersCount, avatar.
	return obj;
}

function getParsedInfo() {//getting obj {groupID, postID}
	return parsed;
}

function waiting() {//maybe wait some time
	var se = 0;
	var t = setTimeout(function() {
		if (se > 1) {
			waiting();
			console.log('waits ----------------------------------');
			se = 0;
		}
		se++;
	}, 500);
}

function groupViewChanges(obj) {//changes UI view
	var a = obj;
	document.getElementById('groupName').innerHTML = 'Name: ' + a[0];
	document.getElementById('members_count').innerHTML = 'Count: ' + a[1];
	document.getElementById('av').src = a[2];
}

function parseLink() {// main function for parse link from text area.
	var link = String(document.getElementById('post').value);

	if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

		if (link.indexOf('=wall') != -1) {
			var adr = link.substring(link.indexOf('=wall') + 5, link.length);
			var p = adr.split('_');
			if ((p[0] === undefined) && (p[1] === undefined)) {
				errorMSG('Wrong: group or post or both');
			} else {
				if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
					parsed[0] = p[0];
					parsed[1] = p[1];
					getGroupInfo(parsed[0]);
				}

			}
		} else {
			errorMSG('Wrong: not wall post');
		}
	} else {
		errorMSG('Wrong: not vk.com');
	}
}

function clearadress() {// clear text area
	document.getElementById('post').value = '';
}

function errorMSG(msg) {// shows error messages in main text area
	document.getElementById('post').value = msg;
	var t = setTimeout(clearadress, 1000);
}<|endoftext|>


<commit_before>/**
 * Created by dell on 2015/6/9.
 */
(function(){

    "use strict";

    var adminServices = angular.module('app.admin.services',["app.services"]);

    adminServices.factory("adminInfo",["ApiServer",function(ApiServer){
        return ApiServer.createResource('admin/login',{},{
            "login":{method:'POST',url:ApiServer.getApiUrl('admin/login')}
        });
    }]);

    adminServices.service('admin',[function(){
        this._id;
        this.name;
        this.last_login;
        this.token;

        this.set = function(info){
            this._id = info._id;
            this.name = info.name;
            this.last_login = info.last_login;
            this.token = info.token;
        };
    }]);

    adminServices.service('adminManager',['adminInfo','$q','admin',function(adminInfo,$q,admin){

        this.login = function(user_info){

            var deferred = $q.defer();

            adminInfo.login(user_info).$promise.then(function(response){

                admin.set(response.context);
                sessionStorage.setItem("AUTHOR",JSON.stringify(response.context));
                deferred.resolve(response);

            },function(){
                deferred.reject();
            });

            return deferred.promise;
        }
    }]);

}).call(this);
<commit_msg>Save token to session storage<commit_after>/**
 * Created by dell on 2015/6/9.
 */
(function(){

    "use strict";

    var adminServices = angular.module('app.admin.services',["app.services"]);

    adminServices.factory("adminInfo",["ApiServer",function(ApiServer){
        return ApiServer.createResource('admin/login',{},{
            "login":{method:'POST',url:ApiServer.getApiUrl('admin/login')}
        });
    }]);

    adminServices.service('admin',[function(){
        this._id;
        this.name;
        this.last_login;
        this.token;

        this.set = function(info){
            this._id = info._id;
            this.name = info.name;
            this.last_login = info.last_login;
            this.token = info.token;
        };
    }]);

    adminServices.service('adminManager',['adminInfo','$q','admin',function(adminInfo,$q,admin){

        this.login = function(user_info){

            var deferred = $q.defer();

            adminInfo.login(user_info).$promise.then(function(response){

                admin.set(response.context);

                sessionStorage.setItem("AUTHOR",JSON.stringify(response.context));
                sessionStorage.setItem("TOKEN",response.context.token);

                deferred.resolve(response);

            },function(){
                deferred.reject();
            });

            return deferred.promise;
        }
    }]);

}).call(this);
<|endoftext|>


<commit_before>
/**
 * Created by expro on 14-1-10.
 * 退货管理
 */
function ReturnsController($scope, Returns, Pagination, $timeout, $injector){

    $injector.invoke(BasicController, this, {$scope: $scope});
    $scope.resource = Returns;
    $scope.searchOptions.fields = ['username']
    $scope.editView = "views/returns/edit.html"

    // profile
    $scope.profileShortcuts = $scope.profileShortcuts.concat([
        {class: "span9"}
        ,	{class: "box quick-button-small span1", icon: "icon-certificate", text: "重置密码", op:"resetPassword(entity)"}
    ])
    $scope.profileAvatar = "img/avatar.jpg"

    // profile
    $scope.profileFields = [
//        {name: "id", title: "id"},
        {name: "shopID", title: "商店ID", listHide:true},
        {name: "dealID", title: "交易ID", listHide:true},
        {name: "billID", title: "账单ID", listHide:true},
        {name: "memo", title: "memo", listHide:true},
        {name: "items", title: "items", listHide:true},
        {name: "deviceID", title: "deviceID", listHide:true},
        {name: "dealSerialNumber", title: "退单号"},
        {name: "serialNumber", title: "交易流水号"},
        {name: "createdAt", title: "退货时间"},
        {name: "quantity", title: "数量"},
        {name: "fee", title: "退款",value:function(entity) {
            return (entity.fee/100).toFixed(2);
        }},
        {name: "customer", title: "顾客",value:function(entity) {
            if (entity.hasOwnProperty("customer")) {
                return entity.customer.name;
            } else {
                return "走入顾客";
            }
        }},
        {name: "agent", title: "经手人", value:function(entity) {
            return entity.agent.name;
        }}

    ];

    // bussiness
    $scope.setStatus = function(status) {
        $scope.entity.status = status
        $scope.update(true)
    }
}<commit_msg>Fix: 退货管理不需要新增和编辑功能 Close: #50<commit_after>
/**
 * Created by expro on 14-1-10.
 * 退货管理
 */
function ReturnsController($scope, Returns, Pagination, $timeout, $injector){

    $injector.invoke(BasicController, this, {$scope: $scope});
    $scope.resource = Returns;
    $scope.searchOptions.fields = ['username']
    $scope.editView = "views/returns/edit.html"

    // profile
    $scope.profileShortcuts = $scope.profileShortcuts.concat([
        {class: "span9"}
        ,	{class: "box quick-button-small span1", icon: "icon-certificate", text: "重置密码", op:"resetPassword(entity)"}
    ])
    $scope.profileAvatar = "img/avatar.jpg"

    // profile
    $scope.profileFields = [
//        {name: "id", title: "id"},
        {name: "shopID", title: "商店ID", listHide:true},
        {name: "dealID", title: "交易ID", listHide:true},
        {name: "billID", title: "账单ID", listHide:true},
        {name: "memo", title: "memo", listHide:true},
        {name: "items", title: "items", listHide:true},
        {name: "deviceID", title: "deviceID", listHide:true},
        {name: "dealSerialNumber", title: "退单号"},
        {name: "serialNumber", title: "交易流水号"},
        {name: "createdAt", title: "退货时间"},
        {name: "quantity", title: "数量"},
        {name: "fee", title: "退款",value:function(entity) {
            return (entity.fee/100).toFixed(2);
        }},
        {name: "customer", title: "顾客",value:function(entity) {
            if (entity.hasOwnProperty("customer")) {
                return entity.customer.name;
            } else {
                return "走入顾客";
            }
        }},
        {name: "agent", title: "经手人", value:function(entity) {
            return entity.agent.name;
        }}

    ];

    // bussiness
    $scope.setStatus = function(status) {
        $scope.entity.status = status
        $scope.update(true)
    }
    $scope.fieldOperations = [
        {class: "btn btn-success", icon: "icon-file", op: "showProfile"}
        ,	{class: "btn btn-danger", icon: "icon-trash", op:"remove"}
    ]

    // profile
    $scope.profileShortcuts = [
        {class: "box quick-button-small span1", icon: "icon-trash", text: "删除", op:"remove"}
    ];
    $scope.isHide = true; //隐藏新增按钮
}<|endoftext|>


<commit_before>/**
 * LayerControl module that presents a map control for adding or deleting layers.
 * It can handle app level events and perform AJAX calls to the server.
 *
 * Event binding:
 *     None
 *
 * Event triggering:
 *     ADD_LAYER - Triggered when the Add widget is clicked
 *     DELETE_LAYER - Triggered when the Delete widget is clicked
 */
MOL.modules.LayerControl = function(mol) {

    mol.ui.LayerControl = {};

    /**
     * The Layer engine.
     */
    mol.ui.LayerControl.Engine = mol.ui.Engine.extend(
        {
            /**
             * Constructs the engine.
             *
             * @constructor
             */
            init: function(api, bus) {
                this._api = api;
                this._bus = bus;
                this._layerIds = {};
            },

            /**
             * Starts the engine by creating and binding the display.
             *
             * @override mol.ui.Engine.start
             */
            start: function(container) {
                this._bindDisplay(new mol.ui.LayerControl.Display());
            },

            /**
             * Gives the engine a new place to go based on a browser history
             * change.
             *
             * @override mol.ui.Engine.go
             */
            go: function(place) {
                var visible = place.lv ? parseInt(place.lv) : 0,
                    display = this._display;

                display.toggleLayers(visible);
            },

            getPlaceState: function() {
                return {
                    lv: this._display.isLayersVisible() ? 1 : 0,
                    layers: _.keys(this._layerIds).join(',')
                };
            },

            /**
             * Binds the display.
             */
            _bindDisplay: function(display, text) {
                var self = this,
                    LayerControlEvent = mol.events.LayerControlEvent,
                    LayerEvent = mol.events.LayerEvent,
                    widget = null,
                    bus = this._bus,
                    ch = null,
                    styles = null,
                    layerId = null;

                this._display = display;
                display.setEngine(this);

                // Clicking the layer button toggles the layer stack:
                widget = display.getLayerToggle();
                widget.click(
                    function(event) {
                        self._display.toggleLayers();
                    }
                );

                // Clicking the share button gets the shareable URL for the current view:
                widget = display.getShareButton();
                widget.click(
                    function(event) {
                        bus.fireEvent(new MOL.env.events.LocationEvent({}, 'get-url'));
                    }
                );

                bus.addHandler(
                  "LocationEvent",
                  function(event){
                    if (event.getAction() == 'take-url') {
                        display.toggleShareLink(event.getLocation().url);
                    }
                  }
                );

                // Clicking the add button fires a LayerControlEvent:
                widget = display.getAddButton();
                widget.click(
                    function(event) {
                        bus.fireEvent(new LayerControlEvent('add-click'));
                        display.toggleShareLink("", false);
                    }
                );

                // Clicking the delete button fires a LayerControlEvent:
                widget = display.getDeleteButton();
                widget.click(
                    function(event) {
                        ch = new mol.ui.Element($('.layer.widgetTheme.selected')[0]);
                        layerId = ch.attr('id');
                        ch.remove();
                        bus.fireEvent(new LayerControlEvent('delete-click', layerId));
                        delete self._layerIds[layerId];
                        self._display.toggleShareLink("", false);
                    }
                );

                this._addDisplayToMap();

                bus.addHandler(
                    LayerEvent.TYPE,
                    function(event) {
                        var action = event.getAction(),
                            layer = event.getLayer(),
                            layerId = layer.getKeyName(),
                            layerType = layer.getType(),
                            layerName = layer.getName(),
                            layerSubName = layer.getSubName(),
                            layerIds = self._layerIds,
                            layerUi = null,
                            display = self._display,
                            LayerEvent = mol.events.LayerEvent,
                            ch = null,
                            toggle = null,
                            widget = null,
                            nullTest = null,
                            styleNames = null;

                        switch (action) {

                        case 'add':
                            if (layerIds[layerId]) {
                                // Duplicate layer.
                                return;
                            }
                            display.toggleLayers(true);
                            display.toggleShareLink("", false);
                            layerIds[layerId] = true;
                            layerUi = display.getNewLayer();
                            layerUi.getName().text(layerName);
                            layerUi.getType().attr("src","/static/maps/search/"+ layerType +".png");
                            layerUi.attr('id', layerId);

                            layerUi.click(function(e) {
                                ch = new mol.ui.Element(e.target).getParent().findChildren('.layer');
                                for (y in ch) {
                                    styleNames = ch[y].getStyleName().split(' ');
                                    if (_.indexOf(styleNames, 'selected') > -1) {
                                        ch[y].removeStyleName('selected');
                                        return;
                                    }
                                }
                                new mol.ui.Element(e.target).addStyleName('selected');
                            });

                            toggle = layerUi.getToggle();
                            toggle.setChecked(true);
                            toggle.click(
                                function(event) {
                                    bus.fireEvent(
                                        new LayerEvent(
                                            {
                                                action: toggle.isChecked() ? 'checked': 'unchecked',
                                                layer: layer
                                            }
                                        )
                                    );
                                }
                            );
                            widget = layerUi.getInfoLink();
                            widget.click(
                                function(event) {
                                    bus.fireEvent(
                                        new LayerEvent(
                                            {
                                                action: 'view-metadata',
                                                layer: layer
                                            }
                                        )
                                    );
                                }
                            );
                            break;
                        }
                    }
                );
            },

            /**
             * Fires a MapControlEvent so that the display is attached to
             * the map as a control in the TOP_LEFT position.
             */
            _addDisplayToMap: function() {
                var MapControlEvent = mol.events.MapControlEvent,
                    display = this._display,
                    bus = this._bus,
                    DisplayPosition = mol.ui.Map.Control.DisplayPosition,
                    ControlPosition = mol.ui.Map.Control.ControlPosition,
                    action = 'add',
                    config = {
                        display: display,
                        action: action,
                        displayPosition: DisplayPosition.TOP,
                        controlPosition: ControlPosition.TOP_RIGHT
                    };
                bus.fireEvent(new MapControlEvent(config));
            }
        }
    );

    mol.ui.LayerControl.Layer = mol.ui.Display.extend(
        {
            init: function() {
                this._super(this._html());
            },

            getName: function() {
                var x = this._layerName,
                    s = '.layerNomial';
                return x ? x : (this._layerName = this.findChild(s));
            },
            getSubName: function() {
                var x = this._layerSubName,
                    s = '.layerAuthor';
                return x ? x : (this._layerSubName = this.findChild(s));
            },
            getToggle: function() {
                var x = this._layerToggle,
                    s = '.toggle';
                return x ? x : (this._layerToggle = this.findChild(s));
            },
            getType: function() {
                var x = this._layerType,
                    s = '.type';
                return x ? x : (this._layerType = this.findChild(s));
            },
            getInfoLink: function() {
                var x = this._layerInfoLink,
                    s = '.info';
                return x ? x : (this._layerInfoLink = this.findChild(s));
            },

            _html: function() {
                return  '
' +
                        '    <button></button>' +
                        '
' +
                        '
Smilisca puma
' +
                        '
' +
                        '
' +
                        '        <input class="toggle" type="checkbox">' +
                        '         ' +
                        '
' +
                        '    <button class="info">i</button>' +
                        '
';
            }
        }
    );

    /**
     * The LayerControl display.
     */
    mol.ui.LayerControl.Display = mol.ui.Display.extend(
        {
            init: function(config) {
                this._super();
                this.setInnerHtml(this._html());
                this._config = config;
                this._show = false;
                this._shareLink = false;
            },
            getLayerToggle: function() {
                var x = this._layersToggle,
                    s = '.label';
                return x ? x : (this._layersToggle = this.findChild(s));
            },
            getAddButton: function() {
                var x = this._addButton,
                    s = '.add';
                return x ? x : (this._addButton = this.findChild(s));
            },
            getDeleteButton: function() {
                var x = this._deleteButton,
                    s = '.delete';
                return x ? x : (this._deleteButton = this.findChild(s));
            },
            getShareButton: function() {
                var x = this._shareButton,
                    s = '.share';
                return x ? x : (this._shareButton = this.findChild(s));
            },

            getNewLayer: function(){
                var Layer = mol.ui.LayerControl.Layer,
                    r = new Layer();
                this.findChild('.scrollContainer').append(r);
                return r;
            },

            isLayersVisible: function() {
                return this._show;
            },

            toggleShareLink: function(url, status) {
                var r = this._linkContainer,
                    p = '.staticLink',
                    u = '.link';
                this._url = url;
                if ( ! r ){
                    r = this.findChild(p);
                    this._linkContainer = r;
                }
                if (status == false) {
                    r.hide();
                    this._shareLink = false;
                } else if (status==true) {
                    r.show();
                    this._shareLink = true;
                } else {
                    if (this._shareLink ) {
                        r.hide();
                        this._shareLink = false;
                    } else {
                        r.show();
                        this._shareLink = true;
                    }
                }
                this.findChild('.linkText').val(url);
                this.findChild('.linkText').select();

            },

            toggleLayers: function(status) {
                var x = this._toggleLayerImg,
                    c = this._layerContainer,
                    s = '.layersToggle',
                    n = '.scrollContainer';
                if ( ! x ){
                    x = this.findChild(s);
                    this._toggleLayerImg = x;
                }
                if ( ! c ){
                    c = this.findChild(n);
                    this._layerContainer = c;
                }
                if (this._show != status) {
                    if (this._show ) {
                        c.hide();
                        x.attr("src","/static/maps/layers/expand.png");
                        this._show = false;
                    } else {
                        c.show();
                        x.attr("src","/static/maps/layers/collapse.png");
                        this._show = true;
                    }
                }
            },

            _html: function(){
                return  '
' +
                        '
' +
                        '       ' +
                        '
' +
                        '
Share
' +
                        '
Delete
' +
                        '
Add
' +
                        '
' +
                        '
' +
                        '
' +
                        '          <input type="text" class="linkText" />' +
                        '
' +
                        '
' +
                        '
' +
                        '
';
            }
        }
    );
};
<commit_msg>delete all selected layers working<commit_after>/**
 * LayerControl module that presents a map control for adding or deleting layers.
 * It can handle app level events and perform AJAX calls to the server.
 *
 * Event binding:
 *     None
 *
 * Event triggering:
 *     ADD_LAYER - Triggered when the Add widget is clicked
 *     DELETE_LAYER - Triggered when the Delete widget is clicked
 */
MOL.modules.LayerControl = function(mol) {

    mol.ui.LayerControl = {};

    /**
     * The Layer engine.
     */
    mol.ui.LayerControl.Engine = mol.ui.Engine.extend(
        {
            /**
             * Constructs the engine.
             *
             * @constructor
             */
            init: function(api, bus) {
                this._api = api;
                this._bus = bus;
                this._layerIds = {};
            },

            /**
             * Starts the engine by creating and binding the display.
             *
             * @override mol.ui.Engine.start
             */
            start: function(container) {
                this._bindDisplay(new mol.ui.LayerControl.Display());
            },

            /**
             * Gives the engine a new place to go based on a browser history
             * change.
             *
             * @override mol.ui.Engine.go
             */
            go: function(place) {
                var visible = place.lv ? parseInt(place.lv) : 0,
                    display = this._display;

                display.toggleLayers(visible);
            },

            getPlaceState: function() {
                return {
                    lv: this._display.isLayersVisible() ? 1 : 0,
                    layers: _.keys(this._layerIds).join(',')
                };
            },

            /**
             * Binds the display.
             */
            _bindDisplay: function(display, text) {
                var self = this,
                    LayerControlEvent = mol.events.LayerControlEvent,
                    LayerEvent = mol.events.LayerEvent,
                    widget = null,
                    bus = this._bus,
                    ch = null,
                    styles = null,
                    layerId = null;

                this._display = display;
                display.setEngine(this);

                // Clicking the layer button toggles the layer stack:
                widget = display.getLayerToggle();
                widget.click(
                    function(event) {
                        self._display.toggleLayers();
                    }
                );

                // Clicking the share button gets the shareable URL for the current view:
                widget = display.getShareButton();
                widget.click(
                    function(event) {
                        bus.fireEvent(new MOL.env.events.LocationEvent({}, 'get-url'));
                    }
                );

                bus.addHandler(
                  "LocationEvent",
                  function(event){
                    if (event.getAction() == 'take-url') {
                        display.toggleShareLink(event.getLocation().url);
                    }
                  }
                );

                // Clicking the add button fires a LayerControlEvent:
                widget = display.getAddButton();
                widget.click(
                    function(event) {
                        bus.fireEvent(new LayerControlEvent('add-click'));
                        display.toggleShareLink("", false);
                    }
                );

                // Clicking the delete button fires a LayerControlEvent:
                widget = display.getDeleteButton();
                widget.click(
                    function(event) {
                        var styleNames = null,
                            e = null;
                        //ch = new mol.ui.Element(event.target).getParent().findChildren('.layer');
                        //ch = new mol.ui.Element($('.layer.widgetTheme.selected')[0]);
                        ch = $('.layer.widgetTheme.selected');
                        ch.each(function(index) {
                            e = new mol.ui.Element(ch[index]);
                            styleNames = e.getStyleName().split(' ');
                            if (_.indexOf(styleNames, 'selected') > -1) {
                                layerId = e.attr('id');
                                e.remove();
                                bus.fireEvent(new LayerControlEvent('delete-click', layerId));
                                delete self._layerIds[layerId];
                                self._display.toggleShareLink("", false);
                            }
                        });

                        // ch = new mol.ui.Element($('.layer.widgetTheme.selected')[0]);
                        // layerId = ch.attr('id');
                        // ch.remove();
                        // bus.fireEvent(new LayerControlEvent('delete-click', layerId));
                        // delete self._layerIds[layerId];
                        // self._display.toggleShareLink("", false);
                    }
                );

                this._addDisplayToMap();

                bus.addHandler(
                    LayerEvent.TYPE,
                    function(event) {
                        var action = event.getAction(),
                            layer = event.getLayer(),
                            layerId = layer.getKeyName(),
                            layerType = layer.getType(),
                            layerName = layer.getName(),
                            layerSubName = layer.getSubName(),
                            layerIds = self._layerIds,
                            layerUi = null,
                            display = self._display,
                            LayerEvent = mol.events.LayerEvent,
                            ch = null,
                            toggle = null,
                            widget = null,
                            nullTest = null,
                            styleNames = null;

                        switch (action) {

                        case 'add':
                            if (layerIds[layerId]) {
                                // Duplicate layer.
                                return;
                            }
                            display.toggleLayers(true);
                            display.toggleShareLink("", false);
                            layerIds[layerId] = true;
                            layerUi = display.getNewLayer();
                            layerUi.getName().text(layerName);
                            layerUi.getType().attr("src","/static/maps/search/"+ layerType +".png");
                            layerUi.attr('id', layerId);

                            layerUi.click(function(e) {
                                ch = new mol.ui.Element(e.target).getParent().findChildren('.layer');
                                for (y in ch) {
                                    styleNames = ch[y].getStyleName().split(' ');
                                    if (_.indexOf(styleNames, 'selected') > -1) {
                                        if (!e.shiftKey) {
                                            ch[y].removeStyleName('selected');
                                            //return;
                                        }
                                    } else {
                                        new mol.ui.Element(e.target).addStyleName('selected');
                                    }
                                }
                            });

                            toggle = layerUi.getToggle();
                            toggle.setChecked(true);
                            toggle.click(
                                function(event) {
                                    bus.fireEvent(
                                        new LayerEvent(
                                            {
                                                action: toggle.isChecked() ? 'checked': 'unchecked',
                                                layer: layer
                                            }
                                        )
                                    );
                                }
                            );
                            widget = layerUi.getInfoLink();
                            widget.click(
                                function(event) {
                                    bus.fireEvent(
                                        new LayerEvent(
                                            {
                                                action: 'view-metadata',
                                                layer: layer
                                            }
                                        )
                                    );
                                }
                            );
                            break;
                        }
                    }
                );
            },

            /**
             * Fires a MapControlEvent so that the display is attached to
             * the map as a control in the TOP_LEFT position.
             */
            _addDisplayToMap: function() {
                var MapControlEvent = mol.events.MapControlEvent,
                    display = this._display,
                    bus = this._bus,
                    DisplayPosition = mol.ui.Map.Control.DisplayPosition,
                    ControlPosition = mol.ui.Map.Control.ControlPosition,
                    action = 'add',
                    config = {
                        display: display,
                        action: action,
                        displayPosition: DisplayPosition.TOP,
                        controlPosition: ControlPosition.TOP_RIGHT
                    };
                bus.fireEvent(new MapControlEvent(config));
            }
        }
    );

    mol.ui.LayerControl.Layer = mol.ui.Display.extend(
        {
            init: function() {
                this._super(this._html());
            },

            getName: function() {
                var x = this._layerName,
                    s = '.layerNomial';
                return x ? x : (this._layerName = this.findChild(s));
            },
            getSubName: function() {
                var x = this._layerSubName,
                    s = '.layerAuthor';
                return x ? x : (this._layerSubName = this.findChild(s));
            },
            getToggle: function() {
                var x = this._layerToggle,
                    s = '.toggle';
                return x ? x : (this._layerToggle = this.findChild(s));
            },
            getType: function() {
                var x = this._layerType,
                    s = '.type';
                return x ? x : (this._layerType = this.findChild(s));
            },
            getInfoLink: function() {
                var x = this._layerInfoLink,
                    s = '.info';
                return x ? x : (this._layerInfoLink = this.findChild(s));
            },

            _html: function() {
                return  '
' +
                        '    <button></button>' +
                        '
' +
                        '
Smilisca puma
' +
                        '
' +
                        '
' +
                        '        <input class="toggle" type="checkbox">' +
                        '         ' +
                        '
' +
                        '    <button class="info">i</button>' +
                        '
';
            }
        }
    );

    /**
     * The LayerControl display.
     */
    mol.ui.LayerControl.Display = mol.ui.Display.extend(
        {
            init: function(config) {
                this._super();
                this.setInnerHtml(this._html());
                this._config = config;
                this._show = false;
                this._shareLink = false;
            },
            getLayerToggle: function() {
                var x = this._layersToggle,
                    s = '.label';
                return x ? x : (this._layersToggle = this.findChild(s));
            },
            getAddButton: function() {
                var x = this._addButton,
                    s = '.add';
                return x ? x : (this._addButton = this.findChild(s));
            },
            getDeleteButton: function() {
                var x = this._deleteButton,
                    s = '.delete';
                return x ? x : (this._deleteButton = this.findChild(s));
            },
            getShareButton: function() {
                var x = this._shareButton,
                    s = '.share';
                return x ? x : (this._shareButton = this.findChild(s));
            },

            getNewLayer: function(){
                var Layer = mol.ui.LayerControl.Layer,
                    r = new Layer();
                this.findChild('.scrollContainer').append(r);
                return r;
            },

            isLayersVisible: function() {
                return this._show;
            },

            toggleShareLink: function(url, status) {
                var r = this._linkContainer,
                    p = '.staticLink',
                    u = '.link';
                this._url = url;
                if ( ! r ){
                    r = this.findChild(p);
                    this._linkContainer = r;
                }
                if (status == false) {
                    r.hide();
                    this._shareLink = false;
                } else if (status==true) {
                    r.show();
                    this._shareLink = true;
                } else {
                    if (this._shareLink ) {
                        r.hide();
                        this._shareLink = false;
                    } else {
                        r.show();
                        this._shareLink = true;
                    }
                }
                this.findChild('.linkText').val(url);
                this.findChild('.linkText').select();

            },

            toggleLayers: function(status) {
                var x = this._toggleLayerImg,
                    c = this._layerContainer,
                    s = '.layersToggle',
                    n = '.scrollContainer';
                if ( ! x ){
                    x = this.findChild(s);
                    this._toggleLayerImg = x;
                }
                if ( ! c ){
                    c = this.findChild(n);
                    this._layerContainer = c;
                }
                if (this._show != status) {
                    if (this._show ) {
                        c.hide();
                        x.attr("src","/static/maps/layers/expand.png");
                        this._show = false;
                    } else {
                        c.show();
                        x.attr("src","/static/maps/layers/collapse.png");
                        this._show = true;
                    }
                }
            },

            _html: function(){
                return  '
' +
                        '
' +
                        '       ' +
                        '
' +
                        '
Share
' +
                        '
Delete
' +
                        '
Add
' +
                        '
' +
                        '
' +
                        '
' +
                        '          <input type="text" class="linkText" />' +
                        '
' +
                        '
' +
                        '
' +
                        '
';
            }
        }
    );
};
<|endoftext|>


<commit_before>"use strict";

let mongoose = require('mongoose');
var Schema   = mongoose.Schema;

let pokemonSighting = new Schema({
    source        : {type: String},
    location      : {type: {type: String, default: 'Point'}, coordinates: {type: [Number]}},
    pokemonID     : {type: Number},
    appearedOn    : {type: Date}
});

pokemonSighting.index({ "location": "2dsphere"}, {"sparse": true});

module.exports = mongoose.model('pokemonSighting', pokemonSighting);<commit_msg>added unique constraint to sightings table<commit_after>"use strict";

let mongoose = require('mongoose');
var Schema   = mongoose.Schema;

let pokemonSighting = new Schema({
    source        : {type: String},
    location      : {type: {type: String, default: 'Point'}, coordinates: {type: [Number]}},
    pokemonID     : {type: Number},
    appearedOn    : {type: Date}
});

pokemonSighting.index({"location": "2dsphere"}, {"sparse": true});
pokemonSighting.index({"appearedOn": -1, "pokemonID": 1, "location": 1}, {"unique": true});

module.exports = mongoose.model('pokemonSighting', pokemonSighting);<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const sanitize = require('sanitize-filename');
const MISSING_DATA_ERROR =
  'No file created. Data was missing during the Export process. This happens sometimes, when com2us failes to include important data during the request. Normally this fixes itself after a few tries.';

module.exports = {
  defaultConfig: {
    enabled: true,
    sortData: true
  },
  defaultConfigDetails: {
    sortData: { label: 'Sort data like ingame' }
  },
  pluginName: 'ProfileExport',
  pluginDescription: 'Exports your monster and rune data.',
  missingDataError:
    'No file created. Data was missing during the Export process. This happens sometimes, when com2us failes to include important data during the request. Normally this fixes itself after a few tries.',
  init(proxy, config) {
    proxy.on('HubUserLogin', (req, resp) => {
      if (config.Config.Plugins[this.pluginName].enabled) {
        if (this.checkData(resp)) {
          return proxy.log({ type: 'error', source: 'plugin', name: this.pluginName, message: MISSING_DATA_ERROR });
        }
        if (config.Config.Plugins[this.pluginName].sortData) {
          resp = this.sortUserData(resp);
        }
        this.writeProfileToFile(proxy, req, resp);
      }
    });
    proxy.on('GuestLogin', (req, resp) => {
      if (config.Config.Plugins[this.pluginName].enabled) {
        if (!this.checkData(resp)) {
          return proxy.log({ type: 'error', source: 'plugin', name: this.pluginName, message: MISSING_DATA_ERROR });
        }
        if (config.Config.Plugins[this.pluginName].sortData) {
          resp = this.sortUserData(resp);
        }
        this.writeProfileToFile(proxy, req, resp);
      }
    });
  },
  writeProfileToFile(proxy, req, resp) {
    const wizardID = resp.wizard_info.wizard_id;
    const wizardName = resp.wizard_info.wizard_name;
    const filename = sanitize(`${wizardName}-${wizardID}`).concat('.json');

    let outFile = fs.createWriteStream(path.join(config.Config.App.filesPath, filename), {
      flags: 'w',
      autoClose: true
    });

    outFile.write(JSON.stringify(resp, true, 2));
    outFile.end();
    proxy.log({ type: 'success', source: 'plugin', name: this.pluginName, message: 'Saved profile data to '.concat(filename) });
  },
  checkData(data) {
    // Sometimes com2us doesn't include al lthe required data in the request
    // Most notably is the missing of the building_list object.
    // So lets return false if it's undefined
    if (!data.building_list) {
      return false;
    }
    return true;
  },
  sortUserData(data) {
    // get storage building id
    let storageID;
    for (let building of data.building_list) {
      if (building.building_master_id === 25) {
        storageID = building.building_id;
      }
    }
    // generic sort function
    cmp = function(x, y) {
      return x > y ? 1 : x < y ? -1 : 0;
    };

    // sort monsters
    data.unit_list = data.unit_list.sort((a, b) =>
      cmp(
        [
          cmp(a.building_id === storageID ? 1 : 0, b.building_id === storageID ? 1 : 0),
          -cmp(a.class, b.class),
          -cmp(a.unit_level, b.unit_level),
          cmp(a.attribute, b.attribute),
          cmp(a.unit_id, b.unit_id)
        ],
        [
          cmp(b.building_id === storageID ? 1 : 0, a.building_id === storageID ? 1 : 0),
          -cmp(b.class, a.class),
          -cmp(b.unit_level, a.unit_level),
          cmp(b.attribute, a.attribute),
          cmp(b.unit_id, a.unit_id)
        ]
      )
    );

    // sort runes on monsters
    for (let monster of data.unit_list) {
      // make sure that runes is actually an array (thanks com2us)
      if (monster.runes === Object(monster.runes)) {
        monster.runes = Object.values(monster.runes);
      }

      monster.runes = monster.runes.sort((a, b) => cmp([cmp(a.slot_no, b.slot_no)], [cmp(b.slot_no, a.slot_no)]));
    }

    // make sure that runes is actually an array (thanks again com2us)
    if (data.runes === Object(data.runes)) {
      data.runes = Object.values(data.runes);
    }

    // sort runes in inventory
    data.runes = data.runes.sort((a, b) =>
      cmp([cmp(a.set_id, b.set_id), cmp(a.slot_no, b.slot_no)], [cmp(b.set_id, a.set_id), cmp(b.slot_no, a.slot_no)])
    );

    // sort crafts
    data.rune_craft_item_list = data.rune_craft_item_list.sort((a, b) =>
      cmp(
        [cmp(a.craft_type, b.craft_type), cmp(a.craft_item_id, b.craft_item_id)],
        [cmp(b.craft_type, a.craft_type), cmp(b.craft_item_id, a.craft_item_id)]
      )
    );

    return data;
  }
};
<commit_msg>Fixed small typo<commit_after>const fs = require('fs');
const path = require('path');
const sanitize = require('sanitize-filename');
const MISSING_DATA_ERROR =
  'No file created. Data was missing during the Export process. This happens sometimes, when com2us failes to include important data during the request. Normally this fixes itself after a few tries.';

module.exports = {
  defaultConfig: {
    enabled: true,
    sortData: true
  },
  defaultConfigDetails: {
    sortData: { label: 'Sort data like ingame' }
  },
  pluginName: 'ProfileExport',
  pluginDescription: 'Exports your monster and rune data.',
  missingDataError:
    'No file created. Data was missing during the Export process. This happens sometimes, when com2us failes to include important data during the request. Normally this fixes itself after a few tries.',
  init(proxy, config) {
    proxy.on('HubUserLogin', (req, resp) => {
      if (config.Config.Plugins[this.pluginName].enabled) {
        if (!this.checkData(resp)) {
          return proxy.log({ type: 'error', source: 'plugin', name: this.pluginName, message: MISSING_DATA_ERROR });
        }
        if (config.Config.Plugins[this.pluginName].sortData) {
          resp = this.sortUserData(resp);
        }
        this.writeProfileToFile(proxy, req, resp);
      }
    });
    proxy.on('GuestLogin', (req, resp) => {
      if (config.Config.Plugins[this.pluginName].enabled) {
        if (!this.checkData(resp)) {
          return proxy.log({ type: 'error', source: 'plugin', name: this.pluginName, message: MISSING_DATA_ERROR });
        }
        if (config.Config.Plugins[this.pluginName].sortData) {
          resp = this.sortUserData(resp);
        }
        this.writeProfileToFile(proxy, req, resp);
      }
    });
  },
  writeProfileToFile(proxy, req, resp) {
    const wizardID = resp.wizard_info.wizard_id;
    const wizardName = resp.wizard_info.wizard_name;
    const filename = sanitize(`${wizardName}-${wizardID}`).concat('.json');

    let outFile = fs.createWriteStream(path.join(config.Config.App.filesPath, filename), {
      flags: 'w',
      autoClose: true
    });

    outFile.write(JSON.stringify(resp, true, 2));
    outFile.end();
    proxy.log({ type: 'success', source: 'plugin', name: this.pluginName, message: 'Saved profile data to '.concat(filename) });
  },
  checkData(data) {
    // Sometimes com2us doesn't include al lthe required data in the request
    // Most notably is the missing of the building_list object.
    // So lets return false if it's undefined
    if (!data.building_list) {
      return false;
    }
    return true;
  },
  sortUserData(data) {
    // get storage building id
    let storageID;
    for (let building of data.building_list) {
      if (building.building_master_id === 25) {
        storageID = building.building_id;
      }
    }
    // generic sort function
    cmp = function(x, y) {
      return x > y ? 1 : x < y ? -1 : 0;
    };

    // sort monsters
    data.unit_list = data.unit_list.sort((a, b) =>
      cmp(
        [
          cmp(a.building_id === storageID ? 1 : 0, b.building_id === storageID ? 1 : 0),
          -cmp(a.class, b.class),
          -cmp(a.unit_level, b.unit_level),
          cmp(a.attribute, b.attribute),
          cmp(a.unit_id, b.unit_id)
        ],
        [
          cmp(b.building_id === storageID ? 1 : 0, a.building_id === storageID ? 1 : 0),
          -cmp(b.class, a.class),
          -cmp(b.unit_level, a.unit_level),
          cmp(b.attribute, a.attribute),
          cmp(b.unit_id, a.unit_id)
        ]
      )
    );

    // sort runes on monsters
    for (let monster of data.unit_list) {
      // make sure that runes is actually an array (thanks com2us)
      if (monster.runes === Object(monster.runes)) {
        monster.runes = Object.values(monster.runes);
      }

      monster.runes = monster.runes.sort((a, b) => cmp([cmp(a.slot_no, b.slot_no)], [cmp(b.slot_no, a.slot_no)]));
    }

    // make sure that runes is actually an array (thanks again com2us)
    if (data.runes === Object(data.runes)) {
      data.runes = Object.values(data.runes);
    }

    // sort runes in inventory
    data.runes = data.runes.sort((a, b) =>
      cmp([cmp(a.set_id, b.set_id), cmp(a.slot_no, b.slot_no)], [cmp(b.set_id, a.set_id), cmp(b.slot_no, a.slot_no)])
    );

    // sort crafts
    data.rune_craft_item_list = data.rune_craft_item_list.sort((a, b) =>
      cmp(
        [cmp(a.craft_type, b.craft_type), cmp(a.craft_item_id, b.craft_item_id)],
        [cmp(b.craft_type, a.craft_type), cmp(b.craft_item_id, a.craft_item_id)]
      )
    );

    return data;
  }
};
<|endoftext|>


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

  $('#tmpltzr').width( window.innerWidth - 400 );

  // header fade in and out
  function fadeSwitchElements(id1, id2)
  {
    var element1 = $('.' + id1);
    var element2 = $('.' + id2);

    if(element1.is(':visible'))
    {
      element1.fadeToggle(500);
      element2.fadeToggle(500);
    }
    else
    {
      element2.fadeToggle(500, function() {
        element1.fadeToggle(500);
      });
    }
    setTimeout(function(){
      fadeSwitchElements(id2, id1);
    }, 2000);
  }

  fadeSwitchElements('full', 'hash');

  // Gradient background

  // make sure this matches all the colors in scss/_vars.scss
  var colors = ['red', 'red-orange', 'orange', 'pink', 'salmon', 'blue', 'blue-alt', 'purple', 'violet', 'fuchsia', 'red-purple'];

  var gradient = $('.gradient');

  function gradientCycle() {
    console.log('gradientCycle()');
    var classes = gradient.attr('class').split(' '),
      oldClass;
    for ( var i = 0; i < classes.length; i++ ) {
      if ( classes[i] !== 'gradient') {
        oldClass = classes[i];
        oldClass = oldClass.replace('gradient-', '');
        break;
      }
    }
    var newClass = colors[(colors.indexOf(oldClass) + 1) % colors.length];
    var newGradient = $('
');
    $('.gradient-' + oldClass).last().after(newGradient);

    //gradient.addClass('faded');
    setTimeout(function(){
      newGradient.removeClass('faded');
    }, 100);

    setTimeout(function(){
      gradient = newGradient;
      gradientCycle();
    }, 5000);
  }
  gradientCycle();

});
<commit_msg>slower title fade<commit_after>$(document).ready(function(){

  $('#tmpltzr').width( window.innerWidth - 400 );

  // header fade in and out
  function fadeSwitchElements(id1, id2, fade_time, cycle)
  {
    var element1 = $('.' + id1);
    var element2 = $('.' + id2);

    if(element1.is(':visible'))
    {
      element1.fadeToggle(fade_time);
      element2.fadeToggle(fade_time);
    }
    else
    {
      element2.fadeToggle(fade_time, function() {
        element1.fadeToggle(fade_time);
      });
    }
    setTimeout(function(){
      fadeSwitchElements(id2, id1, fade_time, cycle);
    }, cycle);
  }

  fadeSwitchElements('full', 'hash', 1000, 3000);

  // Gradient background

  // make sure this matches all the colors in scss/_vars.scss
  var colors = ['red', 'red-orange', 'orange', 'pink', 'salmon', 'blue', 'blue-alt', 'purple', 'violet', 'fuchsia', 'red-purple'];

  var gradient = $('.gradient');

  function gradientCycle() {
    console.log('gradientCycle()');
    var classes = gradient.attr('class').split(' '),
      oldClass;
    for ( var i = 0; i < classes.length; i++ ) {
      if ( classes[i] !== 'gradient') {
        oldClass = classes[i];
        oldClass = oldClass.replace('gradient-', '');
        break;
      }
    }
    var newClass = colors[(colors.indexOf(oldClass) + 1) % colors.length];
    var newGradient = $('
');
    $('.gradient-' + oldClass).last().after(newGradient);

    //gradient.addClass('faded');
    setTimeout(function(){
      newGradient.removeClass('faded');
    }, 100);

    setTimeout(function(){
      gradient = newGradient;
      gradientCycle();
    }, 5000);
  }
  gradientCycle();

});
<|endoftext|>


<commit_before>class TreeBuilder {
  static _appendChild(parent, child){
    if (child == null) {
      return;
    }

    const append = this._appendChild.bind(this);

    if (["string", "number", "boolean"].includes(typeof child)) {
      parent.appendChild(document.createTextNode(child));
    } else if (Array.isArray(child)) {
      child.forEach(_child => append(parent, _child));
    } else if (child.constructor.name === "NodeList") {
      Array.from(child).forEach(_child => append(parent, _child));
    } else {
      parent.appendChild(child);
    }
  }

  static _build(tag, attrs, ...children){
    const el = document.createElement(tag);

    for (let k in attrs) {
      const v = attrs[k];
      if (/^on(click)$/.test(k)) {
        const eventName = k.substring(2);
        el.addEventListener(eventName, v, false);
      } else if (k === "style") {
        for (let sk in v) {
          const sv = v[sk];
          el.style[sk] = sv;
        }
      } else {
        el.setAttribute(k, v);
      }
    }

    if (children != null) {
      children.forEach(child => {
        this._appendChild(el, child);
      });
    }

    return el;
  }

  static build(fn){
    return fn(TreeBuilder._build.bind(TreeBuilder));
  }

  /**
   * @return NodeList
   */
  static buildRawHtml(html){
    const el = document.createElement("div");
    el.innerHTML = html;
    return el.childNodes;
  }
}
<commit_msg>Support onchange event (tree_builder)<commit_after>class TreeBuilder {
  static _appendChild(parent, child){
    if (child == null) {
      return;
    }

    const append = this._appendChild.bind(this);

    if (["string", "number", "boolean"].includes(typeof child)) {
      parent.appendChild(document.createTextNode(child));
    } else if (Array.isArray(child)) {
      child.forEach(_child => append(parent, _child));
    } else if (child.constructor.name === "NodeList") {
      Array.from(child).forEach(_child => append(parent, _child));
    } else {
      parent.appendChild(child);
    }
  }

  static _build(tag, attrs, ...children){
    const el = document.createElement(tag);

    for (let k in attrs) {
      const v = attrs[k];
      if (/^on(click|change)$/.test(k)) {
        const eventName = k.substring(2);
        el.addEventListener(eventName, v, false);
      } else if (k === "style") {
        for (let sk in v) {
          const sv = v[sk];
          el.style[sk] = sv;
        }
      } else {
        el.setAttribute(k, v);
      }
    }

    if (children != null) {
      children.forEach(child => {
        this._appendChild(el, child);
      });
    }

    return el;
  }

  static build(fn){
    return fn(TreeBuilder._build.bind(TreeBuilder));
  }

  /**
   * @return NodeList
   */
  static buildRawHtml(html){
    const el = document.createElement("div");
    el.innerHTML = html;
    return el.childNodes;
  }
}
<|endoftext|>


<commit_before>import path from 'path';
import fs from 'fs';
import chalk from 'chalk';

const logger = console;

export function parseList(str) {
  return str.split(',');
}

export function getHeadHtml(configDirPath) {
  const headHtmlPath = path.resolve(configDirPath, 'preview-head.html');
  const fallbackHtmlPath = path.resolve(configDirPath, 'head.html')
  let headHtml = '';
  if (fs.existsSync(headHtmlPath)) {
    headHtml = fs.readFileSync(headHtmlPath, 'utf8');
  } else if(fs.existsSync(fallbackHtmlPath)) {
    headHtml = fs.readFileSync(fallbackHtmlPath, 'utf8');
    const msg = "WARNING: head.html has been deprecated.\nPlease rename head.html to preview-head.html"
    logger.warn(chalk.bold(msg + chalk.reset('\n')));

  }

  return headHtml;
}

export function getManagerHeadHtml(configDirPath) {
  const scriptPath = path.resolve(configDirPath, 'manager-head.html');
  let scriptHtml = '';
  if (fs.existsSync(scriptPath)) {
    scriptHtml = fs.readFileSync(scriptPath, 'utf8');
  }

  return scriptHtml;
}

export function getEnvConfig(program, configEnv) {
  Object.keys(configEnv).forEach(fieldName => {
    const envVarName = configEnv[fieldName];
    const envVarValue = process.env[envVarName];
    if (envVarValue) {
      program[fieldName] = envVarValue; // eslint-disable-line
    }
  });
}

export function getMiddleware(configDir) {
  const middlewarePath = path.resolve(configDir, 'middleware.js');
  if (fs.existsSync(middlewarePath)) {
    let middlewareModule = require(middlewarePath); // eslint-disable-line
    if (middlewareModule.__esModule) { // eslint-disable-line
      middlewareModule = middlewareModule.default;
    }
    return middlewareModule;
  }
  return () => {};
}
<commit_msg>Use util-deprecate over custom implementation (will only log once)<commit_after>import path from 'path';
import fs from 'fs';
import deprecate from 'util-deprecate';

const fallbackHeadUsage = deprecate(
  () => {},
  'Usage of head.html has been deprecated. Please rename head.html to preview-head.html'
);

export function parseList(str) {
  return str.split(',');
}

export function getHeadHtml(configDirPath) {
  const headHtmlPath = path.resolve(configDirPath, 'preview-head.html');
  const fallbackHtmlPath = path.resolve(configDirPath, 'head.html');
  let headHtml = '';
  if (fs.existsSync(headHtmlPath)) {
    headHtml = fs.readFileSync(headHtmlPath, 'utf8');
  } else if (fs.existsSync(fallbackHtmlPath)) {
    headHtml = fs.readFileSync(fallbackHtmlPath, 'utf8');
    fallbackHeadUsage();
  }

  return headHtml;
}

export function getManagerHeadHtml(configDirPath) {
  const scriptPath = path.resolve(configDirPath, 'manager-head.html');
  let scriptHtml = '';
  if (fs.existsSync(scriptPath)) {
    scriptHtml = fs.readFileSync(scriptPath, 'utf8');
  }

  return scriptHtml;
}

export function getEnvConfig(program, configEnv) {
  Object.keys(configEnv).forEach(fieldName => {
    const envVarName = configEnv[fieldName];
    const envVarValue = process.env[envVarName];
    if (envVarValue) {
      program[fieldName] = envVarValue; // eslint-disable-line
    }
  });
}

export function getMiddleware(configDir) {
  const middlewarePath = path.resolve(configDir, 'middleware.js');
  if (fs.existsSync(middlewarePath)) {
    let middlewareModule = require(middlewarePath); // eslint-disable-line
    if (middlewareModule.__esModule) { // eslint-disable-line
      middlewareModule = middlewareModule.default;
    }
    return middlewareModule;
  }
  return () => {};
}
<|endoftext|>


<commit_before>var Duplex = require('stream').Duplex
, asyncMap = require('slide').asyncMap
, browserify = require('browserify')
, uglifyJS = require('uglify-js')
, stylus = require('stylus')
, util = require('util')
, fs = require('fs')

util.inherits(Compiler, Duplex)

module.exports = Compiler
// compiler prepares files for client

function Compiler (opts) {
  if (!(this instanceof Compiler)) return new Compiler(opts)
  Duplex.call(this, opts)
  console.log(opts)

  var self = this
  , DIR = './_wilds/'
  , READ1 = false
  , UPDATE = false
  , MODCOUNT = 0
  , MODS = []
  , B = browserify()

  this._write = function (chunk, enc, next) {
    if (READ1===false) MODCOUNT++
    var mod = JSON.parse(chunk.toString())
    handleModule(mod)
    next()
  }

  this.end = function () {
    READ1 = true
  }

  function handleModule (mod) {
    asyncMap(mod.deps, function readModDeps (file, next) {
      var filepath = DIR+file
      var ext = file.split('.')[1]
      fs.readFile(filepath, function addDepToMod (err, buf) {
        if (err) console.error(err)
        mod[ext] = buf.toString()
        next()
      })
    }, function handledDeps () {
       if (UPDATE === false) MODS.push(mod)
       if (UPDATE === true) {
         for (var i=0;i<MODS.length;i++) {
           var m = MODS[i]
           if (m.id === mod.id) MODS[i] = mod
         }
         ready()
       }
       if (MODCOUNT === MODS.length) {
         ready()
         UPDATE = true
       }
    })
  }

  function ready () {
    var CSS = ''
    fs.readFile(DIR+'_css.styl', function (e, buf) { // load base styles
      if (e) console.error(e)
      CSS += buf.toString()
      compile(CSS)
    })
  }

  function compile (CSS) {
    B.add('./__clnt.js')
    asyncMap(MODS, function (mod, next) {
      if (mod.styl) CSS += mod.styl // add style to css
      var fil = DIR+mod.id+'.js'
      B.add(DIR+mod.id+'.js') // add js to browserify
      next()
    }, function () {
      var bunF = fs.createWriteStream(DIR+'_bundle.js')
      B.bundle().pipe(bunF)
      bunF.on('finish', function () {
        console.log('wrote _bundle.js')
        if (opts.compress === true) {
          console.log('gonna cmp!')
          var min = uglifyJS.minify('./_wilds/_bundle.js')
          fs.writeFile('./_wilds/_bundle.min.js', min.code, function (e) {
            if (!e) console.log('minified bundle')
          })
        }
      })
      bunF.on('error', function (e) {
        console.error(e)
      })
      stylus.render(CSS, {filename:'_styles.css'}, function (e, css) {
        if (e) console.error(e)
        fs.writeFile(DIR+'_styles.css', css, function (e) {
          if (e) cosole.error(e)
          console.log('wrote _styles.css')
        })
      })
    })
  }
}
<commit_msg>fixed uglify weirdness in _cmp<commit_after>var Duplex = require('stream').Duplex
, asyncMap = require('slide').asyncMap
, browserify = require('browserify')
, uglifyJS = require('uglify-js')
, stylus = require('stylus')
, util = require('util')
, fs = require('fs')

util.inherits(Compiler, Duplex)

module.exports = Compiler
// compiler prepares files for client

function Compiler (opts) {
  if (!(this instanceof Compiler)) return new Compiler(opts)
  Duplex.call(this, opts)
  console.log(opts)

  var self = this
  , DIR = './_wilds/'
  , READ1 = false
  , UPDATE = false
  , MODCOUNT = 0
  , MODS = []

  this._write = function (chunk, enc, next) {
    if (READ1===false) MODCOUNT++
    var mod = JSON.parse(chunk.toString())
    handleModule(mod)
    next()
  }

  this.end = function () {
    READ1 = true
  }

  function handleModule (mod) {
    asyncMap(mod.deps, function readModDeps (file, next) {
      var filepath = DIR+file
      var ext = file.split('.')[1]
      fs.readFile(filepath, function addDepToMod (err, buf) {
        if (err) console.error(err)
        mod[ext] = buf.toString()
        next()
      })
    }, function handledDeps () {
       if (UPDATE === false) MODS.push(mod)
       if (UPDATE === true) {
         for (var i=0;i<MODS.length;i++) {
           var m = MODS[i]
           if (m.id === mod.id) MODS[i] = mod
         }
         ready()
       }
       if (MODCOUNT === MODS.length) {
         ready()
         UPDATE = true
       }
    })
  }

  function ready () {
    var CSS = ''
    fs.readFile(DIR+'_css.styl', function (e, buf) { // load base styles
      if (e) console.error(e)
      CSS += buf.toString()
      compile(CSS)
    })
  }

  function compile (CSS) {
    var b = browserify()
    b.add('./__clnt.js')
    asyncMap(MODS, function (mod, next) {
      if (mod.styl) CSS += mod.styl // add style to css
      var fil = DIR+mod.id+'.js'
      b.add(DIR+mod.id+'.js') // add js to browserify
      next()
    }, function () {
      var bunF = fs.createWriteStream(DIR+'_bundle.js')
      b.bundle().pipe(bunF)
      bunF.on('finish', function () {
        console.log('wrote _bundle.js')
        if (opts.compress === true) {
          console.log('gonna cmp!')
          var min = uglifyJS.minify('./_wilds/_bundle.js')
          fs.writeFile('./_wilds/_bundle.min.js', min.code, function (e) {
            if (!e) console.log('minified bundle')
          })
        }
      })
      bunF.on('error', function (e) {
        console.error(e)
      })
      stylus.render(CSS, {filename:'_styles.css'}, function (e, css) {
        if (e) console.error(e)
        fs.writeFile(DIR+'_styles.css', css, function (e) {
          if (e) cosole.error(e)
          console.log('wrote _styles.css')
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>var Readable = require('stream').Readable
, asyncMap = require('slide').asyncMap
, compressor = require('./_cmp')
, fs = require('fs')

module.exports = function (opts, callback) {

  var self = this
  , DESTCSS = './_wilds/_styles.css'
  , DESTJS = './_wilds/_bundle.js'
  , DIR = opts.dir+'/'
  , CSS = ''
  , FILESTAT = null

  this.server = new Readable
  this.client = new Readable

  this.server._read = function (size) {} // WTF!
  this.client._read = function (size) {}

  fs.readdir(DIR, function handleWildsFiles (e, files) {
    callback(self)
    asyncMap(files, parse, function doneWildsFiles () {
      self.server.emit('end') // call end method but dont' close stream
      self.client.emit('end')
    })
  })

  fs.watch(DIR, function handleFileChange (event, file) {
    var filepath = DIR+file
    fs.stat(filepath, function statFile (err, stats) {
      // make a good data object here
      stats.filepath = filepath
      if (err) console.error(err)
      if (!FILESTAT) FILESTAT = stats
      if (FILESTAT.size !== stats.size) {
        var mod = stats.filepath.split('/')[2]
        var ext = mod.split('.')[1]
        var file = mod
        if (ext !== 'js') file = mod.split('.')[0]+'.js'
        if (file[0] !== '_') {
          parse(file, function () {
            console.log('updated file '+file)
          })
        }
      }
      FILESTAT = stats
    })
  })

  function parse (file,cb) {
    var ext = file.split('.')[1]
    if (ext === 'js' && file[0] !=='_') {
      var f = fs.createReadStream(DIR+file)
      f.on('data', function (chunk) {
        var buf = chunk.toString()
        var m = buf.match(/\/\*\{([\S\s]*)\}\*\//) // fix up this regex
        var modJSON = m[0].replace('/*','').replace('*/','')
        var modOBJ = JSON.parse(modJSON)
        modOBJ.scope.forEach(function (scope) { // push to scoped stream
          self[scope].push(modJSON)
        })
      })
      f.on('end',cb)
    } else {
      cb()
    }
  }
}
<commit_msg>map uses single readable stream instead of client/server split<commit_after>var Readable = require('stream').Readable
, inherits = require('inherits')
, asyncMap = require('slide').asyncMap
, compressor = require('./_cmp')
, fs = require('fs')

inherits(Map, Readable)

module.exports = Map

function Map (opts, callback) {
  Readable.call(this)

  var self = this
  , DESTCSS = './_wilds/_styles.css'
  , DESTJS = './_wilds/_bundle.js'
  , DIR = opts.dir+'/'
  , CSS = ''
  , FILESTAT = null

  this._read = function (size) {} // WTF!

  fs.readdir(DIR, function handleWildsFiles (e, files) {
    callback(self)
    asyncMap(files, parse, function doneWildsFiles () {
      self.emit('end')
    })
  })

  fs.watch(DIR, function handleFileChange (event, file) {
    var filepath = DIR+file
    fs.stat(filepath, function statFile (err, stats) {
      // make a good data object here
      stats.filepath = filepath
      if (err) console.error(err)
      if (!FILESTAT) FILESTAT = stats
      if (FILESTAT.size !== stats.size) {
        var mod = stats.filepath.split('/')[2]
        var ext = mod.split('.')[1]
        var file = mod
        if (ext !== 'js') file = mod.split('.')[0]+'.js'
        if (file[0] !== '_') {
          parse(file, function () {
            console.log('updated file '+file)
          })
        }
      }
      FILESTAT = stats
    })
  })

  function parse (file,cb) {
    var ext = file.split('.')[1]
    if (ext === 'js' && file[0] !=='_') {
      var f = fs.createReadStream(DIR+file)
      f.on('data', function (chunk) {
        var buf = chunk.toString()
        var m = buf.match(/\/\*\{([\S\s]*)\}\*\//) // fix up this regex
        var modJSON = m[0].replace('/*','').replace('*/','')
        var modOBJ = JSON.parse(modJSON)
        modOBJ.scope.forEach(function (scope) { // push to scoped stream
          self.push(modJSON)
        })
      })
      f.on('end',cb)
    } else {
      cb()
    }
  }
}
<|endoftext|>


<commit_before>// WILDS MAPPER
// grab nimoy module data from a dir of node modules with package.json's

var asyncMap = require('slide').asyncMap
var fs = require('fs')

module.exports = Map

function Map (path, ready) {
  if (path[path.length-1] !== '/') path += '/'

  var MAP = {}

  function readPKG (fileName, next) {
    fs.readFile(path+fileName+'/package.json', function (e, buf) {
      if (e) console.error(e)
      if (!e) {
        var jsn = JSON.parse(buf)
        MAP[fileName] = jsn
        next()
      }
    })
  }

  fs.readdir(path, function moduleList(e, modules) {
    asyncMap(modules, readPKG, function () {
      ready(JSON.stringify(MAP,null,2))
    })
  })
}
<commit_msg>cleaned up map<commit_after>// WILDS MAPPER

var asyncMap = require('slide').asyncMap
var fs = require('fs')

module.exports = Map

function Map (path, ready) {
  var MAP = {}

  function readPKG (fileName, next) {
    fs.readFile(path+fileName+'/package.json', function (e, buf) {
      if (e) console.error(e)
      if (!e) {
        var jsn = JSON.parse(buf)
        MAP[fileName] = jsn
        next()
      }
    })
  }

  if (path[path.length-1] !== '/') path += '/'

  fs.readdir(path, function moduleList(e, modules) {
    asyncMap(modules, readPKG, function () {
      ready(JSON.stringify(MAP,null,2))
    })
  })
}
<|endoftext|>