Пример #1
0
	this.generateDynamicFinder = function(attrName, method, dontCapitalize) {

		// Capitalize attribute name if necessary to be syntactically correct
		var preparedAttrName;
		if (dontCapitalize) preparedAttrName = attrName;
		else preparedAttrName = _.str.capitalize(attrName);

		// Figure out actual dynamic method name by injecting attribute name		
		var actualMethodName = method.replace(/\*/g, preparedAttrName);

		// Assign this finder to the collection
		this[actualMethodName] = function dynamicMethod(value, options, cb) {
			if(_.isFunction(options)) {
				cb = options;
				options = null;
			}
			options = options || {};


			var usage = _.str.capitalize(this.identity) + '.' + actualMethodName + '(someValue,[options],callback)';
			if(_.isUndefined(value)) return usageError('No value specified!', usage, cb);
			if(options.where) return usageError('Cannot specify `where` option in a dynamic ' + method + '*() query!', usage, cb);


			// Build criteria query and submit it
			options.where = {};
			options.where[attrName] = value;

			// Make modifications based on method as necessary
			if(method === 'findBy*' || method === 'findBy*In') {
				return self.find(options, cb);
			} else if(method === 'findBy*Like') {
				return self.find(_.extend(options, {
					where: {
						like: options.where
					}
				}), cb);
			}

			// Aggregate finders
			else if(method === 'findAllBy*' || method === 'findAllBy*In') {
				return self.findAll(options, cb);
			} else if(method === 'findAllBy*Like') {
				return self.findAll(_.extend(options, {
					where: {
						like: options.where
					}
				}), cb);
			}

			// Count finders
			else if(method === 'countBy*' || method === 'countBy*In') {
				return self.count(options, cb);
			} else if(method === 'countBy*Like') {
				return self.count(_.extend(options, {
					where: {
						like: options.where
					}
				}), cb);
			}

			// Searchers
			else if (method === '*StartsWith') {
				return self.startsWith(options, cb);
			}
			else if (method === '*Contains') {
				return self.contains(options, cb);
			}
			else if (method === '*EndsWith') {
				return self.endsWith(options, cb);
			}
		};
	};
Пример #2
0
 flash.xhr_error = function(xhr, status, err) {
   var statusString = _.str.sprintf('%s %s', xhr.statusCode().status, xhr.statusText);
   flash.message_bad(statusString);
 };
 * Copyright (c) 2013 Imre Fazekas. All rights reserved.
 *
 * A restful web service middleware for Connect.
 */
var VERSION = '0.7.6';

var connect = require('connect');
var url = require('url');
var async = require('async');
var semver = require('semver');
var bunyan = require('bunyan');
var http = require('http');
var https = require('https');
var _ = require('underscore');
_.str = require('underscore.string');
_.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');

var Route = require('./route');
var Bus = require('./bus');
var httphelper = require('./http-helper');
var bus = new Bus( httphelper );
var util = require('./util');
var Dispatcher = require('./dispatcher');

var CONTEXT = '';

var SERVICE_METHOD_PATTERN = /^[a-zA-Z]([a-zA-Z]|\d|_)*$/g;

var mapping = {
	"HEAD": [],
Пример #4
0
var spaceIt = function(str, startIndex, endIndex) {
    return str.slice(0, startIndex) 
        + _.str.repeat(" ", endIndex - startIndex) 
        + str.slice(endIndex, str.length);
}
Пример #5
0
function capitalize(str) {
	return _.str.capitalize(str);
}
Пример #6
0
 lines = lines.map(function (line) {
     return _.str.rtrim(indent + line);
   });
Пример #7
0
 self.commandChain.items.forEach(function(command) {
   if (command.isVisible()) {
     var fillWidth = self.width - (command.name.length + command.author.length + 4);
     list += '\n\t• ' + command.name + ' ' + _.str.repeat('.', fillWidth)  + ' ' + command.author;
   }
 });
Пример #8
0
var window = {}; ( function() {"use strict";
	//hack start-----------------------------------------------------------
	//npm install -g underscore
	//npm install -g underscore.string
	//npm install -g xmlhttprequest
	var _  = require('underscore');
	// Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)
	_.str = require('underscore.string');
	// Mix in non-conflict functions to Underscore namespace if you want
	_.mixin(_.str.exports());
	// All functions, include conflict, will be available through _.str object
	_.str.include('Underscore.string', 'string'); // => true

	var localStorage = {};
	var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

	var clc = require ( "cli-color" );

	var reader = window.reader = {};
	//hack end--------------------------------------------------------------

	//global constants that will likely be used outside of this file
	reader.TAGS = {
		"like" : "user/-/state/com.google/like",
		"label" : "user/-/label/",
		"star" : "user/-/state/com.google/starred",
		"read" : "user/-/state/com.google/read",
		"fresh" : "user/-/state/com.google/fresh",
		"share" : "user/-/state/com.google/broadcast",
		"kept-unread" : "user/-/state/com.google/kept-unread",
		"reading-list" : "user/-/state/com.google/reading-list"
	};
	//global variables
	reader.is_logged_in = false;
	reader.is_initialized = false;
	reader.has_loaded_prefs = false;

	//constants that will only be used in this file
	var CLIENT = "Tibfib",
	//base urls
	LOGIN_URL = "https://www.google.com/accounts/ClientLogin", BASE_URL = "http://www.google.com/reader/api/0/",
	//url paths
	PREFERENCES_PATH = "preference/stream/list", STREAM_PATH = "stream/contents/", SUBSCRIPTIONS_PATH = "subscription/", LABEL_PATH = "user/-/label/", TAGS_PATH = "tag/",
	//url actions
	LIST_SUFFIX = "list", EDIT_SUFFIX = "edit", MARK_ALL_READ_SUFFIX = "mark-all-as-read", TOKEN_SUFFIX = "token", USERINFO_SUFFIX = "user-info", UNREAD_SUFFIX = "unread-count", RENAME_LABEL_SUFFIX = "rename-tag", EDIT_TAG_SUFFIX = "edit-tag";

	// for public xml "http://www.google.com/reader/public/atom/user/<user>/label/<label>"
	// for private json http://www.google.com/reader/api/0/stream/contents/user%2F-%2Flabel%2Fbuy

	var ITEMS_ROOT = "http://www.google.com/reader/atom/hifi/";

	//managing the feeds
	var readerFeeds = [];
	reader.setFeeds = function(feeds) {
		readerFeeds = feeds;
	};
	reader.getFeeds = function() {
		return readerFeeds;
	};
	reader.getLabels = function() {
		return _(reader.getFeeds()).select(function(feed) {
			return feed.isLabel;
		});
	};
	//managing the logged in user
	reader.setUser = function(user) {
		localStorage.User = JSON.stringify(user);
	};
	reader.getUser = function() {
		return JSON.parse(localStorage.User);
	};
	//managing the app authentication
	var readerAuth = "", readerToken = "";
	reader.getAuth = function() {
		if(readerAuth !== "undefined") {
			return readerAuth;
		}
	};
	reader.setAuth = function(auth) {
		readerAuth = auth;
	};
	//the core ajax function
	var requests = [], makeRequest = function(obj, noAuth) {
		//make sure we have a method
		if(!obj.method) {
			obj.method = "GET";
		}
		//make sure we have a parameters object
		if(!obj.parameters) {
			obj.parameters = {};
		}

		//add the necessary parameters to get our requests to function properly
		if(obj.method === "GET") {
			obj.parameters.ck = Date.now() || new Date().getTime();
			obj.parameters.accountType = "GOOGLE";
			obj.parameters.service = "reader";
			obj.parameters.output = "json";
			// obj.parameters.output = "atom-hifi",
			obj.parameters.client = CLIENT;
		}

		//if we have a token, add it to the parameters
		if(readerToken) {
			if(obj.method === "POST") {
				//it seems that "GET" requests don't care about your token
				obj.parameters.T = readerToken;
			}
		}
		//turn our parameters object into a query string
		var queries = [], key, queryString;

		for(key in obj.parameters) {
			if(obj.parameters.hasOwnProperty(key) && obj.parameters[ key ] ) {
				queries.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj.parameters[key]));
			}
		}
		queryString = queries.join("&");
		//for get requests, attach the queryString
		//for post requests, attach just the client constant
		var url = (obj.method === "GET") ? (obj.url + "?" + queryString) : (obj.url + "?" + encodeURIComponent("client") + "=" + encodeURIComponent(CLIENT));
		var request = new XMLHttpRequest();
		request.open(obj.method, url, true);

console.log ( "makeRequest url: ", clc.blue ( url ) );

		//set request header
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

		if(reader.getAuth() && !noAuth) {
			//this one is important. This is how google does authorization.
			request.setRequestHeader("Authorization", "GoogleLogin auth=" + reader.getAuth());
		}

		var requestIndex = requests.length;
		request.onreadystatechange = function() {
			if((request.readyState === 4) && request.status === 200) {
				if(obj.onSuccess) {
					obj.onSuccess(request);
					if(requests[requestIndex]) {
						delete requests[requestIndex];
					}
				}
			} else if(request.readyState === 4) {
				if(obj.method === "POST") {
					if(!obj.tried) {
						//If it failed and this is a post request, try getting a new token, then do the request again
						reader.getToken(function() {
							obj.tried = true;
							makeRequest(obj);
							if(requests[requestIndex]) {
								delete requests[requestIndex];
							}
						}, obj.onFailure);
					}
				} else {
					if(obj.onFailure) {
						obj.onFailure(request);
						if(requests[requestIndex]) {
							delete requests[requestIndex];
						}
					}
				}
				if(request.status === 401 && request.statusText === "Unauthorized") {
					//Humane is a notification lib.
					if(humane) {
						humane(request.statusText + ". " + "Try logging in again.");
					}
				}

				console.error(request);
			}
		};

		request.send((obj.method === "POST") ? queryString : "");
		requests.push(request);
	};
	// *************************************
	// *
	// * Authentication
	// *
	// *************************************

	reader.load = function() {
		reader.is_logged_in = false;
		reader.is_initialized = true;
		//check storage for the tokens we need.
		if(localStorage.Auth && localStorage.Auth !== "undefined") {
			reader.setAuth(localStorage.Auth);
			reader.is_logged_in = true;
		}
		return (reader.is_logged_in);
	};

	reader.login = function(email, password, successCallback, failCallback) {
		if(email.length === 0 || password.length === 0) {
			failCallback("Blank Info...");
		}
		makeRequest({
			method : "GET",
			url : LOGIN_URL,
			parameters : {
				Email : email,
				Passwd : password
			},
			onSuccess : function(transport) {
				localStorage.Auth = _(transport.responseText).lines()[2].replace("Auth=", "");
				reader.load();

				getUserInfo(successCallback);
			},
			onFailure : function(transport) {
				console.error(transport);
				failCallback(reader.normalizeError(transport.responseText));
			}
		});
	};

	reader.logout = function() {
		reader.is_logged_in = false;
		localStorage.Auth = undefined;
		reader.setUser({});
		reader.setAuth("");
		reader.setFeeds([]);
	};
	var getUserInfo = function(successCallback, failCallback) {
		makeRequest({
			method : "GET",
			url : BASE_URL + USERINFO_SUFFIX,
			parameters : {},
			onSuccess : function(transport) {
				reader.setUser(JSON.parse(transport.responseText));

				successCallback();
			},
			onFailure : function(transport) {
				console.error(transport);
				if(failCallback) {
					failCallback(reader.normalizeError(transport.responseText));
				}
			}
		});
	};
	var getUserPreferences = function(successCallback, failCallback) {
		makeRequest({
			method : "GET",
			url : BASE_URL + PREFERENCES_PATH,
			parameters : {},
			onSuccess : function(transport) {
				reader.has_loaded_prefs = true;
				reader.userPrefs = JSON.parse(transport.responseText).streamprefs;
				if(successCallback) {
					successCallback();
				}
			},
			onFailure : function(transport) {
				console.error(transport);
				if(failCallback) {
					failCallback(reader.normalizeError(transport.responseText));
				}
			}
		});
	};
	//Get the token
	reader.getToken = function(successCallback, failCallback) {
		makeRequest({
			method : "GET",
			url : BASE_URL + TOKEN_SUFFIX,
			parameters : {},
			onSuccess : function(transport) {
				readerToken = transport.responseText;
				successCallback();
			},
			onFailure : function(transport) {
				console.error("failed", transport);
				if(failCallback) {
					failCallback(reader.normalizeError(transport.responseText));
				}
			}
		});
	};
	// *************************************
	// *
	// * Loading Feeds
	// *
	// *************************************

	//Get the user's subscribed feeds
	reader.loadFeeds = function(successCallback) {
		function loadFeeds() {
			makeRequest({
				method : "GET",
				url : BASE_URL + SUBSCRIPTIONS_PATH + LIST_SUFFIX,
				onSuccess : function(transport) {
					//save feeds in an organized state.

					loadTags(function(tags) {
						//get unread counts
						reader.getUnreadCounts(function(unreadcounts) {

							//organize and save feeds
							reader.setFeeds(organizeFeeds(JSON.parse(transport.responseText).subscriptions, tags, unreadcounts, reader.userPrefs));

							//callback with our feeds
							successCallback(reader.getFeeds());
						});
					});
				},
				onFailure : function(transport) {
					console.error(transport);
				}
			});
		}

		if(reader.has_loaded_prefs) {
			loadFeeds();
		} else {
			getUserPreferences(loadFeeds);
		}
	};
	var loadTags = function(successCallback) {
		makeRequest({
			method : "GET",
			url : BASE_URL + TAGS_PATH + LIST_SUFFIX,
			onSuccess : function(transport) {
				//save feeds in an organized state.
				successCallback(JSON.parse(transport.responseText).tags);
			},
			onFailure : function(transport) {
				console.error(transport);
			}
		});
	};
	//organizes feeds based on categories/labels.
	//this function is ridiculous. like really, holy crap.
	var organizeFeeds = function(subscriptions, tags, unreadCounts, userPrefs) {
		var uncategorized = [];

		//prepare tags
		tags.unshift({
			title : "All",
			id : reader.TAGS["reading-list"],
			feeds : subscriptions,
			isAll : true,
			isSpecial : true
		});
		tags.pop();
		//remove "user/-/state/com.blogger/blogger-following". not exactly future friendly *shrug*
		var tagTitleRegExp = /[^\/]+$/i;
		_(tags).each(function(tag) {
			//give tags a .title
			if(!tag.title) {
				tag.title = tagTitleRegExp.exec(tag.id)[0];
			}

			//based on title add unique properties
			if(tag.title === "starred") {
				tag.title = _(tag.title).capitalize();
				tag.isSpecial = true;
			} else if(tag.title === "broadcast") {
				tag.title = "Shared";
				tag.isSpecial = true;
			} else if(!tag.isSpecial) {
				tag.isLabel = true;
			}

			tag.feeds = [];
			//remove digits from the id
			tag.id = reader.correctId(tag.id);

			//apply unreadCounts
			_(unreadCounts).each(function(unreadCount) {
				unreadCount.id = reader.correctId(unreadCount.id);

				if(tag.id === unreadCount.id) {
					tag.count = unreadCount.count;
					tag.newestItemTimestamp = unreadCount.newestItemTimestampUsec;
				}
			});
		});
		//process subscriptions
		_(subscriptions).each(function(sub) {
			//give isFeed property, useful for identifying
			sub.isFeed = true;

			//replace digits from the id
			sub.id = reader.correctId(sub.id);

			//apply unread counts
			_(unreadCounts).each(function(unreadCount) {
				if(sub.id === unreadCount.id) {
					sub.count = unreadCount.count;
					sub.newestItemTimestamp = unreadCount.newestItemTimestampUsec;
				}
			});
			if(sub.categories.length === 0) {
				//if the subscription has no categories, push it onto the uncategorized array
				uncategorized.push(sub);
			} else {
				//otherwise find the category from the tags array and push the sub into its feeds array
				_(sub.categories).each(function(tag) {
					tag.id = reader.correctId(tag.id);
					_(tags).each(function(fullTag) {
						if(tag.id === fullTag.id) {
							var sub_clone = _(sub).clone();
							sub_clone.inside = fullTag.id;

							fullTag.feeds.push(sub_clone);
						}
					});
				});
			}

		});
		//replace digits
		_(userPrefs).each(function(value, key) {
			if(/user\/\d*\//.test(key)) {
				userPrefs[reader.correctId(key)] = value;
			}
		});
		//remove tags with no feeds
		var tagsWithFeeds = _(tags).reject(function(tag) {
			return (tag.feeds.length === 0 && !tag.isSpecial);
		});
		//order the feeds within tags
		_(tagsWithFeeds).each(function(tag) {
			//get the ordering id based on the userPrefs
			var orderingId = _(userPrefs[tag.id]).detect(function(setting) {
				return (setting.id === "subscription-ordering");
			});
			if(orderingId) {
				tag.feeds = _(tag.feeds).sortBy(function(feed) {
					if(orderingId.value.indexOf(feed.sortid) === -1) {
						//if our sortid isn't there, the feed should be at the back.
						return 1000;
					}
					//return the index of our feed sortid, which will be in multiples of 8 since sortid's are 8 characters long.
					return (orderingId.value.indexOf(feed.sortid)) / 8;
				});
			} //there might be another setting we should follow like "alphabetical" or "most recent". Just a guess.
			/*else {
			 tag.feeds.sort();
			 }*/
		});
		//now order ALL feeds and tags
		var orderingId = _(userPrefs["user/-/state/com.google/root"]).detect(function(setting) {
			return (setting.id === "subscription-ordering");
		}) || {
			value : ""
		};

		//our feeds are our tagsWithFeeds + our uncategorized subscriptions
		var feeds = [].concat(tagsWithFeeds, uncategorized);
		//sort them by sortid
		feeds = _(feeds).sortBy(function(feed) {
			if(orderingId.value.indexOf(feed.sortid) === -1 && !feed.isSpecial) {
				return 1000;
			}
			return (orderingId.value.indexOf(feed.sortid)) / 8;
		});
		return feeds;
	};
	//get unread counts from google reader
	//passing true as the second arg gets you an object, extremely useful for notifications
	reader.getUnreadCounts = function(successCallback, returnObject) {
		makeRequest({
			url : BASE_URL + UNREAD_SUFFIX,
			onSuccess : function(transport) {
				var unreadCounts = JSON.parse(transport.responseText).unreadcounts;
				//console.log(transport);
				var unreadCountsObj = {};
				_(unreadCounts).each(function(obj) {
					unreadCountsObj[reader.correctId(obj.id)] = obj.count;
				});
				reader.unreadCountsObj = unreadCountsObj;

				if(returnObject) {
					successCallback(unreadCountsObj);
				} else {
					successCallback(unreadCounts);
				}
			},
			onFailure : function(transport) {
				console.error(transport);
			}
		});
	};
	//this is a function so we can reduce the amount of ajax calls when setting an article as read. Just manually decrement the counts, don't request new numbers.
	reader.decrementUnreadCount = function(feedId, callback) {
		_.each(reader.getFeeds(), function(subscription) {
			if(subscription.id === feedId || (subscription.isAll)) {
				subscription.count -= 1;
			} else if(subscription.feeds && subscription.feeds.length > 0) {
				_.each(subscription.feeds, function(feed) {
					if(feed.id === feedId) {
						subscription.count -= 1;
					}
				});
			}
		});
		callback();
	};
	// *************************************
	// *
	// * Editing Feeds
	// *
	// *************************************

	var editFeed = function(params, successCallback) {
		if(!params) {
			console.error("No params for feed edit");
			return;
		}
		makeRequest({
			method : "POST",
			url : BASE_URL + SUBSCRIPTIONS_PATH + EDIT_SUFFIX,
			parameters : params,
			onSuccess : function(transport) {
				successCallback(transport.responseText);
			},
			onFailure : function(transport) {
				console.error(transport);
			}
		});
	};
	//edit feed title
	reader.editFeedTitle = function(feedId, newTitle, successCallback) {
		editFeed({
			ac : "edit",
			t : newTitle,
			s : feedId
		}, successCallback);
	};
	reader.editFeedLabel = function(feedId, label, opt, successCallback) {
		var obj = {
			ac : "edit",
			s : feedId
		};
		if(opt) {
			obj.a = label;
		} else {
			obj.r = label;
		}
		editFeed(obj, successCallback);
	};

	reader.editLabelTitle = function(labelId, newTitle, successCallback) {
		makeRequest({
			method : "POST",
			url : BASE_URL + RENAME_LABEL_SUFFIX,
			parameters : {
				s : LABEL_PATH + labelId,
				t : labelId,
				dest : LABEL_PATH + newTitle
			},
			onSuccess : function(transport) {
				successCallback(transport.responseText);
			},
			onFailure : function(transport) {
				console.error(transport);
			}
		});
	};

	reader.markAllAsRead = function(feedOrLabelId, successCallback) {
		//feed or label
		makeRequest({
			method : "POST",
			url : BASE_URL + MARK_ALL_READ_SUFFIX,
			parameters : {
				s : feedOrLabelId
			},
			onSuccess : function(transport) {
				successCallback(transport.responseText);
			},
			onFailure : function(transport) {
				console.error(transport);
			}
		});
	};
	// *************************************
	// *
	// * Adding a Feed
	// *
	// *************************************
	reader.unsubscribeFeed = function(feedId, successCallback) {
		editFeed({
			ac : "unsubscribe",
			s : feedId
		}, successCallback);
	};

	reader.subscribeFeed = function(feedUrl, successCallback, title) {
		editFeed({
			ac : "subscribe",
			s : "feed/" + feedUrl,
			t : title || undefined
		}, successCallback);
	};
	var readerUrlRegex = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?\^=%&amp;:\/~\+#]*[\w\-\@?\^=%&amp;\/~\+#])?/;
	reader.processFeedInput = function(input, inputType, successCallback, failCallback) {
		var url = "https://ajax.googleapis.com/ajax/services/feed/";
		if((readerUrlRegex.test(input) || inputType === "url") && inputType !== "keyword") {
			url += "load";
		} else {
			url += "find";
			//replace the .com, or .net from the input, since our search doesn't like that
			input = input.replace(/\.\w{1,3}\.*\w{0,2}$/ig, "");
		}
		makeRequest({
			url : url,
			parameters : {
				q : encodeURI(input),
				v : "1.0"
			},
			onSuccess : function(transport) {
				var response = JSON.parse(transport.responseText);
				if(response.responseStatus === 200) {
					if(response.responseData.entries) {
						successCallback(response.responseData.entries, "keyword");
					} else {
						successCallback(response.responseData.feed, "url");
					}
				} else {
					failCallback(response.responseDetails);
				}

			},
			onFailure : function(transport) {
				console.error(transport);
			}
		}, true);
	};
	// *************************************
	// *
	// * Loading Items
	// *
	// *************************************

	reader.getItems = function(feedUrl, successCallback, opts) {
		var params = opts || {
			n : 50
		};
		params.r = "d";
		makeRequest({
			method : "GET",
			// url : BASE_URL + STREAM_PATH + encodeURIComponent(feedUrl),
			url : ( opts.output && opts.output == "xml" ) ? 
					ITEMS_ROOT + feedUrl : // encodeURIComponent(feedUrl),
					BASE_URL + STREAM_PATH + encodeURIComponent(feedUrl),
			parameters : params, /*{
			 //ot=[unix timestamp] : The time from which you want to retrieve items. Only items that have been crawled by Google Reader after this time will be returned.
			 //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order.
			 //xt=[exclude target] : Used to exclude certain items from the feed. For example, using xt=user/-/state/com.google/read will exclude items that the current user has marked as read, or xt=feed/[feedurl] will exclude items from a particular feed (obviously not useful in this request, but xt appears in other listing requests).
			 },*/
			onSuccess : function(transport) {
				var response = transport.responseText;

console.log ( "got response of length ", response.length );

				try {
					let tmp = JSON.parse(transport.responseText);
					response = tmp;
				} catch ( ex ) {
					console.log ( clc.bold ( "response not json" ) );
				}
				successCallback(response.items,response);
			},
			onFailure : function(transport) {
				console.error( clc.red ( transport ) );
			}
		});
	};
	// *************************************
	// *
	// * Editing Items
	// *
	// *************************************

	reader.setItemTag = function(feed, item, tag, add, successCallback) {
		//feed/label id
		//item id
		//tag in simple form: "like", "read", "share", "label", "star", "kept-unread"
		//add === true, or add === false

		var params = {
			s : feed,
			i : item,
			async : "true",
			ac : "edit-tags"
		};
		if(add === true) {
			params.a = reader.TAGS[tag];
		} else {
			params.r = reader.TAGS[tag];
		}
		makeRequest({
			method : "POST",
			url : BASE_URL + EDIT_TAG_SUFFIX,
			parameters : params,
			onSuccess : function(transport) {
				if(transport.responseText === "OK") {
					successCallback(transport.responseText);
				}
			},
			onFailure : function(transport) {
				console.error(transport);
			}
		});
	};
	// *************************************
	// *
	// * Useful Utilities
	// *
	// *************************************
	//this function replaces the number id with a dash. Helpful for comparison
	var readerIdRegExp = /user\/\d*\//;
	reader.correctId = function(id) {
		return id.replace(readerIdRegExp, "user\/-\/");
	};
	//returns url for image to use in the icon
	reader.getIconForFeed = function(feedUrl) {
		return "http://www.google.com/s2/favicons?domain_url=" + encodeURIComponent(feedUrl);
	};
	//normalizes error response for logging in
	reader.normalizeError = function(inErrorResponse) {
		return _(inErrorResponse).lines()[0].replace("Error=", "").replace(/(\w)([A-Z])/g, "$1 $2");
	};
}());
Пример #9
0
 isIgnoredFile = function(file) {
   var pathFromBase = file.path.substring(file.base.length, file.path.length);
   var extname = path.extname(pathFromBase);
   return _.str.endsWith(pathFromBase, '.ignore' + extname) || _.str.endsWith(pathFromBase, '.min' + extname);
 };
Пример #10
0
 this._actionGroups.forEach(function (group) {
   if (titleGroupMap.indexOf(group.title) >= 0) {
     throw new Error(_.str.sprintf('Cannot merge actions - two groups are named "%(group.title)s".', group));
   }
   titleGroupMap[group.title] = group;
 });
Пример #11
0
(function (_undef) {
    "use strict";

    /**
     * Function wraps the library code to allow passing in the
     * dependencies easily.
     * @param {Object} _ - Reference to underscore.js
     * @param {Object} stemmer - Porter stemmer implementation in js.
     * @return {Function} Sumarization function.
     */
    var wrapper = function (_, stemmer) {

        // Params default values.
        var defaults = {
            nSentences: 1,
            exclude: [],
            emphasise: []
        };

        // regexes
        var sentenceDelimiter = /[.!?;]/;
        var nGramDelimiter = /[.,!?;]/;
        var wordDelimiter = /\s/mg;
        var matchJunk = /["#$%&'()*+,\-\/:<=>@\[\\\]\^_`{|}]/mg ;

        // List of words which are ignored when computing top relevant sentences.
        var stopWords = ["", "a", "about", "above", "above", "across", "after",
            "afterwards", "again", "against", "all", "almost", "alone", "along",
            "already", "also","although","always","am","among", "amongst",
            "amoungst", "amount",  "an", "and", "another", "any","anyhow",
            "anyone","anything","anyway", "anywhere", "are", "around", "as",
            "at", "back","be","became", "because","become","becomes",
            "becoming", "been", "before", "beforehand", "behind", "being",
            "below", "beside", "besides", "between", "beyond", "bill", "both",
            "bottom","but", "by", "call", "can", "cannot", "cant", "co", "con",
            "could", "couldnt", "cry", "de", "describe", "detail", "do", "done",
            "down", "due", "during", "each", "eg", "eight", "either", "eleven",
            "else", "elsewhere", "empty", "enough", "etc", "even", "ever",
            "every", "everyone", "everything", "everywhere", "except", "few",
            "fifteen", "fify", "fill", "find", "fire", "first", "five", "for",
            "former", "formerly", "forty", "found", "four", "from", "front",
            "full", "further", "get", "give", "go", "had", "has", "hasnt",
            "have", "he", "hence", "her", "here", "hereafter", "hereby",
            "herein", "hereupon", "hers", "herself", "him", "himself", "his",
            "how", "however", "hundred", "ie", "if", "in", "inc", "indeed",
            "interest", "into", "is", "it", "its", "itself", "keep", "last",
            "latter", "latterly", "least", "less", "ltd", "made", "many", "may",
            "me", "meanwhile", "might", "mill", "mine", "more", "moreover",
            "most", "mostly", "move", "much", "must", "my", "myself", "name",
            "namely", "neither", "never", "nevertheless", "next", "nine", "no",
            "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere",
            "of", "off", "often", "on", "once", "one", "only", "onto", "or",
            "other", "others", "otherwise", "our", "ours", "ourselves", "out",
            "over", "own","part", "per", "perhaps", "please", "put", "rather",
            "re", "same", "see", "seem", "seemed", "seeming", "seems",
            "serious", "several", "she", "should", "show", "side", "since",
            "sincere", "six", "sixty", "so", "some", "somehow", "someone",
            "something", "sometime", "sometimes", "somewhere", "still", "such",
            "system", "take", "ten", "than", "that", "the", "their", "them",
            "themselves", "then", "thence", "there", "thereafter", "thereby",
            "therefore", "therein", "thereupon", "these", "they", "thickv",
            "thin", "third", "this", "those", "though", "three", "through",
            "throughout", "thru", "thus", "to", "together", "too", "top",
            "toward", "towards", "twelve", "twenty", "two", "un", "under",
            "until", "up", "upon", "us", "very", "via", "was", "we", "well",
            "were", "what", "whatever", "when", "whence", "whenever", "where",
            "whereafter", "whereas", "whereby", "wherein", "whereupon",
            "wherever", "whether", "which", "while", "whither", "who",
            "whoever", "whole", "whom", "whose", "why", "will", "with",
            "within", "without", "would", "yet", "you", "your", "yours",
            "yourself", "yourselves", "the"];

        /**
         * Function used to clean sentences before splitting into words
         * @param {String} str
         * @return {String}
         */
        var clean = function (str) {
            return _(str).chain()
                .unescapeHTML()
                .stripTags()
                .clean()
                .value()
                .replace( matchJunk, '' )
                .toLowerCase();
        };

        /**
         * Sentence Module. Creates object with format:
         *  {orig:String, words:Array<String>, remove:Function}
         */
        var Sentence = function (s) {
            var c = clean( s );
            var all = _.words( c, wordDelimiter );
            var words = _(all).chain()
                    // remove stop words
                    .filter( function (w) {
                        return (stopWords.indexOf( w ) === -1) ;
                    })
                    // apply stemmer
                    .map( function (w) {
                        return stemmer( w );
                    })
                    // collect word frequencies
                    .reduce( function (collect, w) {
                        collect[w] = collect[w] ? collect[w] + 1 : 1 ;
                        return collect;
                    }, {}).value();
            // remove a word from this sentence to reduce redundancy in results
            var remove = function (w) {
                return delete words[w];
            };
            return {
                orig: s,
                words: words,
                remove: remove
            };
        };

        /**
         * Text summarization function.
         * @param {Object} opts
         * @param {String} opts.corpus - String to summarize.
         * @param {String} opts.nWords - Number of words the summary should have.
         * @param {String} opts.nSentences - Number of sentences the summary should have.
         * @return {Object} output
         * @return {Array<String>} output.sentences - The summary sentences in
         *                                  order of relevance to the input text.
         * @return {String} output.summary - the concatenation of the summary
         *                                  sentences for convenience.
         */
        var sum = function (opts){
            // Handle options.
            opts = _.extend( {}, defaults, opts );
            opts.corpus = opts.corpus || _undef;
            if (opts.corpus === _undef) {
                throw Error( 'No input corpus' );
            }
            if (opts.nWords !== _undef && !_.isNumber(opts.nWords)) {
                throw Error('Bad value for nWords');
            }

            // Clean corpus.
            var s = opts.corpus.split(sentenceDelimiter);
            var sentences = _(s).map( function (s) {
                return new Sentence(s);
            });

            // Splits the sentences into nGrams then applies the same algorithm.
            if (opts.nWords) {

                // `opts.nSentences` is ignored, output size is determined by lexem size.
                opts.nSentences = 1;

                var nGrams = _(sentences).reduce( function (collect, s) {
                    var orig = s.orig;
                    var partials = _(s.words).reduce( function (memo, freq, w) {
                        var pos = orig.indexOf(' ');
                        if (pos === -1) {
                            pos = orig.length;
                        }
                        var partial = orig.substr(0, pos);
                        orig = orig.substr(pos + 1);
                        if (partial !== '') {
                            memo.push(partial);
                        }
                        return memo;
                    }, []);
                    if (partials.length <= opts.nWords) {
                        var newSentence = new Sentence( partials.join(' '));
                        collect.push( newSentence );
                        return collect;
                    }
                    var i = 0,
                        j = 0,
                        n = partials.length - opts.nWords,
                        m = partials.length,
                        tmp;
                    for (i = 0; i < n; i ++) {
                        var tmp = ''
                        for (j = i; j < i+opts.nWords; j ++) {
                            tmp += partials[j] + ' ';
                        }
                        var newSentence = new Sentence(tmp);
                        collect.push(newSentence);
                    }
                    return collect;
                }, []);
                sentences = nGrams;
            }


            /**
             * Return all sentences that contain a givven word.
             * @param {String} w - word
             * @return {Array<Object>}
             */
            var containing = function (w) {
                return _(sentences).filter( function (s) {
                    return (s.words[w] !== undefined) ;
                });
            };

            // If summary must exclude words in opts.exclude remove sentences
            // that contain those words.
            if ( _.isArray(opts.exclude) && opts.exclude.length !== 0) {
                var excludes = _(opts.exclude).map( function (w) {
                    return stemmer(clean(w));
                });
                sentences = _(sentences).filter( function (s) {
                    var words = _(s.words).keys();
                    return (_.intersection( words, excludes ).length === 0);
                });
            }

            var summary = [];
            var counter = 0;

            // Extract sentences in order of their relevance.
            while (true) {
                var N = sentences.length;

                // Builds a hash of all words with global frequencies.
                var words = _(sentences).reduce( function (collect,s) {
                    _(s.words).each( function (count, w) {
                        collect[w] = collect[w] ? collect[w] + count : count ;
                    });
                    return collect;
                }, {});

                // If summary must have the words in opts.emphasise.
                var emphasise = [];
                if ( _.isArray(opts.emphasise) && opts.emphasise.length !== 0) {
                    emphasise = _(opts.emphasise).map( function (w) {
                        return stemmer(clean(w));
                    });
                }

                // Calculate relevance for each sentence.
                _(sentences).each( function (s) {
                    var relevance = _(s.words).reduce( function (memo, freq, w) {
                        var local = Math.log(1 + freq);
                        var global = Math.log(N / containing(w).length);
                        return memo = memo + (local * global);
                    }, 0);

                    // If current sentence containes emphasised words,
                    // bumb up the relevance.
                    var bump = _.intersection(emphasise, _(s.words).keys()).length;
                    relevance += bump * 1000;

                    s.relevance = relevance;
                })

                // Highest relevance sentence.
                var highest = _(sentences).max( function (s) {
                    return s.relevance;
                });

                // Remove words from the remaining sentences to reduce redundancy.
                sentences = _(sentences).chain()
                    .without(highest)
                    .map( function (s) {
                        _(highest.words).each( function (w) {
                            s.remove( w );
                        });
                        return s;
                    })
                    .value();

                summary.push( highest.orig ) ;
                counter += 1;

                var stop = (counter === opts.nSentences || sentences.length === 0);
                if (stop) break;
            }

            return {
                'summary': summary.join('.'),
                'sentences': summary
            };
        };

        return sum;
    };


    // exports the `sum` function in node.js
    if (typeof exports !== 'undefined'
        && typeof module !== 'undefined'
        && module.exports
        && typeof require !== 'undefined') {
        var stemmer = require( 'porter-stemmer' ).stemmer;
        var _ = require( 'underscore' );
        _.str = require( 'underscore.string' );
        _.mixin( _.str.exports() );
        module.exports = wrapper(_, stemmer);
    }
    // exports `sum` to AMD module, defining dependencies
    else if (typeof define === 'function' && define.amd) {
        define('sum', [
            'underscore',
            'underscore.string',
            'porter-stemmer'
        ], function(_, str, stemmer) {
            return wrapper(_, stemmer);
        });
    }
    // export in browser
    else if (typeof this !== 'undefined'
             && this._ && this.stemmer) {
        this._.mixin( this._.str.exports() );
        this.sum = wrapper(this._, this.stemmer);
    }
    else {
        throw Error( 'Unsupported js environment detected' );
    }

}).call(this);
Пример #12
0
exports.camelize = function(string) {
    return _.str.camelize(string);
};
Пример #13
0
exports.classify = function(string) {
    return _.str.classify(string);
};
Пример #14
0
var theApp = (function(theApp, undefined) {

	var fs = require("fs"),				cronJob = require('cron').CronJob,			_ = require('underscore'),
		io = require('socket.io'),		http = require('http'),						express = require('express'),
		stylus = require('stylus'),		fontFace = require('stylus-font-face'),		nib = require('nib'),
		axis = require('axis-css'),		fluidity = require('fluidity'),				compressor = require('node-minify'),
		twitter = require('ntwitter'),	passport = require('passport'),
		FacebookStrategy = require('passport-facebook').Strategy,
		path = require('path');
		
	var env = process.env.NODE_ENV || 'development', cfg = require('./config')[env];

		_.str = require('underscore.string');
		_.mixin(_.str.exports()),
		_.str.include('Underscore.string', 'string');

	var app = express(),
		server = http.createServer(app),
		compile = function(str, path) {
			return stylus(str).set('filename', path).use( axis() ).use( nib() ).use( fluidity() ).use( fontFace() );
		};

	app.configure('development', function () {app.use(express.errorHandler());});
	var __dirName = __dirname;
	__dirName = __dirName.slice(0, __dirName.lastIndexOf('/')); 	// use the app dir (parent)
	app.configure(function () {
		app.set( 'views', __dirName + '/views' );
		app.set( 'view engine', 'jade' );
		app.use( express.favicon() );
		app.use( express.logger( { immediate: true, format: 'dev' } ) );
		app.use( express.cookieParser() );
		app.use( express.bodyParser() );
		app.use( express.session( { secret: 'bukalemun' } ) );
		app.use( stylus.middleware( {
			debug: true,
			force: true,
			src: 	__dirName + '/style',
			dest: 	__dirName + '/public/css/',
			compile : function(str, path) {
				console.log('compiling');
				return stylus(str)
					.use( nib() ).use( fontFace() ).use( axis() ).use( fluidity() )
					.set('filename', path).set('warn', true).set('compress', true)
			}
		} ) );
		app.use( passport.initialize() );
		app.use( passport.session() );
		app.use( express.methodOverride() );
		app.use( app.router );
		app.use( express.static(__dirName + '/public') );
		app.use( express.errorHandler( { dumpExceptions: true, showStack: true } ) );
	});
/*
	new compressor.minify({
		type: 'clean-css',
		fileIn: ['public/css/reset.css', 'public/css/style.css'],
		fileOut: 'public/css/style-min.css',
		callback: function(err, min){
			if(err) console.log(err);
		}
	});
*/
	var sockets = io.listen(server);
	sockets.configure(function() { //THIS IS NECESSARY ONLY FOR HEROKU!
		sockets.set('transports', ['xhr-polling']);
		sockets.set('polling duration', 10);
	});
	sockets.sockets.on('connection', function(socket) { 
		socket.emit('data', watchList);
	});

	process.on('uncaughtException', function(err) {
		if(err.errno === 'EADDRINUSE') {
			console.log("Port in use!");
		} else {
			console.log(err);
		}
		process.exit(1);
	});
	app.use(function(req, res, next){
		res.status(404);
		if (req.accepts('html')) {
			res.render('404', { url: req.url });
			return;
		}
		if (req.accepts('json')) {
			res.send({ error: 'Not found' });
			return;
		}
		res.type('txt').send('Not found');
	});
	require('./routes')(cfg, app);
	var port = process.env.PORT || 5000;
	app.listen(port, function() {
		console.log("Listening on " + port);
	});

}(theApp = theApp || {} ));
Пример #15
0
module.exports = function enhanceRequest(req, res, controllerName, actionName) {

	// Provide error messages for req.listen and res.broadcast if they don't exist
	req.listen = req.listen || notSupported("req.listen()");
	res.broadcast = res.broadcast || notSupported("res.broadcast()");

	// Always share some data with views
	res.locals({
		userAgent: req.headers['user-agent'],
		session: req.session,
		title: sails.config.appName + " | " + _.str.capitalize(actionName),
		controller: controllerName,
		action: actionName,
		req: req,
		res: res
	});

	// Add req.protocol
	req.protocol = req.protocol ? req.protocol : req.header('X-Forwarded-Protocol') == "https" ? "https" : "http";

	// Add req.host
	// (remove port if it exists)
	req.host = req.host || req.header('host');
	req.rawHost = req.host.split(':')[0];

	// Add req.port
	req.port = req.port ? req.port : sails.express.app.address().port;

	// Add req.rootUrl convenience method
	req.rootUrl = req.protocol + '://' + req.rawHost + (req.port == 80 || req.port == 443 ? '' : ':' + req.port);


	// Set action and controller as request parameters for use in controllers and views
	req.params = req.params || {};
	req.params.controller = req.params.entity = controllerName;
	req.params.action = actionName;

	// Add *verb* attribute to request object
	req.verb = req.method;

	// Add flags to request object
	req.isAjax = req.xhr;
	req.isJson = req.header('content-type') === 'application/json';
	req.acceptJson = req.header('Accept') === 'application/json';
	req.isJsony = req.isJson || req.acceptJson;

	// Add res.view() method to response object
	// res.view() is an enhanced version of  Express's res.render()
	// which automatically renders the appropriate view based on the entity and action
	// Note: the original function is still accessible via res.render()
	res.view = function(specifiedPath, data, fun) {
		data = data || {};

		// By default, generate a path to the view using what we know about the controller+action
		var path = req.param('entity') + "/" + req.param('action');

		// If the path to a view was explicitly specified, use that
		if(_.isString(specifiedPath)) {
			path = specifiedPath;
		}
		// If a map of data is provided as the first argument, use it (and just use the default path)
		else if(_.isObject(specifiedPath)) {
			data = specifiedPath;
		}

		// TODO: work with the appropriate Adapters to fulfill promise objects in *data*

		res.render(path, data, fun);
	};

	// Respond with a message indicating that the feature is not currently supported
	function notSupported(method) {
		return function() {
			sails.log.warn(method + " is only supported using Socket.io!");
		};
	}
};
Пример #16
0
ArgumentParser.prototype._parseOptional = function (argString) {
  var action, optionString, argExplicit, optionTuples;

  // if it's an empty string, it was meant to be a positional
  if (!argString) {
    return null;
  }

  // if it doesn't start with a prefix, it was meant to be positional
  if (this.prefixChars.indexOf(argString[0]) < 0) {
    return null;
  }

  // if the option string is present in the parser, return the action
  if (!!this._optionStringActions[argString]) {
    return [this._optionStringActions[argString], argString, null];
  }

  // if it's just a single character, it was meant to be positional
  if (argString.length === 1) {
    return null;
  }

  // if the option string before the "=" is present, return the action
  if (argString.indexOf('=') >= 0) {
    var argStringSplit = argString.split('=');
    optionString = argStringSplit[0];
    argExplicit = argStringSplit[1];

    if (!!this._optionStringActions[optionString]) {
      action = this._optionStringActions[optionString];
      return [action, optionString, argExplicit];
    }
  }

  // search through all possible prefixes of the option string
  // and all actions in the parser for possible interpretations
  optionTuples = this._getOptionTuples(argString);

  // if multiple actions match, the option string was ambiguous
  if (optionTuples.length > 1) {
    var optionStrings = optionTuples.map(function (optionTuple) {
      return optionTuple[1];
    });
    this.error(_.str.sprintf(
          'Ambiguous option: "%(argument)s" could match %(values)s.',
          {argument: argString, values: optionStrings.join(', ')}
    ));
  // if exactly one action matched, this segmentation is good,
  // so return the parsed action
  } else if (optionTuples.length === 1) {
    return optionTuples[0];
  }

  // if it was not found as an option, but it looks like a negative
  // number, it was meant to be positional
  // unless there are negative-number-like options
  if (argString.match(this._regexpNegativeNumber)) {
    if (!_.any(this._hasNegativeNumberOptionals)) {
      return null;
    }
  }
  // if it contains a space, it was meant to be a positional
  if (argString.search(' ') >= 0) {
    return null;
  }

  // it was meant to be an optional but there is no such option
  // in this parser (though it might be a valid option in a subparser)
  return [null, argString, null];
};
Пример #17
0
var Context = function (server, req, res, type) {

    this.server = server;
    this.req = req;
    this.res = res;
    this.type = type || 'html';

    var uri = new parseUri('http://' + server.host + req.url);

    if (!_.str.endsWith(uri.path, '/'))
        uri.path += '/';

    uri = new parseUri(('http://' + server.host + uri.path).toLowerCase() + (uri.query !== '' ? '?' + uri.query : ''));

    var timer = new TimeLogger('context: ' + uri.relative);
    timer.start();

    this.dbgLogger = new DebugLogger();

    if (uri.path === '/' || uri.path.toLowerCase() === '/index.html')
        uri.path = '/';
    else {
        uri.path = _.str.rtrim(uri.path, '/').toLowerCase();
    }

    uri.parts = _.str.trim(uri.path, '/').split('/');
    uri.first = uri.parts.length > 0 ? _.first(uri.parts).toLowerCase() : '';
    uri.last = uri.parts.length > 0 ? _.last(uri.parts).toLowerCase() : '';

    this.method = req.method;
    
    this.timer = timer;

    this.node = undefined;
    this.hierarchy = [];
    this.pointer = undefined;
    this.layouts = [];

    this.meta = {
        title: '',
        description: '',
        keywords: []
    };

    this.params = [];

    this.robots = {
        noindex: false,
        nofollow: false,
        noarchive: false,
        nosnipet: false,
        notranslate: false,
        noimageindex: false
    };

    this.template = '';

    this.uri = {
        url: uri.relative,
        scheme: uri.protocol,
        host: uri.host,
        port: uri.port,
        path: uri.path,
        parts: uri.parts,
        query: uri.queryKey,
        first: uri.first,
        last: uri.last,
        getBaseHref: function () {
            var href = this.scheme;
            href += '://';
            href += this.host;

            if (this.scheme === 'https') {
                href += (this.port !== '433' && this.port !== '433') ? ':' + this.port : '';
            }
            else {
                href += (this.port !== '80' && this.port !== '') ? ':' + this.port : '';
            }
            href += '/';
            return href;
        }
    };

    this.restricted = false;
};
Пример #18
0
function func(data, bFirstline) {
  var temp = _.str.rtrim(data, "\n");

  if (bFirstline) {
    legendArray = _.str.words(temp, "|");
  }
  else {
    lineArray = _.str.words(temp, "|");

    if (legendArray.length === lineArray.length) {
      var cdr = {};

      cdr.callId = lineArray[_.indexOf(legendArray, 'fbasename')];
      cdr.calldate = lineArray[_.indexOf(legendArray, 'calldate')];
      cdr.duration = lineArray[_.indexOf(legendArray, 'duration')];
      cdr.caller = lineArray[_.indexOf(legendArray, 'caller')];
      cdr.callerDomain = lineArray[_.indexOf(legendArray, 'caller_domain')];
      cdr.callerName = lineArray[_.indexOf(legendArray, 'callername')];
      cdr.called = lineArray[_.indexOf(legendArray, 'called')];
      cdr.calledDomain = lineArray[_.indexOf(legendArray, 'called_domain')];
      cdr.lastSipResponseNum = lineArray[_.indexOf(legendArray, 'lastSIPresponseNum')];
      cdr.sensorId = lineArray[_.indexOf(legendArray, 'id_sensor')];
      
// a_mos_f1
// a_mos_f2
// a_mos_adapt
// b_mos_f1
// b_mos_f2
// b_mos_adapt
// a_rtcp_loss
// a_rtcp_maxfr
// a_rtcp_avgfr
// a_rtcp_maxjitter
// a_rtcp_avgjitter
// b_rtcp_loss
// b_rtcp_maxfr
// b_rtcp_avgfr
// b_rtcp_maxjitter
// b_rtcp_avgjitter
// jitter
// mos_min
// a_mos_min
// b_mos_min
// packet_loss_perc
// a_packet_loss_perc
// b_packet_loss_perc
// delay_sum
// a_delay_sum
// b_delay_sum
// delay_avg
// a_delay_avg
// b_delay_avg

      //console.log('xxxx:', cdr.callId);
 
      cdrArray.push(cdr);
    }
    else {
      console.log('data mismatch', legendArray.length, "!=", lineArray.length);
      process.exit();
    }
  }
  //console.log('Line: ' + temp);
  //console.log(legendArray);
}
Пример #19
0
 return _.reduce(attrs, function(memo, val, key) {
   memo[_.str.underscored(key)] = val;
   return memo;
 }, {});
Пример #20
0
    gbk.fetch(url).to('string', function(err, string) {
      if (err) {
        return reject(err);
      }

      var $ = cheerio.load(string);

      string = string.replace(/\n/g, '');
      string = string.replace(/\r/g, '');
      string = string.replace(/\t/g, '');
      string = string.replace(/"/g, '\'');
      string = string.replace(/\s/g, '');

      var reg = {
        detail: /var_DATA_Detail=(.*?);<\/script>/,
        skip: /var_DATA_Mdskip=(.*?)<\/script>/,
        promoPrice: /"promotionList":(.*?)]}/
      };

      var detail = string.match(reg.detail)[1];
      detail = detail.replace(/'/g, '"');
      try {
        detail = JSON.parse(detail);
      } catch (err) {
        throw new Error(err);
      }

      var skip = string.match(reg.skip)[1];
      skip = skip.replace(/'/g, '"');

      try {
        skip = JSON.parse(skip);
      } catch (err) {
        throw new Error(err);
      }

      var promoPriceData;
      var promoPrice;
      var province;
      var city;
      var title = detail.itemDO.title;
      var picUrl = detail.itemDO.mainPic;

      // var originPrice = detail.detail.defaultItemPrice;
      var originPrice = detail.itemDO.reservePrice;

      promoPriceData = JSON.stringify(skip.defaultModel.itemPriceResultDO);

      if (promoPriceData.indexOf('"promotionList":') > -1) {
        promoPriceData = JSON.parse(promoPriceData.match(reg.promoPrice)[1] + ']')[0];
        promoPrice = promoPriceData.price;
      } else {
        promoPrice = promoPriceData.match(/,"price":"(.*?)"[},|}},]/)[1];
      }

      var discount = originPrice === promoPrice ? 10 : (promoPrice / originPrice) * 10;
      var delivery = _.str.include(JSON.stringify(skip.defaultModel.deliveryDO.extDeliverySkuMap), '快递: 0.00') ? true : false;
      var deliveryAddress = skip.defaultModel.deliveryDO.deliveryAddress;

      var shopTitle = $('.shop-t').text();
      var shopUrl = 'http:' + $('.go-shop').attr('href');
      var sellCount = skip.defaultModel.sellCountDO ? skip.defaultModel.sellCountDO.sellCount : 0;
      var itemUrl = 'http://detail.tmall.com/item.htm?id=' + id;
      var goodId = id;
      var source = 2; // 2代表商品来源是天猫

      // ==================获取省市======================
      _.each(provinces, function(i) {
        if (deliveryAddress.indexOf(i) > -1) {
          province = i;
        }
      });

      city = deliveryAddress.substring(province.length);

      var data = {
        title: title,
        picUrl: picUrl,
        originPrice: parseFloat(originPrice),
        promoPrice: parseFloat(promoPrice),
        discount: parseFloat(_.str.numberFormat(discount, 1)),
        delivery: delivery,
        province: province,
        city: city,
        shopTitle: shopTitle,
        shopUrl: shopUrl,
        sellerNick: decodeURI(detail.itemDO.sellerNickName),
        sellCount: parseInt(sellCount, 10),
        itemUrl: itemUrl,
        goodId: goodId,
        source: source
      };

      resolve(data);
    });
Пример #21
0
 _.each( process.env, function(val, key ) {
     if ( _.str.startsWith( key, "FORGE_CFG_" ) ) {
         var new_key = key.slice( 10 ).toLowerCase();
         config[ new_key ] = val;
     }
 });
Пример #22
0
	criteria: function normalizeCriteria(origCriteria) {
		var criteria = _.clone(origCriteria);

		if(!criteria) return {
			where: null
		};

		// Empty undefined values from criteria object
		_.each(criteria, function(val, key) {
			if(_.isUndefined(val)) delete criteria[key];
		});

		// Convert non-objects (ids) into a criteria
		// TODO: use customizable primary key attribute
		if(!_.isObject(criteria)) {
			criteria = {
				id: +criteria || criteria
			};
		}

		// Return string to indicate an error
		if(!_.isObject(criteria)) throw new Error('Invalid options/criteria :: ' + criteria);

		// If criteria doesn't seem to contain operational keys, assume all the keys are criteria
		if(!criteria.where && !criteria.limit && !criteria.skip && !criteria.sort) {

			// Delete any residuals and then use the remaining keys as attributes in a criteria query
			delete criteria.where;
			delete criteria.limit;
			delete criteria.skip;
			delete criteria.skip;
			criteria = {
				where: criteria
			};
		}
		// If where is null, turn it into an object
		else if(_.isNull(criteria.where)) criteria.where = {};

		// If WHERE is {}, always change it back to null
		if(criteria.where && _.keys(criteria.where).length === 0) {
			criteria.where = null;
		}

		// If a LIKE was specified, normalize it
		if(criteria.where && criteria.where.like) {
			_.each(criteria.where.like, function(criterion, attrName) {
				criteria.where.like[attrName] = normalizePercentSigns(criterion);
			});
		}

		// Normalize sort criteria
		if(criteria.sort) {
			// Split string into attr and sortDirection parts (default to 'asc')
			if(_.isString(criteria.sort)) {
				var parts = _.str.words(criteria.sort);
				parts[1] = parts[1] ? parts[1].toLowerCase() : 'asc';
				if(parts.length !== 2 || (parts[1] !== 'asc' && parts[1] !== 'desc')) {
					throw new Error('Invalid sort criteria :: ' + criteria.sort);
				}
				criteria.sort = {};
				criteria.sort[parts[0]] = (parts[1] === 'asc') ? 1 : -1;
			}

			// Verify that user either specified a proper object
			// or provided explicit comparator function
			if(!_.isObject(criteria.sort) && !_.isFunction(criteria.sort)) {
				throw new Error('Invalid sort criteria for ' + attrName + ' :: ' + direction);
			}
		}

		return criteria;
	},
Пример #23
0
function trimSlashes(str) {
	return _.str.trim(str, '/');
}
Пример #24
0
var _ = require('underscore');
_.str = require('underscore.string');

var mongoose = require('mongoose');
mongoose.connect(_.str.sprintf('%(db)s://%(host)s:%(port)s/%(name)s', require('../webconfig').dbCfg));

module.exports = mongoose;
Пример #25
0
  function consumeOptional(startIndex) {
    // get the optional identified at this index
    var optionTuple = optionStringIndices[startIndex];
    var action = optionTuple[0];
    var optionString = optionTuple[1];
    var explicitArg = optionTuple[2];

    // identify additional optionals in the same arg string
    // (e.g. -xyz is the same as -x -y -z if no args are required)
    var actionTuples = [];

    var args, argCount, start, stop;

    while (true) {
      if (!action) {
	extras.push(argStrings[startIndex]);
	return startIndex + 1;
      }
      if (!!explicitArg) {
	argCount = self._matchArgument(action, 'A');

	// if the action is a single-dash option and takes no
	// arguments, try to parse more single-dash options out
	// of the tail of the option string
	var chars = self.prefixChars;
	if (argCount === 0 && chars.indexOf(optionString[1]) < 0) {
	  actionTuples.push([action, [], optionString]);
	  optionString = optionString[0] + explicitArg[0];
	  var newExplicitArg = explicitArg.slice(1) || null;
	  var optionalsMap = self._optionStringActions;

	  if (_.keys(optionalsMap).indexOf(optionString) >= 0) {
	    action = optionalsMap[optionString];
	    explicitArg = newExplicitArg;
	  }
	  else {
	    var msg = 'ignored explicit argument %r';
	    throw argumentErrorHelper(action, msg);
	  }
	}
	// if the action expect exactly one argument, we've
	// successfully matched the option; exit the loop
	else if (argCount === 1) {
	  stop = startIndex + 1;
	  args = [explicitArg];
	  actionTuples.push([action, args, optionString]);
	  break;
	}
	// error if a double-dash option did not use the
	// explicit argument
	else {
	  var message = 'ignored explicit argument %r';
	  throw argumentErrorHelper(action, _.str.sprintf(message, explicitArg));
	}
      }
      // if there is no explicit argument, try to match the
      // optional's string arguments with the following strings
      // if successful, exit the loop
      else {

	start = startIndex + 1;
	var selectedPatterns = argStringsPattern.substr(start);

	argCount = self._matchArgument(action, selectedPatterns);
	stop = start + argCount;


	args = argStrings.slice(start, stop);

	actionTuples.push([action, args, optionString]);
	break;
      }

    }

    // add the Optional to the list and return the index at which
    // the Optional's string args stopped
    if (actionTuples.length < 1) {
      throw new Error('length should be > 0');
    }
    for (var i = 0; i < actionTuples.length; i++) {
      takeAction.apply(self, actionTuples[i]);
    }
    return stop;
  }
Пример #26
0
 init: function () {
   console.log('You called the filter subgenerator with the argument ' + this.name + '.');
   this.name = _.str.camelize(this.name);
 },
Пример #27
0
    async.some(extensionsToIgnore, function(extension, callback){

      callback(_.str.endsWith(req.path, extension));

    }, function (exist) {
 function cleanParam(param){
   return _.str.camelize(param.substr(1,param.length - 2));
 }
Пример #29
0
// Generated on 2014-03-28 using generator-phaser-official 0.0.8-rc-2
'use strict';
var config = require('./config.json');
var _ = require('underscore');
_.str = require('underscore.string');

// Mix in non-conflict functions to Underscore namespace if you want
_.mixin(_.str.exports());

var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.initConfig({
    watch: {
      scripts: {
        files: [
            'game/**/*.js',
            'assets/levels/*.txt',
            '!game/main.js'
        ],
        options: {
          spawn: false,
          livereload: LIVERELOAD_PORT
        },
Пример #30
0
		this[actualMethodName] = function dynamicMethod(value, options, cb) {
			if(_.isFunction(options)) {
				cb = options;
				options = null;
			}
			options = options || {};


			var usage = _.str.capitalize(this.identity) + '.' + actualMethodName + '(someValue,[options],callback)';
			if(_.isUndefined(value)) return usageError('No value specified!', usage, cb);
			if(options.where) return usageError('Cannot specify `where` option in a dynamic ' + method + '*() query!', usage, cb);


			// Build criteria query and submit it
			options.where = {};
			options.where[attrName] = value;

			// Make modifications based on method as necessary
			if(method === 'findBy*' || method === 'findBy*In') {
				return self.find(options, cb);
			} else if(method === 'findBy*Like') {
				return self.find(_.extend(options, {
					where: {
						like: options.where
					}
				}), cb);
			}

			// Aggregate finders
			else if(method === 'findAllBy*' || method === 'findAllBy*In') {
				return self.findAll(options, cb);
			} else if(method === 'findAllBy*Like') {
				return self.findAll(_.extend(options, {
					where: {
						like: options.where
					}
				}), cb);
			}

			// Count finders
			else if(method === 'countBy*' || method === 'countBy*In') {
				return self.count(options, cb);
			} else if(method === 'countBy*Like') {
				return self.count(_.extend(options, {
					where: {
						like: options.where
					}
				}), cb);
			}

			// Searchers
			else if (method === '*StartsWith') {
				return self.startsWith(options, cb);
			}
			else if (method === '*Contains') {
				return self.contains(options, cb);
			}
			else if (method === '*EndsWith') {
				return self.endsWith(options, cb);
			}
		};