code stringlengths 2 1.05M |
|---|
$(document).ready( () => {
var button = $('#fileSave')
$(document).on({
'file:modified': () => {
setButtonStyle('warning')
},
'file:saving': () => {
// disable to prevent user from sending many requests
button.prop('disabled', true)
},
'file:saved': () => {
setButtonStyle('success')
button.prop('disabled', false)
},
'app:error': () => {
// re-enable the button in case the api responded with an error
button.prop('disabled', false)
},
})
// style should be either 'success' or 'warning'
function setButtonStyle(style) {
button.removeClass('btn-success btn-warning').addClass('btn-'+style)
}
})
|
/*
Product Name: dhtmlxSuite
Version: 4.3
Edition: Standard
License: content of this file is covered by GPL. Usage outside GPL terms is prohibited. To obtain Commercial or Enterprise license contact sales@dhtmlx.com
Copyright UAB Dinamenta http://www.dhtmlx.com
*/
/*
Copyright DHTMLX LTD. http://www.dhtmlx.com
You allowed to use this component or parts of it under GPL terms
To use it on other terms or get Professional edition of the component please contact us at sales@dhtmlx.com
*/
/*
2014 March 19
*/
/* DHX DEPEND FROM FILE 'assert.js'*/
if (!window.dhtmlx)
dhtmlx={};
//check some rule, show message as error if rule is not correct
dhtmlx.assert = function(test, message){
if (!test) dhtmlx.error(message);
};
dhtmlx.assert_enabled=function(){ return false; };
//register names of event, which can be triggered by the object
dhtmlx.assert_event = function(obj, evs){
if (!obj._event_check){
obj._event_check = {};
obj._event_check_size = {};
}
for (var a in evs){
obj._event_check[a.toLowerCase()]=evs[a];
var count=-1; for (var t in evs[a]) count++;
obj._event_check_size[a.toLowerCase()]=count;
}
};
dhtmlx.assert_method_info=function(obj, name, descr, rules){
var args = [];
for (var i=0; i < rules.length; i++) {
args.push(rules[i][0]+" : "+rules[i][1]+"\n "+rules[i][2].describe()+(rules[i][3]?"; optional":""));
}
return obj.name+"."+name+"\n"+descr+"\n Arguments:\n - "+args.join("\n - ");
};
dhtmlx.assert_method = function(obj, config){
for (var key in config)
dhtmlx.assert_method_process(obj, key, config[key].descr, config[key].args, (config[key].min||99), config[key].skip);
};
dhtmlx.assert_method_process = function (obj, name, descr, rules, min, skip){
var old = obj[name];
if (!skip)
obj[name] = function(){
if (arguments.length != rules.length && arguments.length < min)
dhtmlx.log("warn","Incorrect count of parameters\n"+obj[name].describe()+"\n\nExpecting "+rules.length+" but have only "+arguments.length);
else
for (var i=0; i<rules.length; i++)
if (!rules[i][3] && !rules[i][2](arguments[i]))
dhtmlx.log("warn","Incorrect method call\n"+obj[name].describe()+"\n\nActual value of "+(i+1)+" parameter: {"+(typeof arguments[i])+"} "+arguments[i]);
return old.apply(this, arguments);
};
obj[name].describe = function(){ return dhtmlx.assert_method_info(obj, name, descr, rules); };
};
dhtmlx.assert_event_call = function(obj, name, args){
if (obj._event_check){
if (!obj._event_check[name])
dhtmlx.log("warn","Not expected event call :"+name);
else if (dhtmlx.isNotDefined(args))
dhtmlx.log("warn","Event without parameters :"+name);
else if (obj._event_check_size[name] != args.length)
dhtmlx.log("warn","Incorrect event call, expected "+obj._event_check_size[name]+" parameter(s), but have "+args.length +" parameter(s), for "+name+" event");
}
};
dhtmlx.assert_event_attach = function(obj, name){
if (obj._event_check && !obj._event_check[name])
dhtmlx.log("warn","Unknown event name: "+name);
};
//register names of properties, which can be used in object's configuration
dhtmlx.assert_property = function(obj, evs){
if (!obj._settings_check)
obj._settings_check={};
dhtmlx.extend(obj._settings_check, evs);
};
//check all options in collection, against list of allowed properties
dhtmlx.assert_check = function(data,coll){
if (typeof data == "object"){
for (var key in data){
dhtmlx.assert_settings(key,data[key],coll);
}
}
};
//check if type and value of property is the same as in scheme
dhtmlx.assert_settings = function(mode,value,coll){
coll = coll || this._settings_check;
//if value is not in collection of defined ones
if (coll){
if (!coll[mode]) //not registered property
return dhtmlx.log("warn","Unknown propery: "+mode);
var descr = "";
var error = "";
var check = false;
for (var i=0; i<coll[mode].length; i++){
var rule = coll[mode][i];
if (typeof rule == "string")
continue;
if (typeof rule == "function")
check = check || rule(value);
else if (typeof rule == "object" && typeof rule[1] == "function"){
check = check || rule[1](value);
if (check && rule[2])
dhtmlx["assert_check"](value, rule[2]); //temporary fix , for sources generator
}
if (check) break;
}
if (!check )
dhtmlx.log("warn","Invalid configuration\n"+dhtmlx.assert_info(mode,coll)+"\nActual value: {"+(typeof value)+"} "+value);
}
};
dhtmlx.assert_info=function(name, set){
var ruleset = set[name];
var descr = "";
var expected = [];
for (var i=0; i<ruleset.length; i++){
if (typeof rule == "string")
descr = ruleset[i];
else if (ruleset[i].describe)
expected.push(ruleset[i].describe());
else if (ruleset[i][1] && ruleset[i][1].describe)
expected.push(ruleset[i][1].describe());
}
return "Property: "+name+", "+descr+" \nExpected value: \n - "+expected.join("\n - ");
};
if (dhtmlx.assert_enabled()){
dhtmlx.assert_rule_color=function(check){
if (typeof check != "string") return false;
if (check.indexOf("#")!==0) return false;
if (check.substr(1).replace(/[0-9A-F]/gi,"")!=="") return false;
return true;
};
dhtmlx.assert_rule_color.describe = function(){
return "{String} Value must start from # and contain hexadecimal code of color";
};
dhtmlx.assert_rule_template=function(check){
if (typeof check == "function") return true;
if (typeof check == "string") return true;
return false;
};
dhtmlx.assert_rule_template.describe = function(){
return "{Function},{String} Value must be a function which accepts data object and return text string, or a sting with optional template markers";
};
dhtmlx.assert_rule_boolean=function(check){
if (typeof check == "boolean") return true;
return false;
};
dhtmlx.assert_rule_boolean.describe = function(){
return "{Boolean} true or false";
};
dhtmlx.assert_rule_object=function(check, sub){
if (typeof check == "object") return true;
return false;
};
dhtmlx.assert_rule_object.describe = function(){
return "{Object} Configuration object";
};
dhtmlx.assert_rule_string=function(check){
if (typeof check == "string") return true;
return false;
};
dhtmlx.assert_rule_string.describe = function(){
return "{String} Plain string";
};
dhtmlx.assert_rule_htmlpt=function(check){
return !!dhtmlx.toNode(check);
};
dhtmlx.assert_rule_htmlpt.describe = function(){
return "{Object},{String} HTML node or ID of HTML Node";
};
dhtmlx.assert_rule_notdocumented=function(check){
return false;
};
dhtmlx.assert_rule_notdocumented.describe = function(){
return "This options wasn't documented";
};
dhtmlx.assert_rule_key=function(obj){
var t = function (check){
return obj[check];
};
t.describe=function(){
var opts = [];
for(var key in obj)
opts.push(key);
return "{String} can take one of next values: "+opts.join(", ");
};
return t;
};
dhtmlx.assert_rule_dimension=function(check){
if (check*1 == check && !isNaN(check) && check >= 0) return true;
return false;
};
dhtmlx.assert_rule_dimension.describe=function(){
return "{Integer} value must be a positive number";
};
dhtmlx.assert_rule_number=function(check){
if (typeof check == "number") return true;
return false;
};
dhtmlx.assert_rule_number.describe=function(){
return "{Integer} value must be a number";
};
dhtmlx.assert_rule_function=function(check){
if (typeof check == "function") return true;
return false;
};
dhtmlx.assert_rule_function.describe=function(){
return "{Function} value must be a custom function";
};
dhtmlx.assert_rule_any=function(check){
return true;
};
dhtmlx.assert_rule_any.describe=function(){
return "Any value";
};
dhtmlx.assert_rule_mix=function(a,b){
var t = function(check){
if (a(check)||b(check)) return true;
return false;
};
t.describe = function(){
return a.describe();
};
return t;
};
}
/* DHX DEPEND FROM FILE 'dhtmlx.js'*/
/*DHX:Depend assert.js*/
/*
Common helpers
*/
dhtmlx.codebase="./";
//coding helpers
dhtmlx.copy = function(source){
var f = dhtmlx.copy._function;
f.prototype = source;
return new f();
};
dhtmlx.copy._function = function(){};
//copies methods and properties from source to the target
dhtmlx.extend = function(target, source){
for (var method in source)
target[method] = source[method];
//applying asserts
if (dhtmlx.assert_enabled() && source._assert){
target._assert();
target._assert=null;
}
dhtmlx.assert(target,"Invalid nesting target");
dhtmlx.assert(source,"Invalid nesting source");
//if source object has init code - call init against target
if (source._init)
target._init();
return target;
};
dhtmlx.proto_extend = function(){
var origins = arguments;
var compilation = origins[0];
var construct = [];
for (var i=origins.length-1; i>0; i--) {
if (typeof origins[i]== "function")
origins[i]=origins[i].prototype;
for (var key in origins[i]){
if (key == "_init")
construct.push(origins[i][key]);
else if (!compilation[key])
compilation[key] = origins[i][key];
}
};
if (origins[0]._init)
construct.push(origins[0]._init);
compilation._init = function(){
for (var i=0; i<construct.length; i++)
construct[i].apply(this, arguments);
};
compilation.base = origins[1];
var result = function(config){
this._init(config);
if (this._parseSettings)
this._parseSettings(config, this.defaults);
};
result.prototype = compilation;
compilation = origins = null;
return result;
};
//creates function with specified "this" pointer
dhtmlx.bind=function(functor, object){
return function(){ return functor.apply(object,arguments); };
};
//loads module from external js file
dhtmlx.require=function(module){
if (!dhtmlx._modules[module]){
dhtmlx.assert(dhtmlx.ajax,"load module is required");
//load and exec the required module
dhtmlx.exec( dhtmlx.ajax().sync().get(dhtmlx.codebase+module).responseText );
dhtmlx._modules[module]=true;
}
};
dhtmlx._modules = {}; //hash of already loaded modules
//evaluate javascript code in the global scoope
dhtmlx.exec=function(code){
if (window.execScript) //special handling for IE
window.execScript(code);
else window.eval(code);
};
/*
creates method in the target object which will transfer call to the source object
if event parameter was provided , each call of method will generate onBefore and onAfter events
*/
dhtmlx.methodPush=function(object,method,event){
return function(){
var res = false;
//if (!event || this.callEvent("onBefore"+event,arguments)){ //not used anymore, probably can be removed
res=object[method].apply(object,arguments);
// if (event) this.callEvent("onAfter"+event,arguments);
//}
return res; //result of wrapped method
};
};
//check === undefined
dhtmlx.isNotDefined=function(a){
return typeof a == "undefined";
};
//delay call to after-render time
dhtmlx.delay=function(method, obj, params, delay){
setTimeout(function(){
var ret = method.apply(obj,params);
method = obj = params = null;
return ret;
},delay||1);
};
//common helpers
//generates unique ID (unique per window, nog GUID)
dhtmlx.uid = function(){
if (!this._seed) this._seed=(new Date).valueOf(); //init seed with timestemp
this._seed++;
return this._seed;
};
//resolve ID as html object
dhtmlx.toNode = function(node){
if (typeof node == "string") return document.getElementById(node);
return node;
};
//adds extra methods for the array
dhtmlx.toArray = function(array){
return dhtmlx.extend((array||[]),dhtmlx.PowerArray);
};
//resolve function name
dhtmlx.toFunctor=function(str){
return (typeof(str)=="string") ? eval(str) : str;
};
//dom helpers
//hash of attached events
dhtmlx._events = {};
//attach event to the DOM element
dhtmlx.event=function(node,event,handler,master){
node = dhtmlx.toNode(node);
var id = dhtmlx.uid();
dhtmlx._events[id]=[node,event,handler]; //store event info, for detaching
if (master)
handler=dhtmlx.bind(handler,master);
//use IE's of FF's way of event's attaching
if (node.addEventListener)
node.addEventListener(event, handler, false);
else if (node.attachEvent)
node.attachEvent("on"+event, handler);
return id; //return id of newly created event, can be used in eventRemove
};
//remove previously attached event
dhtmlx.eventRemove=function(id){
if (!id) return;
dhtmlx.assert(this._events[id],"Removing non-existing event");
var ev = dhtmlx._events[id];
//browser specific event removing
if (ev[0].removeEventListener)
ev[0].removeEventListener(ev[1],ev[2],false);
else if (ev[0].detachEvent)
ev[0].detachEvent("on"+ev[1],ev[2]);
delete this._events[id]; //delete all traces
};
//debugger helpers
//anything starting from error or log will be removed during code compression
//add message in the log
dhtmlx.log = function(type,message,details){
if (window.console && console.log){
type=type.toLowerCase();
if (window.console[type])
window.console[type](message||"unknown error");
else
window.console.log(type +": "+message);
if (details)
window.console.log(details);
}
};
//register rendering time from call point
dhtmlx.log_full_time = function(name){
dhtmlx._start_time_log = new Date();
dhtmlx.log("Info","Timing start ["+name+"]");
window.setTimeout(function(){
var time = new Date();
dhtmlx.log("Info","Timing end ["+name+"]:"+(time.valueOf()-dhtmlx._start_time_log.valueOf())/1000+"s");
},1);
};
//register execution time from call point
dhtmlx.log_time = function(name){
var fname = "_start_time_log"+name;
if (!dhtmlx[fname]){
dhtmlx[fname] = new Date();
dhtmlx.log("Info","Timing start ["+name+"]");
} else {
var time = new Date();
dhtmlx.log("Info","Timing end ["+name+"]:"+(time.valueOf()-dhtmlx[fname].valueOf())/1000+"s");
dhtmlx[fname] = null;
}
};
//log message with type=error
dhtmlx.error = function(message,details){
dhtmlx.log("error",message,details);
};
//event system
dhtmlx.EventSystem={
_init:function(){
this._events = {}; //hash of event handlers, name => handler
this._handlers = {}; //hash of event handlers, ID => handler
this._map = {};
},
//temporary block event triggering
block : function(){
this._events._block = true;
},
//re-enable event triggering
unblock : function(){
this._events._block = false;
},
mapEvent:function(map){
dhtmlx.extend(this._map, map);
},
//trigger event
callEvent:function(type,params){
if (this._events._block) return true;
type = type.toLowerCase();
dhtmlx.assert_event_call(this, type, params);
var event_stack =this._events[type.toLowerCase()]; //all events for provided name
var return_value = true;
if (dhtmlx.debug) //can slowdown a lot
dhtmlx.log("info","["+this.name+"] event:"+type,params);
if (event_stack)
for(var i=0; i<event_stack.length; i++)
/*
Call events one by one
If any event return false - result of whole event will be false
Handlers which are not returning anything - counted as positive
*/
if (event_stack[i].apply(this,(params||[]))===false) return_value=false;
if (this._map[type] && !this._map[type].callEvent(type,params))
return_value = false;
return return_value;
},
//assign handler for some named event
attachEvent:function(type,functor,id){
type=type.toLowerCase();
dhtmlx.assert_event_attach(this, type);
id=id||dhtmlx.uid(); //ID can be used for detachEvent
functor = dhtmlx.toFunctor(functor); //functor can be a name of method
var event_stack=this._events[type]||dhtmlx.toArray();
//save new event handler
event_stack.push(functor);
this._events[type]=event_stack;
this._handlers[id]={ f:functor,t:type };
return id;
},
//remove event handler
detachEvent:function(id){
if(this._handlers[id]){
var type=this._handlers[id].t;
var functor=this._handlers[id].f;
//remove from all collections
var event_stack=this._events[type];
event_stack.remove(functor);
delete this._handlers[id];
}
}
};
//array helper
//can be used by dhtmlx.toArray()
dhtmlx.PowerArray={
//remove element at specified position
removeAt:function(pos,len){
if (pos>=0) this.splice(pos,(len||1));
},
//find element in collection and remove it
remove:function(value){
this.removeAt(this.find(value));
},
//add element to collection at specific position
insertAt:function(data,pos){
if (!pos && pos!==0) //add to the end by default
this.push(data);
else {
var b = this.splice(pos,(this.length-pos));
this[pos] = data;
this.push.apply(this,b); //reconstruct array without loosing this pointer
}
},
//return index of element, -1 if it doesn't exists
find:function(data){
for (i=0; i<this.length; i++)
if (data==this[i]) return i;
return -1;
},
//execute some method for each element of array
each:function(functor,master){
for (var i=0; i < this.length; i++)
functor.call((master||this),this[i]);
},
//create new array from source, by using results of functor
map:function(functor,master){
for (var i=0; i < this.length; i++)
this[i]=functor.call((master||this),this[i]);
return this;
}
};
dhtmlx.env = {};
//environment detection
if (navigator.userAgent.indexOf('Opera') != -1)
dhtmlx._isOpera=true;
else{
//very rough detection, but it is enough for current goals
dhtmlx._isIE=!!document.all;
dhtmlx._isFF=!document.all;
dhtmlx._isWebKit=(navigator.userAgent.indexOf("KHTML")!=-1);
if (navigator.appVersion.indexOf("MSIE 8.0")!= -1 && document.compatMode != "BackCompat")
dhtmlx._isIE=8;
if (navigator.appVersion.indexOf("MSIE 9.0")!= -1 && document.compatMode != "BackCompat")
dhtmlx._isIE=9;
}
dhtmlx.env = {};
// dhtmlx.env.transform
// dhtmlx.env.transition
(function(){
dhtmlx.env.transform = false;
dhtmlx.env.transition = false;
var options = {};
options.names = ['transform', 'transition'];
options.transform = ['transform', 'WebkitTransform', 'MozTransform', 'oTransform','msTransform'];
options.transition = ['transition', 'WebkitTransition', 'MozTransition', 'oTransition'];
var d = document.createElement("DIV");
var property;
for(var i=0; i<options.names.length; i++) {
while (p = options[options.names[i]].pop()) {
if(typeof d.style[p] != 'undefined')
dhtmlx.env[options.names[i]] = true;
}
}
})();
dhtmlx.env.transform_prefix = (function(){
var prefix;
if(dhtmlx._isOpera)
prefix = '-o-';
else {
prefix = ''; // default option
if(dhtmlx._isFF)
prefix = '-moz-';
if(dhtmlx._isWebKit)
prefix = '-webkit-';
}
return prefix;
})();
dhtmlx.env.svg = (function(){
return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
})();
//store maximum used z-index
dhtmlx.zIndex={ drag : 10000 };
//html helpers
dhtmlx.html={
create:function(name,attrs,html){
attrs = attrs || {};
var node = document.createElement(name);
for (var attr_name in attrs)
node.setAttribute(attr_name, attrs[attr_name]);
if (attrs.style)
node.style.cssText = attrs.style;
if (attrs["class"])
node.className = attrs["class"];
if (html)
node.innerHTML=html;
return node;
},
//return node value, different logic for different html elements
getValue:function(node){
node = dhtmlx.toNode(node);
if (!node) return "";
return dhtmlx.isNotDefined(node.value)?node.innerHTML:node.value;
},
//remove html node, can process an array of nodes at once
remove:function(node){
if (node instanceof Array)
for (var i=0; i < node.length; i++)
this.remove(node[i]);
else
if (node && node.parentNode)
node.parentNode.removeChild(node);
},
//insert new node before sibling, or at the end if sibling doesn't exist
insertBefore: function(node,before,rescue){
if (!node) return;
if (before)
before.parentNode.insertBefore(node, before);
else
rescue.appendChild(node);
},
//return custom ID from html element
//will check all parents starting from event's target
locate:function(e,id){
e=e||event;
var trg=e.target||e.srcElement;
while (trg){
if (trg.getAttribute){ //text nodes has not getAttribute
var test = trg.getAttribute(id);
if (test) return test;
}
trg=trg.parentNode;
}
return null;
},
//returns position of html element on the page
offset:function(elem) {
if (elem.getBoundingClientRect) { //HTML5 method
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { y: Math.round(top), x: Math.round(left) };
} else { //fallback to naive approach
var top=0, left=0;
while(elem) {
top = top + parseInt(elem.offsetTop,10);
left = left + parseInt(elem.offsetLeft,10);
elem = elem.offsetParent;
}
return {y: top, x: left};
}
},
//returns position of event
pos:function(ev){
ev = ev || event;
if(ev.pageX || ev.pageY) //FF, KHTML
return {x:ev.pageX, y:ev.pageY};
//IE
var d = ((dhtmlx._isIE)&&(document.compatMode != "BackCompat"))?document.documentElement:document.body;
return {
x:ev.clientX + d.scrollLeft - d.clientLeft,
y:ev.clientY + d.scrollTop - d.clientTop
};
},
//prevent event action
preventEvent:function(e){
if (e && e.preventDefault) e.preventDefault();
dhtmlx.html.stopEvent(e);
},
//stop event bubbling
stopEvent:function(e){
(e||event).cancelBubble=true;
return false;
},
//add css class to the node
addCss:function(node,name){
node.className+=" "+name;
},
//remove css class from the node
removeCss:function(node,name){
node.className=node.className.replace(RegExp(name,"g"),"");
}
};
//autodetect codebase folder
(function(){
var temp = document.getElementsByTagName("SCRIPT"); //current script, most probably
dhtmlx.assert(temp.length,"Can't locate codebase");
if (temp.length){
//full path to script
temp = (temp[temp.length-1].getAttribute("src")||"").split("/");
//get folder name
temp.splice(temp.length-1, 1);
dhtmlx.codebase = temp.slice(0, temp.length).join("/")+"/";
}
})();
if (!dhtmlx.ui)
dhtmlx.ui={};
/* DHX DEPEND FROM FILE 'destructor.js'*/
/*
Behavior:Destruction
@export
destructor
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.Destruction = {
_init:function(){
//register self in global list of destructors
dhtmlx.destructors.push(this);
},
//will be called automatically on unload, can be called manually
//simplifies job of GC
destructor:function(){
this.destructor=function(){}; //destructor can be called only once
//html collection
this._htmlmap = null;
this._htmlrows = null;
//temp html element, used by toHTML
if (this._html)
document.body.appendChild(this._html); //need to attach, for IE's GC
this._html = null;
if (this._obj) {
this._obj.innerHTML="";
this._obj._htmlmap = null;
}
this._obj = this._dataobj=null;
this.data = null;
this._events = this._handlers = {};
if(this.render)
this.render = function(){};//need in case of delayed method calls (virtual render case)
}
};
//global list of destructors
dhtmlx.destructors = [];
dhtmlx.event(window,"unload",function(){
//call all registered destructors
if (dhtmlx.destructors){
for (var i=0; i<dhtmlx.destructors.length; i++)
dhtmlx.destructors[i].destructor();
dhtmlx.destructors = [];
}
//detach all known DOM events
for (var a in dhtmlx._events){
var ev = dhtmlx._events[a];
if (ev[0].removeEventListener)
ev[0].removeEventListener(ev[1],ev[2],false);
else if (ev[0].detachEvent)
ev[0].detachEvent("on"+ev[1],ev[2]);
delete dhtmlx._events[a];
}
});
/* DHX DEPEND FROM FILE 'load.js'*/
/*
ajax operations
can be used for direct loading as
dhtmlx.ajax(ulr, callback)
or
dhtmlx.ajax().item(url)
dhtmlx.ajax().post(url)
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.ajax = function(url,call,master){
//if parameters was provided - made fast call
if (arguments.length!==0){
var http_request = new dhtmlx.ajax();
if (master) http_request.master=master;
http_request.get(url,null,call);
}
if (!this.getXHR) return new dhtmlx.ajax(); //allow to create new instance without direct new declaration
return this;
};
dhtmlx.ajax.prototype={
//creates xmlHTTP object
getXHR:function(){
if (dhtmlx._isIE)
return new ActiveXObject("Microsoft.xmlHTTP");
else
return new XMLHttpRequest();
},
/*
send data to the server
params - hash of properties which will be added to the url
call - callback, can be an array of functions
*/
send:function(url,params,call){
var x=this.getXHR();
if (typeof call == "function")
call = [call];
//add extra params to the url
if (typeof params == "object"){
var t=[];
for (var a in params){
var value = params[a];
if (value === null || value === dhtmlx.undefined)
value = "";
t.push(a+"="+encodeURIComponent(value));// utf-8 escaping
}
params=t.join("&");
}
if (params && !this.post){
url=url+(url.indexOf("?")!=-1 ? "&" : "?")+params;
params=null;
}
x.open(this.post?"POST":"GET",url,!this._sync);
if (this.post)
x.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//async mode, define loading callback
//if (!this._sync){
var self=this;
x.onreadystatechange= function(){
if (!x.readyState || x.readyState == 4){
//dhtmlx.log_full_time("data_loading"); //log rendering time
if (call && self)
for (var i=0; i < call.length; i++) //there can be multiple callbacks
if (call[i])
call[i].call((self.master||self),x.responseText,x.responseXML,x);
self.master=null;
call=self=null; //anti-leak
}
};
//}
x.send(params||null);
return x; //return XHR, which can be used in case of sync. mode
},
//GET request
get:function(url,params,call){
this.post=false;
return this.send(url,params,call);
},
//POST request
post:function(url,params,call){
this.post=true;
return this.send(url,params,call);
},
sync:function(){
this._sync = true;
return this;
}
};
dhtmlx.AtomDataLoader={
_init:function(config){
//prepare data store
this.data = {};
if (config){
this._settings.datatype = config.datatype||"json";
this._after_init.push(this._load_when_ready);
}
},
_load_when_ready:function(){
this._ready_for_data = true;
if (this._settings.url)
this.url_setter(this._settings.url);
if (this._settings.data)
this.data_setter(this._settings.data);
},
url_setter:function(value){
if (!this._ready_for_data) return value;
this.load(value, this._settings.datatype);
return value;
},
data_setter:function(value){
if (!this._ready_for_data) return value;
this.parse(value, this._settings.datatype);
return true;
},
//loads data from external URL
load:function(url,call){
this.callEvent("onXLS",[]);
if (typeof call == "string"){ //second parameter can be a loading type or callback
this.data.driver = dhtmlx.DataDriver[call];
call = arguments[2];
}
else
this.data.driver = dhtmlx.DataDriver["xml"];
//load data by async ajax call
dhtmlx.ajax(url,[this._onLoad,call],this);
},
//loads data from object
parse:function(data,type){
this.callEvent("onXLS",[]);
this.data.driver = dhtmlx.DataDriver[type||"xml"];
this._onLoad(data,null);
},
//default after loading callback
_onLoad:function(text,xml,loader){
var driver = this.data.driver;
var top = driver.getRecords(driver.toObject(text,xml))[0];
this.data=(driver?driver.getDetails(top):text);
this.callEvent("onXLE",[]);
},
_check_data_feed:function(data){
if (!this._settings.dataFeed || this._ignore_feed || !data) return true;
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, (data.id||data), data);
url = url+(url.indexOf("?")==-1?"?":"&")+"action=get&id="+encodeURIComponent(data.id||data);
this.callEvent("onXLS",[]);
dhtmlx.ajax(url, function(text,xml){
this._ignore_feed=true;
this.setValues(dhtmlx.DataDriver.json.toObject(text)[0]);
this._ignore_feed=false;
this.callEvent("onXLE",[]);
}, this);
return false;
}
};
/*
Abstraction layer for different data types
*/
dhtmlx.DataDriver={};
dhtmlx.DataDriver.json={
//convert json string to json object if necessary
toObject:function(data){
if (!data) data="[]";
if (typeof data == "string"){
eval ("dhtmlx.temp="+data);
return dhtmlx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
if (data && !(data instanceof Array))
return [data];
return data;
},
//get hash of properties for single record
getDetails:function(data){
return data;
},
//get count of data and position at which new data need to be inserted
getInfo:function(data){
return {
_size:(data.total_count||0),
_from:(data.pos||0),
_key:(data.dhx_security)
};
}
};
dhtmlx.DataDriver.json_ext={
//convert json string to json object if necessary
toObject:function(data){
if (!data) data="[]";
if (typeof data == "string"){
var temp;
eval ("temp="+data);
dhtmlx.temp = [];
var header = temp.header;
for (var i = 0; i < temp.data.length; i++) {
var item = {};
for (var j = 0; j < header.length; j++) {
if (typeof(temp.data[i][j]) != "undefined")
item[header[j]] = temp.data[i][j];
}
dhtmlx.temp.push(item);
}
return dhtmlx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
if (data && !(data instanceof Array))
return [data];
return data;
},
//get hash of properties for single record
getDetails:function(data){
return data;
},
//get count of data and position at which new data need to be inserted
getInfo:function(data){
return {
_size:(data.total_count||0),
_from:(data.pos||0)
};
}
};
dhtmlx.DataDriver.html={
/*
incoming data can be
- collection of nodes
- ID of parent container
- HTML text
*/
toObject:function(data){
if (typeof data == "string"){
var t=null;
if (data.indexOf("<")==-1) //if no tags inside - probably its an ID
t = dhtmlx.toNode(data);
if (!t){
t=document.createElement("DIV");
t.innerHTML = data;
}
return t.getElementsByTagName(this.tag);
}
return data;
},
//get array of records
getRecords:function(data){
if (data.tagName)
return data.childNodes;
return data;
},
//get hash of properties for single record
getDetails:function(data){
return dhtmlx.DataDriver.xml.tagToObject(data);
},
//dyn loading is not supported by HTML data source
getInfo:function(data){
return {
_size:0,
_from:0
};
},
tag: "LI"
};
dhtmlx.DataDriver.jsarray={
//eval jsarray string to jsarray object if necessary
toObject:function(data){
if (typeof data == "string"){
eval ("dhtmlx.temp="+data);
return dhtmlx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
return data;
},
//get hash of properties for single record, in case of array they will have names as "data{index}"
getDetails:function(data){
var result = {};
for (var i=0; i < data.length; i++)
result["data"+i]=data[i];
return result;
},
//dyn loading is not supported by js-array data source
getInfo:function(data){
return {
_size:0,
_from:0
};
}
};
dhtmlx.DataDriver.csv={
//incoming data always a string
toObject:function(data){
return data;
},
//get array of records
getRecords:function(data){
return data.split(this.row);
},
//get hash of properties for single record, data named as "data{index}"
getDetails:function(data){
data = this.stringToArray(data);
var result = {};
for (var i=0; i < data.length; i++)
result["data"+i]=data[i];
return result;
},
//dyn loading is not supported by csv data source
getInfo:function(data){
return {
_size:0,
_from:0
};
},
//split string in array, takes string surrounding quotes in account
stringToArray:function(data){
data = data.split(this.cell);
for (var i=0; i < data.length; i++)
data[i] = data[i].replace(/^[ \t\n\r]*(\"|)/g,"").replace(/(\"|)[ \t\n\r]*$/g,"");
return data;
},
row:"\n", //default row separator
cell:"," //default cell separator
};
dhtmlx.DataDriver.xml={
//convert xml string to xml object if necessary
toObject:function(text,xml){
if (xml && (xml=this.checkResponse(text,xml))) //checkResponse - fix incorrect content type and extra whitespaces errors
return xml;
if (typeof text == "string"){
return this.fromString(text);
}
return text;
},
//get array of records
getRecords:function(data){
return this.xpath(data,this.records);
},
records:"/*/item",
//get hash of properties for single record
getDetails:function(data){
return this.tagToObject(data,{});
},
//get count of data and position at which new data_loading need to be inserted
getInfo:function(data){
return {
_size:(data.documentElement.getAttribute("total_count")||0),
_from:(data.documentElement.getAttribute("pos")||0),
_key:(data.documentElement.getAttribute("dhx_security"))
};
},
//xpath helper
xpath:function(xml,path){
if (window.XPathResult){ //FF, KHTML, Opera
var node=xml;
if(xml.nodeName.indexOf("document")==-1)
xml=xml.ownerDocument;
var res = [];
var col = xml.evaluate(path, node, null, XPathResult.ANY_TYPE, null);
var temp = col.iterateNext();
while (temp){
res.push(temp);
temp = col.iterateNext();
}
return res;
}
else {
var test = true;
try {
if (typeof(xml.selectNodes)=="undefined")
test = false;
} catch(e){ /*IE7 and below can't operate with xml object*/ }
//IE
if (test)
return xml.selectNodes(path);
else {
//Google hate us, there is no interface to do XPath
//use naive approach
var name = path.split("/").pop();
return xml.getElementsByTagName(name);
}
}
},
//convert xml tag to js object, all subtags and attributes are mapped to the properties of result object
tagToObject:function(tag,z){
z=z||{};
var flag=false;
//map attributes
var a=tag.attributes;
if(a && a.length){
for (var i=0; i<a.length; i++)
z[a[i].name]=a[i].value;
flag = true;
}
//map subtags
var b=tag.childNodes;
var state = {};
for (var i=0; i<b.length; i++){
if (b[i].nodeType==1){
var name = b[i].tagName;
if (typeof z[name] != "undefined"){
if (!(z[name] instanceof Array))
z[name]=[z[name]];
z[name].push(this.tagToObject(b[i],{}));
}
else
z[b[i].tagName]=this.tagToObject(b[i],{}); //sub-object for complex subtags
flag=true;
}
}
if (!flag)
return this.nodeValue(tag);
//each object will have its text content as "value" property
z.value = this.nodeValue(tag);
return z;
},
//get value of xml node
nodeValue:function(node){
if (node.firstChild)
return node.firstChild.wholeText||node.firstChild.data;
return "";
},
//convert XML string to XML object
fromString:function(xmlString){
if (window.DOMParser && !dhtmlx._isIE) // FF, KHTML, Opera
return (new DOMParser()).parseFromString(xmlString,"text/xml");
if (window.ActiveXObject){ // IE, utf-8 only
var temp=new ActiveXObject("Microsoft.xmlDOM");
temp.loadXML(xmlString);
return temp;
}
dhtmlx.error("Load from xml string is not supported");
},
//check is XML correct and try to reparse it if its invalid
checkResponse:function(text,xml){
if (xml && ( xml.firstChild && xml.firstChild.tagName != "parsererror") )
return xml;
//parsing as string resolves incorrect content type
//regexp removes whitespaces before xml declaration, which is vital for FF
var a=this.fromString(text.replace(/^[\s]+/,""));
if (a) return a;
dhtmlx.error("xml can't be parsed",text);
}
};
/* DHX DEPEND FROM FILE 'datastore.js'*/
/*DHX:Depend load.js*/
/*DHX:Depend dhtmlx.js*/
/*
Behavior:DataLoader - load data in the component
@export
load
parse
*/
dhtmlx.DataLoader={
_init:function(config){
//prepare data store
config = config || "";
this.name = "DataStore";
this.data = (config.datastore)||(new dhtmlx.DataStore());
this._readyHandler = this.data.attachEvent("onStoreLoad",dhtmlx.bind(this._call_onready,this));
},
//loads data from external URL
load:function(url,call){
dhtmlx.AtomDataLoader.load.apply(this, arguments);
//prepare data feed for dyn. loading
if (!this.data.feed)
this.data.feed = function(from,count){
//allow only single request at same time
if (this._load_count)
return this._load_count=[from,count]; //save last ignored request
else
this._load_count=true;
this.load(url+((url.indexOf("?")==-1)?"?":"&")+"posStart="+from+"&count="+count,function(){
//after loading check if we have some ignored requests
var temp = this._load_count;
this._load_count = false;
if (typeof temp =="object")
this.data.feed.apply(this, temp); //load last ignored request
});
};
},
//default after loading callback
_onLoad:function(text,xml,loader){
this.data._parse(this.data.driver.toObject(text,xml));
this.callEvent("onXLE",[]);
if(this._readyHandler){
this.data.detachEvent(this._readyHandler);
this._readyHandler = null;
}
},
dataFeed_setter:function(value){
this.data.attachEvent("onBeforeFilter", dhtmlx.bind(function(text, value){
if (this._settings.dataFeed){
var filter = {};
if (!text && !filter) return;
if (typeof text == "function"){
if (!value) return;
text(value, filter);
} else
filter = { text:value };
this.clearAll();
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, value, filter);
var urldata = [];
for (var key in filter)
urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key]));
this.load(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&"), this._settings.datatype);
return false;
}
},this));
return value;
},
_call_onready:function(){
if (this._settings.ready){
var code = dhtmlx.toFunctor(this._settings.ready);
if (code && code.call) code.apply(this, arguments);
}
}
};
/*
DataStore is not a behavior, it standalone object, which represents collection of data.
Call provideAPI to map data API
@export
exists
idByIndex
indexById
get
set
refresh
dataCount
sort
filter
next
previous
clearAll
first
last
*/
dhtmlx.DataStore = function(){
this.name = "DataStore";
dhtmlx.extend(this, dhtmlx.EventSystem);
this.setDriver("xml"); //default data source is an XML
this.pull = {}; //hash of IDs
this.order = dhtmlx.toArray(); //order of IDs
};
dhtmlx.DataStore.prototype={
//defines type of used data driver
//data driver is an abstraction other different data formats - xml, json, csv, etc.
setDriver:function(type){
dhtmlx.assert(dhtmlx.DataDriver[type],"incorrect DataDriver");
this.driver = dhtmlx.DataDriver[type];
},
//process incoming raw data
_parse:function(data){
this.callEvent("onParse", [this.driver, data]);
if (this._filter_order)
this.filter();
//get size and position of data
var info = this.driver.getInfo(data);
if (info._key)
dhtmlx.security_key = info._key;
//get array of records
var recs = this.driver.getRecords(data);
var from = (info._from||0)*1;
if (from === 0 && this.order[0]) //update mode
from = this.order.length;
var j=0;
for (var i=0; i<recs.length; i++){
//get has of details for each record
var temp = this.driver.getDetails(recs[i]);
var id = this.id(temp); //generate ID for the record
if (!this.pull[id]){ //if such ID already exists - update instead of insert
this.order[j+from]=id;
j++;
}
this.pull[id]=temp;
//if (this._format) this._format(temp);
if (this.extraParser)
this.extraParser(temp);
if (this._scheme){
if (this._scheme.$init)
this._scheme.$update(temp);
else if (this._scheme.$update)
this._scheme.$update(temp);
}
}
//for all not loaded data
for (var i=0; i < info._size; i++)
if (!this.order[i]){
var id = dhtmlx.uid();
var temp = {id:id, $template:"loading"}; //create fake records
this.pull[id]=temp;
this.order[i]=id;
}
this.callEvent("onStoreLoad",[this.driver, data]);
//repaint self after data loading
this.refresh();
},
//generate id for data object
id:function(data){
return data.id||(data.id=dhtmlx.uid());
},
changeId:function(old, newid){
dhtmlx.assert(this.pull[old],"Can't change id, for non existing item: "+old);
this.pull[newid] = this.pull[old];
this.pull[newid].id = newid;
this.order[this.order.find(old)]=newid;
if (this._filter_order)
this._filter_order[this._filter_order.find(old)]=newid;
this.callEvent("onIdChange", [old, newid]);
if (this._render_change_id)
this._render_change_id(old, newid);
},
get:function(id){
return this.item(id);
},
set:function(id, data){
return this.update(id, data);
},
//get data from hash by id
item:function(id){
return this.pull[id];
},
//assigns data by id
update:function(id,data){
if (this._scheme && this._scheme.$update)
this._scheme.$update(data);
if (this.callEvent("onBeforeUpdate", [id, data]) === false) return false;
this.pull[id]=data;
this.refresh(id);
},
//sends repainting signal
refresh:function(id){
if (this._skip_refresh) return;
if (id)
this.callEvent("onStoreUpdated",[id, this.pull[id], "update"]);
else
this.callEvent("onStoreUpdated",[null,null,null]);
},
silent:function(code){
this._skip_refresh = true;
code.call(this);
this._skip_refresh = false;
},
//converts range IDs to array of all IDs between them
getRange:function(from,to){
//if some point is not defined - use first or last id
//BEWARE - do not use empty or null ID
if (from)
from = this.indexById(from);
else
from = this.startOffset||0;
if (to)
to = this.indexById(to);
else {
to = Math.min((this.endOffset||Infinity),(this.dataCount()-1));
if (to<0) to = 0; //we have not data in the store
}
if (from>to){ //can be in case of backward shift-selection
var a=to; to=from; from=a;
}
return this.getIndexRange(from,to);
},
//converts range of indexes to array of all IDs between them
getIndexRange:function(from,to){
to=Math.min((to||Infinity),this.dataCount()-1);
var ret=dhtmlx.toArray(); //result of method is rich-array
for (var i=(from||0); i <= to; i++)
ret.push(this.item(this.order[i]));
return ret;
},
//returns total count of elements
dataCount:function(){
return this.order.length;
},
//returns truy if item with such ID exists
exists:function(id){
return !!(this.pull[id]);
},
//nextmethod is not visible on component level, check DataMove.move
//moves item from source index to the target index
move:function(sindex,tindex){
if (sindex<0 || tindex<0){
dhtmlx.error("DataStore::move","Incorrect indexes");
return;
}
var id = this.idByIndex(sindex);
var obj = this.item(id);
this.order.removeAt(sindex); //remove at old position
//if (sindex<tindex) tindex--; //correct shift, caused by element removing
this.order.insertAt(id,Math.min(this.order.length, tindex)); //insert at new position
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"move"]);
},
scheme:function(config){
/*
some.scheme({
order:1,
name:"dummy",
title:""
})
*/
this._scheme = config;
},
sync:function(source, filter, silent){
if (typeof filter != "function"){
silent = filter;
filter = null;
}
if (dhtmlx.debug_bind){
this.debug_sync_master = source;
dhtmlx.log("[sync] "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id+" <= "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id);
}
var topsource = source;
if (source.name != "DataStore")
source = source.data;
var sync_logic = dhtmlx.bind(function(id, data, mode){
if (mode != "update" || filter)
id = null;
if (!id){
this.order = dhtmlx.toArray([].concat(source.order));
this._filter_order = null;
this.pull = source.pull;
if (filter)
this.silent(filter);
if (this._on_sync)
this._on_sync();
}
if (dhtmlx.debug_bind)
dhtmlx.log("[sync:request] "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id + " <= "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id);
if (!silent)
this.refresh(id);
else
silent = false;
}, this);
source.attachEvent("onStoreUpdated", sync_logic);
this.feed = function(from, count){
topsource.loadNext(count, from);
};
sync_logic();
},
//adds item to the store
add:function(obj,index){
if (this._scheme){
obj = obj||{};
for (var key in this._scheme)
obj[key] = obj[key]||this._scheme[key];
if (this._scheme){
if (this._scheme.$init)
this._scheme.$update(obj);
else if (this._scheme.$update)
this._scheme.$update(obj);
}
}
//generate id for the item
var id = this.id(obj);
//by default item is added to the end of the list
var data_size = this.dataCount();
if (dhtmlx.isNotDefined(index) || index < 0)
index = data_size;
//check to prevent too big indexes
if (index > data_size){
dhtmlx.log("Warning","DataStore:add","Index of out of bounds");
index = Math.min(this.order.length,index);
}
if (this.callEvent("onBeforeAdd", [id, obj, index]) === false) return false;
if (this.exists(id)) return dhtmlx.error("Not unique ID");
this.pull[id]=obj;
this.order.insertAt(id,index);
if (this._filter_order){ //adding during filtering
//we can't know the location of new item in full dataset, making suggestion
//put at end by default
var original_index = this._filter_order.length;
//put at start only if adding to the start and some data exists
if (!index && this.order.length)
original_index = 0;
this._filter_order.insertAt(id,original_index);
}
this.callEvent("onafterAdd",[id,index]);
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"add"]);
return id;
},
//removes element from datastore
remove:function(id){
//id can be an array of IDs - result of getSelect, for example
if (id instanceof Array){
for (var i=0; i < id.length; i++)
this.remove(id[i]);
return;
}
if (this.callEvent("onBeforeDelete",[id]) === false) return false;
if (!this.exists(id)) return dhtmlx.error("Not existing ID",id);
var obj = this.item(id); //save for later event
//clear from collections
this.order.remove(id);
if (this._filter_order)
this._filter_order.remove(id);
delete this.pull[id];
this.callEvent("onafterdelete",[id]);
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"delete"]);
},
//deletes all records in datastore
clearAll:function(){
//instead of deleting one by one - just reset inner collections
this.pull = {};
this.order = dhtmlx.toArray();
this.feed = null;
this._filter_order = null;
this.callEvent("onClearAll",[]);
this.refresh();
},
//converts id to index
idByIndex:function(index){
if (index>=this.order.length || index<0)
dhtmlx.log("Warning","DataStore::idByIndex Incorrect index");
return this.order[index];
},
//converts index to id
indexById:function(id){
var res = this.order.find(id); //slower than idByIndex
//if (!this.pull[id])
// dhtmlx.log("Warning","DataStore::indexById Non-existing ID: "+ id);
return res;
},
//returns ID of next element
next:function(id,step){
return this.order[this.indexById(id)+(step||1)];
},
//returns ID of first element
first:function(){
return this.order[0];
},
//returns ID of last element
last:function(){
return this.order[this.order.length-1];
},
//returns ID of previous element
previous:function(id,step){
return this.order[this.indexById(id)-(step||1)];
},
/*
sort data in collection
by - settings of sorting
or
by - sorting function
dir - "asc" or "desc"
or
by - property
dir - "asc" or "desc"
as - type of sortings
Sorting function will accept 2 parameters and must return 1,0,-1, based on desired order
*/
sort:function(by, dir, as){
var sort = by;
if (typeof by == "function")
sort = {as:by, dir:dir};
else if (typeof by == "string")
sort = {by:by, dir:dir, as:as};
var parameters = [sort.by, sort.dir, sort.as];
if (!this.callEvent("onbeforesort",parameters)) return;
if (this.order.length){
var sorter = dhtmlx.sort.create(sort);
//get array of IDs
var neworder = this.getRange(this.first(), this.last());
neworder.sort(sorter);
this.order = neworder.map(function(obj){ return this.id(obj); },this);
}
//repaint self
this.refresh();
this.callEvent("onaftersort",parameters);
},
/*
Filter datasource
text - property, by which filter
value - filter mask
or
text - filter method
Filter method will receive data object and must return true or false
*/
filter:function(text,value){
if (!this.callEvent("onBeforeFilter", [text, value])) return;
//remove previous filtering , if any
if (this._filter_order){
this.order = this._filter_order;
delete this._filter_order;
}
if (!this.order.length) return;
//if text not define -just unfilter previous state and exit
if (text){
var filter = text;
value = value||"";
if (typeof text == "string"){
text = dhtmlx.Template.fromHTML(text);
value = value.toString().toLowerCase();
filter = function(obj,value){ //default filter - string start from, case in-sensitive
return text(obj).toLowerCase().indexOf(value)!=-1;
};
}
var neworder = dhtmlx.toArray();
for (var i=0; i < this.order.length; i++){
var id = this.order[i];
if (filter(this.item(id),value))
neworder.push(id);
}
//set new order of items, store original
this._filter_order = this.order;
this.order = neworder;
}
//repaint self
this.refresh();
this.callEvent("onAfterFilter", []);
},
/*
Iterate through collection
*/
each:function(method,master){
for (var i=0; i<this.order.length; i++)
method.call((master||this), this.item(this.order[i]));
},
/*
map inner methods to some distant object
*/
provideApi:function(target,eventable){
this.debug_bind_master = target;
if (eventable){
this.mapEvent({
onbeforesort: target,
onaftersort: target,
onbeforeadd: target,
onafteradd: target,
onbeforedelete: target,
onafterdelete: target,
onbeforeupdate: target/*,
onafterfilter: target,
onbeforefilter: target*/
});
}
var list = ["get","set","sort","add","remove","exists","idByIndex","indexById","item","update","refresh","dataCount","filter","next","previous","clearAll","first","last","serialize"];
for (var i=0; i < list.length; i++)
target[list[i]]=dhtmlx.methodPush(this,list[i]);
if (dhtmlx.assert_enabled())
this.assert_event(target);
},
/*
serializes data to a json object
*/
serialize: function(){
var ids = this.order;
var result = [];
for(var i=0; i< ids.length;i++)
result.push(this.pull[ids[i]]);
return result;
}
};
dhtmlx.sort = {
create:function(config){
return dhtmlx.sort.dir(config.dir, dhtmlx.sort.by(config.by, config.as));
},
as:{
"int":function(a,b){
a = a*1; b=b*1;
return a>b?1:(a<b?-1:0);
},
"string_strict":function(a,b){
a = a.toString(); b=b.toString();
return a>b?1:(a<b?-1:0);
},
"string":function(a,b){
a = a.toString().toLowerCase(); b=b.toString().toLowerCase();
return a>b?1:(a<b?-1:0);
}
},
by:function(prop, method){
if (!prop)
return method;
if (typeof method != "function")
method = dhtmlx.sort.as[method||"string"];
prop = dhtmlx.Template.fromHTML(prop);
return function(a,b){
return method(prop(a),prop(b));
};
},
dir:function(prop, method){
if (prop == "asc")
return method;
return function(a,b){
return method(a,b)*-1;
};
}
};
/* DHX DEPEND FROM FILE 'key.js'*/
/*
Behavior:KeyEvents - hears keyboard
*/
dhtmlx.KeyEvents = {
_init:function(){
//attach handler to the main container
dhtmlx.event(this._obj,"keypress",this._onKeyPress,this);
},
//called on each key press , when focus is inside of related component
_onKeyPress:function(e){
e=e||event;
var code = e.which||e.keyCode; //FIXME better solution is required
this.callEvent((this._edit_id?"onEditKeyPress":"onKeyPress"),[code,e.ctrlKey,e.shiftKey,e]);
}
};
/* DHX DEPEND FROM FILE 'mouse.js'*/
/*
Behavior:MouseEvents - provides inner evnets for mouse actions
*/
dhtmlx.MouseEvents={
_init: function(){
//attach dom events if related collection is defined
if (this.on_click){
dhtmlx.event(this._obj,"click",this._onClick,this);
dhtmlx.event(this._obj,"contextmenu",this._onContext,this);
}
if (this.on_dblclick)
dhtmlx.event(this._obj,"dblclick",this._onDblClick,this);
if (this.on_mouse_move){
dhtmlx.event(this._obj,"mousemove",this._onMouse,this);
dhtmlx.event(this._obj,(dhtmlx._isIE?"mouseleave":"mouseout"),this._onMouse,this);
}
},
//inner onclick object handler
_onClick: function(e) {
return this._mouseEvent(e,this.on_click,"ItemClick");
},
//inner ondblclick object handler
_onDblClick: function(e) {
return this._mouseEvent(e,this.on_dblclick,"ItemDblClick");
},
//process oncontextmenu events
_onContext: function(e) {
var id = dhtmlx.html.locate(e, this._id);
if (id && !this.callEvent("onBeforeContextMenu", [id,e]))
return dhtmlx.html.preventEvent(e);
},
/*
event throttler - ignore events which occurs too fast
during mouse moving there are a lot of event firing - we need no so much
also, mouseout can fire when moving inside the same html container - we need to ignore such fake calls
*/
_onMouse:function(e){
if (dhtmlx._isIE) //make a copy of event, will be used in timed call
e = document.createEventObject(event);
if (this._mouse_move_timer) //clear old event timer
window.clearTimeout(this._mouse_move_timer);
//this event just inform about moving operation, we don't care about details
this.callEvent("onMouseMoving",[e]);
//set new event timer
this._mouse_move_timer = window.setTimeout(dhtmlx.bind(function(){
//called only when we have at least 100ms after previous event
if (e.type == "mousemove")
this._onMouseMove(e);
else
this._onMouseOut(e);
},this),500);
},
//inner mousemove object handler
_onMouseMove: function(e) {
if (!this._mouseEvent(e,this.on_mouse_move,"MouseMove"))
this.callEvent("onMouseOut",[e||event]);
},
//inner mouseout object handler
_onMouseOut: function(e) {
this.callEvent("onMouseOut",[e||event]);
},
//common logic for click and dbl-click processing
_mouseEvent:function(e,hash,name){
e=e||event;
var trg=e.target||e.srcElement;
var css = "";
var id = null;
var found = false;
//loop through all parents
while (trg && trg.parentNode){
if (!found && trg.getAttribute){ //if element with ID mark is not detected yet
id = trg.getAttribute(this._id); //check id of current one
if (id){
if (trg.getAttribute("userdata"))
this.callEvent("onLocateData",[id,trg]);
if (!this.callEvent("on"+name,[id,e,trg])) return; //it will be triggered only for first detected ID, in case of nested elements
found = true; //set found flag
}
}
css=trg.className;
if (css){ //check if pre-defined reaction for element's css name exists
css = css.split(" ");
css = css[0]||css[1]; //FIXME:bad solution, workaround css classes which are starting from whitespace
if (hash[css])
return hash[css].call(this,e,id||dhtmlx.html.locate(e, this._id),trg);
}
trg=trg.parentNode;
}
return found; //returns true if item was located and event was triggered
}
};
/* DHX DEPEND FROM FILE 'config.js'*/
/*
Behavior:Settings
@export
customize
config
*/
/*DHX:Depend template.js*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.Settings={
_init:function(){
/*
property can be accessed as this.config.some
in same time for inner call it have sense to use _settings
because it will be minified in final version
*/
this._settings = this.config= {};
},
define:function(property, value){
if (typeof property == "object")
return this._parseSeetingColl(property);
return this._define(property, value);
},
_define:function(property,value){
dhtmlx.assert_settings.call(this,property,value);
//method with name {prop}_setter will be used as property setter
//setter is optional
var setter = this[property+"_setter"];
return this._settings[property]=setter?setter.call(this,value):value;
},
//process configuration object
_parseSeetingColl:function(coll){
if (coll){
for (var a in coll) //for each setting
this._define(a,coll[a]); //set value through config
}
},
//helper for object initialization
_parseSettings:function(obj,initial){
//initial - set of default values
var settings = dhtmlx.extend({},initial);
//code below will copy all properties over default one
if (typeof obj == "object" && !obj.tagName)
dhtmlx.extend(settings,obj);
//call config for each setting
this._parseSeetingColl(settings);
},
_mergeSettings:function(config, defaults){
for (var key in defaults)
switch(typeof config[key]){
case "object":
config[key] = this._mergeSettings((config[key]||{}), defaults[key]);
break;
case "undefined":
config[key] = defaults[key];
break;
default: //do nothing
break;
}
return config;
},
//helper for html container init
_parseContainer:function(obj,name,fallback){
/*
parameter can be a config object, in such case real container will be obj.container
or it can be html object or ID of html object
*/
if (typeof obj == "object" && !obj.tagName)
obj=obj.container;
this._obj = this.$view = dhtmlx.toNode(obj);
if (!this._obj && fallback)
this._obj = fallback(obj);
dhtmlx.assert(this._obj, "Incorrect html container");
this._obj.className+=" "+name;
this._obj.onselectstart=function(){return false;}; //block selection by default
this._dataobj = this._obj;//separate reference for rendering modules
},
//apply template-type
_set_type:function(name){
//parameter can be a hash of settings
if (typeof name == "object")
return this.type_setter(name);
dhtmlx.assert(this.types, "RenderStack :: Types are not defined");
dhtmlx.assert(this.types[name],"RenderStack :: Inccorect type name",name);
//or parameter can be a name of existing template-type
this.type=dhtmlx.extend({},this.types[name]);
this.customize(); //init configs
},
customize:function(obj){
//apply new properties
if (obj) dhtmlx.extend(this.type,obj);
//init tempaltes for item start and item end
this.type._item_start = dhtmlx.Template.fromHTML(this.template_item_start(this.type));
this.type._item_end = this.template_item_end(this.type);
//repaint self
this.render();
},
//config.type - creates new template-type, based on configuration object
type_setter:function(value){
this._set_type(typeof value == "object"?dhtmlx.Type.add(this,value):value);
return value;
},
//config.template - creates new template-type with defined template string
template_setter:function(value){
return this.type_setter({template:value});
},
//config.css - css name for top level container
css_setter:function(value){
this._obj.className += " "+value;
return value;
}
};
/* DHX DEPEND FROM FILE 'template.js'*/
/*
Template - handles html templates
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.Template={
_cache:{
},
empty:function(){
return "";
},
setter:function(value){
return dhtmlx.Template.fromHTML(value);
},
obj_setter:function(value){
var f = dhtmlx.Template.setter(value);
var obj = this;
return function(){
return f.apply(obj, arguments);
};
},
fromHTML:function(str){
if (typeof str == "function") return str;
if (this._cache[str])
return this._cache[str];
//supported idioms
// {obj} => value
// {obj.attr} => named attribute or value of sub-tag in case of xml
// {obj.attr?some:other} conditional output
// {-obj => sub-template
str=(str||"").toString();
str=str.replace(/[\r\n]+/g,"\\n");
str=str.replace(/\{obj\.([^}?]+)\?([^:]*):([^}]*)\}/g,"\"+(obj.$1?\"$2\":\"$3\")+\"");
str=str.replace(/\{common\.([^}\(]*)\}/g,"\"+common.$1+\"");
str=str.replace(/\{common\.([^\}\(]*)\(\)\}/g,"\"+(common.$1?common.$1(obj):\"\")+\"");
str=str.replace(/\{obj\.([^}]*)\}/g,"\"+obj.$1+\"");
str=str.replace(/#([a-z0-9_]+)#/gi,"\"+obj.$1+\"");
str=str.replace(/\{obj\}/g,"\"+obj+\"");
str=str.replace(/\{-obj/g,"{obj");
str=str.replace(/\{-common/g,"{common");
str="return \""+str+"\";";
return this._cache[str]= Function("obj","common",str);
}
};
dhtmlx.Type={
/*
adds new template-type
obj - object to which template will be added
data - properties of template
*/
add:function(obj, data){
//auto switch to prototype, if name of class was provided
if (!obj.types && obj.prototype.types)
obj = obj.prototype;
//if (typeof data == "string")
// data = { template:data };
if (dhtmlx.assert_enabled())
this.assert_event(data);
var name = data.name||"default";
//predefined templates - autoprocessing
this._template(data);
this._template(data,"edit");
this._template(data,"loading");
obj.types[name]=dhtmlx.extend(dhtmlx.extend({},(obj.types[name]||this._default)),data);
return name;
},
//default template value - basically empty box with 5px margin
_default:{
css:"default",
template:function(){ return ""; },
template_edit:function(){ return ""; },
template_loading:function(){ return "..."; },
width:150,
height:80,
margin:5,
padding:0
},
//template creation helper
_template:function(obj,name){
name = "template"+(name?("_"+name):"");
var data = obj[name];
//if template is a string - check is it plain string or reference to external content
if (data && (typeof data == "string")){
if (data.indexOf("->")!=-1){
data = data.split("->");
switch(data[0]){
case "html": //load from some container on the page
data = dhtmlx.html.getValue(data[1]).replace(/\"/g,"\\\"");
break;
case "http": //load from external file
data = new dhtmlx.ajax().sync().get(data[1],{uid:(new Date()).valueOf()}).responseText;
break;
default:
//do nothing, will use template as is
break;
}
}
obj[name] = dhtmlx.Template.fromHTML(data);
}
}
};
/* DHX DEPEND FROM FILE 'single_render.js'*/
/*
REnders single item.
Can be used for elements without datastore, or with complex custom rendering logic
@export
render
*/
/*DHX:Depend template.js*/
dhtmlx.SingleRender={
_init:function(){
},
//convert item to the HTML text
_toHTML:function(obj){
/*
this one doesn't support per-item-$template
it has not sense, because we have only single item per object
*/
return this.type._item_start(obj,this.type)+this.type.template(obj,this.type)+this.type._item_end;
},
//render self, by templating data object
render:function(){
if (!this.callEvent || this.callEvent("onBeforeRender",[this.data])){
if (this.data)
this._dataobj.innerHTML = this._toHTML(this.data);
if (this.callEvent) this.callEvent("onAfterRender",[]);
}
}
};
/* DHX DEPEND FROM FILE 'tooltip.js'*/
/*
UI: Tooltip
@export
show
hide
*/
/*DHX:Depend tooltip.css*/
/*DHX:Depend template.js*/
/*DHX:Depend single_render.js*/
dhtmlx.ui.Tooltip=function(container){
this.name = "Tooltip";
if (dhtmlx.assert_enabled()) this._assert();
if (typeof container == "string"){
container = { template:container };
}
dhtmlx.extend(this, dhtmlx.Settings);
dhtmlx.extend(this, dhtmlx.SingleRender);
this._parseSettings(container,{
type:"default",
dy:0,
dx:20
});
//create container for future tooltip
this._dataobj = this._obj = document.createElement("DIV");
this._obj.className="dhx_tooltip";
dhtmlx.html.insertBefore(this._obj,document.body.firstChild);
};
dhtmlx.ui.Tooltip.prototype = {
//show tooptip
//pos - object, pos.x - left, pox.y - top
show:function(data,pos){
if (this._disabled) return;
//render sefl only if new data was provided
if (this.data!=data){
this.data=data;
this.render(data);
}
//show at specified position
this._obj.style.top = pos.y+this._settings.dy+"px";
this._obj.style.left = pos.x+this._settings.dx+"px";
this._obj.style.display="block";
},
//hide tooltip
hide:function(){
this.data=null; //nulify, to be sure that on next show it will be fresh-rendered
this._obj.style.display="none";
},
disable:function(){
this._disabled = true;
},
enable:function(){
this._disabled = false;
},
types:{
"default":dhtmlx.Template.fromHTML("{obj.id}")
},
template_item_start:dhtmlx.Template.empty,
template_item_end:dhtmlx.Template.empty
};
/* DHX DEPEND FROM FILE 'autotooltip.js'*/
/*
Behavior: AutoTooltip - links tooltip to data driven item
*/
/*DHX:Depend tooltip.js*/
dhtmlx.AutoTooltip = {
tooltip_setter:function(value){
var t = new dhtmlx.ui.Tooltip(value);
this.attachEvent("onMouseMove",function(id,e){ //show tooltip on mousemove
t.show(this.get(id),dhtmlx.html.pos(e));
});
this.attachEvent("onMouseOut",function(id,e){ //hide tooltip on mouseout
t.hide();
});
this.attachEvent("onMouseMoving",function(id,e){ //hide tooltip just after moving start
t.hide();
});
return t;
}
};
/* DHX DEPEND FROM FILE 'compatibility.js'*/
/*
Collection of compatibility hacks
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.compat=function(name, obj){
//check if name hash present, and applies it when necessary
if (dhtmlx.compat[name])
dhtmlx.compat[name](obj);
};
/* DHX DEPEND FROM FILE 'compatibility_layout.js'*/
/*DHX:Depend dhtmlx.js*/
/*DHX:Depend compatibility.js*/
if (!dhtmlx.attaches)
dhtmlx.attaches = {};
dhtmlx.attaches.attachAbstract=function(name, conf){
var obj = document.createElement("DIV");
obj.id = "CustomObject_"+dhtmlx.uid();
obj.style.width = "100%";
obj.style.height = "100%";
obj.cmp = "grid";
document.body.appendChild(obj);
this.attachObject(obj.id);
conf.container = obj.id;
var that = this.vs[this.av];
that.grid = new window[name](conf);
that.gridId = obj.id;
that.gridObj = obj;
that.grid.setSizes = function(){
if (this.resize) this.resize();
else this.render();
};
var method_name="_viewRestore";
return this.vs[this[method_name]()].grid;
};
dhtmlx.attaches.attachDataView = function(conf){
return this.attachAbstract("dhtmlXDataView",conf);
};
dhtmlx.attaches.attachChart = function(conf){
return this.attachAbstract("dhtmlXChart",conf);
};
dhtmlx.compat.layout = function(){};
|
const SimpleSource = require('../../lib/sources/simple-source.js')
const JsSource = require('../../lib/sources/js-source.js')
describe('sources/js-source.js', () => {
it('should return the type', () => {
expect(JsSource.from('var x = 1')).to.have.property('type', 'js')
})
describe('#join', () => {
it('should join to another JsSource', () => {
const sourceA = JsSource.from('var x = "foo"')
const sourceB = JsSource.from('var b = "bar"')
expect(sourceA.join(sourceB)).to.have.property('type', 'js')
expect(sourceB.join(sourceA)).to.have.property('type', 'js')
})
it('should not join to a malformed JsSource', () => {
const sourceA = JsSource.from('var x = "foo')
const sourceB = JsSource.from('var b = "bar"')
expect(() => sourceA.join(sourceB)).to.throw()
expect(() => sourceB.join(sourceA)).to.throw()
})
it('should not join to another non-JsSource', () => {
const sourceA = JsSource.from('var x = "foo"')
const sourceB = new SimpleSource('other content')
expect(() => sourceA.join(sourceB)).to.throw()
expect(() => sourceB.join(sourceA)).to.throw()
})
})
describe('#contains', () => {
context('when script is simple', () => {
const script = `
const myVar = 'the-class'
const otherVar = 'the-OtHer-cLass'
const html = '<div class="inner-class">Content</div>'
const dynamicVar = ['fa', 'icon'].join('-')
const classes = {
inVisIble: true,
blocK__Element: true,
}
classes.aDditIonal_class = false
const no_find = window.should_not_be_found(classes.also_not_found)
`
const source = JsSource.from(script)
it('should find tokens as strings', () => {
expect(source).to.contain('the-class')
expect(source).to.contain('the-other-class')
expect(source).to.contain('fa')
expect(source).to.contain('tHe-cLaSs')
})
it('should find tokens within strings', () => {
expect(source).to.contain('div')
expect(source).to.contain('inner-class')
})
it('should find tokens as combinations of strings', () => {
expect(source).to.contain('fa-icon')
})
it('should find tokens as object keys', () => {
expect(source).to.contain('invisible')
expect(source).to.contain('block__element')
})
it('should find tokens as object key assignment', () => {
expect(source).to.contain('additional_class')
})
it('should not find tokens as identifiers', () => {
expect(source).to.not.contain('const')
expect(source).to.not.contain('myVar')
expect(source).to.not.contain('otherVar')
expect(source).to.not.contain('dynamicVar')
expect(source).to.not.contain('window')
expect(source).to.not.contain('no_find')
})
it('should not find tokens as object key access', () => {
expect(source).to.not.contain('should_not_be_found')
expect(source).to.not.contain('also_not_found')
})
})
context('when options.strict=true', () => {
const script = `
const myVar = 'the-class'
const otherVar = 'the-OtHer-cLass'
const html = '<div class="inner-class">Content</div>'
const dynamicVar = ['fa', 'icon'].join('-')
const obj = {inVisible: true, BLOCK__element: 1}
obj.additional_class = false
`
const source = JsSource.from(script, {strict: true})
it('should find tokens as strings', () => {
expect(source).to.contain('the-class')
expect(source).to.contain('the-other-class')
expect(source).to.contain('fa')
expect(source).to.contain('tHe-cLaSs')
})
it('should not find tokens within strings', () => {
expect(source).to.not.contain('div')
expect(source).to.not.contain('inner-class')
})
it('should not find tokens as combinations of strings', () => {
expect(source).to.not.contain('fa-icon')
})
it('should find tokens as object keys', () => {
expect(source).to.contain('invisible')
expect(source).to.contain('block__element')
})
it('should find tokens as object key assignment', () => {
expect(source).to.contain('additional_class')
})
})
context('when script is malformed', () => {
it('should not throw', () => {
expect(() => JsSource.from('const foo != "whaaaa')).to.not.throw()
})
it('should fallback to SimpleSource', () => {
const source = JsSource.from('const foo != "whaaa-is-going onhere')
expect(source).to.have.property('type', 'simple')
expect(source).to.contain('const')
expect(source).to.contain('foo')
expect(source).to.contain('whaaa-is-going')
expect(source).to.contain('is')
expect(source).to.not.contain('going on')
})
})
context('when script is joined', () => {
it('should find tokens stretching across both', () => {
const sourceA = JsSource.from('var x = "foo"')
const sourceB = JsSource.from('var b = "bar"; var c = "-"')
const joined = sourceA.join(sourceB)
expect(joined.contains('foo')).to.equal(true)
expect(joined.contains('bar')).to.equal(true)
expect(joined.contains('foo-bar')).to.equal(true)
})
})
})
})
|
/*
(c) 2010 Geraud Boyer
Adapted from rhino.js from Douglas Crockford (www.JSLint.com)
This is the node companion to fulljslint.js.
*/
/*global JSLINT
*/
/*jslint rhino: false, node: true, strict: false
*/
/*global require,util,__filename,process
*/(function(args) {
var JSLINT, filename, fs, input, input_filename, options, path, print_syntax, util;
util = require('util');
fs = require('fs');
path = require('path');
print_syntax = function() {
util.puts('Usage: jslint.js [options] file.js');
return process.exit(1);
};
if (args.length === 0) {
print_syntax();
}
filename = path.join(path.dirname(__filename), 'jslint.js');
JSLINT = fs.readFileSync(filename).toString('UTF8');
eval(JSLINT);
options = {
rhino: false,
node: false,
passfail: false,
bitwise: true,
immed: true,
newcap: true,
nomen: true,
onevar: true,
plusplus: true,
regexp: true,
undef: true,
white: true
};
input = null;
input_filename = null;
args.forEach(function(arg, index) {
if (arg.match(/^--no-(\w+)$/)) {
options[RegExp.$1] = false;
} else if (arg.match(/^--(\w+)=(\S.*)$/)) {
options[RegExp.$1] = JSON.parse(RegExp.$2);
} else if (arg.match(/^--(\w+)$/)) {
options[RegExp.$1] = true;
} else {
input_filename = arg;
input = fs.readFileSync(input_filename);
if (!input) {
util.puts("jslint: Couldn't open file '" + input_filename + "'.");
process.exit(1);
} else {
input = input.toString('UTF8');
}
}
});
if (!input) {
print_syntax();
}
if (!JSLINT(input, options)) {
JSLINT.errors.forEach(function(error) {
if (error) {
util.puts("Lint at line " + error.line + " character " + error.character + ": " + error.reason);
util.puts((error.evidence || '').replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
return util.puts('');
}
});
process.exit(2);
} else {
util.puts("jslint: No problems found in " + input_filename);
process.exit(0);
}
})(process.argv.slice(2));
|
export class CreateTaskAction {
constructor(title) {
this.title = title;
}
}
export class UpdateTaskAction {
constructor(taskId, attrs) {
this.taskId = taskId;
this.attrs = attrs;
}
}
|
/** _ _____ _ _
* | | |_ _| |_| |
* | |_ _| | | _ |
* |___|_|_| |_| |_|
* @author lo.th / http://lo-th.github.io/labs/
* THREE ultimate manager
*/
'use strict';
// MATH ADD
Math.degtorad = Math.PI / 180;//0.0174532925199432957;
Math.radtodeg = 180 / Math.PI;//57.295779513082320876;
Math.Pi = 3.141592653589793;
Math.TwoPI = 6.283185307179586;
Math.PI90 = 1.570796326794896;
Math.PI270 = 4.712388980384689;
Math.lerp = function (a, b, percent) { return a + (b - a) * percent; };
Math.rand = function (a, b) { return Math.lerp(a, b, Math.random()); };
Math.randInt = function (a, b, n) { return Math.lerp(a, b, Math.random()).toFixed(n || 0)*1; };
Math.int = function(x) { return ~~x; };
var view = ( function () {
var time = 0;
var temp = 0;
var count = 0;
var fps = 0;
var canvas, renderer, scene, camera, controls, debug;
var ray, mouse, content, targetMouse, rayCallBack, moveplane, isWithRay = false;;
var vs = { w:1, h:1, l:0, x:0 };
var helper;
var meshs = [];
var statics = [];
var terrains = [];
var softs = [];
var cars = [];
//var carsSpeed = [];
var heros = [];
var extraGeo = [];
var byName = {};
var currentFollow = null;
//var softsPoints = [];
var geo = {};
var mat = {};
// key[8] = controle.
//var key = [ 0,0,0,0,0,0,0,0,0 ];
var imagesLoader;
//var currentCar = -1;
var isCamFollow = false;
var isWithShadow = false;
var shadowGround, light, ambient;
var spy = -0.01;
var perlin = null;//new Perlin();
var environment, envcontext, nEnv = 0, isWirframe = true;
var envLists = ['wireframe','ceramic','plastic','smooth','metal','chrome','brush','black','glow','red','sky'];
var envMap;
view = function () {};
view.init = function ( callback ) {
canvas = document.createElement("canvas");
canvas.className = 'canvas3d';
canvas.oncontextmenu = function(e){ e.preventDefault(); };
canvas.ondrop = function(e) { e.preventDefault(); };
document.body.appendChild( canvas );
// RENDERER
try {
renderer = new THREE.WebGLRenderer({ canvas:canvas, antialias:true, alpha:false });
//renderer = new THREE.WebGLRenderer({ canvas:canvas, precision:"mediump", antialias:true, alpha:false });
} catch( error ) {
if(intro !== null ) intro.message('<p>Sorry, your browser does not support WebGL.</p>'
+ '<p>This application uses WebGL to quickly draw'
+ ' AMMO Physics.</p>'
+ '<p>AMMO Physics can be used without WebGL, but unfortunately'
+ ' this application cannot.</p>'
+ '<p>Have a great day!</p>');
return;
}
if(intro !== null ) intro.clear();
renderer.setClearColor(0x2B2A2D, 1);
//renderer.setSize( 100, 100 );
renderer.setPixelRatio( window.devicePixelRatio );
//renderer.sortObjects = false;
renderer.gammaInput = true;
renderer.gammaOutput = true;
// SCENE
scene = new THREE.Scene();
content = new THREE.Object3D();
scene.add(content);
// CAMERA / CONTROLER
camera = new THREE.PerspectiveCamera( 60 , 1 , 1, 1000 );
camera.position.set( 0, 0, 30 );
controls = new THREE.OrbitControls( camera, canvas );
controls.target.set( 0, 0, 0 );
controls.enableKeys = false;
controls.update();
// GEOMETRY
geo['box'] = new THREE.BufferGeometry().fromGeometry( new THREE.BoxGeometry(1,1,1) );
geo['sphere'] = new THREE.SphereBufferGeometry( 1, 12, 10 );
geo['cylinder'] = new THREE.BufferGeometry().fromGeometry( new THREE.CylinderGeometry( 1,1,1,12,1 ) );
geo['cone'] = new THREE.BufferGeometry().fromGeometry( new THREE.CylinderGeometry( 0,1,0.5 ) );
geo['wheel'] = new THREE.BufferGeometry().fromGeometry( new THREE.CylinderGeometry( 1,1,1, 18 ) );
geo['wheel'].rotateZ( -Math.PI90 );
// MATERIAL
mat['terrain'] = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors, name:'terrain', wireframe:true });
mat['cloth'] = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors, name:'cloth', wireframe:true, transparent:true, opacity:0.9, side: THREE.DoubleSide });
mat['ball'] = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors, name:'ball', wireframe:true });
mat['statique'] = new THREE.MeshBasicMaterial({ color:0x333399, name:'statique', wireframe:true, transparent:true, opacity:0.6 });
mat['hero'] = new THREE.MeshBasicMaterial({ color:0x993399, name:'hero', wireframe:true });
mat['move'] = new THREE.MeshBasicMaterial({ color:0x999999, name:'move', wireframe:true });
mat['cars'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'cars', wireframe:true, transparent:true, side: THREE.DoubleSide });
mat['tmp1'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'tmp1', wireframe:true, transparent:true });
mat['tmp2'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'tmp2', wireframe:true, transparent:true });
mat['movehigh'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'movehigh', wireframe:true });
mat['sleep'] = new THREE.MeshBasicMaterial({ color:0x383838, name:'sleep', wireframe:true });
mat['meca1'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'meca1', wireframe:true });
mat['meca2'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'meca2', wireframe:true });
mat['meca3'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'meca3', wireframe:true });
mat['both'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'both', wireframe:true, side:THREE.DoubleSide });
mat['back'] = new THREE.MeshBasicMaterial({ color:0xffffff, name:'back', wireframe:true, side:THREE.BackSide });
// GROUND
helper = new THREE.GridHelper( 50, 2 );
helper.setColors( 0xFFFFFF, 0x666666 );
helper.material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, transparent:true, opacity:0.1 } );
scene.add( helper );
// RAYCAST
ray = new THREE.Raycaster();
mouse = new THREE.Vector2();
// EVENT
window.addEventListener( 'resize', view.resize, false );
imagesLoader = new THREE.TextureLoader();
this.resize();
this.initEnv();
// charge basic geometry
//this.load ( 'basic', callback );
if(callback)callback();
};
view.setLeft = function ( x ) { vs.x = x; };
view.resize = function () {
vs.h = window.innerHeight;
vs.w = window.innerWidth - vs.x;
canvas.style.left = vs.x +'px';
camera.aspect = vs.w / vs.h;
camera.updateProjectionMatrix();
renderer.setSize( vs.w, vs.h );
if(editor) editor.resizeMenu( vs.w );
};
view.getFps = function () {
return fps;
};
view.getInfo = function () {
return renderer.info.programs.length;
};
view.render = function () {
time = now();
if ( (time - 1000) > temp ){ temp = time; fps = count; count = 0; }; count++;
this.controlUpdate();
renderer.render( scene, camera );
};
view.addMap = function( name, matName ) {
var map = imagesLoader.load( 'textures/' + name );
//map.wrapS = THREE.RepeatWrapping;
//map.wrapT = THREE.RepeatWrapping;
map.flipY = false;
mat[matName].map = map;
}
view.getGeo = function () {
return geo;
};
view.getMat = function () {
return mat;
};
view.getScene = function () {
return scene;
};
view.removeRay = function(){
if(isWithRay){
isWithRay = false;
canvas.removeEventListener( 'mousemove', view.rayTest, false );
rayCallBack = null;
content.remove(moveplane);
scene.remove(targetMouse);
}
}
view.activeRay = function ( callback ) {
isWithRay = true;
var g = new THREE.PlaneBufferGeometry(100,100);
g.rotateX( -Math.PI90 );
moveplane = new THREE.Mesh( g, new THREE.MeshBasicMaterial({ color:0xFFFFFF, transparent:true, opacity:0 }));
content.add(moveplane);
//moveplane.visible = false;
targetMouse = new THREE.Mesh( geo['box'] , new THREE.MeshBasicMaterial({color:0xFF0000}));
scene.add(targetMouse);
canvas.addEventListener( 'mousemove', view.rayTest, false );
rayCallBack = callback;
};
view.rayTest = function (e) {
//vs.h = window.innerHeight;
//vs.w = window.innerWidth - vs.x;
mouse.x = ( (e.clientX- vs.x )/ vs.w ) * 2 - 1;
mouse.y = - ( e.clientY / vs.h ) * 2 + 1;
ray.setFromCamera( mouse, camera );
var intersects = ray.intersectObjects( content.children, true );
if ( intersects.length) {
targetMouse.position.copy( intersects[0].point )
//paddel.position.copy( intersects[0].point.add(new THREE.Vector3( 0, 20, 0 )) );
rayCallBack( targetMouse );
}
}
view.changeMaterial = function ( type ) {
var m, matType, name, i, j, k;
if( type == 0 ) {
isWirframe = true;
matType = 'MeshBasicMaterial';
this.removeShadow();
}else{
isWirframe = false;
matType = 'MeshStandardMaterial';
this.addShadow();
}
// create new material
for( var old in mat ) {
m = mat[old];
name = m.name;
mat[name] = new THREE[matType]({ map:m.map, vertexColors:m.vertexColors, color:m.color.getHex(), name:name, wireframe:isWirframe, transparent:m.transparent, opacity:m.opacity, side:m.side });
if(!isWirframe){
mat[name].envMap = envMap;
mat[name].metalness = 0.5;
mat[name].roughness = 0.5;
}
}
// re-apply material
i = meshs.length;
while(i--){
name = meshs[i].material.name;
meshs[i].material = mat[name];
};
i = statics.length;
while(i--){
name = statics[i].material.name;
statics[i].material = mat[name];
};
i = cars.length;
while(i--){
if(cars[i].material == undefined){
k = cars[i].children.length;
while(k--){
name = cars[i].children[k].material.name;
if( name !=='helper') cars[i].children[k].material = mat[name]
}
}else{
name = cars[i].material.name;
cars[i].material = mat[name];
}
j = cars[i].userData.w.length;
while(j--){
name = cars[i].userData.w[j].material.name;
cars[i].userData.w[j].material = mat[name];
}
};
i = terrains.length;
while(i--){
name = terrains[i].material.name;
terrains[i].material = mat[name];
};
i = softs.length;
while(i--){
if(softs.softType!==2){
name = softs[i].material.name;
softs[i].material = mat[name];
}
};
}
view.needFocus = function () {
canvas.addEventListener('mouseover', editor.unFocus, false );
};
view.haveFocus = function () {
canvas.removeEventListener('mouseover', editor.unFocus, false );
};
view.initEnv = function () {
var env = document.createElement( 'div' );
env.className = 'env';
var canvas = document.createElement( 'canvas' );
canvas.width = canvas.height = 64;
env.appendChild( canvas );
document.body.appendChild( env );
envcontext = canvas.getContext('2d');
env.onclick = this.loadEnv;
env.oncontextmenu = this.loadEnv;
this.loadEnv();
};
view.loadEnv = function (e) {
var b = 0;
if(e){
e.preventDefault();
b = e.button;
if( b == 0 ) nEnv++;
else nEnv--;
if( nEnv == envLists.length ) nEnv = 0;
if( nEnv < 0 ) nEnv = envLists.length-1;
}
var img = new Image();
img.onload = function(){
envcontext.drawImage(img,0,0,64,64);
envMap = new THREE.Texture(img);
envMap.mapping = THREE.SphericalReflectionMapping;
envMap.format = THREE.RGBFormat;
envMap.needsUpdate = true;
if( nEnv == 0 && !isWirframe ) view.changeMaterial( 0 );
if( nEnv !== 0 ) {
if(isWirframe) view.changeMaterial( 1 );
else{
for( var mm in mat ){
mat[mm].envMap = envMap;
}
}
}
}
img.src = 'textures/spherical/'+ envLists[nEnv] +'.jpg';
};
view.sh_grid = function(){
if(helper.visible) helper.visible = false;
else helper.visible = true;
}
view.hideGrid = function(){
helper.visible = false;
}
// LOAD
view.load = function ( name, callback ) {
var loader = new THREE.SEA3D({});
loader.onComplete = function( e ) {
var i = loader.geometries.length, g;
while(i--){
g = loader.geometries[i];
geo[g.name] = g;
};
if(callback) callback();
//console.log('loaded !! ', loader);
};
loader.load( 'models/'+ name +'.sea' );
};
//--------------------------------------
//
// SRC UTILS ViewUtils
//
//--------------------------------------
view.mergeMesh = function(m){
return THREE.ViewUtils.mergeGeometryArray(m);
};
view.prepaGeometry = function ( g, type ) {
return THREE.ViewUtils.prepaGeometry( g, type );
};
//--------------------------------------
//
// CAMERA AND CONTROL
//
//--------------------------------------
view.controlUpdate = function(){
//+Math.PI90;
//key[9] = controls.getPolarAngle();
//key[8] = controls.getAzimuthalAngle();
//key[9] = controls.getPolarAngle();
//tell( key[8] * Math.radtodeg + '/' + key[9] * Math.radtodeg);
if( isCamFollow ) this.follow();
//else key[8] = controls.getAzimuthalAngle();
};
view.setFollow = function ( name ) {
currentFollow = this.getByName(name);
if( currentFollow !== null ) isCamFollow = true;
};
view.follow = function ( name ) {
if( currentFollow === null ) return;
//if( currentCar == -1 ) return;
var mesh = currentFollow;
if( mesh.userData.speed !== undefined && mesh.userData.type == 'car') {
if( mesh.userData.speed < 10 && mesh.userData.speed > -10 ){
// controls.update();
//key[8] = controls.getAzimuthalAngle();
return;
}
}
//if( carsSpeed[currentCar] < 10 && carsSpeed[currentCar] > -10 ) return;
//if( cars[currentCar] == undefined ) return;
//cars[currentCar].body;
var matrix = new THREE.Matrix4();
matrix.extractRotation( mesh.matrix );
var front = new THREE.Vector3( 0, 0, 1 );
front.applyMatrix4( matrix );
//matrix.multiplyVector3( front );
var target = mesh.position;
//var front = cars[currentCar].body.position;
//var h = Math.atan2( front.z, front.x ) * Math.radtodeg;
var h = (Math.atan2( front.x, front.z ) * Math.radtodeg)-180;
view.moveCamera( h, 20, 10, 0.3, target );
};
view.moveCamera = function ( h, v, d, l, target ) {
l = l || 1;
if( target ) controls.target.set( target.x || 0, target.y || 0, target.z || 0 );
//camera.position.copy( this.orbit( h, v, d ) );
camera.position.lerp( this.orbit( h, v, d ), l );
controls.update();
};
view.orbit = function( h, v, d ) {
var offset = new THREE.Vector3();
var phi = (v-90) * Math.degtorad;
var theta = (h+180) * Math.degtorad;
offset.x = d * Math.sin(phi) * Math.sin(theta);
offset.y = d * Math.cos(phi);
offset.z = d * Math.sin(phi) * Math.cos(theta);
var p = new THREE.Vector3();
p.copy(controls.target).add(offset);
/*
p.x = ( d * Math.sin(phi) * Math.cos(theta)) + controls.target.x;
p.y = ( d * Math.cos(phi)) + controls.target.y;
p.z = ( d * Math.sin(phi) * Math.sin(theta)) + controls.target.z;*/
//key[8] = theta;
return p;
};
view.setDriveCar = function ( name ) {
ammo.send('setDriveCar', { n:this.getByName(name).userData.id });
};
view.toRad = function ( r ) {
var i = r.length;
while(i--) r[i] *= Math.degtorad;
return r;
};
//--------------------------------------
//
// RESET
//
//--------------------------------------
view.reset = function () {
view.removeRay();
view.setShadowPosY(-0.01);
helper.visible = true;
var c, i;
while( meshs.length > 0 ){
scene.remove( meshs.pop() );
}
while( statics.length > 0 ){
scene.remove( statics.pop() );
}
while( terrains.length > 0 ){
scene.remove( terrains.pop() );
}
while( softs.length > 0 ){
scene.remove( softs.pop() );
}
while( heros.length > 0 ){
scene.remove( heros.pop() );
}
while( extraGeo.length > 0 ){
extraGeo.pop().dispose();
}
while( cars.length > 0 ){
c = cars.pop();
if( c.userData.helper ){
c.remove( c.userData.helper );
c.userData.helper.dispose();
}
i = c.userData.w.length;
while( i-- ){
scene.remove( c.userData.w[i] );
}
scene.remove( c );
}
meshs.length = 0;
perlin = null;
byName = {};
currentFollow = null;
};
//--------------------------------------
//
// ADD
//
//--------------------------------------
view.add = function ( o ) {
var isCustomGeometry = false;
o.mass = o.mass == undefined ? 0 : o.mass;
o.type = o.type == undefined ? 'box' : o.type;
// position
o.pos = o.pos == undefined ? [0,0,0] : o.pos;
// size
o.size = o.size == undefined ? [1,1,1] : o.size;
if(o.size.length == 1){ o.size[1] = o.size[0]; }
if(o.size.length == 2){ o.size[2] = o.size[0]; }
if(o.geoSize){
if(o.geoSize.length == 1){ o.geoSize[1] = o.geoSize[0]; }
if(o.geoSize.length == 2){ o.geoSize[2] = o.geoSize[0]; }
}
// rotation is in degree
o.rot = o.rot == undefined ? [0,0,0] : this.toRad(o.rot);
o.quat = new THREE.Quaternion().setFromEuler( new THREE.Euler().fromArray( o.rot ) ).toArray();
if(o.rotA) o.quatA = new THREE.Quaternion().setFromEuler( new THREE.Euler().fromArray( this.toRad( o.rotA ) ) ).toArray();
if(o.rotB) o.quatB = new THREE.Quaternion().setFromEuler( new THREE.Euler().fromArray( this.toRad( o.rotB ) ) ).toArray();
if(o.angUpper) o.angUpper = this.toRad( o.angUpper );
if(o.angLower) o.angLower = this.toRad( o.angLower );
var mesh = null;
if(o.type.substring(0,5) == 'joint') {
ammo.send( 'add', o );
return;
}
if(o.type == 'plane'){
helper.position.set( o.pos[0], o.pos[1], o.pos[2] )
ammo.send( 'add', o );
return;
}
if(o.type == 'softTriMesh'){
this.softTriMesh( o );
return;
}
if(o.type == 'softConvex'){
this.softConvex( o );
return;
}
if(o.type == 'cloth'){
this.cloth( o );
return;
}
if(o.type == 'rope'){
this.rope( o );
return;
}
if(o.type == 'ellipsoid'){
this.ellipsoid( o );
return;
}
if(o.type == 'terrain'){
this.terrain( o );
return;
}
var material;
if(o.material !== undefined) material = mat[o.material];
else material = o.mass ? mat.move : mat.statique;
if( o.type == 'capsule' ){
var g = new THREE.CapsuleBufferGeometry( o.size[0] , o.size[1]*0.5 );
//g.applyMatrix(new THREE.Matrix4().makeRotationY(-Math.PI*0.5));
mesh = new THREE.Mesh( g, material );
extraGeo.push(mesh.geometry);
isCustomGeometry = true;
} else if( o.type == 'mesh' || o.type == 'convex' ){
o.v = view.prepaGeometry( o.shape, o.type );
if(o.geometry){
mesh = new THREE.Mesh( o.geometry, material );
extraGeo.push(o.geometry);
extraGeo.push(o.shape);
} else {
mesh = new THREE.Mesh( o.shape, material );
extraGeo.push(mesh.geometry);
}
/*} else if( o.type == 'convex' ){
o.v = view.prepaGeometry( o.shape, true, false );
if(o.geometry){
mesh = new THREE.Mesh( o.geometry, material );
extraGeo.push(o.geometry);
extraGeo.push(o.shape);
} else {
mesh = new THREE.Mesh( o.shape, material );
extraGeo.push(mesh.geometry);
}
//mesh = new THREE.Mesh( o.shape, material );
//extraGeo.push(mesh.geometry);*/
} else {
if(o.geometry){
if(o.geoRot || o.geoScale) o.geometry = o.geometry.clone();
// rotation only geometry
if(o.geoRot){ o.geometry.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler().fromArray(this.toRad(o.geoRot))));}
// scale only geometry
if(o.geoScale){
o.geometry.applyMatrix( new THREE.Matrix4().makeScale( o.geoScale[0], o.geoScale[1], o.geoScale[2] ) );
//material = mat['back'];//material.clone();
//material.side = THREE.BackSide;
}
}
mesh = new THREE.Mesh( o.geometry || geo[o.type], material );
if( o.geometry ){
extraGeo.push(o.geometry);
mesh.scale.fromArray( o.geoSize );
isCustomGeometry = true;
}
}
if(mesh){
if( !isCustomGeometry ) mesh.scale.fromArray( o.size );//.set( o.size[0], o.size[1], o.size[2] );
mesh.position.fromArray( o.pos );
mesh.quaternion.fromArray( o.quat );
mesh.receiveShadow = true;
mesh.castShadow = true;
this.setName( o, mesh );
scene.add(mesh);
// push
if( o.mass ) meshs.push( mesh );
else statics.push( mesh );
}
// send to worker
ammo.send( 'add', o );
};
view.getGeoByName = function ( name, Buffer ) {
var g;
var i = geo.length;
var buffer = Buffer || false;
while(i--){
if( name == geo[i].name) g = geo[i];
}
if( buffer ) g = new THREE.BufferGeometry().fromGeometry( g );
return g;
};
view.character = function ( o ) {
o.size = o.size == undefined ? [0.5,1,1] : o.size;
if(o.size.length == 1){ o.size[1] = o.size[0]; }
if(o.size.length == 2){ o.size[2] = o.size[0]; }
//var pos = o.pos || [0,3,0];
o.pos = o.pos == undefined ? [0,3,0] : pos;
//var rot = o.rot || [0,0,0];
o.rot = o.rot == undefined ? [0,0,0] : this.toRad(o.rot);
o.quat = new THREE.Quaternion().setFromEuler( new THREE.Euler().fromArray( o.rot ) ).toArray();
var g = new THREE.CapsuleBufferGeometry( o.size[0] , o.size[1]*0.5 );
var mesh = new THREE.Mesh( g, mat.hero );
extraGeo.push(mesh.geometry);
//mesh.position.set( pos[0], pos[1], pos[2] );
//mesh.rotation.set( rot[0], rot[1], rot[2] );
mesh.position.fromArray( o.pos );
mesh.quaternion.fromArray( o.quat );
// copy rotation quaternion
//o.quat = mesh.quaternion.toArray();
//o.pos = pos;
mesh.userData.speed = 0;
mesh.userData.type = 'hero';
scene.add(mesh);
heros.push(mesh);
this.setName( o, mesh );
// send to worker
ammo.send( 'character', o );
};
view.vehicle = function ( o ) {
//var type = o.type || 'box';
var size = o.size || [2,0.5,4];
var pos = o.pos || [0,0,0];
var rot = o.rot || [0,0,0];
var wPos = o.wPos || [1, 0, 1.6];
var massCenter = o.massCenter || [0,0.25,0];
this.toRad( rot );
// chassis
var mesh;
if( o.mesh ){
mesh = o.mesh;
var k = mesh.children.length;
while(k--){
mesh.children[k].position.set( massCenter[0], massCenter[1], massCenter[2] );
//mesh.children[k].geometry.translate( massCenter[0], massCenter[1], massCenter[2] );
mesh.children[k].castShadow = true;
mesh.children[k].receiveShadow = true;
}
} else {
var g = new THREE.BufferGeometry().fromGeometry( new THREE.BoxGeometry(size[0], size[1], size[2]) );//geo.box;
g.translate( massCenter[0], massCenter[1], massCenter[2] );
extraGeo.push( g );
mesh = new THREE.Mesh( g, mat.move );
}
//mesh.scale.set( size[0], size[1], size[2] );
mesh.position.set( pos[0], pos[1], pos[2] );
mesh.rotation.set( rot[0], rot[1], rot[2] );
// copy rotation quaternion
o.quat = mesh.quaternion.toArray();
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
this.setName( o, mesh );
mesh.userData.speed = 0;
mesh.userData.steering = 0;
mesh.userData.NumWheels = o.nw || 4;
mesh.userData.type = 'car';
if(o.helper){
mesh.userData.helper = new THREE.CarHelper( wPos );
mesh.add( mesh.userData.helper );
}
// wheels
var radius = o.radius || 0.4;
var deep = o.deep || 0.3;
var wPos = o.wPos || [1, -0.25, 1.6];
var w = [];
var needScale = o.wheel == undefined ? true : false;
var gw = o.wheel || geo['wheel'];
var gwr = gw.clone();
gwr.rotateY( Math.Pi );
extraGeo.push( gwr );
var i = o.nw || 4;
while(i--){
if(i==1 || i==2) w[i] = new THREE.Mesh( gw, mat.move );
else w[i] = new THREE.Mesh( gwr, mat.move );
if( needScale ) w[i].scale.set( deep, radius, radius );
else w[i].material = mat.cars;
w[i].castShadow = true;
w[i].receiveShadow = true;
scene.add( w[i] );
}
mesh.userData.w = w;
//var car = { body:mesh, w:w, axe:helper.mesh, nw:o.nw || 4, helper:helper, speed:0 };
cars.push( mesh );
mesh.userData.id = cars.length-1;
//carsSpeed.push( 0 );
if( o.mesh ) o.mesh = null;
if( o.wheel ) o.wheel = null;
if ( o.type == 'mesh' || o.type == 'convex' ) o.v = view.prepaGeometry( o.shape, o.type );
// send to worker
ammo.send( 'vehicle', o );
};
//--------------------------------------
// SOFT TRI MESH
//--------------------------------------
view.softTriMesh = function ( o ) {
//console.log(o.shape)
//if(o.shape.bones)
var g = o.shape.clone();
var pos = o.pos || [0,0,0];
var size = o.size || [1,1,1];
var rot = o.rot || [0,0,0];
g.rotateX( rot[0] *= Math.degtorad );
g.rotateY( rot[1] *= Math.degtorad );
g.rotateZ( rot[2] *= Math.degtorad );
g.translate( pos[0], pos[1], pos[2] );
g.scale( size[0], size[1], size[2] );
//console.log('start', g.getIndex().count);
view.prepaGeometry(g);
extraGeo.push( g );
//console.log('mid', g.realIndices.length);
// extra color
/*var color = new Float32Array( g.maxi*3 );
var i = g.maxi*3;
while(i--){
color[i] = 1;
}
g.addAttribute( 'color', new THREE.BufferAttribute( color, 3 ) );*/
o.v = g.realVertices;
o.i = g.realIndices;
o.ntri = g.numFaces;
var mesh = new THREE.Mesh( g, o.material || mat.cloth );
o.shape = null;
o.material = null;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.softType = 5;
scene.add( mesh );
softs.push( mesh );
// send to worker
ammo.send( 'add', o );
}
//--------------------------------------
// SOFT CONVEX
//--------------------------------------
view.softConvex = function ( o ) {
var g = o.shape;
var pos = o.pos || [0,0,0];
g.translate( pos[0], pos[1], pos[2] );
view.prepaGeometry(g);
o.v = g.realVertices;
var mesh = new THREE.Mesh( g, mat.cloth );
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.softType = 4;
scene.add( mesh );
softs.push( mesh );
// send to worker
ammo.send( 'add', o );
}
//--------------------------------------
// CLOTH
//--------------------------------------
view.cloth = function ( o ) {
var i, x, y, n;
var div = o.div || [16,16];
var size = o.size || [100,0,100];
var pos = o.pos || [0,0,0];
var max = div[0] * div[1];
var g = new THREE.PlaneBufferGeometry( size[0], size[2], div[0] - 1, div[1] - 1 );
g.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( max*3 ), 3 ) );
g.rotateX( -Math.PI90 );
//g.translate( -size[0]*0.5, 0, -size[2]*0.5 );
var numVerts = g.attributes.position.array.length / 3;
var mesh = new THREE.Mesh( g, mat.cloth );
this.setName( o, mesh );
// mesh.material.needsUpdate = true;
mesh.position.set( pos[0], pos[1], pos[2] );
mesh.castShadow = true;
mesh.receiveShadow = true;//true;
//mesh.frustumCulled = false;
mesh.softType = 1;
scene.add( mesh );
softs.push( mesh );
o.size = size;
o.div = div;
o.pos = pos;
// send to worker
ammo.send( 'add', o );
}
//--------------------------------------
// ROPE
//--------------------------------------
view.rope = function ( o ) {
var max = o.numSegment || 10;
var start = o.start || [0,0,0];
var end = o.end || [0,10,0];
max += 2;
var ropeIndices = [];
//var n;
//var pos = new Float32Array( max * 3 );
for(var i=0; i<max-1; i++){
ropeIndices.push( i, i + 1 );
}
var g = new THREE.BufferGeometry();
g.setIndex( new THREE.BufferAttribute( new Uint16Array( ropeIndices ), 1 ) );
g.addAttribute('position', new THREE.BufferAttribute( new Float32Array( max * 3 ), 3 ));
g.addAttribute('color', new THREE.BufferAttribute( new Float32Array( max * 3 ), 3 ));
//var mesh = new THREE.LineSegments( g, new THREE.LineBasicMaterial({ vertexColors: true }));
var mesh = new THREE.LineSegments( g, new THREE.LineBasicMaterial({ color: 0xFFFF00 }));
this.setName( o, mesh );
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.softType = 2;
//mesh.frustumCulled = false;
scene.add( mesh );
softs.push( mesh );
// send to worker
ammo.send( 'add', o );
}
//--------------------------------------
// ELLIPSOID
//--------------------------------------
view.ellipsoid = function ( o ) {
// send to worker
ammo.send( 'add', o );
}
view.ellipsoidMesh = function ( o ) {
var max = o.lng;
var points = [];
var ar = o.a;
var i, j, k, v, n;
// create temp convex geometry and convert to buffergeometry
for( i = 0; i<max; i++ ){
n = i*3;
points.push(new THREE.Vector3(ar[n], ar[n+1], ar[n+2]));
}
var gt = new THREE.ConvexGeometry( points );
var indices = new Uint32Array( gt.faces.length * 3 );
var vertices = new Float32Array( max * 3 );
var order = new Float32Array( max );
//var normals = new Float32Array( max * 3 );
//var uvs = new Float32Array( max * 2 );
// get new order of vertices
var v = gt.vertices;
var i = max, j, k;
while(i--){
j = max;
while(j--){
n = j*3;
if(ar[n]==v[i].x && ar[n+1]==v[i].y && ar[n+2]==v[i].z) order[j] = i;
}
}
i = max
while(i--){
n = i*3;
k = order[i]*3;
/*vertices[n] = v[i].x;
vertices[n+1] = v[i].y;
vertices[n+2] = v[i].z;*/
vertices[k] = ar[n];
vertices[k+1] = ar[n+1];
vertices[k+2] = ar[n+2];
}
// get indices of faces
var i = gt.faces.length;
while(i--){
n = i*3;
var face = gt.faces[i];
indices[n] = face.a;
indices[n+1] = face.b;
indices[n+2] = face.c;
}
//console.log(gtt.vertices.length)
var g = new THREE.BufferGeometry();
g.setIndex( new THREE.BufferAttribute( indices, 1 ) );
g.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
g.addAttribute('color', new THREE.BufferAttribute( new Float32Array( max * 3 ), 3 ));
g.addAttribute('order', new THREE.BufferAttribute( order, 1 ));
//g.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
//g.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
g.computeVertexNormals();
extraGeo.push( g );
gt.dispose();
//g.addAttribute('color', new THREE.BufferAttribute( new Float32Array( max * 3 ), 3 ));
var mesh = new THREE.Mesh( g, mat.ball );
this.setName( o, mesh );
mesh.softType = 3;
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
softs.push( mesh );
}
//--------------------------------------
//
// TERRAIN
//
//--------------------------------------
view.terrain = function ( o ) {
var i, x, y, n, c;
o.div = o.div == undefined ? [64,64] : o.div;
o.size = o.size == undefined ? [100,10,100] : o.size;
o.pos = o.pos == undefined ? [0,0,0] : o.pos;
o.dpos = o.dpos == undefined ? [0,0,0] : o.dpos;
o.complexity = o.complexity == undefined ? 30 : o.complexity;
o.lng = o.div[0] * o.div[1];
o.hdata = new Float32Array( o.lng );
if( !perlin ) perlin = new Perlin();
var sc = 1 / o.complexity;
var r = 1 / o.div[0];
var rx = (o.div[0] - 1) / o.size[0];
var rz = (o.div[1] - 1) / o.size[2];
var colors = new Float32Array( o.lng * 3 );
var g = new THREE.PlaneBufferGeometry( o.size[0], o.size[2], o.div[0] - 1, o.div[1] - 1 );
g.rotateX( -Math.PI90 );
var vertices = g.attributes.position.array;
i = o.lng;
while(i--){
n = i * 3;
x = i % o.div[0];
y = ~~ ( i * r );
c = 0.5 + ( perlin.noise( (x+(o.dpos[0]*rx))*sc, (y+(o.dpos[2]*rz))*sc ) * 0.5); // from 0 to 1
o.hdata[ i ] = c * o.size[ 1 ]; // final h size
vertices[ n + 1 ] = o.hdata[i];
colors[ n ] = c;
colors[ n + 1 ] = c;
colors[ n + 2 ] = c;
}
g.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
g.computeBoundingSphere();
g.computeVertexNormals();
extraGeo.push( g );
var mesh = new THREE.Mesh( g, mat.terrain );
mesh.position.set( o.pos[0], o.pos[1], o.pos[2] );
mesh.castShadow = false;
mesh.receiveShadow = true;
this.setName( o, mesh );
scene.add( mesh );
terrains.push( mesh );
// send to worker
ammo.send( 'add', o );
if(shadowGround) scene.remove( shadowGround );
};
view.moveTerrain = function ( o ) {
};
//--------------------------------------
//
// OBJECT NAME
//
//--------------------------------------
view.setName = function ( o, mesh ) {
if( o.name !== undefined ){
byName[o.name] = mesh;
mesh.name = o.name;
}
};
view.getByName = function (name){
return byName[name] || null;
};
//--------------------------------------
//
// UPDATE OBJECT
//
//--------------------------------------
view.update = function(){
this.bodyStep();
this.heroStep();
this.carsStep();
this.softStep();
}
view.bodyStep = function(){
if( !meshs.length ) return;
meshs.forEach( function( b, id ) {
var n = id * 8;
var s = Br[n];
if ( s > 0 ) {
if ( b.material.name == 'sleep' ) b.material = mat.move;
if( s > 50 && b.material.name == 'move' ) b.material = mat.movehigh;
else if( s < 50 && b.material.name == 'movehigh') b.material = mat.move;
b.position.set( Br[n+1], Br[n+2], Br[n+3] );
b.quaternion.set( Br[n+4], Br[n+5], Br[n+6], Br[n+7] );
} else {
if ( b.material.name == 'move' || b.material.name == 'movehigh' ) b.material = mat.sleep;
}
});
};
view.heroStep = function(){
if(heros.length == 0 ) return;
heros.forEach( function( b, id ) {
var n = id * 8;
b.userData.speed = Hr[n] * 100;
b.position.set( Hr[n+1], Hr[n+2], Hr[n+3] );
b.quaternion.set( Hr[n+4], Hr[n+5], Hr[n+6], Hr[n+7] );
});
};
view.carsStep = function(){
if( !cars.length ) return;
cars.forEach( function( b, id ) {
var n = id * 56;
//carsSpeed[id] = Cr[n];
b.userData.speed = Cr[n];
b.position.set( Cr[n+1], Cr[n+2], Cr[n+3] );
b.quaternion.set( Cr[n+4], Cr[n+5], Cr[n+6], Cr[n+7] );
//b.axe.position.copy( b.body.position );
//b.axe.quaternion.copy( b.body.quaternion );
var j = b.userData.NumWheels, w;
if(b.userData.helper){
if( j == 4 ){
w = 8 * ( 4 + 1 );
b.userData.helper.updateSuspension(Cr[n+w+0], Cr[n+w+1], Cr[n+w+2], Cr[n+w+3]);
}
}
while(j--){
w = 8 * ( j + 1 );
//if( j == 1 ) steering = a[n+w];// for drive wheel
//if( j == 1 ) b.axe.position.x = Cr[n+w];
//if( j == 2 ) b.axe.position.y = Cr[n+w];
//if( j == 3 ) b.axe.position.z = Cr[n+w];
b.userData.w[j].position.set( Cr[n+w+1], Cr[n+w+2], Cr[n+w+3] );
b.userData.w[j].quaternion.set( Cr[n+w+4], Cr[n+w+5], Cr[n+w+6], Cr[n+w+7] );
}
});
};
view.softStep = function(){
if( !softs.length ) return;
var softPoints = 0;
softs.forEach( function( b, id ) {
var n, c, cc, p, j, k;
var t = b.softType; // type of softBody
var order = null;
var isWithColor = b.geometry.attributes.color ? true : false;
var isWithNormal = b.geometry.attributes.normal ? true : false;
p = b.geometry.attributes.position.array;
if(isWithColor) c = b.geometry.attributes.color.array;
if( t == 5 || t == 4 ){ // softTriMesh // softConvex
var max = b.geometry.numVertices;
var maxi = b.geometry.maxi;
var pPoint = b.geometry.pPoint;
var lPoint = b.geometry.lPoint;
j = max;
while(j--){
n = (j*3) + softPoints;
if( j == max-1 ) k = maxi - pPoint[j];
else k = pPoint[j+1] - pPoint[j];
var d = pPoint[j];
while(k--){
var id = lPoint[d+k]*3;
p[id] = Sr[n];
p[id+1] = Sr[n+1];
p[id+2] = Sr[n+2];
}
}
}else{
if( b.geometry.attributes.order ) order = b.geometry.attributes.order.array;
//if( m.geometry.attributes.same ) same = m.geometry.attributes.same.array;
j = p.length;
n = 2;
if(order!==null) {
j = order.length;
while(j--){
k = order[j] * 3;
n = j*3 + softPoints;
p[k] = Sr[n];
p[k+1] = Sr[n+1];
p[k+2] = Sr[n+2];
cc = Math.abs(Sr[n+1]/10);
c[k] = cc;
c[k+1] = cc;
c[k+2] = cc;
}
} else {
while(j--){
p[j] = Sr[j+softPoints];
if(n==1){
cc = Math.abs(p[j]/10);
c[j-1] = cc;
c[j] = cc;
c[j+1] = cc;
}
n--;
n = n<0 ? 2 : n;
}
}
}
if(t!==2) b.geometry.computeVertexNormals();
b.geometry.attributes.position.needsUpdate = true;
if(isWithNormal){
var norm = b.geometry.attributes.normal.array;
j = max;
while(j--){
if( j == max-1 ) k = maxi - pPoint[j];
else k = pPoint[j+1] - pPoint[j];
var d = pPoint[j];
var ref = lPoint[d]*3;
while(k--){
var id = lPoint[d+k]*3;
norm[id] = norm[ref];
norm[id+1] = norm[ref+1];
norm[id+2] = norm[ref+2];
}
}
b.geometry.attributes.normal.needsUpdate = true;
}
if(isWithColor) b.geometry.attributes.color.needsUpdate = true;
b.geometry.computeBoundingSphere();
if( t == 5 ) softPoints += b.geometry.numVertices * 3;
else softPoints += p.length;
});
};
//--------------------------------------
// SHADOW
//--------------------------------------
view.removeShadow = function(){
if(!isWithShadow) return;
isWithShadow = false;
renderer.shadowMap.enabled = false;
if(shadowGround) scene.remove(shadowGround);
scene.remove(light);
scene.remove(ambient);
};
view.setShadowPosY = function( y ){
spy = y;
if(shadowGround) shadowGround.position.y = spy;
}
view.addShadow = function(){
if(isWithShadow) return;
isWithShadow = true;
renderer.shadowMap.enabled = true;
renderer.shadowMap.soft = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.cullFace = THREE.CullFaceBack;
if(!terrains.length){
shadowGround = new THREE.Mesh( new THREE.PlaneBufferGeometry( 200, 200, 1, 1 ), TransparentShadow(0x040205, 0.5) );
shadowGround.geometry.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI*0.5));
shadowGround.position.y = spy;
shadowGround.castShadow = false;
shadowGround.receiveShadow = true;
scene.add( shadowGround );
}
light = new THREE.DirectionalLight( 0xffffff, 1 );
light.position.set( -3, 50, 5 );
//light = new THREE.SpotLight( 0xffffff, 1, 0, Math.PI / 2, 10, 2 );
//light.position.set( 0, 100, 0 );
light.target.position.set( 0, 0, 0 );
light.castShadow = true;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
light.shadowCameraNear = 25;
light.shadowCameraFar = 170;
light.shadowDarkness = 1;
light.shadowBias = -0.005;
var c = 70;
light.shadowCameraRight = c;
light.shadowCameraLeft = -c;
light.shadowCameraTop = c;
light.shadowCameraBottom = -c;
//light.shadowCameraFov = 80;
//light.shadowCameraFov = 70;
//scene.add( new THREE.CameraHelper( light.shadow.camera ) );
scene.add( light );
ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
/*ambient = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.8 );
ambient.color.setHSL( 0.6, 1, 0.6 );
ambient.groundColor.setHSL( 0.095, 1, 0.75 );
ambient.position.set( 0, 10, 0 );
scene.add( ambient );*/
}
return view;
})();
|
const User = require("./user-model");
const Gemstone = require("./gemstone-model");
const Data = require("./data-initilize");
module.exports = {
User,
Gemstone,
Data
}; |
import axios from 'axios'
/**
* This is an example SYNC action creator
* it simply returns an action object
*/
export const somethingReceivedActionCreator = response => ({
type: 'SOMETHING_RECEIVED',
payload: response,
})
/**
* This is an example ASYNC action creator
* it returns a function that is passed `dispatch` function by redux
* when it is called.
*
* Inside that function you can call any async action directly.
* @returns {Function}
*/
export const asyncActionCreator = function (id) {
/** this returned function is called when you dispatch the action and the `dispatch` function
* is passed as an argument to it
*/
return function (dispatch) {
return axios.get('/asd/' + id)
.then(response => dispatch(somethingReceivedActionCreator(response)))
// .catch(error => dispatch(failedActionCreator(error)))
}
}
/**
* ES6 way to write the above (preferred) =>
*/
export const asyncActionCreatorES6 = url => dispatch =>
axios.get(url)
.then(response => dispatch(somethingReceivedActionCreator(response)))
// .catch(error => dispatch(failedActionCreator(error)))
|
module.exports = {"AlegreyaSansSC":{"black":"AlegreyaSansSC-Black.ttf","blackitalics":"AlegreyaSansSC-BlackItalic.ttf","bold":"AlegreyaSansSC-Bold.ttf","bolditalics":"AlegreyaSansSC-BoldItalic.ttf","extrabold":"AlegreyaSansSC-ExtraBold.ttf","extrabolditalics":"AlegreyaSansSC-ExtraBoldItalic.ttf","italics":"AlegreyaSansSC-Italic.ttf","light":"AlegreyaSansSC-Light.ttf","lightitalics":"AlegreyaSansSC-LightItalic.ttf","medium":"AlegreyaSansSC-Medium.ttf","mediumitalics":"AlegreyaSansSC-MediumItalic.ttf","normal":"AlegreyaSansSC-Regular.ttf","thin":"AlegreyaSansSC-Thin.ttf","thinitalics":"AlegreyaSansSC-ThinItalic.ttf"}}; |
var router = require('express').Router(),
usersController = require('../controllers/users.js'),
jwtUtils = require('../middlewares/jwt-validator.js'),
userSchema = require('../json-schemas/user.js'),
schemaValidator = require('../middlewares/schema-validator.js');
router.post('/',
jwtUtils.verifyToken,
schemaValidator.validate(userSchema.whenCreate),
usersController.save
);
router.get('/',
jwtUtils.verifyToken,
usersController.getAll
);
router.get('/:userId',
jwtUtils.verifyToken,
usersController.getOne
);
router.put('/:userId',
jwtUtils.verifyToken,
schemaValidator.validate(userSchema.whenUpdate),
usersController.update
);
router.delete('/:userId',
jwtUtils.verifyToken,
usersController.remove
);
module.exports = router;
|
//! moment.js locale configuration
//! locale : dutch (nl)
//! author : Joris Röling : https://github.com/jjupiter
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) {
'use strict';
var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');
var nl = moment.defineLocale('nl', {
months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
monthsShort: function (m, format) {
if (/-MMM-/.test(format)) {
return monthsShortWithoutDots[m.month()];
} else {
return monthsShortWithDots[m.month()];
}
},
monthsParseExact: true,
weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),
weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'),
weekdaysMin: 'Zo_Ma_Di_Wo_Do_Vr_Za'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD-MM-YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm'
},
calendar: {
sameDay: '[vandaag om] LT',
nextDay: '[morgen om] LT',
nextWeek: 'dddd [om] LT',
lastDay: '[gisteren om] LT',
lastWeek: '[afgelopen] dddd [om] LT',
sameElse: 'L'
},
relativeTime: {
future: 'over %s',
past: '%s geleden',
s: 'een paar seconden',
m: 'één minuut',
mm: '%d minuten',
h: 'één uur',
hh: '%d uur',
d: 'één dag',
dd: '%d dagen',
M: 'één maand',
MM: '%d maanden',
y: 'één jaar',
yy: '%d jaar'
},
ordinalParse: /\d{1,2}(ste|de)/,
ordinal: function (number) {
return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
},
week: {
dow: 1, // Monday is the first day of the week.
doy: 4 // The week that contains Jan 4th is the first week of the year.
}
});
return nl;
})); |
import webpack from 'webpack';
import commonsChunk from 'webpack/lib/optimize/CommonsChunkPlugin';
import uglifyWebpack from 'webpack/lib/optimize/UglifyJsPlugin';
import autoprefixer from 'autoprefixer';
import poststylus from 'poststylus';
export default {
watch: true,
entry:{
app: './src/Main.js',
ng2: [
'zone.js/dist/zone',
'zone.js/dist/long-stack-trace-zone',
'reflect-metadata',
'@angular/platform-browser-dynamic',
'@angular/platform-browser',
'@angular/http',
'@angular/router',
'@angular/core',
'@angular/compiler',
'@angular/common'
]
},
plugins:[
new commonsChunk('ng2'),
new webpack.optimize.UglifyJsPlugin({
mangle: false,
compress: {
warnings: false,
},
output: {
comments: false,
}
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
__dirname
)
],
output:{
path: './public/js',
filename:'[name].js',
library: 'app',
libraryTarget: 'this'
},
module:{
loaders: [
{test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/},
{test: /\.styl$/, loaders: ['style-loader','css-loader','stylus-loader']},
{test: /\.jade$/, loader: 'jade'},
{test: /\.css$/, loaders: ['style-loader','css-loader']}
]
},
stylus: {
use: [
poststylus(['autoprefixer'])
]
}
};
|
var mongoose = require('mongoose'),
ApiSchema = new mongoose.Schema({
creation_date: {
type: Date,
required: true,
default: Date.now
},
format: {
type: String,
required: true
},
link: {
type: String,
required: true
},
organization: {
type: String,
required: true
},
title: {
type: String,
required: true
},
type: {
type: String,
required: true
}
});
module.exports = mongoose.model('Api', ApiSchema);
|
// get a connection to the DB
var db = require('../lib/storage').db
, hash = require('../lib/hash')
, Cart = require('../models/Cart').Cart;
var UserSchema = db.Schema({
firstName: String,
lastName: String,
email: String,
salt: String,
hash: String,
cart: { type: db.Schema.Types.ObjectId, ref: 'Cart' }
});
UserSchema.statics.isValidUserPassword = function(email, password, done) {
this.findOne({email : email}, function(err, user){
if(err) return done(err);
if(!user) return done(null, false, { message : 'Incorrect email.' });
hash(password, user.salt, function(err, hash){
if(err) return done(err);
if(hash == user.hash) return done(null, user);
done(null, false, {
message : 'Incorrect password'
});
});
});
};
UserSchema.statics.signup = function(email, password, fname, lname, done){
var User = this;
hash(password, function(err, salt, hash) {
if(err) throw err;
if (err) return done(err);
Cart.create({
products: []
}, function(err, cart) {
if(err) {
cart = null
}
User.create({
firstName : fname,
lastName : lname,
email : email,
salt : salt,
hash : hash,
cart: (cart ? [db.Types.ObjectId(cart.id)] : null)
}, function(err, user){
if (err) return done(err);
done(null, user);
});
});
});
};
UserSchema.statics.getByEmail = function(email, done) {
this.findOne({email : email})
.populate('cart')
.exec(function(err, user) {
console.log('gotByEmail: ', user);
done(err, user);
});
};
UserSchema.statics.getById = function(id, done) {
this.findOne({ _id: id })
.populate('cart')
.exec(function(err, user) {
console.log('getById: ', user, id);
done(err, user);
});
};
/*
UserSchema.statics.findOrCreateFaceBookUser = function(profile, done){
var User = this;
this.findOne({ 'facebook.id' : profile.id }, function(err, user){
if(err) throw err;
// if (err) return done(err);
if(user){
done(null, user);
}else{
User.create({
email : profile.emails[0].value,
facebook : {
id: profile.id,
email: profile.emails[0].value,
name: profile.displayName
}
}, function(err, user){
if(err) throw err;
// if (err) return done(err);
done(null, user);
});
}
});
}
*/
var User = db.model("User", UserSchema);
module.exports = User; |
'use strict'
module.exports = (req, allowedOrigins) => {
if (allowedOrigins === '*') return '*'
if (allowedOrigins != null) {
const origins = allowedOrigins.split(',')
return origins.find((origin) => origin.includes(req.headers.origin) || origin.includes(req.headers.host))
}
} |
jQuery.fn.highlight=function(c,e,d,b){var e=e||"highlight";if(d==undefined&&b==undefined){var d="mouseover";var b="mouseout"}else{if(d==b||d!=undefined&&b==undefined){var a=true}}this.each(function(){var f=this.tagName.toLowerCase();if(f=="form"){c=c||"li";var g=jQuery("textarea, select, multi-select, :text, :image, :password, :radio, :checkbox, :file",this);g.bind("focus",function(){var h=jQuery(this).parents(c);var i=jQuery(h.get(0));i.addClass(e)});g.bind("blur",function(){var h=jQuery(this).parents(c);var i=jQuery(h.get(0));i.removeClass(e)})}else{if(f.match(/^(table|tbody)$/)!=null){c=c||"tr"}else{if(f.match(/^(ul|ol)$/)!=null){c=c||"li"}else{c="*"}}var g=jQuery(c,this);if(a){g.bind(d,function(){if(jQuery(this).hasClass(e)){jQuery(this).removeClass(e)}else{jQuery(this).addClass(e)}})}else{g.bind(d,function(){jQuery(this).addClass(e)});g.bind(b,function(){jQuery(this).removeClass(e)})}}})}; |
import Geometry from './geometry';
import { vec3, mat4 } from 'gl-matrix';
/**
* A cube of size 1x1x1
*/
export class Cube extends Geometry {
constructor() {
const points = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1];
super({
vertices: points.map(n => 0.5 * n),
normals: points.map(n => Math.sqrt(3) / 3 * n),
texcoords: [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1],
indices: [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 1, 9, 8, 9, 10, 11, 12, 13, 11, 13, 14, 15, 16, 2, 15, 2, 17, 15, 18, 19, 15, 19, 10]
});
}
}
/**
* A plane of size 1x1 in the xz-plane, facing up.
* If a texture map is used, no normals are generated, use generateNormals() manually.
*/
export class Plane extends Geometry {
constructor({ size = 8, heightmap = null, repeat = false } = {}) {
let data = null;
let width, height;
if (heightmap === null) {
width = size;
height = size;
} else {
width = heightmap.width;
height = heightmap.height;
data = heightmap.image.data;
}
const vertexCount = width * height;
const triangleCount = (width - 1) * height * 2;
const vertices = new Float32Array(3 * vertexCount);
const texcoords = new Float32Array(2 * vertexCount);
const indices = new Uint16Array(3 * triangleCount);
let x, z, offset;
for (x = 0; x < width; ++x) {
for (z = 0; z < height; ++z) {
offset = x + z * width;
vertices[3 * offset] = x / (width - 1) - 0.5;
vertices[3 * offset + 1] = data ? data[4 * offset] / 255 : 0; // Sample R-value in texture
vertices[3 * offset + 2] = z / (height - 1) - 0.5;
texcoords[2 * offset] = repeat ? (x % 2 !== 0) : x / width;
texcoords[2 * offset + 1] = repeat ? (z % 2 !== 0) : 1 - z / height;
}
}
for (x = 0; x < width - 1; ++x) {
for (z = 0; z < height - 1; ++z) {
offset = 6 * (x + z * (width - 1));
// Triangle 1
indices[offset] = x + z * width;
indices[offset + 1] = x + (z+1) * width;
indices[offset + 2] = x+1 + z * width;
// Triangle 2
indices[offset + 3] = x+1 + z * width;
indices[offset + 4] = x + (z+1) * width;
indices[offset + 5] = x+1 + (z+1) * width;
}
}
const config = { vertices, texcoords, indices };
if (!data) {
const normals = new Float32Array(vertices.length);
// Set all Y-values to 1
for (let offset = 1, len = vertices.length; offset < len; offset += 3) {
normals[offset] = 1;
}
config.normals = normals;
}
super(config);
this.heightmap = heightmap;
}
}
|
/// <reference path="../main.js" />
function viewsGenerate() {
gameViews.viewNavbar = {
player: player,
dayCount: dayCount,
dayTimerToggle: dayTimer.timer.myToggle,
//dayTimer: dayTimer,
food: player.cityCapital.food,
population: player.cityCapital.population,
research: player.research,
isRunning: ko.observable(false)
};
gameViews.viewEmpireOptions = {
player: player
};
gameViews.viewGameOptions = {
gameOptions: gameOptions
};
gameViews.viewTutorialModal = {
gameVariables: gameVariables
};
gameViews.viewEmpireTechnology = {
technology: player.technology,
advancedTech: gameOptions.advancedTech
};
gameViews.viewCapitalCity = {
population: player.cityCapital.population,
resource: player.cityCapital.resource,
buildingPrimary: player.cityCapital.buildingPrimary,
buildingFactory: player.cityCapital.buildingFactory,
buildingStorage: player.cityCapital.buildingStorage,
buildingHouse: player.cityCapital.buildingHouse,
tool: player.cityCapital.tool,
machine: player.cityCapital.machine,
item: player.cityCapital.item
};
}
var gameViews = {
newGameOptions: {
newGame: function() {
newGame();
$("#newGameOptions").modal("hide");
},
loadGame: function() {
loadGame();
$("#newGameOptions").modal("hide");
}
}
};
function viewsApply() {
ko.applyBindings(gameViews.viewNavbar, $("#navbar")[0]);
ko.applyBindings(gameViews.viewEmpireOptions, $("#empireOptions")[0]);
ko.applyBindings(gameViews.viewGameOptions, $("#gameOptions")[0]);
ko.applyBindings(gameViews.viewGameOptions, $("#hotkeyOptions")[0]);
ko.applyBindings(gameViews.viewTutorialModal, $("#tutorialModal")[0]);
ko.applyBindings(gameViews.viewEmpireTechnology, $("#mainContentEmpireTechnology")[0]);
ko.applyBindings(gameViews.viewCapitalCity, $("#mainContentPlayerCityCapital")[0]);
}
function viewsClear() {
ko.cleanNode($("#navbar")[0]);
ko.cleanNode($("#empireOptions")[0]);
ko.cleanNode($("#gameOptions")[0]);
ko.cleanNode($("#hotkeyOptions")[0]);
ko.cleanNode($("#tutorialModal")[0]);
ko.cleanNode($("#mainContentEmpireTechnology")[0]);
ko.cleanNode($("#mainContentPlayerCityCapital")[0]);
} |
var fs = require('fs');
var crypto = require('crypto')
var algorithm = 'aes-256-gcm'
var password = process.env.FIREBASE_PASSWORD
var iv = process.env.FIREBASE_IV
function encrypt(text) {
var cipher = crypto.createCipheriv(algorithm, password, iv)
var encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex');
var tag = cipher.getAuthTag();
return {
content: encrypted,
tag: tag
};
}
fs.readFile('private.json', 'utf8', function(err, data) {
if (err) throw err;
fs.writeFile('private.enc.json', JSON.stringify(encrypt(data)), 'utf8', function(err) {
if (err) throw err;
});
});
|
import React, {Component} from "react"
import {HBox, VBox, Spacer} from "appy-comps";
import {Input, ListView, Scroll, Toolbar} from './GUIUtils'
import RemoteDB from "./RemoteDB";
export default class FileViewer extends Component {
constructor(props) {
super(props);
this.db = new RemoteDB("files");
this.db.connect();
this.files = this.db.makeLiveQuery({})
this.files.openFile = (file) => {
if(file.type === 'note') {
this.db.sendMessage({
type:'command',
target: 'system',
command: "open",
withApp: 'texteditor',
withFile:file.id
});
}
}
this.state = {
view: 'grid',
sources: [
{
title: 'Places',
type: 'header'
},
{
title: 'Photos',
type: 'source',
},
{
type:'source',
title:'Documents'
},
{
type:'source',
title:'trash'
},
{
title:'Queries',
type:'header'
},
{
type:'source',
title:'Recent'
},
{
type:'source',
title:'All By Date'
},
{
type:'source',
title:'All MP3s'
},
{
type:'source',
title:'tag == special'
},
]
}
this.db.whenConnected(()=>{
this.db.sendMessage({
type:'command',
target: 'system',
command: "resize",
appid: this.props.appid,
width:700,
height:350
});
})
}
render() {
return <VBox grow>
<Toolbar>
<button className="fa fa-table" onClick={()=>this.setState({"view":"grid"})}/>
<button className="fa fa-th-list" onClick={()=>this.setState({"view":"list"})}/>
<Spacer/>
<Input className='search' db={this.db}/>
</Toolbar>
<div className="grid-2">
{this.renderSourceList(this.state.sources)}
{this.renderFileList(this.files,this.state.view)}
</div>
</VBox>
}
renderSourceList(sources) {
const srcs = sources.map((s,i)=>{
const sty = {
padding:'0.25em',
}
if(s.type === 'header') {
sty.backgroundColor = 'gray'
sty.color = 'white';
sty.fontWeight = 'bold'
}
return <li key={i} style={sty}>{s.title}</li>
})
return <ul style={{
backgroundColor:'lightGray',
margin:0,
padding:0,
}}
>{srcs}</ul>
}
renderFileList(files, view) {
if(view === 'grid') {
return <ListView model={files} template={FileIconTemplate} className="listview-grid"/>
}
return <ListView model={files} template={FileListItemTemplate}/>
}
}
const chooseIcon = (type) => {
if(type === 'system') return 'fa-gears'
if(type === 'event') return 'fa-calendar'
if(type === 'alarm') return 'fa-clock-o'
if(type === 'song') return 'fa-file-audio-o'
if(type === 'contact') return 'fa-address-card-o'
if(type === 'note') return 'fa-file-text-o'
if(type === 'image') return 'fa-file-image-o'
if(type === 'email') return 'fa-envelope-o'
if(type === 'message') return 'fa-comment-o'
if(type === 'clip') return 'fa-paste'
if(type === 'script') return 'fa-code'
if(type === 'todo') return 'fa-list-ul'
if(type === 'folder') return 'fa-folder-o'
return 'fa-file-o'
}
function openFile(file) {
console.log("opening the file",file)
}
const FileIconTemplate = (props) => {
return <VBox className="file" onDoubleClick={()=>props.model.openFile(props.item)}>
<i className={` file-icon fa ${chooseIcon(props.item.type)}`}/>
{props.item.type}
</VBox>
}
const FileListItemTemplate = (props) => {
return <HBox>
<b>{props.item.type}</b>
<i>item</i>
</HBox>
}
|
module.exports = function( Gibber ) {
var GE,
$ = Gibber.dollar //require( './dollar' )
var Browser = {
demoColumn: null,
userFilesLoaded: false,
setupSearchGUI : function() {
var btns = $( '.searchOption' )
for( var i = 0; i < btns.length; i++ ) {
!function() {
var num = i, btn = btns[ num ]
btn.state = num === 1
if( btn.state ) $( btn ).css({ backgroundColor:'#666' })
$( btn ).on( 'click', function() {
for( var j = 0; j < btns.length; j++ ) {
var bgColor
btns[ j ].state = btns[ j ] === btn
bgColor = btns[ j ].state ? '#666' : '#000'
$( btns[ j ] ).css({ backgroundColor:bgColor })
}
})
}()
}
//btns[0].click()
$( '.search input').on( 'keypress', function(e) { if( e.keyCode === 13 ) { $('.browserSearch').click() }})
$( '.browserSearch' ).on( 'click', GE.Browser.search )
},
column: null,
userfiles: null,
currentBrowserSection: null,
isLoaded: false,
open: function() {
GE = Gibber.Environment
this.column = self = GE.Layout.addColumn({ header:'Browse Giblets', type:'info' })
this.column.onclose = function() {
Browser.isLoaded = false
}
$.ajax({
url: GE.SERVER_URL + "/browser",
dataType:'html'
})
.done( Browser.onLoad )
if( GE.Account.nick ) {
if( Browser.files && Browser.files.userfiles.length > 0 ) {
Browser.showUserFiles( Browser.files.userfiles )
}else{
$.ajax({
type:'POST',
url: GE.SERVER_URL + "/userfiles",
data:{ username:GE.Account.nick },
dataType:'json',
})
.done( GE.Browser.showUserFiles )
}
}else{
$.subscribe( '/account/login', function( _name ) {
$.ajax({
type:'POST',
url: GE.SERVER_URL + "/userfiles",
data:{ username:_name },
dataType:'json',
})
.done( GE.Browser.showUserFiles )
})
}
$.subscribe( '/account/logout', function( _name ) {
$( '#browser_userfiles' ).find( 'li' ).remove()
GE.Browser.files.userfiles.length = 0
})
},
_onload : null,
onLoad: function( data ) {
var browserHTML = $( data )
Browser.createLayout( browserHTML )
GE.Browser.setupSearchGUI()
Browser.isLoaded = true
if( Browser._onload !== null ) {
Browser._onload()
Browser._onload = null
}
},
createLayout : function( browserHTML ) {
$( Browser.column.bodyElement ).append( browserHTML[0] )
$( 'head' ).append( browserHTML[1] )
$( '#search_button' ).on( 'click', Browser.search )
GE.Layout.setColumnBodyHeight( Browser.column )
$( '#browser_tutorials_button' ).on( 'click', Browser.openBrowserSection.bind( Browser, 'tutorials' ) )
$( '#browser_demos_button' ).on( 'click', Browser.openBrowserSection.bind( Browser, 'demos' ) )
$( '#browser_search_button' ).on( 'click', Browser.openBrowserSection.bind( Browser, 'search' ) )
$( '#browser_recent_button' ).on( 'click', Browser.openBrowserSection.bind( Browser, 'recent' ) )
$( '#browser_user_button' ).on( 'click', Browser.openBrowserSection.bind( Browser, 'user' ) )
Browser.currentBrowserSection = $('#browser_demos')
Browser.createLinks()
},
createLinks : function() {
var linksDivs = $( '.browserLinks' ),
types = [ 'demosAudio', 'demosVisual', 'demosAudiovisual','audio', '_2d', '_3d', 'misc', 'recent' ],
prev
for( var i = 0; i < linksDivs.length; i++ ) {
(function() {
var cell = linksDivs[ i ]
var links = $( cell ).find( 'li' )
for( var j = 0; j < links.length; j++ ) {
(function() {
// TODO: could this be any hackier???
var num = j, type = types[ i ], link = links[j], demoTypeName = type.slice(5).toLowerCase()
var pubCategory = Browser.files[ type ] || Browser.files.demos[ demoTypeName ]
if( typeof pubCategory !== 'undefined' ) {
var pub = pubCategory[ num ], obj, id
if( typeof pub === 'undefined' ) {
console.log( 'UNDEFINED', type, num )
return;
}
obj = pub.value || pub, // recently added has slightly different format
id = pub.id || obj._id // see above
$( link ).on( 'mouseover', function() {
$( link ).css({ background:'#444' })
if( prev ) {
$( prev ).css({ background:'transparent' })
}
prev = link
$( '#browser_title' ).text( id.split('/')[2].split('*')[0] )//$( link ).text() )
$( '#browser_notes' ).text( obj.notes )
$( '#browser_tags' ).text( obj.tags ? obj.tags.toString() : 'none' )
$( '#browser_author' ).text( id.split('/')[0] )
})
}
})()
}
})()
}
},
showUserFiles: function( data ) {
if( !Browser.isLoaded ) {
Browser._onload = Browser.showUserFiles.bind( Browser, data )
return
}
var userdiv = $( '#browser_userfiles' ),
list = $( '<ul>' ),
prev
userdiv.empty()
// var edit = $('<button>edit files</button>')
// .css({ right:0, marginLeft:'4em', position:'relative' })
// .on('click', function() { Browser.showFileEditingButtons() })
//
// $('#browser_user .browserHeader h2').append( edit )
Browser.files.userfiles = data.files || data
for( var j = 0; j < Browser.files.userfiles.length; j++ ) {
!function() {
var num = j,
file = Browser.files.userfiles[ num ],
obj = file.value,
id = file.id,
link
//GE.Browser.files.userfiles.push( file )
link = $('<li>')
.text( id.split('/')[2] )
.on( 'click', function() {
Gibber.Environment.Browser.openCode( id )
})
$( link ).on( 'mouseover', function() {
$( link ).css({ background:'#444' })
if( prev ) {
$( prev ).css({ background:'transparent' })
}
prev = link
$( '#browser_title' ).text( id.split('/')[2].split('*')[0] )//$( link ).text() )
$( '#browser_notes' ).text( obj.notes )
$( '#browser_tags' ).text( obj.tags ? obj.tags.toString() : 'none' )
$( '#browser_author' ).text( id.split('/')[0] )
})
list.append( link )
}()
}
userdiv.append( list )
},
showFileEditingButtons: function() {
var list = $( '#browser_userfiles ul li')
for( var i = 1; i < list.length; i++ ) {
!function() {
var listData = Browser.files.userfiles[ i ],
li = list[ i ]
$(li).append( $( '<button>e</button>' ).css({ float:'right', marginLeft:'.5em', position:'relative', height:$( li ).height() }) )
var deleteBtn = $( '<button>x</button>' )
.css({ float:'right', height:$( li ).height() })
.on( 'click', function( e ) {
e.stopPropagation()
var msgtxt = "Are you sure you want to delete " + listData.id.split('/')[2] + "? This operation cannot be undone."
GE.Message.confirm( msgtxt, 'cancel', 'delete' )
.done( function( shouldDelete ) {
if( shouldDelete ) {
$.ajax({
type:'POST',
url: GE.SERVER_URL + "/deleteUserFile",
data:listData,
dataType:'json',
})
.then( function( data ) {
console.log( "DELETED?", data )
li.remove()
},
function(e) {
console.log("SOME TYPE OF ERROR", e )
})
}
})
})
$(li).append( deleteBtn )
}()
}
},
openBrowserSection: function( section ) {
GE.Browser.currentBrowserSection.hide()
GE.Browser.currentBrowserSection = $( '#browser_' + section )
GE.Browser.currentBrowserSection.show()
},
// publication name : author : rating : code fragment?
search : function(e) {
var btns = $( '.searchOption' ),
btnText = [ 'tags','code','author' ],
queryFilter = 'code', query = null
query = $( '.browser .search input' ).val()
if( query === '' ) {
GE.Message.post( 'You must type in a search query.' )
return
}
for( var i = 0; i < btns.length; i++ ) {
if( btns[ i ].state ){
queryFilter = btnText[ i ]
break;
}
}
var data = {
'query': query,
filter: queryFilter
}
$( '.searchResults' ).remove()
// var sr = $('<div class="searchResults">').css({ width:'5em', height:'5em', display:'block', position:'relative', 'box-sizing': 'content-box !important' })
// var spinner = GE.Spinner.spin( sr )
$( '.browser .search td' ).append( $('<p class="searchResults">Getting search results...</p>'))
//var data = { query:$( '#search_field' ).val() }
$.post(
GE.SERVER_URL + '/search',
data,
function ( data ) {
$('.searchResults').remove()
var results = $( '<ul class="searchResults">' ),
count = 0
//console.log( data )
if( data.error ) {
console.error( data.error )
return
}
for( var i = 0; i < data.rows.length; i++ ) {
count++
if( data.rows[i] === null ) continue; // sometimes things go missing...
(function() {
var d = JSON.parse( data.rows[ i ] ),
pubname = d._id,
li = $( '<li>' )
$('.searchResults').remove()
li.html( pubname )
.on( 'click', function() {
GE.Browser.openCode( pubname )
})
.hover( function() {
li.css({ backgroundColor:'#444'})
GE.Browser.displayFileMetadata( d )
},
function() { li.css({ backgroundColor:'rgba(0,0,0,0)' })
})
.css({ cursor: 'pointer' })
results.append( li )
})()
}
var h4 = $('<h4 class="searchResults">Results</h4>').css({ display:'inline-block', width:'10em', marginBottom:0 }),
clearBtn = $('<button class="searchResults">clear results</button>').on('click', function() {
$('.searchResults').remove()
clearBtn.remove()
h4.remove()
})
$( '.browser .search td' ).append( h4, clearBtn )
if( data.rows.length === 0 ) {
$( '.browser .search td' ).append( $('<p class="searchResults">No results were found for your search</p>') )
}
$( '.browser .search td' ).append( results )
},
'json'
)
},
displayFileMetadata: function( obj ) {
$( '#browser_title' ).text( obj._id.split('/')[2].split('*')[0] )//$( link ).text() )
$( '#browser_notes' ).text( obj.notes )
$( '#browser_tags' ).text( obj.tags ? obj.tags.toString() : 'none' )
$( '#browser_author' ).text( obj._id.split('/')[0] )
},
openCode : function( addr ) {
// console.log( "ADDR", addr )
$.post(
GE.SERVER_URL + '/retrieve',
{ address:addr },
function( d ) {
var data = JSON.parse( d ),
col = GE.Layout.addColumn({ fullScreen:false, type:'code', mode: data.language })
col.editor.setValue( data.text )
col.fileInfo = data
col.revision = d // retain compressed version to potentially use as attachement revision if publication is updated
//if( d.author === 'gibber' && d.name.indexOf('*') > -1 ) d.name = d.name.split( '*' )[0] // for demo files with names like Rhythm*audio*
return false
}
)
},
openDemo : function( addr, hasGraphics ) {
// console.log( "ADDR", addr )
$.post(
GE.SERVER_URL + '/retrieve',
{ address:addr },
function( d ) {
//console.log( d )
var data = JSON.parse( d ),
col = Browser.demoColumn === null || typeof Browser.demoColumn === 'undefined' || Browser.demoColumn.isClosed ? GE.Layout.addColumn({ fullScreen:false, type:'code' }) : Browser.demoColumn
col.editor.setValue( data.text )
col.fileInfo = data
col.revision = d // retain compressed version to potentially use as attachement revision if publication is updated
if( data.language && col.mode !== data.language ) {
col.mode === GE.modes.nameMappings[ data.language ] || data.language
col.editor.setOption( 'mode', GE.modes.nameMappings[ col.mode ] )
col.setLanguageSelect( data.language )
}else if ( typeof data.language === 'undefined' && col.mode !== 'javascript' ) {
col.editor.setOption( 'mode', 'javascript' )
col.setLanguageSelect( 'javascript ')
}
Browser.demoColumn = col
if( hasGraphics ) {
GE.Layout.textBGOpacity( .6 )
}else{
GE.Layout.textBGOpacity( 0 )
}
Gibber.clear()
if( Gibber.Environment.Welcome.div !== null ) {
GE.Welcome.close()
}
//run: function( column, script, pos, cm, shouldDelay ) {
GE.modes.javascript.run(
col,
data.text,
{
start:{ line:0, ch:0 },
end:{ line:col.editor.lastLine(), ch:0 }
},
col.editor,
true
)
//if( d.author === 'gibber' && d.name.indexOf('*') > -1 ) d.name = d.name.split( '*' )[0] // for demo files with names like Rhythm*audio*
return false
}
)
},
}
return Browser
}
|
'use strict';
const dotenv = require('dotenv');
const webpack = require('webpack');
const HTMLPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
dotenv.load();
const production = process.env.NODE_ENV === 'production';
let plugins = [
new ExtractTextPlugin('bundle.css'),
new HTMLPlugin({
template: `${__dirname}/app/index.html`
}),
new webpack.DefinePlugin({
__API_URL__: JSON.stringify(process.env.API_URL),
__DEBUG__: JSON.stringify(!production)
}),
new webpack.LoaderOptionsPlugin({
sassLoader: {
includePaths: [`${__dirname}/app/scss`]
}
})
];
if(production) {
plugins = plugins.concat([
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
mangle: true,
compress: {
warnings: true
}
}),
new CleanPlugin()
]);
}
module.exports = {
entry: './app/index.jsx',
devtool: production ? false : 'eval',
plugins,
output: {
path: `${__dirname}/build`,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /.jsx?/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.html$/,
use: 'html-loader'
},
{
test: /\.(woff|ttf|svg|eot).*/,
loader: 'file-loader',
options: {
name: '[path][name].[hash].[ext]',
},
},
{
test: /\.(jpg|jpeg|svg|bmp|tiff|gif|png)$/,
loader: 'file-loader',
options: {
name: '[path][name].[hash].[ext]',
},
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!resolve-url-loader!sass-loader?sourceMap',
})
}
]
}
}; |
const cleanEcrImages = require('./clean_ecr_images/index');
module.exports.handle = (event, context, callback) => {
console.log(event);
cleanEcrImages(event).then(() => {
callback(null, {});
}).catch(e => {
console.error(e);
});
};
|
'use strict';
var mongoose = require('mongoose');
var commentsSchema =
new mongoose.Schema({
userId: {type: String, required: true},
groupId: {type: String, required: true},
isActive: {type: Boolean, default: true},
createdOn: {type: Date, default: Date.now()},
text: {type: String, required: true}
},
{collection: 'comments'});
commentsSchema.index({name: 1, createdBy: 1}, {unique: true});
module.exports = mongoose.model('Comment', require(commentsSchema));
|
import {
getVersions,
retrievePackageJson,
writePackageJson,
getBabelDependencies,
installDependencies,
copyTemplate,
} from '../../lib/helpers';
export default async (npmOptions, { storyFormat = 'csf' }) => {
const [storybookVersion, actionsVersion, linksVersion, addonsVersion] = await getVersions(
npmOptions,
'@storybook/preact',
'@storybook/addon-actions',
'@storybook/addon-links',
'@storybook/addons'
);
copyTemplate(__dirname, storyFormat);
const packageJson = await retrievePackageJson();
packageJson.dependencies = packageJson.dependencies || {};
packageJson.devDependencies = packageJson.devDependencies || {};
packageJson.scripts = packageJson.scripts || {};
packageJson.scripts.storybook = 'start-storybook -p 6006';
packageJson.scripts['build-storybook'] = 'build-storybook';
writePackageJson(packageJson);
const babelDependencies = await getBabelDependencies(npmOptions, packageJson);
installDependencies({ ...npmOptions, packageJson }, [
`@storybook/preact@${storybookVersion}`,
`@storybook/addon-actions@${actionsVersion}`,
`@storybook/addon-links@${linksVersion}`,
`@storybook/addons@${addonsVersion}`,
...babelDependencies,
]);
};
|
/**
* Module dependencies.
*/
var express = require('express'),
// routes = require('./routes'),
repl = require("repl"),
http = require('http'),
path = require('path'),
stylus = require('stylus'),
fluidity = require('fluidity'),
cons = require('consolidate'),
swig = require('swig'),
util = require('util');
// Responder = require('./libs/Responder');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('.html', cons.swig);
app.set('view engine', 'html');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(app.router);
app.use(stylus.middleware({
src: __dirname + '/assets',
dest: __dirname + '/public',
compile: function (str, path) {
return stylus(str)
.set('filename', path)
.set('compress', false)
.use(fluidity());
}
}));
app.use(express['static'](path.join(__dirname, 'public')));
});
var swigInit = function(developmentMode) {
swig.init({
root: __dirname + '/views',
cache: developmentMode ? false : true,
allowErrors: true // allows errors to be thrown and caught by express instead of suppressed by Swig
});
};
app.set('views', __dirname + '/views');
app.configure('development', function(){
console.log("DEVELOPMENT MODE ON");
app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));
swigInit(true);
});
app.configure("production",function() {
swiginit(false);
});
// db = require('mongoskin').db('192.168.122.249:27017/syncitserv',{w:true});
var setupRoutes = function(app,mode) {
var i = 0;
var getTemplateSlice = function(paths) {
var worker = function(paths,excludeLast) {
var np = [],
i = 0;
for (i=0;i<(paths.length-excludeLast);i++) {
np.push(paths[i]);
}
return np;
};
if (paths.length > 3) {
return worker(paths,3);
}
return worker(paths,0);
};
var getTemplateBaseAfterCreation = function(paths) {
var r = getTemplateSlice(paths);
if (r.length > 1) {
r.pop();
return r.join('/');
}
return r.join('/');
};
var getTemplateFromPaths = function(paths) {
return getTemplateSlice(paths).join('/');
};
var responseSelector = (function(responses) {
var responseSelector = new (require('./libs/ResponseSelector'))({
format: { points:16, required: true },
controller: { points:8, required: true },
action: { points:4, required: true },
method: { points:2, required: true },
status: { points:1, required: true }
});
var path = '';
var constructPathObj = function(str) {
var map = ['format','controller','action','method','status'],
i = 0;
r = {};
str = str.split('/');
for (i=0;i<str.length;i++) {
if (str[i].length) {
r[map[i]] = str[i];
}
}
return r;
};
for (path in responses) {
if (responses.hasOwnProperty(path)) {
responseSelector.set(constructPathObj(path),responses[path]);
}
}
return responseSelector;
})({
'json///post/accepted':
function(res,paths,status,data) { res.send(201,data); },
'json///post/created':
function(res,paths,status,data) { res.send(201,data); },
'json///post/validation_error':
function(res,paths,status,data) { res.send(422,data); },
'json///post/unauthorized':
function(res,paths,status,data) { res.send(401,"Unauthorized"); },
'json///post/forbidden':
function(res,paths,status,data) { res.send(403,"Forbidden"); },
'json///post/not_acceptable':
function(res,paths,status,data) { res.send(406,"Not Acceptable"); },
'json///get/ok':
function(res,paths,status,data) { res.send(200,data); },
'json///get/unauthorized':
function(res,paths,status,data) { res.send(401,"Unauthorized"); },
'json///get/forbidden':
function(res,paths,status,data) { res.send(403,"Forbidden"); },
'json///get/not_acceptable':
function(res,paths,status,data) { res.send(406,"Not Acceptable"); },
'html/user/activate/patch/accepted':
function(res,paths,data) {
data.redirect = '/user/'+data.userId;
res.cookie('auth',data.auth);
res.cookie('userId',data.userId);
res.status(202)
.render('user/created',data);
},
'html//session//ok':
function(res,paths,status,data) { res.render('user/register',data); },
'html//session//validation_error':
function(res,paths,status,data) { res.render('user/register',data); },
'html//session//created':
function(res,paths,data) {
var collectionLocation = getTemplateBaseAfterCreation(paths);
data.redirect = '/user/'+data.userId;
res.cookie('auth',data.auth);
res.cookie('userId',data.userId);
res.status(201)
.render(collectionLocation+'/created',data);
},
'html////created':
function(res,paths,status,data) {
res.status(201).render(getTemplateBaseAfterCreation(paths)+'/accepted',data);
},
'html////not_found':
function(res,paths,status,data) {
res.status(404).render(getTemplateFromPaths(paths),data);
},
'html////unauthorized':
function(res,paths,status,data) {
res.status(401).render(getTemplateFromPaths(paths),data);
},
'html////accepted':
function(res,paths,status,data) {
res.status(202).render(getTemplateBaseAfterCreation(paths)+'/accepted',data);
},
'html////ok':
function(res,paths,status,data) {
res.render(getTemplateFromPaths(paths),data);
},
'html////validation_error':
function(res,paths,status,data) {
res.status(422).render(getTemplateFromPaths(paths),data);
}
});
var Utils = require('./libs/dev.utils.js'),
utils = new Utils({
mongoskin_database: db
});
//utils.addIndexes(user.INDEXES);
// Setup responses
(function() {
var getExpressRequestHandler = function(controllerName, actionName, controllerActionFunc, utils, responseSelector) {
return function(req,res,next) {
var responder = new Responder(req,res,next,controllerName,actionName,responseSelector);
console.log(req);
controllerActionFunc.call(
this,
req,
res,
utils,
responder,
next
);
};
};
var appRoutes = [
{ method:'post', requestPath:'/register', controller:'user', action:'register', func:user.register.process },
{ method:'get', requestPath:'/register', controller:'user', action:'register', func:user.register.get },
{ method:'get', requestPath:'/', controller:'index', action:'index', func:routes.index, },
{ method:'get', requestPath:'/user/:_id/activate/:activationPad', controller:'user', action:'activate', func:user.activate.get },
{ method:'patch', requestPath:'/user/:_id/activate/:activationPad',controller:'user',action:'activate',func:user.activate.process },
{ method:'get', requestPath:'/session', controller:'user', action:'login', func:user.login.get },
{ method:'post', requestPath:'/session', controller:'user', action:'login', func:user.login.process },
{ method:'get', requestPath:'/user/:_id', controller:'user', action:'get', func:user.get },
{ method:'get', requestPath:'/sync', controller:'sync', action:'sync', func:sync.sync },
];
var i = 0,
route = {};
for (i=0;i<appRoutes.length;i++) {
route = appRoutes[i];
app[route.method].call(app,route.requestPath,getExpressRequestHandler(
route.controller,
route.action,
route.func,
utils,
responseSelector
));
}
})();
app.get('/session', function(req,res,next) {
user.login.get.call(this,req,res,utils,responder,next);
});
app.post('/session', function(req,res,next) {
user.login.process.call(this,req,res,utils,responder,next);
});
app.get('/user/:_id', function(req,res,next) {
user.show.call(this,req,res,utils,responder,next);
});
app.get('/user/:_id', function(req,res,next) {
user.get.call(this,req,res,utils,responder,next);
});
};
http.createServer(app).listen(app.get('port'), function(){
console.log("LISTENING ON PORT " + app.get('port'));
});
|
require('./stripe');
|
game.Tree = me.AnimationSheet.extend({
init : function() {
this.parent(me.game.viewport.width / 2 - 128, me.game.viewport.height - 512 - 50, me.loader.getImage('tree'), 256, 512);
this.addAnimation('idle', [2], 1);
this.addAnimation('wobble', [2,3,4,3,2,1,0,1,2,3,4,3,2,1,0,1,2], 2);
this.setCurrentAnimation('idle');
this.z = 2;
this.wobbling = false;
},
animate : function() {
this.wobbling = true;
this.setCurrentAnimation('wobble', (function() {
this.wobbling = false;
this.setCurrentAnimation('idle');
}).bind(this));
},
update : function(time) {
this.parent(time);
if(this.wobbling) {
return true;
}
}
}); |
'use strict';
let Gerencianet = require('gn-api-sdk-node');
let options = require('../../credentials');
let params = {
id: "95"
}
let gerencianet = new Gerencianet(options);
gerencianet.pixGenerateQRCode(params)
.then((resposta) => {
console.log(resposta);
})
.catch((error) => {
console.log(error);
})
|
"use strict";
/**
*
* Parse
*
*/
const _toArray = require('lodash.toarray')
module.exports = function (config) {
// parse loader
[
'loaders',
'preLoaders',
'postLoaders'
].forEach(function (key) {
config.module[key] = _toArray(config.module[key])
})
// parse plugin
config.plugins = _toArray(config.plugins)
return config
}
|
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var context ;
var canvasWidth = 600
var canvasHeight = 300;
var canvas;
var canvasDiv;
//Color
var curColor = "#000000";
var clickColor = new Array();
//Size
var clickSize = new Array();
var curSize = 10;
function initialize(){
canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");
$('#canvas').mousedown(function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function(e){
if(paint){
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function(e){
paint = false;
});
$('#canvas').mouseleave(function(e){
paint = false;
});
$('#prediccion').mousedown(function(e){
prediccion();
});
$('#clear').mousedown(function(e)
{
clearCanvas_simpleSizes();
});
}
function clearCanvas_simpleSizes()
{
context.clearRect(0, 0, canvasWidth, canvasHeight);
}
function addClick(x, y, dragging){
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
clickColor.push(curColor);
clickSize.push(curSize);
}
function redraw(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.lineJoin = "round";
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.strokeStyle = clickColor[i];
context.lineWidth = curSize;
context.stroke();
}
}
/**
* Descargamos la canvas en archivo.png
*/
//function prediccion() {
//
// var canvasElement = document.getElementById('canvas');
//
// var MIME_TYPE = "image/png";
//
// var imgURL = canvasElement.toDataURL(MIME_TYPE);
//
// var dlLink = document.createElement('a');
// dlLink.download = 'number';
// dlLink.href = imgURL.replace(/^data:image\/[^;]/, 'data:application/octet-stream');;
//
// dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
// document.body.appendChild(dlLink);
// dlLink.click();
// document.body.removeChild(dlLink);
//}
function round(number) {
return Math.ceil(number*100)
}
function append_percent(number){
return number+"%";
}
function append_class(number){
return "p"+number
}
function prediccion(){
var img = document.getElementById("canvas");
var data = img.toDataURL();
$.ajax({
url : "/",
data:'{"image":"'+data+'"}',
type:"POST",
dataType: 'json',
contentType: 'application/json',
success: function(data){
$("#digit_text").text(data.prediccion) ;
var lst = JSON.parse(data.porcentajes);
$("#zero_graph_title").text(append_percent(round(lst[0])));
$("#zero_graph").addClass(append_class(round(lst[0])));
$("#one_graph_title").text(append_percent(round(lst[1])));
$("#one_graph").addClass(append_class(round(lst[1])));
$("#two_graph_title").text(append_percent(round(lst[2])));
$("#two_graph").addClass(append_class(round(lst[2])));
$("#three_graph_title").text(append_percent(round(lst[3])));
$("#three_graph").addClass(append_class(round(lst[3])));
$("#four_graph_title").text(append_percent(round(lst[4])));
$("#four_graph").addClass(append_class(round(lst[4])));
$("#five_graph_title").text(append_percent(round(lst[5])));
$("#five_graph").addClass(append_class(round(lst[5])));
$("#six_graph_title").text(append_percent(round(lst[6])));
$("#six_graph").addClass(append_class(round(lst[6])));
$("#seven_graph_title").text(append_percent(round(lst[7])));
$("#seven_graph").addClass(append_class(round(lst[7])));
$("#eight_graph_title").text(append_percent(round(lst[8])));
$("#eight_graph").addClass(append_class(round(lst[8])));
$("#nine_graph_title").text(append_percent(round(lst[9])));
$("#nine_graph").addClass(append_class(round(lst[9])));
}
});
}
|
import React from 'react'
import { ResponsiveCalendarCanvas, calendarCanvasDefaultProps } from '@nivo/calendar'
import { generateDayCounts } from '@nivo/generators'
import { ComponentTemplate } from '../../components/components/ComponentTemplate'
import meta from '../../data/components/calendar/meta.yml'
import mapper from '../../data/components/calendar/mapper'
import { groups } from '../../data/components/calendar/props'
import { graphql, useStaticQuery } from 'gatsby'
const from = new Date(2013, 3, 1)
const to = new Date(2019, 7, 12)
const generateData = () => generateDayCounts(from, to)
const Tooltip = data => {
/* return custom tooltip */
}
const initialProperties = {
pixelRatio:
typeof window !== 'undefined' && window.devicePixelRatio ? window.devicePixelRatio : 1,
from: '2013-03-01',
to: '2019-07-12',
align: 'center',
emptyColor: '#aa7942',
colors: ['#61cdbb', '#97e3d5', '#e8c1a0', '#f47560'],
minValue: 0,
maxValue: 'auto',
margin: {
top: 40,
right: 40,
bottom: 50,
left: 40,
},
direction: 'vertical',
yearSpacing: 30,
yearLegendPosition: 'before',
yearLegendOffset: 10,
monthSpacing: 0,
monthBorderWidth: 2,
monthBorderColor: '#ffffff',
monthLegendPosition: 'before',
monthLegendOffset: 10,
daySpacing: 0,
dayBorderWidth: 0,
dayBorderColor: '#ffffff',
isInteractive: true,
'custom tooltip example': false,
legends: [
{
anchor: 'bottom-right',
direction: 'row',
translateY: 36,
itemCount: 4,
itemWidth: 42,
itemHeight: 36,
itemsSpacing: 14,
itemDirection: 'right-to-left',
},
],
}
const CalendarCanvas = () => {
const {
image: {
childImageSharp: { gatsbyImageData: image },
},
} = useStaticQuery(graphql`
query {
image: file(absolutePath: { glob: "**/src/assets/captures/calendar.png" }) {
childImageSharp {
gatsbyImageData(layout: FIXED, width: 700, quality: 100)
}
}
}
`)
return (
<ComponentTemplate
name="CalendarCanvas"
meta={meta.CalendarCanvas}
icon="calendar"
flavors={meta.flavors}
currentFlavor="canvas"
properties={groups}
initialProperties={initialProperties}
defaultProperties={calendarCanvasDefaultProps}
propertiesMapper={mapper}
codePropertiesMapper={properties => ({
...properties,
tooltip: properties.tooltip ? Tooltip : undefined,
})}
generateData={generateData}
image={image}
>
{(properties, data, theme, logAction) => {
return (
<ResponsiveCalendarCanvas
data={data}
{...properties}
theme={theme}
onClick={day => {
logAction({
type: 'click',
label: `[day] ${day.day}: ${day.value}`,
color: day.color,
data: day,
})
}}
/>
)
}}
</ComponentTemplate>
)
}
export default CalendarCanvas
|
import React from 'react'
import { render } from 'react-dom'
import App from '../../cra-template-bs/template/src/App'
render(<App />, document.querySelector('#demo'))
|
var age_groups,items,follow_up_triggers,auto_order_triggers,customers,devices;
$(document).ready(function() {
if ($("select.sexes").length) {
init_input_space("sexes",function (data) {
var select = $("select.sexes")
select.empty()
select.append('<option value="" disabled selected>性別</option>')
for(var i in data){
select.append('<option value="'+data[i].id+'">'+data[i].sex+'</option>')
}
})
}
if ($("select.ranks").length || $("select.device_statuses").length || $("select.age_groups").length) {
init_input_space("ranks",function (data) {
var select = $("select.ranks")
select.empty()
select.append('<option value="" disabled selected>ランク</option>')
for(var i in data){
select.append('<option value="'+data[i].id+'">'+data[i].rank+'</option>')
}
})
init_input_space("device_statuses",function (data) {
var select = $("select.device_statuses")
select.empty()
select.append('<option value="" disabled selected>端末状況</option>')
for(var i in data){
select.append('<option value="'+data[i].id+'">'+data[i].device_status+'</option>')
}
})
init_input_space("age_groups",function (data) {
var select = $("select.age_groups")
select.empty()
select.append('<option value="" disabled selected>年代</option>')
age_groups = data
for(var i in data){
select.append('<option value="'+data[i].id+'">'+data[i].age_group+'</option>')
}
})
}
if ($("select.auto_order_triggers").length) {
init_input_space("auto_order_triggers",function (data) {
var select = $("select.auto_order_triggers")
select.empty()
select.append('<option value="" disabled selected>自動注文トリガー</option>')
auto_order_triggers = data
for(var i in data){
select.append('<option value="'+data[i].id+'">'
+ data[i].param_1_name
+ " " + data[i].condition_name + " "
+ data[i].param_2_name
+ '</option>')
}
})
}
if ($("select.follow_up_triggers").length) {
init_input_space("follow_up_triggers",function (data) {
var select = $("select.follow_up_triggers")
select.empty()
select.append('<option value="" disabled selected>フォローアップトリガー</option>')
follow_up_triggers = data
for(var i in data){
select.append('<option value="'+data[i].id+'">'
+ data[i].param_1_name
+ " " + data[i].condition_name + " "
+ data[i].param_2_name
+ '</option>')
}
})
}
if ($("select.items").length) {
init_input_space("items",function (data) {
var select = $("select.items")
select.empty()
select.append('<option value="" disabled selected>商品名 (商品番号)</option>')
items = data
for(var i in data){
select.append('<option value="'+data[i].id+'">'
+ data[i].item_name
+ ' ( ' +data[i].item_code+' )'
+ '</option>')
}
})
}
init_input_space("customers",function (data) {
customers = data
})
// for send test data
if ($('select.uuid').length) {
init_input_space("devices",function (data) {
var select = $("select.uuid")
select.empty()
select.append('<option value="" disabled selected>既存UUID</option>')
devices = data
for(var i in data){
select.append('<option value="'+data[i].id+'">'
+ data[i].uuid
+ '</option>')
}
})
}
$('select.uuid').on('change',function () {
var tmp_device = devices.filter(function (device) {
return device.id == $('select.uuid').val()
})[0]
$('input.uuid').val(tmp_device.uuid)
})
// footer button listener
$('.box-footer').on('click','button.clear',function () {
clear_input_boxes()
})
$('.box-footer').on('click','.send_test',function () {
var this_button = this
//console.log(this_button);
var url = "/api?uuid=" + $('input.uuid').val()
+ "&remain_lvl=" + $('select.remain_lvl').val()
+ "&battery_lvl=" + $('select.battery_lvl').val()
+ "&opened=" + $('select.opened').val()
//console.log(url);
if ($('input.uuid').val() && $('select.remain_lvl').val() && $('select.battery_lvl').val() && $('select.opened').val() ) {
//console.log("send!!!");
//$(this_button).html("送信中").addClass("disabled")
$(this_button).html("送信中").toggleClass("disabled").prop("disabled", true);
$.get(url,function (data,status) {
}).done(function (data) {
$(this_button).html("送信完成").addClass("btn-success").prop("disabled", true);
//raw_datasを更新
datatables_test_send.ajax.reload(function ( json ) {
console.log(json);
});
//console.log(data);
}).fail(function (data,status) {
//console.log(data);
//console.log(status);
$(this_button).html("送信失敗").addClass("btn-danger").prop("disabled", true);
}).always(function (data) {
setTimeout(function () {
$(this_button).html("送信")
.removeClass("btn-success")
.removeClass("btn-danger")
.toggleClass("disabled").prop("disabled", false);
}, 1500);
})
}else {
alert("データ不完全!\n"+url)
}
})
})
function init_input_space(table_name,call_back) {
//var table_name = "devices"
$.get("/ajax/init_input?table_name="+table_name,function (data,status) {
//console.log(data);
call_back(data);
})
}
function set_device_from_table(device) {
//console.log(device.uuid);
var tmp_customer = customers.filter(function (customer) {
return customer.id == device.customer_id;
})[0]
/*
var tmp_age_group = age_groups.filter(function (age_group) {
return age_group.id == tmp_customer.age_group_id;
})[0]*/
//console.log(tmp_customer);
$("input.uuid").val(device.uuid)
$("select.battery_lvl").val(device.battery_lvl)
$("select.device_statuses").val(device.device_status_id)
$("select.device_statuses").val(device.device_status_id)
$("input.item_code").val(device.item_code)
$("select.items").val(device.item_id)
$("select.ranks").val(device.rank_id)
$("select.auto_order_triggers").val(device.individual_auto_order_trigger_id)
$("select.follow_up_triggers").val(device.individual_follow_up_trigger_id)
$("input.customer_name").val(device.name)
$("input.mail").val(device.mail)
$("select.age_groups").val(tmp_customer.age_group_id)
$("input.zip_code").val(tmp_customer.zip_code)
$("input.ruby").val(tmp_customer.ruby)
$("select.sexes").val(tmp_customer.sex_id)
$("input.address").val( tmp_customer.state
+ tmp_customer.city
+ tmp_customer.district
+ tmp_customer.area)
}
function clear_input_boxes() {
$(".box input").val("")
$(".box select").val("")
}
|
/**
* @class Resizer
* @author Bruno SIMON / http://bruno-simon.com
*/
B.Tools.Ticker = B.Core.Event_Emitter.extend(
{
static : 'ticker',
options :
{
auto_run : true
},
/**
* Initialise and merge options
* @constructor
* @param {object} options Properties to merge with defaults
*/
construct : function( options )
{
this._super( options );
this.reseted = false;
this.running = false;
this.time = {};
this.time.start = 0;
this.time.elapsed = 0;
this.time.delta = 0;
this.time.current = 0;
this.waits = {};
this.waits.before = [];
this.waits.after = [];
this.intervals = {};
if( this.options.auto_run )
this.run();
},
/**
* Reset the ticker by setting time infos to 0
* @param {boolean} run Start the ticker
* @return {object} Context
*/
reset : function( run )
{
this.reseted = true;
this.time.start = + ( new Date() );
this.time.current = this.time.start;
this.time.elapsed = 0;
this.time.delta = 0;
if( run )
this.run();
return this;
},
/**
* Run the ticker
* @return {object} Context
*/
run : function()
{
var that = this;
// Already running
if( this.running )
return;
this.running = true;
var loop = function()
{
if(that.running)
window.requestAnimationFrame( loop );
that.tick();
};
loop();
return this;
},
/**
* Stop ticking
* @return {object} Context
*/
stop : function()
{
this.running = false;
return this;
},
/**
* Tick (or is it tack ?)
* @return {object} Context
*/
tick : function()
{
// Reset if needed
if( !this.reseted )
this.reset();
// Set time infos
this.time.current = + ( new Date() );
this.time.delta = this.time.current - this.time.start - this.time.elapsed;
this.time.elapsed = this.time.current - this.time.start;
var i = 0,
len = this.waits.before.length,
wait = null;
// Do next (before trigger)
for( ; i < len; i++ )
{
// Set up
wait = this.waits.before[ i ];
// Frame count down to 0
if( --wait.frames_count === 0 )
{
// Apply action
wait.action.apply( this, [ this.time ] );
// Remove from actions
this.waits.before.splice( i, 1 );
// Update loop indexes
i--;
len--;
}
}
// Trigger
this.trigger( 'tick', [ this.time ] );
// Trigger intervals
this.trigger_intervals();
// Do next (after trigger)
i = 0;
len = this.waits.after.length;
for( ; i < len; i++ )
{
// Set up
wait = this.waits.after[ i ];
// Frame count down to 0
if( --wait.frames_count === 0 )
{
// Apply action
wait.action.apply( this, [ this.time ] );
// Remove from actions
this.waits.after.splice( i, 1 );
// Update loop indexes
i--;
len--;
}
}
return this;
},
/**
* Apply function on X frames
* @param {number} frames_count How many frames before applying the function
* @param {function} action Function to apply
* @param {boolean} after Should apply the function after the 'tick' event is triggered
* @return {object} Context
*/
wait : function( frames_count, action, after )
{
// Errors
if( typeof action !== 'function' )
return false;
if( typeof frames_count !== 'number' )
return false;
this.waits[ after ? 'after' : 'before' ].push( {
frames_count : frames_count,
action : action
} );
return this;
},
/**
* Create interval
* @param {integer} interval Milliseconds between each tick
* @return {object} Context
*/
create_interval : function( interval )
{
this.intervals[ interval ] = {
interval : interval,
next_trigger : interval,
start : this.time.elapsed,
last_trigger : this.time.elapsed,
};
return this;
},
/**
* Destroy interval
* @param {integer} interval Milliseconds between each tick
* @return {object} Context
*/
destroy_interval : function( interval )
{
delete this.intervals[ interval ];
return this;
},
/**
* Trigger intervals
* @return {object} Context
*/
trigger_intervals : function()
{
// Each interval
for( var _key in this.intervals )
{
var interval = this.intervals[ _key ];
// Test if interval should trigger
if( this.time.elapsed - interval.last_trigger > interval.next_trigger )
{
// Update next trigger to stay as close as possible to the interval
interval.next_trigger = interval.interval - ( this.time.elapsed - interval.start ) % interval.interval;
interval.last_trigger = this.time.elapsed;
this.trigger( 'tick-' + interval.interval, [ this.time, interval ] );
}
}
return this;
},
/**
* Start listening specified events
* @param {string} names Events names (can contain namespace)
* @param {function} callback Function to apply if events are triggered
* @return {object} Context
*/
on : function( names, callback )
{
// Set up
var that = this,
resolved_names = this.resolve_names( names );
// Each resolved name
resolved_names.forEach( function( name )
{
// Has interval interval
if( name.match( /^tick([0-9]+)$/) )
{
// Extract interval interval
var interval = parseInt( name.replace( /^tick([0-9]+)$/, '$1' ) );
// Create interval
if( interval )
that.create_interval( interval );
}
} );
return this._super( names, callback );
},
/**
* Stop listening specified events
* @param {string} names Events names (can contain namespace or be the namespace only)
* @return {object} Context
*/
off : function( names )
{
// Set up
var that = this,
resolved_names = this.resolve_names( names );
// Each resolved name
resolved_names.forEach( function( name )
{
// Has interval interval
if( name.match( /^tick([0-9]+)$/) )
{
// Extract interval interval
var interval = parseInt( name.replace( /^tick([0-9]+)$/, '$1' ) );
// Create interval
if( interval )
that.destroy_interval( interval );
}
} );
return this._super( names );
},
} );
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var db = require('../config').db(mongoose);
var Publisher = require('../models/publisher.js').make(Schema, mongoose);
//
// list
//
exports.index = function(request, response) {
response.contentType('application/json');
Publisher.find({}, function (err, publishersResult) {
if (! err) {
response.send({status: {error: false, message: null}, data: {publishers: publishersResult}});
} else {
response.send({status: {error: true, message: 'Não foi possível listar os publicantes.'}});
}
});
};
//
// view
//
exports.show = function(request, response) {
response.contentType('application/json');
if (! request.params.publisher) {
response.send({status: {error: true, message: 'Informe a key do publicante.'}});
} else {
Publisher.findById(request.params.publisher, function (err, publisherDb) {
if (err) {
response.send({status: {error: true, message: 'O publicante não pode ser localizado.'}});
} else {
response.send({status: {error: false, message: null}, data: {publisher: publisherDb}});
}
});
}
};
//
// add
//
exports.create = function(request, response) {
response.contentType('application/json');
if (typeof request.body.active === 'string') {
request.body.active = (request.body.active == 'false' ? false : true);
}
var publisher = new Publisher({
description: request.body.description,
status: request.body.status,
active: request.body.active
});
if (! publisher.description) {
response.send({status: {error: true, message: 'O publicante não pode ser adicionando. Informe a descrição.'}});
} else if (publisher.description.length < 2) {
response.send({status: {error: true, message: 'O publicante não pode ser adicionando. A descrição é inválida.'}});
} else {
publisher.save(function(err, room) {
if (err) {
response.send({status: {error: true, message: 'O publicante não pode ser adicionando. Erro no servidor.'}});
} else {
response.send({status: {error: false, message: null}, data: {key: room.id}});
}
});
}
};
//
// edit
//
exports.update = function(request, response) {
response.contentType('application/json');
var update = {};
if (request.body.description)
update.description = request.body.description;
if (request.body.status)
update.status = request.body.status;
if (request.body.active) {
if (typeof request.body.active === 'string') {
request.body.active = (request.body.active == 'false' ? false : true);
}
update.active = request.body.active;
}
if (! request.params.publisher) {
response.send({status: {error: true, message: 'Informe a key do publicante.'}});
} else if (request.body.description && update.description.length < 2) {
response.send({status: {error: true, message: 'O publicante não pode ser atualizado. A descrição é inválida.'}});
} else {
//
// editar tambem em queue
//
Publisher.findByIdAndUpdate(request.params.publisher, {$set: update}, function (err, publisherDb) {
if (err) {
response.send({status: {error: true, message: 'O publicante não pode ser localizado.'}});
} else {
response.send({status: {error: false, message: null}, data: {publisher: publisherDb}});
}
});
}
};
//
// delete
//
exports.destroy = function(request, response) {
response.contentType('application/json');
if (! request.params.publisher) {
response.send({status: {error: true, message: 'Informe a key do publicante.'}});
} else {
//
// remover tambem em inscribe e queue
//
Publisher.findByIdAndRemove(request.params.publisher, function (err) {
if (err) {
response.send({status: {error: true, message: 'O publicante não pode ser localizado.'}});
} else {
response.send({status: {error: false, message: null}});
}
});
}
};
|
var require = {
baseUrl: 'js'
}
|
var class_tempo_test_1_1_tests_1_1_ref_count_test =
[
[ "ListCellSelectRefCount", "class_tempo_test_1_1_tests_1_1_ref_count_test.html#ac02144aeb6b307640f0df07298d43d3c", null ],
[ "RefCountHelpersReleaseRange", "class_tempo_test_1_1_tests_1_1_ref_count_test.html#ad71a331eddc1d0d97673817f2a9c550a", null ],
[ "TemporalScopeRefCount", "class_tempo_test_1_1_tests_1_1_ref_count_test.html#ab7e034a6bf0b8e7cbba6afb09e477833", null ],
[ "ValueCellRefCount", "class_tempo_test_1_1_tests_1_1_ref_count_test.html#ac78cfac3c99822d2a3c435f7de3c1bb3", null ]
]; |
with(require('./helpers')) {
describe('A node attribute', function() {
it('can be read', function() {
// reading a node is implied during all tests
var doc = new libxml.Document();
elem = doc.node('name');
new libxml.Attribute(elem, 'to', 'wongfoo');
assert.equal('wongfoo', elem.attr('to').value());
});
it('will return null when an attr is not found', function() {
var doc = new libxml.Document();
elem = doc.node('name');
assert.equal(null, elem.attr('to'));
});
it('can be assigned on creation', function() {
var doc = new libxml.Document();
var elem = doc.node('name', {to: 'wongfoo'});
assert.equal('wongfoo', elem.attr('to').value());
});
it('can be assigned with an object', function() {
var doc = new libxml.Document();
elem = doc.node('name');
elem.attr({to: 'wongfoo'});
assert.equal('wongfoo', elem.attr('to').value());
});
it('can be reassigned', function() {
var doc = new libxml.Document();
var elem = doc.node('name', {to: 'wongfoo'});
assert.equal('wongfoo', elem.attr('to').value());
elem.attr({to: 'julie newmar'});
assert.equal('julie newmar', elem.attr('to').value());
});
it('can be retrieved in an array', function() {
var doc = new libxml.Document();
var elem = doc.node('root');
assert.deepEqual([], elem.attrs());
elem.attr({foo: 'bar'})
.attr({bar: 'baz'})
.attr({baz: 'foo'});
var attrs = [elem.attr('foo'), elem.attr('bar'), elem.attr('baz')];
var i;
for (i = 0; i < 3; i++)
assert.equal(attrs[i], elem.attrs()[i]);
});
it('can traverse over its siblings', function() {
var doc = new libxml.Document();
var elem = doc.node('root')
.attr({foo: 'bar'})
.attr({bar: 'baz'})
.attr({baz: 'foo'});
assert.equal(elem.attr('baz'), elem.attr('bar').nextSibling());
assert.equal(elem.attr('foo'), elem.attr('bar').prevSibling());
assert.equal(null, elem.attr('foo').prevSibling());
assert.equal(null, elem.attr('baz').nextSibling());
});
it('can get back to its node', function() {
var doc = new libxml.Document();
var elem = doc.node('root')
.attr({foo: 'bar'});
assert.equal(elem, elem.attr('foo').parent());
});
it('can get back to its document', function() {
var doc = new libxml.Document();
var elem = doc.node('root')
.attr({foo: 'bar'});
assert.equal(doc, elem.attr('foo').doc());
});
});
}
|
import Component from '@ember/component';
import events from '../../utils/global-event-handlers';
import layout from '../../templates/components/mdc-card/primary';
export default Component.extend({
//region Ember Hooks
layout,
tagName: 'section',
classNames: ['mdc-card__primary'],
attributeBindings: [...events],
//endregion
});
|
var assert = require("assert");
var math = require("../lib/math.js");
describe("math", function() {
describe(".sinh", function() {
it("RubyのMath.sinhと同じ動きをすること", function() {
assert(Math.abs(math.sinh(-2.0) - -3.6268604078470186) < 1e-15);
assert(Math.abs(math.sinh(-1.0) - -1.1752011936438014) < 1e-15);
assert.equal(0.0, math.sinh(0.0));
assert(Math.abs(math.sinh(+1.0) - +1.1752011936438014) < 1e-15);
assert(Math.abs(math.sinh(+2.0) - +3.6268604078470186) < 1e-15);
});
});
describe(".cosh", function() {
it("RubyのMath.coshと同じ動きをすること", function() {
assert(Math.abs(math.cosh(-2.0) - +3.7621956910836314) < 1e-15);
assert(Math.abs(math.cosh(-1.0) - +1.5430806348152437) < 1e-15);
assert.equal(1.0, math.cosh(0.0));
assert(Math.abs(math.cosh(+1.0) - +1.5430806348152437) < 1e-15);
assert(Math.abs(math.cosh(+2.0) - +3.7621956910836314) < 1e-15);
});
});
describe(".tanh", function() {
it("RubyのMath.tanhと同じ動きをすること", function() {
assert(Math.abs(math.tanh(-2.0) - -0.9640275800758169) < 1e-15);
assert(Math.abs(math.tanh(-1.0) - -0.7615941559557649) < 1e-15);
assert.equal(0.0, math.tanh(0.0));
assert(Math.abs(math.tanh(+1.0) - +0.7615941559557649) < 1e-15);
assert(Math.abs(math.tanh(+2.0) - +0.9640275800758169) < 1e-15);
});
});
describe(".atanh", function() {
it("RubyのMath.atanhと同じ動きをすること", function() {
assert(Math.abs(math.atanh(-0.2) - -0.2027325540540822) < 1e-15);
assert(Math.abs(math.atanh(-0.1) - -0.1003353477310756) < 1e-15);
assert.equal(0.0, math.atanh(0.0));
assert(Math.abs(math.atanh(+0.1) - +0.1003353477310756) < 1e-15);
assert(Math.abs(math.atanh(+0.2) - +0.2027325540540822) < 1e-15);
});
});
describe(".mod", function() {
it("Rubyの剰余と同じ動きをすること", function() {
assert.equal(0, math.mod(0, 1));
assert.equal(0, math.mod(1, 1));
assert.equal(1, math.mod(+10, +3));
assert.equal(2, math.mod(+10, +4));
assert.equal(0, math.mod(+10, +5));
// TODO: 無限ループしてしまう。実装を修正すること。
// assert.equal(-2, math.mod(+10, -3));
// assert.equal(-2, math.mod(+10, -4));
// assert.equal( 0, math.mod(+10, -5));
assert.equal(2, math.mod(-10, +3));
assert.equal(2, math.mod(-10, +4));
assert.equal(0, math.mod(-10, +5));
// TODO: 無限ループしてしまう。実装を修正すること。
// assert.equal(-1, math.mod(-10, -3));
// assert.equal(-2, math.mod(-10, -4));
// assert.equal( 0, math.mod(-10, -5));
});
});
});
|
(function(c){var b={inEffect:{opacity:"show"},inEffectDuration:600,stayTime:3E3,text:"",sticky:false,type:"notice",position:"top-right",closeText:"",close:null};var a={init:function(d){if(d)c.extend(b,d)},showNotify:function(f){var g={};c.extend(g,b,f);var j,e,d,i,h;j=!c(".notify-container").length?c("<div></div>").addClass("notify-container").addClass("notify-position-"+g.position).appendTo("body"):c(".notify-container");e=c("<div></div>").addClass("notify-item-wrapper");d=c("<div></div>").hide().addClass("notify-item notify-type-"+
g.type).appendTo(j).html(c("<p>").append(g.text)).animate(g.inEffect,g.inEffectDuration).wrap(e);i=c("<div></div>").addClass("notify-item-close").prependTo(d).html(g.closeText).click(function(){c().shownotify("removeNotify",d,g)});h=c("<div></div>").addClass("notify-item-image").addClass("notify-item-image-"+g.type).prependTo(d);if(navigator.userAgent.match(/MSIE 6/i))j.css({top:document.documentElement.scrollTop});if(!g.sticky)setTimeout(function(){c().shownotify("removeNotify",d,g)},g.stayTime);
return d},showNoticeNotify:function(e){var d={text:e,type:"notice"};return c().shownotify("showNotify",d)},showSuccessNotify:function(e){var d={text:e,type:"success"};return c().shownotify("showNotify",d)},showErrorNotify:function(e){var d={text:e,type:"error"};return c().shownotify("showNotify",d)},showWarningNotify:function(e){var d={text:e,type:"warning"};return c().shownotify("showNotify",d)},removeNotify:function(e,d){e.animate({opacity:"0"},600,function(){e.parent().animate({height:"0px"},300,
function(){e.parent().remove()})});if(d&&d.close!==null)d.close()}};c.fn.shownotify=function(d){if(a[d])return a[d].apply(this,Array.prototype.slice.call(arguments,1));else if(typeof d==="object"||!d)return a.init.apply(this,arguments);else c.error("Method "+d+" does not exist on jQuery.shownotify")}})(jQuery);
|
import { renderComponent , expect } from '../test_helper';
import Entry from '../../src/components/entry';
describe('Entry' , () => {
let component;
beforeEach(() => {
component = renderComponent(Entry);
});
it('contains an input field', () => {
expect(component.find('textarea')).to.exist;
});
it('contains an button', () => {
expect(component.find('button')).to.exist;
});
});
|
'use strict';
//route for getting all stocks for portfolio
const express = require('express');
const router = express.Router();
const portfolioCtrl = require("../ctrlrs/portfolioCtrl")
//queries db and sends back data as json to /api/portfolio route
router.get("/api/portfolio", portfolioCtrl.getAllStock);
//updates db with new quantity after stocks are sold
router.put("/api/portfolio/:qty/:stockId/:operation", portfolioCtrl.updateQuantity);
//refresh db with updated prices
router.put("/api/portfolio/:qty/:stockId/:operation", portfolioCtrl.updateStockPrice);
module.exports = router; |
/**
* Copyright (C) 2013 Emay Komarudin
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Emay Komarudin
*
**/
Ext.define('App.view.master.gudang.tab', {
extend: 'Ext.tab.Panel',
title: 'Gudang',
requires: [
'App.view.master.gudang.List'
],
layout: { type: 'fit', align: 'stretch'},
alias: 'widget.tabgudang',
initComponent: function () {
var me = this;
Ext.apply(me, {
items: [
{
xtype: 'gudangGridList',
title: 'Daftar'
},
{
xtype: 'container',
title: 'Kategori',
layout: { type: 'fit', align: 'stretch'},
items: [
{
xtype: 'grid',
itemId: 'gridcategory',
columns: [
{ xtype: 'rownumberer'},
{
text: 'Nama',
dataIndex: 'name',
flex:1,
editor: {
allowBlank: false,
minLength:2
}
},
{
text: 'Keterangan',
dataIndex: 'info',
flex:2,
editor: {
allowBlank: true
}
},
{
header: 'Aksi',
xtype: 'actioncolumn',
width: 40,
items: [
{
iconCls: 'delete',
tooltip: 'Hapus',
handler: function (grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
Ext.MessageBox.confirm('Konfirmasi', 'Apakah Anda Yakin Akan Menghapus Record ?', function (btn, text) {
var rec = grid.getStore().getAt(rowIndex);
if (btn == 'yes') {
rec.destroy({
callback: function (recs, ops, success) {
if (!ops.error) {
App.util.box.info('Record Berhasil dihapus');
grid.getStore().load();
} else {
App.util.box.error('Record Gagal dihapus');
return false;
}
},
failure: function (r, o) {
App.util.box.error('Record Gagal dihapus');
return false;
}
})
// grid.getStore().remove(rec);
// grid.getStore().sync();
// grid.getStore().load();
}
});
}
}
]
}
],
store: 'App.store.warehouse.category',
columnLines: true,
selModel: App.util.box.createSelectionModel(),
/*========== Plugins ==========*/
plugins: [
Ext.create('Ext.grid.plugin.RowEditing', {
clicksToEdit: !1,
pluginId: 'cellEditorGudangC',
clicksToMoveEditor: 1
})
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{ text: 'Tambah', iconCls: 'add',action: 'add' }
]
},
{
xtype: 'pagingtoolbar',
dock: 'bottom',
displayInfo: true,
store: 'App.store.warehouse.category'
}
]
}
]
}
]
});
me.callParent(arguments);
// me.down('#gridcategory').getStore().load();
}
});
|
/**
* @file 首页数据仓库
* @author dongkunshan(windwithfo@yeah.net)
*/
import {
action,
computed,
observable
} from 'mobx';
import fetch from 'isomorphic-fetch';
class {{{Name}}}State {
@observable list = [];
constructor(data) {
this.list = data || [];
}
@action fetchData() {
fetch('/mock/test')
.then(function (response) {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then((stories) => {
console.log(stories);
// this.list = stories.list;
});
}
@action popItem() {
this.list.pop();
this.fetchData();
}
@computed get len() {
return this.list.length;
}
}
export default {{{Name}}}State;
|
var _ = require('lodash');
var chai = require('chai');
var fs = require('fs');
var path = require('path');
var sinon = require('sinon');
var Formatter = require('../lib/formatter');
var Logger = require('../lib/logger');
chai.use(require('chai-string'));
var assert = chai.assert;
var getErrorMsgByLine = function(lineNum, errors) {
var whereLine = {
line: lineNum
};
return _.result(_.find(errors, whereLine), 'msg') || '';
};
describe(
'Formatter.JS',
function() {
'use strict';
beforeEach(
function() {
sinon.createSandbox();
}
);
afterEach(
function() {
sinon.restore();
}
);
var testFilePath = path.join(__dirname, 'fixture', 'test.js');
var jsLogger = new Logger.constructor();
var jsFormatter = new Formatter.JS(testFilePath, jsLogger);
var source = fs.readFileSync(testFilePath, 'utf-8');
jsFormatter.format(source, false);
var jsErrors = jsLogger.getErrors(testFilePath);
it(
'should ignore values in comments',
function() {
assert.equal(getErrorMsgByLine(1, jsErrors), '');
}
);
it(
'should recognize an invalid conditional',
function() {
assert.startsWith(getErrorMsgByLine(5, jsErrors), 'Needs a space between ")" and "{":');
}
);
it(
'should recognize an invalid argument format',
function() {
assert.startsWith(getErrorMsgByLine(11, jsErrors), 'These arguments should each be on their own line:');
}
);
it(
'should recognize an invalid function format',
function() {
assert.startsWith(getErrorMsgByLine(16, jsErrors), 'Anonymous function expressions should be formatted as function(:');
}
);
it(
'should recognize variable line spacing',
function() {
assert.startsWith(getErrorMsgByLine(23, jsErrors), 'Variable declaration needs a new line after it:');
}
);
it(
'should print code as source',
function() {
var srcCode = 'var foo = 1';
assert.equal(jsFormatter._printAsSource(srcCode), '1 ' + srcCode);
}
);
it(
'should use a custom lint log filter',
function() {
var jsLoggerFilter = new Logger.constructor();
var jsFormatterFilter = new Formatter.JS(testFilePath, jsLoggerFilter);
var lintLogFilter = sinon.stub().returnsArg(0);
jsFormatterFilter.lintLogFilter = lintLogFilter;
jsFormatterFilter.format('var _PN_var = 1;');
assert.isTrue(lintLogFilter.called);
}
);
it(
'should parse JS syntax',
function() {
var jsLoggerParse = new Logger.constructor();
var jsFormatterParse = new Formatter.JS(testFilePath, jsLoggerParse);
var processed = false;
jsFormatterParse.processor.VariableDeclaration = function(node, parent) {
assert.isObject(node);
assert.isObject(parent);
assert.equal(node.type, 'VariableDeclaration');
assert.isArray(node.declarations);
assert.equal(node.declarations[0].id.name, 'x');
processed = true;
};
jsFormatterParse._processSyntax('var x = 123;');
assert.isTrue(processed, 'JS was not processed');
jsFormatterParse._processSyntax('var x = ;');
var parseErrors = jsLoggerParse.getErrors(testFilePath);
assert.equal(parseErrors.length, 1);
assert.startsWith(parseErrors[0].msg, 'Could not parse JavaScript: Unexpected token ');
var jsLoggerParseVerbose = new Logger.constructor();
var jsFormatterParseVerbose = new Formatter.JS(testFilePath, jsLoggerParseVerbose);
jsFormatterParseVerbose.flags.verbose = true;
jsFormatterParseVerbose._processSyntax('var x = ;');
var verboseDetails = jsLoggerParseVerbose.verboseDetails[testFilePath];
assert.isString(verboseDetails);
assert.isAbove(verboseDetails.length, 0);
}
);
it(
'should handle errors during JS parsing',
function() {
var jsLoggerParse = new Logger.constructor();
var jsFormatterParse = new Formatter.JS(testFilePath, jsLoggerParse);
jsFormatterParse.processor.VariableDeclaration = function(node, parent) {
(function() {
null.indexOf('foo');
}());
};
jsFormatterParse._processSyntax('var x = 1;');
var parseErrors = jsLoggerParse.getErrors(testFilePath);
assert.equal(parseErrors.length, 1);
var parseError = parseErrors[0];
assert.startsWith(parseError.msg, 'Could not parse JavaScript:');
assert.equal(parseError.line, 'n/a');
}
);
}
);
describe(
'Formatter.JS Node',
function() {
'use strict';
var testFilePath = path.join(__dirname, 'fixture', 'test_node.js');
var jsLogger = new Logger.constructor();
var jsFormatter = new Formatter.JS(testFilePath, jsLogger);
var source = fs.readFileSync(testFilePath, 'utf-8');
jsFormatter.format(source, false);
var jsErrors = jsLogger.getErrors(testFilePath);
it(
'should not recognize debugging statements',
function() {
assert.equal(getErrorMsgByLine(3, jsErrors), '');
}
);
}
);
describe(
'Formatter.JS Excludes',
function() {
'use strict';
it(
'should ignore excluded files',
function() {
_.forEach(
['min', 'soy', 'nocsf'],
function(item, index) {
['-', '_', '.'].forEach(
function(n, i) {
var testFilePath = 'test' + n + item + '.js';
var jsLogger = new Logger.constructor();
var jsFormatter = new Formatter.get(testFilePath, jsLogger);
var jsErrors = jsLogger.getErrors(testFilePath);
assert.startsWith(getErrorMsgByLine('n/a', jsErrors), 'This file was ignored.');
}
);
}
);
}
);
}
);
describe(
'Formatter.JS Lint',
function() {
'use strict';
beforeEach(
function() {
sinon.createSandbox();
}
);
afterEach(
function() {
sinon.restore();
}
);
var lintConfig = require('../lib/config/eslint');
var testFilePath = path.join(__dirname, 'fixture', 'test.js');
var jsLogger = new Logger.constructor();
var jsFormatter = new Formatter.JS(testFilePath, jsLogger);
var source = fs.readFileSync(testFilePath, 'utf-8');
var lint = require('../lib/lint_js');
it(
'should find at least one lint error',
function() {
jsFormatter.format(source, true);
var jsErrors = jsLogger.getErrors(testFilePath);
var foundLintErrors = _.reduce(
jsErrors,
function(res, item, index) {
if (item.type) {
res[item.type] = true;
}
return res;
},
{}
);
var hasLintError = _.some(
lintConfig.rules,
function(item, index) {
var val = _.isArray(item) ? item[0] : item;
return val > 0 && foundLintErrors[index];
}
);
assert.isTrue(hasLintError);
}
);
it(
'should use default configuration properties',
function() {
var eslint = lint.eslint;
var verify = function(contents, config, file) {
return {
line: 1,
message: '',
column: 0,
ruleId: ''
}
};
sinon.stub(eslint.linter, 'verify').callsFake(verify);
lint.runLinter(source, testFilePath, {});
var args = eslint.linter.verify.args[0];
assert.isUndefined(args[1].plugins);
}
);
it(
'should merge configuration properties',
function() {
var eslint = lint.eslint;
var verify = function(contents, config, file) {
return {
line: 1,
message: '',
column: 0,
ruleId: ''
}
};
sinon.stub(eslint.linter, 'verify').callsFake(verify);
jsFormatter.format(
source,
{
parserOptions: {
ecmaVersion: 6
}
}
);
var args = eslint.linter.verify.args[0];
assert.equal(args[1].parserOptions.ecmaVersion, 6);
assert.isArray(args[1].plugins);
}
);
it(
'load a custom eslint plugin',
function() {
var eslint = lint.eslint;
sinon.spy(eslint.linter, 'verify');
lint.runLinter(
source,
testFilePath,
{
fileConfig: {
_paths: {
obj: {
filepath: path.join(__dirname, '../package.json')
}
}
},
lintConfig: {
parserOptions: {
ecmaVersion: 7
},
plugins: ['dollar-sign']
}
}
);
var linterRules = eslint.linter.getRules();
assert.isTrue(linterRules.has('dollar-sign/dollar-sign'));
}
);
it(
'load a custom eslint plugin via path',
function() {
var eslint = lint.eslint;
var linterRulesPrev = eslint.linter.getRules();
lint.runLinter(
source,
testFilePath,
{
fileConfig: {
_paths: {
obj: {
filepath: path.join(__dirname, '../package.json')
}
}
},
lintConfig: {
parserOptions: {
ecmaVersion: 7
},
plugins: ['./test/fixture/eslint-plugin-custom-lint']
}
}
);
var linterRules = eslint.linter.getRules();
assert.isTrue(linterRules.has('custom-lint/foo'));
}
);
it(
'ignore non-existent rules',
function() {
var eslint = lint.eslint;
var linterRulesPrev = eslint.linter.getRules();
lint.runLinter(
source,
testFilePath,
{
lintConfig: {
parserOptions: {
ecmaVersion: 7
},
plugins: ['non-existent-plugin', './other-non-existent-plugin']
}
}
);
var linterRules = eslint.linter.getRules();
assert.equal(linterRulesPrev.size, linterRules.size);
}
);
}
); |
/**
* `tasks/config/sync`
*
* ---------------------------------------------------------------
*
* Synchronize files from the `assets` folder to `.tmp/public`,
* smashing anything that's already there.
*
* For more information, see:
* https://sailsjs.com/anatomy/tasks/config/sync.js
*
*/
module.exports = function(grunt) {
grunt.config.set('sync', {
dev: {
files: [{
cwd: './assets',
src: ['**/*.!(coffee|less)'],
dest: '.tmp/public'
}]
}
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// This Grunt plugin is part of the default asset pipeline in Sails,
// so it's already been automatically loaded for you at this point.
//
// Of course, you can always remove this Grunt plugin altogether by
// deleting this file. But check this out: you can also use your
// _own_ custom version of this Grunt plugin.
//
// Here's how:
//
// 1. Install it as a local dependency of your Sails app:
// ```
// $ npm install grunt-sync --save-dev --save-exact
// ```
//
//
// 2. Then uncomment the following code:
//
// ```
// // Load Grunt plugin from the node_modules/ folder.
grunt.loadNpmTasks('grunt-sync');
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
};
|
'use strict';
const Gpio = require('../onoff').Gpio;
const assert = require('assert');
const button = new Gpio(4, 'in', 'rising', {
debounceTimeout : 10
});
let count = 0;
assert(button.direction() === 'in');
assert(button.edge() === 'rising');
console.info('Please press button connected to GPIO4 5 times...');
button.watch((err, value) => {
if (err) {
throw err;
}
count += 1;
console.log('button pressed ' + count + ' times, value was ' + value);
if (count === 5) {
button.unexport();
console.log('ok - ' + __filename);
}
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from 'react-helmet';
import { compose } from 'redux';
import TextInput from '../../components/Form/TextInput';
import FormContainer from '../LoginPage/FormContainer';
import Button from '../../components/Form/Button';
import { submitRegister } from './thunks';
import Logo from '../../components/Logo';
import Header from '../LoginPage/Header';
import AlternatePageMessage from '../LoginPage/AlternatePageMessage';
import StyledLink from '../../components/StyledLink';
import { LOGIN_URL } from '../../common/constants';
export class RegisterPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
register: PropTypes.func.isRequired,
};
state = {
email: '',
username: '',
password: '',
passwordConfirmation: ''
};
setEmail = (email) => {
this.setState((prevState) => ({
...prevState,
email,
}));
}
setUsername = (username) => {
this.setState((prevState) => ({
...prevState,
username,
}));
}
setPassword = (password) => {
this.setState((prevState) => ({
...prevState,
password,
}));
}
setPasswordConfirmation = (passwordConfirmation) => {
this.setState((prevState) => ({
...prevState,
passwordConfirmation,
}));
}
render() {
const { register } = this.props;
return (
<div>
<Helmet>
<title>Register</title>
<meta name="description" content="Register for an account" />
</Helmet>
<Header>
<Logo>MMDb</Logo>
</Header>
<FormContainer>
<form
onSubmit={(e) => {
e.preventDefault();
register({
username: this.state.username,
password: this.state.password,
email: this.state.email,
passwordConfirmation: this.state.passwordConfirmation
});
}}
>
<TextInput
label="Username"
name="username"
onChangeHandler={this.setUsername}
/>
<TextInput
label="Email"
name="email"
type="email"
onChangeHandler={this.setEmail}
/>
<TextInput
label="Password"
name="password"
type="password"
onChangeHandler={this.setPassword}
/>
<TextInput
label="Confirm Password"
name="passwordConfirmation"
type="password"
spaced="40px"
onChangeHandler={this.setPasswordConfirmation}
/>
<Button wide>Register</Button>
</form>
<AlternatePageMessage>
Already have an account? <StyledLink to={LOGIN_URL}>Login</StyledLink>.
</AlternatePageMessage>
</FormContainer>
</div>
);
}
}
const withConnect = connect(
() => ({}),
(dispatch) => ({
register: ({ email, username, password, passwordConfirmation }) => {
return dispatch(submitRegister({ email, username, password, passwordConfirmation }));
},
})
);
export default compose(
withConnect,
)(RegisterPage);
|
import { StyleSheet } from 'react-native';
import theme from '../../../theme';
const { margins } = theme;
export default StyleSheet.create({
list: {
width: '100%',
},
containerUSER: {
marginLeft: 60,
marginRight: 20,
marginTop: margins.xs,
marginBottom: margins.xs,
alignItems: 'flex-end',
},
containerTINTINA: {
flexDirection: 'row',
marginRight: 60,
marginLeft: 20,
marginTop: margins.xs,
marginBottom: margins.xs,
alignItems: 'flex-start',
},
avatar: {
height: 30,
width: 30,
marginRight: margins.xs,
},
});
|
var LoginAssistant = Class.create(BaseAssistant, {
initialize: function($super, credentials) {
$super()
this.hidePreferences = true
this.credentials = credentials || new Credentials()
this.api = new Api()
this.triedLogin = false
this.hideLogout = true
},
setup: function($super) {
$super()
Log.debug("sending metrix data")
Feeder.Metrix.postDeviceData()
},
activate: function($super, changes) {
$super(changes)
this.controller.serviceRequest('palm://com.palm.systemservice/time', {
method: 'getSystemTime',
parameters: {},
onSuccess: function(response) {
if(this.credentials.email && this.credentials.password) {
if(this.triedLogin) {
Log.debug("ALREADY TRIED LOGGING IN, WHAT MAKES YOU THINK ITS GOING TO WORK NOW")
}
else {
this.triedLogin = true
Log.debug("logging in as " + this.credentials.email)
this.spinnerOn($L("logging in..."))
this.api.login(this.credentials, this.loginSuccess.bind(this), this.loginFailure.bind(this))
}
}
else {
Log.debug("no credentials found")
this.controller.stageController.swapScene("credentials", this.credentials)
}
}.bind(this)
})
},
loginSuccess: function() {
this.credentials.save()
this.controller.stageController.swapScene("home", this.api)
},
loginFailure: function() {
this.controller.stageController.swapScene("credentials", this.credentials, true)
}
})
|
Rox = {
/* Here we've just got some global level vars that persist regardless of State swaps */
score: 0,
/* If the music in your game needs to play through-out a few State swaps, then you could reference it here */
music: null,
/* Your game can check Rox.orientated in internal loops to know if it should pause or not */
orientated: false
};
Rox.Boot = function (game) {
};
Rox.Boot.prototype = {
preload: function () {
this.load.image('preloaderBar', 'images/preload.png');
},
create: function () {
// this.stage.smoothed = false;
this.physics.startSystem(Phaser.Physics.ARCADE);
this.input.maxPointers = 1;
// this.stage.disableVisibilityChange = true;
if (this.game.device.desktop)
{
// this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// this.scale.minWidth = 320;
// this.scale.minHeight = 200;
// this.scale.maxWidth = 800;
// this.scale.maxHeight = 600;
// this.scale.pageAlignHorizontally = true;
// this.scale.pageAlignVertically = true;
// this.scale.setScreenSize(true);
}
else
{
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.minWidth = 480;
this.scale.minHeight = 260;
this.scale.maxWidth = 1024;
this.scale.maxHeight = 768;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
this.scale.forceOrientation(true, false);
this.scale.hasResized.add(this.gameResized, this);
this.scale.enterIncorrectOrientation.add(this.enterIncorrectOrientation, this);
this.scale.leaveIncorrectOrientation.add(this.leaveIncorrectOrientation, this);
this.scale.setScreenSize(true);
}
this.state.start('Preloader');
},
gameResized: function (width, height) {
},
enterIncorrectOrientation: function () {
Rox.orientated = false;
document.getElementById('orientation').style.display = 'block';
},
leaveIncorrectOrientation: function () {
Rox.orientated = true;
document.getElementById('orientation').style.display = 'none';
}
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:02ee2312d4c44d6b196d6a1194fe5039c2e156a5119113aae34d80d685ec578b
size 2486
|
module.exports = {
replaceNewlines: text => text.replace(/\n+(?!$)/g, ' '),
formatSigilText: sigilText => {
return sigilText.replace(/^%/, '%25').slice(0, 8) + '...'
},
// https://github.com/joypixels/emojione/issues/644
removeBadBytes: text =>
text
.split('')
.filter(f => f.codePointAt(0) !== 0xfe0f)
.join(''),
// input: { a: 'A', b: 'B' }
// output: { A: 'a', B: 'b' {
reverseKeyValue: obj =>
Object.entries(obj).reduce((acc, entry) => {
const [key, val] = entry
acc[val] = key
return acc
}, {})
}
|
//download.js v3.1, by dandavis; 2008-2014. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
// https://github.com/rndme/download
// data can be a string, Blob, File, or dataURL
window.downloadFile = function download(data, strFileName, strMimeType) {
var self = window, // this script is only for browsers anyway...
u = "application/octet-stream", // this default mime also triggers iframe downloads
m = strMimeType || u,
x = data,
D = document,
a = D.createElement("a"),
z = function(a) {
return String(a);
},
B = (self.Blob || self.MozBlob || self.WebKitBlob || z);
B = B.call ? B.bind(self) : Blob;
var fn = strFileName || "download",
blob,
fr;
if (String(this) === "true") { //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
x = [x, m];
m = x[0];
x = x[1];
}
//go ahead and download dataURLs right away
if (String(x).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/)) {
return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
navigator.msSaveBlob(d2b(x), fn) :
saver(x); // everyone else can save dataURLs un-processed
} //end if dataURL passed?
blob = x instanceof B ?
x :
new B([x], {
type: m
});
function d2b(u) {
var p = u.split(/[:;,]/),
t = p[1],
dec = p[2] == "base64" ? atob : decodeURIComponent,
bin = dec(p.pop()),
mx = bin.length,
i = 0,
uia = new Uint8Array(mx);
for (i; i < mx; ++i) uia[i] = bin.charCodeAt(i);
return new B([uia], {
type: t
});
}
function saver(url, winMode) {
if ('download' in a) { //html5 A[download]
a.href = url;
a.setAttribute("download", fn);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
a.click();
D.body.removeChild(a);
if (winMode === true) {
setTimeout(function() {
self.URL.revokeObjectURL(a.href);
}, 250);
}
}, 66);
return true;
}
if (typeof safari !== "undefined") { // handle non-a[download] safari as best we can:
url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, u);
if (!window.open(url)) { // popup blocked, offer direct download:
if (confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")) {
location.href = url;
}
}
return true;
}
//do iframe dataURL download (old ch+FF):
var f = D.createElement("iframe");
D.body.appendChild(f);
if (!winMode) { // force a mime that will download:
url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, u);
}
f.src = url;
setTimeout(function() {
D.body.removeChild(f);
}, 333);
} //end saver
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fn);
}
if (self.URL) { // simple fast and modern way using Blob and URL:
saver(self.URL.createObjectURL(blob), true);
} else {
// handle non-Blob()+non-URL browsers:
if (typeof blob === "string" || blob.constructor === z) {
try {
return saver("data:" + m + ";base64," + self.btoa(blob));
} catch (y) {
return saver("data:" + m + "," + encodeURIComponent(blob));
}
}
// Blob but not URL:
fr = new FileReader();
fr.onload = function(e) {
saver(this.result);
};
fr.readAsDataURL(blob);
}
return true;
} /* end download() */
|
const dataTableDriverFactory = component => ({
clickRowByIndex: index => component.$$('tbody tr').get(index).click(),
getRowTextByIndex: index => component.$$('tbody tr').get(index).getText(),
element: () => component
});
export default dataTableDriverFactory;
|
/**
* Copyright (C) 2010-2015 KO GmbH <copyright@kogmbh.com>
*
* @licstart
* This file is part of WebODF.
*
* WebODF is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License (GNU AGPL)
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* WebODF is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with WebODF. If not, see <http://www.gnu.org/licenses/>.
* @licend
*
* @source: http://www.webodf.org/
* @source: https://github.com/kogmbh/WebODF/
*/
|
version https://git-lfs.github.com/spec/v1
oid sha256:912159daaef9ef3f33150924ba16d2b73ffb872fe75e9db472e944acdca08a76
size 280900
|
#!/usr/bin/env node
/*====================================================*
| SORT PACKAGE.JSON |
| |
| I think documentation order matters and given that |
| NPM docs regarding `package.json` follow an order, |
| I wanted to respect it and follow in my projects. |
| |
| Usage: node sort-pkg.js |
| (run from directory with `package.json`) |
*====================================================*/
const fs = require('fs'),
diff = require('arr-diff');
const defCfg = require('npm/lib/config/defaults').defaults;
/*================*
| MAIN |
*================*/
const file = process.argv[2] || 'package.json';
fs.readFile(file, 'utf8', (err, data) => {
if (err) throw err;
const pkg = sortPkg(JSON.parse(data)),
txt = JSON.stringify(pkg, null, 2) + '\n';
fs.writeFile(file, txt, err => {
if (err) throw err;
console.log(`Sorted "${file}"!`);
});
});
/*================*
| KEYS |
*================*/
function s(x) { return x.split(' '); }
const KEYS = {
scripts: [],
bugs: s('url email'),
engines: s('node npm'),
repository: s('type url'),
author: s('name email url'),
config: Object.keys(defCfg),
directories: s('lib bin man doc example test'),
pkg: s(
'name version description keywords homepage bugs license licenses author ' +
'contributors files main bin man directories repository scripts config ' +
'dependencies devDependencies peerDependencies bundledDependencies ' +
'bundleDependencies optionalDependencies engines engineStrict os cpu ' +
'preferGlobal private publishConfig'
)
};
// Taken from NPM
s('publish install uninstall test stop start restart version').
forEach(p => (KEYS.scripts.push('pre' + p, p, 'post' + p)));
/*================*
| HELPERS |
*================*/
function sortArr(arr) {
if (!Array.isArray(arr))
return arr;
return arr.sort();
}
function sortDir(arr) {
const exc = arr.filter(k => (k[0] == '!')).sort(),
inc = diff(arr, exc).sort();
return inc.concat(exc);
}
function sortObj(obj, key) {
if (obj.constructor !== Object)
return obj;
key = KEYS[key];
if (!key) return obj;
const all = Object.keys(obj),
rej = diff(all, key),
acc = diff(all, rej);
const res = {};
acc.sort((a, b) => key.indexOf(a) - key.indexOf(b));
acc.concat(rej).forEach(key => (res[key] = obj[key]));
return res;
}
function sortPkg(obj) {
// General first
obj = sortObj(obj, 'pkg');
// By key
//noinspection CommaExpressionJS
return Object.keys(obj).
map(key => {
let val = obj[key];
//noinspection SwitchStatementWithNoDefaultBranchJS
switch (key) {
case 'keywords':
val = sortArr(val);
break;
case 'bugs':
case 'author':
case 'directories':
case 'repository':
case 'scripts':
case 'engines':
val = sortObj(val, key);
break;
case 'contributors':
// TODO: Alpha by name?
val = val.map(e => sortObj(e, 'author'));
break;
case 'files':
case 'os':
case 'cpu':
val = sortDir(val);
break;
case 'bin':
case 'man':
case 'bundledDependencies':
case 'bundleDependencies':
val = sortArr(val);
break;
case 'config':
case 'publishConfig':
val = sortObj(val, 'config');
break;
case 'dependencies':
case 'devDependencies':
case 'peerDependencies':
case 'optionalDependencies':
KEYS.tmp = sortArr(Object.keys(val));
val = sortObj(val, 'tmp');
delete KEYS.tmp;
break;
}
return [key, val];
}).
reduce((o, [k, v]) => (o[k] = v, o), {});
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.7-6-a-11
description: >
Object.defineProperties - 'P' is inherited accessor property
without a get function (8.12.9 step 1 )
includes: [runTestCase.js]
---*/
function testcase() {
var proto = {};
Object.defineProperty(proto, "prop", {
set: function () { },
configurable: false
});
var Con = function () { };
Con.prototype = proto;
var obj = new Con();
Object.defineProperties(obj, {
prop: {
get: function () {
return 12;
},
configurable: true
}
});
return obj.hasOwnProperty("prop") && obj.prop === 12;
}
runTestCase(testcase);
|
// Copyright 2014 LastLeaf
'use strict';
fw.main(function(pg){
fw.loadingLogo.show();
// parse servers
var serverStrs = app.config.get('servers');
var servers = [];
for(var i=0; i<serverStrs.length; i++) {
var str = serverStrs[i];
var match = str.match(/\{([0-9]+)\,([0-9]+)\}/);
if(!match) servers.push(str);
else {
for(var j=Number(match[1]); j<=Number(match[2]); j++) {
servers.push( str.replace(/\{[0-9]+\,[0-9]+\}/, j) );
}
}
}
// init connection
pg.rpc('server:setPrivateKey', app.config.get('privateKey'), function(){
pg.rpc('server:set', servers, function(){
pg.rpc('server:listenStatus', function(status){
initPage(status);
});
});
});
pg.on('socketDisconnect', function(){
if(!pg.destroyed) fw.go('/');
});
// history obj
var history = {};
servers.forEach(function(server){
history[server] = [];
});
// connected
var initPage = function(status){
// init page structure
fw.loadingLogo.hide();
$('#wrapper').html(pg.tmpl.main(status));
var $statusList = $('#statusList');
var $statusButtons = $('#statusButtons');
// status listeners
pg.msg('connected', function(server){
$statusList.find('[server="'+server+'"]').removeClass('status-disconnected status-busy status-error').addClass('status-connected');
});
pg.msg('disconnected', function(server){
$statusList.find('[server="'+server+'"]').removeClass('status-connected status-busy status-error').addClass('status-disconnected');
});
pg.msg('execStart', function(server, command){
$statusList.find('[server="'+server+'"]').removeClass('status-connected status-disconnected status-error').addClass('status-busy')
.attr('title', command);
history[server].push({ type: 'execStart', text: command });
historyUpdated(server);
});
pg.msg('execDone', function(server, command){
$statusList.find('[server="'+server+'"]').removeClass('status-disconnected status-busy status-error').addClass('status-connected');
history[server].push({ type: 'execDone', text: 'Done.' });
historyUpdated(server);
});
pg.msg('execError', function(server, command, err){
$statusList.find('[server="'+server+'"]').removeClass('status-connected status-disconnected status-busy').addClass('status-error')
.attr('title', command + '\n' + err);
history[server].push({ type: 'execError', text: err });
historyUpdated(server);
});
pg.msg('execFail', function(server, command, code, signal){
$statusList.find('[server="'+server+'"]').removeClass('status-connected status-disconnected status-busy').addClass('status-error')
.attr('title', command + '\nExit Code: ' + code + ' Signal: ' + signal);
history[server].push({ type: 'execFail', text: 'Exit Code: ' + code + ' Signal: ' + signal });
historyUpdated(server);
});
pg.msg('execStdout', function(server, command, data){
history[server].push({ type: 'execStdout', text: data });
historyUpdated(server);
});
pg.msg('execStderr', function(server, command, data){
history[server].push({ type: 'execStderr', text: data });
historyUpdated(server);
});
// select/unselect
$statusList.on('click', '[server]', function(e){
var $server = $(this);
if($server.hasClass('status-busy')) $server.removeClass('status-selected');
else $server.toggleClass('status-selected');
});
$statusButtons.find('.statusSelectAll').click(function(e){
$statusList.find('[server]').addClass('status-selected').filter('.status-busy').removeClass('status-selected');
});
$statusButtons.find('.statusSelectNone').click(function(e){
$statusList.find('[server]').removeClass('status-selected');
});
// command
var prevCommands = '';
var prevArgs = '';
$statusButtons.find('.statusCommand').click(function(e){
var servers = [];
$statusList.find('.status-selected').each(function(){
servers.push($(this).attr('server'));
});
var $form = $('#main').html(pg.tmpl.commands({
servers: servers,
serverCount: servers.length
}));
$form.find('.commandsSubmit').click(function(e){
$statusList.find('.status-selected').removeClass('status-selected');
var $btn = $(this).attr('disabled', true);
pg.rpc('server:execCommands', servers, $form.find('[name=commands]').val(), $form.find('[name=args]').val(), function(){
$form.find('textarea').attr('disabled', true);
}, function(err){
$btn.removeAttr('disabled');
if(err) {
$form.find('[name=args]').val( 'Error: ' + err + '\n\n' + $form.find('[name=args]').val() ).focus();
}
});
});
$form.find('[name=commands]').val(prevCommands).change(function(){
prevCommands = $(this).val();
});
$form.find('[name=args]').val(prevArgs).change(function(){
prevArgs = $(this).val();
});
currentHistory = '';
});
// show history
var currentHistory = '';
$statusList.on('dblclick', '[server]', function(e){
var server = $(this).attr('server');
var $main = $('#main').html(pg.tmpl.history({
server: server,
history: history[server]
}));
$main.find('.historyClear').click(function(e){
history[server] = [];
$('#main').html('');
});
$main.find('.historyCommand').submit(function(e){
e.preventDefault();
var $form = $(this);
var cmd = $form.find('[type=text]').val();
$form.find('[type=submit]').attr('disabled', true);
pg.rpc('server:execCommands', [server], cmd, '', function(){
$form.find('[type=text]').val('');
$form.find('[type=submit]').removeAttr('disabled');
}, function(){
$form.find('[type=submit]').removeAttr('disabled');
});
});
currentHistory = server;
});
var historyUpdated = function(server){
if(currentHistory !== server) return;
var item = history[server][ history[server].length - 1 ];
$(pg.tmpl.historyItem(item)).insertBefore($('#main').find('.historyCommand'));
};
};
});
|
function booksPublishController($scope, $routeParams, $http) {
$scope.onLoad=onLoad;
$scope.title={};
$scope.session = {};
onLoad();
function onLoad(){
var text;
var signed;
console.log("in on load");
$http.post('/userManage/getSessionInfo')
.success(function(data){
signed = data.signed;
$scope.session = data.session;
if(signed)
{
document.getElementById("name").textContent = $scope.session.user.userName+" | ";
}
})
.error(function(data){
console.log("Error: "+data);
});
}
}
|
var React = require('react')
// takes react out of global
// DOM components
var div = React.DOM.div
var h1 = React.DOM.h1
// Custom components
var MyTitle = React.createClass({
// render: function (){} alternative ES6 syntax
render () {
return (
div(null,
h1({style: {color: this.props.color}}, this.props.title || 'this is my custom component')
)
)
}
})
module.exports = MyTitle
|
// libs
import React, {PropTypes} from 'react';
import styles from './index.css';
export default function ProgressBar({children, pctComplete, backgroundColor}) {
return (
<div className={styles.component}>
<div style={{backgroundColor, width: `${pctComplete}%`}} className={styles.body}>
{children}
</div>
</div>
);
}
ProgressBar.propTypes = {
children: PropTypes.oneOfType([
PropTypes.node,
PropTypes.arrayOf(PropTypes.node),
]),
pctComplete: PropTypes.number,
backgroundColor: PropTypes.string,
};
|
export const CLIENT_CONNECT = 'CLIENT_CONNECT';
export const CLIENT_ERR = 'CLIENT_ERR';
export const CLIENT_CONNECT_FAILURE = 'CLIENT_CONNECT_FAILURE';
export const CLIENT_DISCONNECT = 'CLIENT_DISCONNECT';
export const STATS_UPDATE_DEVICES = 'STATS_UPDATE_DEVICES';
export const STATS_UPDATE_DEVICEIDS = 'STATS_UPDATE_DEVICEIDS';
export const STATS_UPDATE_CHANNELS = 'STATS_UPDATE_CHANNELS';
export const STATS_UPDATE_CHANNEL_NAMES = 'STATS_UPDATE_CHANNEL_NAMES';
export const DEVICES_API_UPDATE = 'DEVICES_API_UPDATE';
export const DEVICE_UPDATE = "DEVICE_UPDATE";
export const ROBOT_UPDATE = "ROBOT_UPDATE";
export const ROBOT_UNSUBSCRIBE = "ROBOT_UNSUBSCRIBE";
export const CHANNEL_SUBSCRIBE = 'CHANNEL_SUBSCRIBE';
export const CHANNEL_UNSUBSCRIBE = 'CHANNEL_UNSUBSCRIBE';
export const CHANNEL_UPDATE = 'CHANNEL_UPDATE';
export const CHANNEL_MESSAGE = 'CHANNEL_MESSAGE';
|
version https://git-lfs.github.com/spec/v1
oid sha256:25ccefb37f263139fbe715b78715501e0c93686edf2b10a981c8c39a892355c3
size 190701
|
/* jshint -W024 */
/* jshint expr:true */
var webdriverjs = require('../index'),
assert = require('assert');
describe('my webdriverjs tests', function(){
this.timeout(99999999);
var client = {};
before(function(){
client = webdriverjs.remote({ desiredCapabilities: {browserName: 'phantomjs'} });
client.init();
});
it('Github test',function(done) {
client
.url('https://github.com/')
.getElementSize('.header-logo-wordmark', function(err, result) {
assert(err === null);
assert(result.height === 30);
assert(result.width === 94);
})
.getTitle(function(err, title) {
assert(err === null);
assert(title === 'GitHub · Build software better, together.');
})
.getElementCssProperty('class name','subheading', 'color', function(err, result){
assert(err === null);
assert(result === 'rgba(136, 136, 136, 1)');
})
.call(done);
});
after(function(done) {
client.end(done);
});
}); |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33s-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"
}), 'BluetoothAudioOutlined'); |
/*
In NativeScript, the app.ts file is the entry point to your application.
You can use this file to perform app-level initialization, but the primary
purpose of the file is to pass control to the app’s first module.
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("./bundle-config");
var app = require("application");
app.start({ moduleName: 'main-page' });
/*
Do not place any code after the application has been started as it will not
be executed on iOS.
*/
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiYXBwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7O0VBSUU7OztBQUVGLDJCQUF5QjtBQUN6QixpQ0FBbUM7QUFFbkMsR0FBRyxDQUFDLEtBQUssQ0FBQyxFQUFFLFVBQVUsRUFBRSxXQUFXLEVBQUUsQ0FBQyxDQUFDO0FBRXZDOzs7RUFHRSIsInNvdXJjZXNDb250ZW50IjpbIi8qXG5JbiBOYXRpdmVTY3JpcHQsIHRoZSBhcHAudHMgZmlsZSBpcyB0aGUgZW50cnkgcG9pbnQgdG8geW91ciBhcHBsaWNhdGlvbi5cbllvdSBjYW4gdXNlIHRoaXMgZmlsZSB0byBwZXJmb3JtIGFwcC1sZXZlbCBpbml0aWFsaXphdGlvbiwgYnV0IHRoZSBwcmltYXJ5XG5wdXJwb3NlIG9mIHRoZSBmaWxlIGlzIHRvIHBhc3MgY29udHJvbCB0byB0aGUgYXBw4oCZcyBmaXJzdCBtb2R1bGUuXG4qL1xuXG5pbXBvcnQgXCIuL2J1bmRsZS1jb25maWdcIjtcbmltcG9ydCAqIGFzIGFwcCBmcm9tICdhcHBsaWNhdGlvbic7XG5cbmFwcC5zdGFydCh7IG1vZHVsZU5hbWU6ICdtYWluLXBhZ2UnIH0pO1xuXG4vKlxuRG8gbm90IHBsYWNlIGFueSBjb2RlIGFmdGVyIHRoZSBhcHBsaWNhdGlvbiBoYXMgYmVlbiBzdGFydGVkIGFzIGl0IHdpbGwgbm90XG5iZSBleGVjdXRlZCBvbiBpT1MuXG4qL1xuIl19 |
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var imageuploaders = require('../../app/controllers/imageuploaders.server.controller');
var multipart = require('connect-multiparty')();
// Imageuploaders Routes
app.route('/imageuploaders')
.get(imageuploaders.list)
.post(users.requiresLogin, imageuploaders.create);
app.route('/imageuploaders/:imageuploaderId')
.get(imageuploaders.read)
.put(users.requiresLogin, imageuploaders.hasAuthorization, imageuploaders.update)
.delete(users.requiresLogin, imageuploaders.hasAuthorization, imageuploaders.delete);
// Finish by binding the Imageuploader middleware
app.param('imageuploaderId', imageuploaders.imageuploaderByID);
app.route('/upload').post(
users.requiresLogin,
multipart,
imageuploaders.upload);
};
|
myApp.factory('InitializeApp', ['$resource',
function($resource){
return $resource('http://dev2.cabotprojects.com/asthma/webservices?method=initializeApp');
}]);
|
module.exports = {
type : String,
enum : [ 'BOISSON', 'NOURRITURE', 'TOILETTES'],
default : 'BOISSON'
};
|
'use strict';
module.exports = function(grunt) {
// Unified Watch Object
var watchFiles = {
serverViews: ['app/views/**/*.*'],
serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
clientViews: ['public/modules/**/views/**/*.html'],
clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
clientCSS: ['public/modules/**/*.css'],
mochaTests: ['app/tests/**/*.js']
};
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
serverViews: {
files: watchFiles.serverViews,
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint'],
options: {
livereload: true
}
}
},
jshint: {
all: {
src: watchFiles.clientJS.concat(watchFiles.serverJS),
options: {
jshintrc: true
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc'
},
all: {
src: watchFiles.clientCSS
}
},
uglify: {
production: {
options: {
mangle: false
},
files: {
'public/dist/application.min.js': 'public/dist/application.js'
}
}
},
cssmin: {
combine: {
files: {
'public/dist/application.min.css': '<%= applicationCSSFiles %>'
}
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug'],
ext: 'js,html',
watch: watchFiles.serverViews.concat(watchFiles.serverJS)
}
}
},
'node-inspector': {
custom: {
options: {
'web-port': 1337,
'web-host': 'localhost',
'debug-port': 5858,
'save-live-edit': true,
'no-preload': true,
'stack-trace-limit': 50,
'hidden': []
}
}
},
ngAnnotate: {
production: {
files: {
'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
}
}
},
concurrent: {
default: ['nodemon', 'watch'],
debug: ['nodemon', 'watch', 'node-inspector'],
options: {
logConcurrentOutput: true,
limit: 10
}
},
env: {
test: {
NODE_ENV: 'test'
},
secure: {
NODE_ENV: 'secure'
}
},
mochaTest: {
src: watchFiles.mochaTests,
options: {
reporter: 'spec',
require: 'server.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
shell: {
mongodb: {
command: 'mongod --dbpath ./data/db',
options: {
async: true,
stdout: false,
stderr: true,
failOnError: true,
execOptions: {
cwd: '.'
}
}
}
}
});
// Load NPM tasks
require('load-grunt-tasks')(grunt);
//Call grunt-shell-spawn to enable async and multitask
grunt.loadNpmTasks('grunt-shell-spawn');
// Making grunt default to force in order not to break the project.
grunt.option('force', true);
// A Task for loading the configuration object
grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
var init = require('./config/init')();
var config = require('./config/config');
grunt.config.set('applicationJavaScriptFiles', config.assets.js);
grunt.config.set('applicationCSSFiles', config.assets.css);
});
// Default task(s).
grunt.registerTask('default', ['shell:mongodb', 'lint', 'concurrent:default']);
// Debug task.
grunt.registerTask('debug', ['shell:mongodb', 'lint', 'concurrent:debug']);
// Secure task(s).
grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']);
// Lint task(s).
grunt.registerTask('lint', ['jshint', 'csslint']);
// Build task(s).
grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']);
// Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
|
/**********************************************************
* Copyright (c) SESHENGHUO.COM All rights reserved *
**********************************************************/
/*!
* Crypto-JS v1.1.0
* http://code.google.com/p/crypto-js/
* Copyright (c) 2009, Jeff Mott. All rights reserved.
* http://code.google.com/p/crypto-js/wiki/License
*/
/**
* Crypto-SHA1
* @charset utf-8
* @author lijun
* @git: https://github.com/zwlijun/se.builder
* @date 2018.8
*/
;define(function(require, exports, module){
var Base = require("mod/crypto/base");
// Public API
var SHA1 = function (message, options) {
var digestbytes = Base.wordsToBytes(SHA1._sha1(message));
return options && options.asBytes ? digestbytes :
options && options.asString ? Base.bytesToString(digestbytes) :
Base.bytesToHex(digestbytes);
};
// The core
SHA1._sha1 = function (message) {
var m = Base.stringToWords(message),
l = message.length * 8,
w = [],
H0 = 1732584193,
H1 = -271733879,
H2 = -1732584194,
H3 = 271733878,
H4 = -1009589776;
// Padding
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >>> 9) << 4) + 15] = l;
for (var i = 0; i < m.length; i += 16) {
var a = H0,
b = H1,
c = H2,
d = H3,
e = H4;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = m[i + j];
else {
var n = w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16];
w[j] = (n << 1) | (n >>> 31);
}
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
(H1 ^ H2 ^ H3) - 899497514);
H4 = H3;
H3 = H2;
H2 = (H1 << 30) | (H1 >>> 2);
H1 = H0;
H0 = t;
}
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += e;
}
return [H0, H1, H2, H3, H4];
};
// Package private blocksize
SHA1._blocksize = 16;
module.exports = {
"version": "R18B0815",
"blocksize": SHA1._blocksize,
encode: function(message, options){
return SHA1(message, options);
}
};
}); |
// GA addon for convnet.js
(function(global) {
"use strict";
var Vol = convnetjs.Vol; // convenience
// used utilities, make explicit local references
var randf = convnetjs.randf;
var randn = convnetjs.randn;
var randi = convnetjs.randi;
var zeros = convnetjs.zeros;
var Net = convnetjs.Net;
var maxmin = convnetjs.maxmin;
var randperm = convnetjs.randperm;
var weightedSample = convnetjs.weightedSample;
var getopt = convnetjs.getopt;
var arrUnique = convnetjs.arrUnique;
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
// returns a random cauchy random variable with gamma (controls magnitude sort of like stdev in randn)
// http://en.wikipedia.org/wiki/Cauchy_distribution
var randc = function(m, gamma) {
return m + gamma * 0.01 * randn(0.0, 1.0) / randn(0.0, 1.0);
};
// chromosome implementation using an array of floats
var Chromosome = function(floatArray) {
this.fitness = 0; // default value
this.nTrial = 0; // number of trials subjected to so far.
this.gene = floatArray;
};
Chromosome.prototype = {
burst_mutate: function(burst_magnitude_) { // adds a normal random variable of stdev width, zero mean to each gene.
var burst_magnitude = burst_magnitude_ || 0.1;
var i, N;
N = this.gene.length;
for (i = 0; i < N; i++) {
this.gene[i] += randn(0.0, burst_magnitude);
}
},
randomize: function(burst_magnitude_) { // resets each gene to a random value with zero mean and stdev
var burst_magnitude = burst_magnitude_ || 0.1;
var i, N;
N = this.gene.length;
for (i = 0; i < N; i++) {
this.gene[i] = randn(0.0, burst_magnitude);
}
},
mutate: function(mutation_rate_, burst_magnitude_) { // adds random gaussian (0,stdev) to each gene with prob mutation_rate
var mutation_rate = mutation_rate_ || 0.1;
var burst_magnitude = burst_magnitude_ || 0.1;
var i, N;
N = this.gene.length;
for (i = 0; i < N; i++) {
if (randf(0,1) < mutation_rate) {
this.gene[i] += randn(0.0, burst_magnitude);
}
}
},
crossover: function(partner, kid1, kid2) { // performs one-point crossover with partner to produce 2 kids
//assumes all chromosomes are initialised with same array size. pls make sure of this before calling
var i, N;
N = this.gene.length;
var l = randi(0, N); // crossover point
for (i = 0; i < N; i++) {
if (i < l) {
kid1.gene[i] = this.gene[i];
kid2.gene[i] = partner.gene[i];
} else {
kid1.gene[i] = partner.gene[i];
kid2.gene[i] = this.gene[i];
}
}
},
copyFrom: function(c) { // copies c's gene into itself
var i, N;
this.copyFromGene(c.gene);
},
copyFromGene: function(gene) { // gene into itself
var i, N;
N = this.gene.length;
for (i = 0; i < N; i++) {
this.gene[i] = gene[i];
}
},
clone: function() { // returns an exact copy of itself (into new memory, doesn't return reference)
var newGene = zeros(this.gene.length);
var i;
for (i = 0; i < this.gene.length; i++) {
newGene[i] = Math.round(10000*this.gene[i])/10000;
}
var c = new Chromosome(newGene);
c.fitness = this.fitness;
return c;
}
};
// counts the number of weights and biases in the network
function getNetworkSize(net) {
var layer = null;
var filter = null;
var bias = null;
var w = null;
var count = 0;
var i, j, k;
for ( i = 0; i < net.layers.length; i++) {
layer = net.layers[i];
filter = layer.filters;
if (filter) {
for ( j = 0; j < filter.length; j++) {
w = filter[j].w;
count += w.length;
}
}
bias = layer.biases;
if (bias) {
w = bias.w;
count += w.length;
}
}
return count;
}
function pushGeneToNetwork(net, gene) { // pushes the gene (floatArray) to fill up weights and biases in net
var count = 0;
var layer = null;
var filter = null;
var bias = null;
var w = null;
var i, j, k;
for ( i = 0; i < net.layers.length; i++) {
layer = net.layers[i];
filter = layer.filters;
if (filter) {
for ( j = 0; j < filter.length; j++) {
w = filter[j].w;
for ( k = 0; k < w.length; k++) {
w[k] = gene[count++];
}
}
}
bias = layer.biases;
if (bias) {
w = bias.w;
for ( k = 0; k < w.length; k++) {
w[k] = gene[count++];
}
}
}
}
function getGeneFromNetwork(net) { // gets all the weight/biases from network in a floatArray
var gene = [];
var layer = null;
var filter = null;
var bias = null;
var w = null;
var i, j, k;
for ( i = 0; i < net.layers.length; i++) {
layer = net.layers[i];
filter = layer.filters;
if (filter) {
for ( j = 0; j < filter.length; j++) {
w = filter[j].w;
for ( k = 0; k < w.length; k++) {
gene.push(w[k]);
}
}
}
bias = layer.biases;
if (bias) {
w = bias.w;
for ( k = 0; k < w.length; k++) {
gene.push(w[k]);
}
}
}
return gene;
}
function copyFloatArray(x) { // returns a FloatArray copy of real numbered array x.
var N = x.length;
var y = zeros(N);
for (var i = 0; i < N; i++) {
y[i] = x[i];
}
return y;
}
function copyFloatArrayIntoArray(x, y) { // copies a FloatArray copy of real numbered array x into y
var N = x.length;
for (var i = 0; i < N; i++) {
y[i] = x[i];
}
}
// implementation of basic conventional neuroevolution algorithm (CNE)
//
// options:
// population_size : positive integer
// mutation_rate : [0, 1], when mutation happens, chance of each gene getting mutated
// elite_percentage : [0, 0.3], only this group mates and produces offsprings
// mutation_size : positive floating point. stdev of gausian noise added for mutations
// target_fitness : after fitness achieved is greater than this float value, learning stops
// burst_generations : positive integer. if best fitness doesn't improve after this number of generations
// then mutate everything!
// best_trial : default 1. save best of best_trial's results for each chromosome.
//
// initGene: init float array to initialize the chromosomes. can be result obtained from pretrained sessions.
var GATrainer = function(net, options_, initGene) {
this.net = net;
var options = options_ || {};
this.population_size = typeof options.population_size !== 'undefined' ? options.population_size : 100;
this.population_size = Math.floor(this.population_size/2)*2; // make sure even number
this.mutation_rate = typeof options.mutation_rate !== 'undefined' ? options.mutation_rate : 0.01;
this.elite_percentage = typeof options.elite_percentage !== 'undefined' ? options.elite_percentage : 0.2;
this.mutation_size = typeof options.mutation_size !== 'undefined' ? options.mutation_size : 0.05;
this.target_fitness = typeof options.target_fitness !== 'undefined' ? options.target_fitness : 10000000000000000;
this.burst_generations = typeof options.burst_generations !== 'undefined' ? options.burst_generations : 10;
this.best_trial = typeof options.best_trial !== 'undefined' ? options.best_trial : 1;
this.chromosome_size = getNetworkSize(this.net);
var initChromosome = null;
if (initGene) {
initChromosome = new Chromosome(initGene);
}
this.chromosomes = []; // population
for (var i = 0; i < this.population_size; i++) {
var chromosome = new Chromosome(zeros(this.chromosome_size));
if (initChromosome) { // if initial gene supplied, burst mutate param.
chromosome.copyFrom(initChromosome);
pushGeneToNetwork(this.net, initChromosome.gene);
if (i > 0) { // don't mutate the first guy.
chromosome.burst_mutate(this.mutation_size);
}
} else {
chromosome.randomize(1.0);
}
this.chromosomes.push(chromosome);
}
this.bestFitness = -10000000000000000;
this.bestFitnessCount = 0;
};
GATrainer.prototype = {
train: function(fitFunc) { // has to pass in fitness function. returns best fitness
var bestFitFunc = function(nTrial, net) {
var bestFitness = -10000000000000000;
var fitness;
for (var i = 0; i < nTrial; i++) {
fitness = fitFunc(net);
if (fitness > bestFitness) {
bestFitness = fitness;
}
}
return bestFitness;
};
var i, N;
var fitness;
var c = this.chromosomes;
N = this.population_size;
var bestFitness = -10000000000000000;
// process first net (the best one)
pushGeneToNetwork(this.net, c[0].gene);
fitness = bestFitFunc(this.best_trial, this.net);
c[0].fitness = fitness;
bestFitness = fitness;
if (bestFitness > this.target_fitness) {
return bestFitness;
}
for (i = 1; i < N; i++) {
pushGeneToNetwork(this.net, c[i].gene);
fitness = bestFitFunc(this.best_trial, this.net);
c[i].fitness = fitness;
if (fitness > bestFitness) {
bestFitness = fitness;
}
}
// sort the chromosomes by fitness
c = c.sort(function (a, b) {
if (a.fitness > b.fitness) { return -1; }
if (a.fitness < b.fitness) { return 1; }
return 0;
});
var Nelite = Math.floor(Math.floor(this.elite_percentage*N)/2)*2; // even number
for (i = Nelite; i < N; i+=2) {
var p1 = randi(0, Nelite);
var p2 = randi(0, Nelite);
c[p1].crossover(c[p2], c[i], c[i+1]);
}
for (i = 1; i < N; i++) { // keep best guy the same. don't mutate the best one, so start from 1, not 0.
c[i].mutate(this.mutation_rate, this.mutation_size);
}
// push best one to network.
pushGeneToNetwork(this.net, c[0].gene);
if (bestFitness < this.bestFitness) { // didn't beat the record this time
this.bestFitnessCount++;
if (this.bestFitnessCount > this.burst_generations) { // stagnation, do burst mutate!
for (i = 1; i < N; i++) {
c[i].copyFrom(c[0]);
c[i].burst_mutate(this.mutation_size);
}
//c[0].burst_mutate(this.mutation_size); // don't mutate best solution.
}
} else {
this.bestFitnessCount = 0; // reset count for burst
this.bestFitness = bestFitness; // record the best fitness score
}
return bestFitness;
}
};
// variant of ESP network implemented
// population of N sub neural nets, each to be co-evolved by ESPTrainer
// fully recurrent. outputs of each sub nn is also the input of all other sub nn's and itself.
// inputs should be order of ~ -10 to +10, and expect output to be similar magnitude.
// user can grab outputs of the the N sub networks and use them to accomplish some task for training
//
// Nsp: Number of sub populations (ie, 4)
// Ninput: Number of real inputs to the system (ie, 2). so actual number of input is Niput + Nsp
// Nhidden: Number of hidden neurons in each sub population (ie, 16)
// genes: (optional) array of Nsp genes (floatArrays) to initialise the network (pretrained);
var ESPNet = function(Nsp, Ninput, Nhidden, genes) {
this.net = []; // an array of convnet.js feed forward nn's
this.Ninput = Ninput;
this.Nsp = Nsp;
this.Nhidden = Nhidden;
this.input = new convnetjs.Vol(1, 1, Nsp+Ninput); // hold most up to date input vector
this.output = zeros(Nsp);
// define the architecture of each sub nn:
var layer_defs = [];
layer_defs.push({
type: 'input',
out_sx: 1,
out_sy: 1,
out_depth: (Ninput+Nsp)
});
layer_defs.push({
type: 'fc',
num_neurons: Nhidden,
activation: 'sigmoid'
});
layer_defs.push({
type: 'regression',
num_neurons: 1 // one output for each sub nn, gets fed back into inputs.
});
var network;
for (var i = 0; i < Nsp; i++) {
network = new convnetjs.Net();
network.makeLayers(layer_defs);
this.net.push(network);
}
// if pretrained network is supplied:
if (genes) {
this.pushGenes(genes);
}
};
ESPNet.prototype = {
feedback: function() { // feeds output back to last bit of input vector
var i;
var Ninput = this.Ninput;
var Nsp = this.Nsp;
for (i = 0; i < Nsp; i++) {
this.input.w[i+Ninput] = this.output[i];
}
},
setInput: function(input) { // input is a vector of length this.Ninput of real numbers
// this function also grabs the previous most recent output and put it into the internal input vector
var i;
var Ninput = this.Ninput;
var Nsp = this.Nsp;
for (i = 0; i < Ninput; i++) {
this.input.w[i] = input[i];
}
this.feedback();
},
forward: function() { // returns array of output of each Nsp neurons after a forward pass.
var i, j;
var Ninput = this.Ninput;
var Nsp = this.Nsp;
var y = zeros(Nsp);
var a; // temp variable to old output of forward pass
for (i = Nsp-1; i >= 0; i--) {
if (i === 0) { // for the base network, forward with output of other support networks
this.feedback();
}
a = this.net[i].forward(this.input); // forward pass sub nn # i
y[i] = a.w[0]; // each sub nn only has one output.
this.output[i] = y[i]; // set internal output to track output
}
return y;
},
getNetworkSize: function() { // return total number of weights and biases in a single sub nn.
return getNetworkSize(this.net[0]); // each network has identical architecture.
},
getGenes: function() { // return an array of Nsp genes (floatArrays of length getNetworkSize())
var i;
var Nsp = this.Nsp;
var result = [];
for (i = 0; i < Nsp; i++) {
result.push(getGeneFromNetwork(this.net[i]));
}
return result;
},
pushGenes: function(genes) { // genes is an array of Nsp genes (floatArrays)
var i;
var Nsp = this.Nsp;
for (i = 0; i < Nsp; i++) {
pushGeneToNetwork(this.net[i], genes[i]);
}
}
};
// implementation of variation of Enforced Sub Population neuroevolution algorithm
//
// options:
// population_size : population size of each subnetwork inside espnet
// mutation_rate : [0, 1], when mutation happens, chance of each gene getting mutated
// elite_percentage : [0, 0.3], only this group mates and produces offsprings
// mutation_size : positive floating point. stdev of gausian noise added for mutations
// target_fitness : after fitness achieved is greater than this float value, learning stops
// num_passes : number of times each neuron within a sub population is tested
// on average, each neuron will be tested num_passes * esp.Nsp times.
// burst_generations : positive integer. if best fitness doesn't improve after this number of generations
// then start killing neurons that don't contribute to the bottom line! (reinit them with randoms)
// best_mode : if true, this will assign each neuron to the best fitness trial it has experienced.
// if false, this will use the average of all trials experienced.
// initGenes: init Nsp array of floatarray to initialize the chromosomes. can be result obtained from pretrained sessions.
var ESPTrainer = function(espnet, options_, initGenes) {
this.espnet = espnet;
this.Nsp = espnet.Nsp;
var Nsp = this.Nsp;
var options = options_ || {};
this.population_size = typeof options.population_size !== 'undefined' ? options.population_size : 50;
this.population_size = Math.floor(this.population_size/2)*2; // make sure even number
this.mutation_rate = typeof options.mutation_rate !== 'undefined' ? options.mutation_rate : 0.2;
this.elite_percentage = typeof options.elite_percentage !== 'undefined' ? options.elite_percentage : 0.2;
this.mutation_size = typeof options.mutation_size !== 'undefined' ? options.mutation_size : 0.02;
this.target_fitness = typeof options.target_fitness !== 'undefined' ? options.target_fitness : 10000000000000000;
this.num_passes = typeof options.num_passes !== 'undefined' ? options.num_passes : 2;
this.burst_generations = typeof options.burst_generations !== 'undefined' ? options.burst_generations : 10;
this.best_mode = typeof options.best_mode !== 'undefined' ? options.best_mode : false;
this.chromosome_size = this.espnet.getNetworkSize();
this.initialize(initGenes);
};
ESPTrainer.prototype = {
initialize: function(initGenes) {
var i, j;
var y;
var Nsp = this.Nsp;
this.sp = []; // sub populations
this.bestGenes = []; // array of Nsp number of genes, records the best combination of genes for the bestFitness achieved so far.
var chromosomes, chromosome;
for (i = 0; i < Nsp; i++) {
chromosomes = []; // empty list of chromosomes
for (j = 0; j < this.population_size; j++) {
chromosome = new Chromosome(zeros(this.chromosome_size));
if (initGenes) {
chromosome.copyFromGene(initGenes[i]);
if (j > 0) { // don't mutate first guy (pretrained)
chromosome.burst_mutate(this.mutation_size);
}
} else { // push random genes to this.bestGenes since it has not been initalized.
chromosome.randomize(1.0); // create random gene array if no pretrained one is supplied.
}
chromosomes.push(chromosome);
}
y = copyFloatArray(chromosomes[0].gene); // y should either be random init gene, or pretrained.
this.bestGenes.push(y);
this.sp.push(chromosomes); // push array of chromosomes into each population
}
assert(this.bestGenes.length === Nsp);
this.espnet.pushGenes(this.bestGenes); // initial
this.bestFitness = -10000000000000000;
this.bestFitnessCount = 0;
},
train: function(fitFunc) { // has to pass in fitness function. returns best fitness
var i, j, k, m, N, Nsp;
var fitness;
var c = this.sp; // array of arrays that holds every single chromosomes (Nsp x N);
N = this.population_size; // number of chromosomes in each sub population
Nsp = this.Nsp; // number of sub populations
var bestFitness = -10000000000000000;
var bestSet, bestGenes;
var cSet;
var genes;
// helper function to return best fitness run nTrial times
var bestFitFunc = function(nTrial, net) {
var bestFitness = -10000000000000000;
var fitness;
for (var i = 0; i < nTrial; i++) {
fitness = fitFunc(net);
if (fitness > bestFitness) {
bestFitness = fitness;
}
}
return bestFitness;
};
// helper function to create a new array filled with genes from an array of chromosomes
// returns an array of Nsp floatArrays
function getGenesFromChromosomes(s) {
var g = [];
for (var i = 0; i < s.length; i++) {
g.push(copyFloatArray(s[i].gene));
}
return g;
}
// makes a copy of an array of gene, helper function
function makeCopyOfGenes(s) {
var g = [];
for (var i = 0; i < s.length; i++) {
g.push(copyFloatArray(s[i]));
}
return g;
}
// helper function, randomize all of nth sub population of entire chromosome set c
function randomizeSubPopulation(n, c) {
for (var i = 0; i < N; i++) {
c[n][i].randomize(1.0);
}
}
// helper function used to sort the list of chromosomes according to their fitness
function compareChromosomes(a, b) {
if ((a.fitness/a.nTrial) > (b.fitness/b.nTrial)) { return -1; }
if ((a.fitness/a.nTrial) < (b.fitness/b.nTrial)) { return 1; }
return 0;
}
// iterate over each gene in each sub population to initialise the nTrial to zero (will be incremented later)
for (i = 0; i < Nsp; i++) { // loop over every sub population
for (j = 0; j < N; j++) {
if (this.best_mode) { // best mode turned on, no averaging, but just recording best score.
c[i][j].nTrial = 1;
c[i][j].fitness = -10000000000000000;
} else {
c[i][j].nTrial = 0;
c[i][j].fitness = 0;
}
}
}
// see if the global best gene has met target. if so, can end it now.
assert(this.bestGenes.length === Nsp);
this.espnet.pushGenes(this.bestGenes); // put the random set of networks into the espnet
fitness = fitFunc(this.espnet); // try out this set, and get the fitness
if (fitness > this.target_fitness) {
return fitness;
}
bestGenes = makeCopyOfGenes(this.bestGenes);
bestFitness = fitness;
//this.bestFitness = fitness;
// for each chromosome in a sub population, choose random chromosomes from all othet sub populations to
// build a espnet. perform fitFunc on that esp net to get the fitness of that combination. add the fitness
// to this chromosome, and all participating chromosomes. increment the nTrial of all participating
// chromosomes by one, so afterwards they can be sorted by average fitness
// repeat this process this.num_passes times
for (k = 0; k < this.num_passes; k++) {
for (i = 0; i < Nsp; i++) {
for (j = 0; j < N; j++) {
// build an array of chromosomes randomly
cSet = [];
for (m = 0; m < Nsp; m++) {
if (m === i) { // push current iterated neuron
cSet.push(c[m][j]);
} else { // push random neuron in sub population m
cSet.push(c[m][randi(0, N)]);
}
}
genes = getGenesFromChromosomes(cSet);
assert(genes.length === Nsp);
this.espnet.pushGenes(genes); // put the random set of networks into the espnet
fitness = fitFunc(this.espnet); // try out this set, and get the fitness
for (m = 0; m < Nsp; m++) { // tally the scores into each participating neuron
if (this.best_mode) {
if (fitness > cSet[m].fitness) { // record best fitness this neuron participated in.
cSet[m].fitness = fitness;
}
} else {
cSet[m].nTrial += 1; // increase participation count for each participating neuron
cSet[m].fitness += fitness;
}
}
if (fitness > bestFitness) {
bestFitness = fitness;
bestSet = cSet;
bestGenes = genes;
}
}
}
}
// sort the chromosomes by average fitness
for (i = 0; i < Nsp; i++) {
c[i] = c[i].sort(compareChromosomes);
}
var Nelite = Math.floor(Math.floor(this.elite_percentage*N)/2)*2; // even number
for (i = 0; i < Nsp; i++) {
for (j = Nelite; j < N; j+=2) {
var p1 = randi(0, Nelite);
var p2 = randi(0, Nelite);
c[i][p1].crossover(c[i][p2], c[i][j], c[i][j+1]);
}
}
// mutate the population size after 2*Nelite (keep one set of crossovers unmutiliated!)
for (i = 0; i < Nsp; i++) {
for (j = 2*Nelite; j < N; j++) {
c[i][j].mutate(this.mutation_rate, this.mutation_size);
}
}
// put global and local bestgenes in the last element of each gene
for (i = 0; i < Nsp; i++) {
c[i][N-1].copyFromGene( this.bestGenes[i] );
c[i][N-2].copyFromGene( bestGenes[i] );
}
if (bestFitness < this.bestFitness) { // didn't beat the record this time
this.bestFitnessCount++;
if (this.bestFitnessCount > this.burst_generations) { // stagnation, do burst mutate!
// add code here when progress stagnates later.
console.log('stagnating. burst mutate based on best solution.');
var bestGenesCopy = makeCopyOfGenes(this.bestGenes);
var bestFitnessCopy = this.bestFitness;
this.initialize(bestGenesCopy);
this.bestGenes = bestGenesCopy;
this.bestFitness = this.bestFitnessCopy;
}
} else {
this.bestFitnessCount = 0; // reset count for burst
this.bestFitness = bestFitness; // record the best fitness score
this.bestGenes = bestGenes; // record the set of genes that generated the best fitness
}
// push best one (found so far from all of history, not just this time) to network.
assert(this.bestGenes.length === Nsp);
this.espnet.pushGenes(this.bestGenes);
return bestFitness;
}
};
convnetjs.ESPNet = ESPNet;
convnetjs.ESPTrainer = ESPTrainer;
convnetjs.GATrainer = GATrainer;
})(convnetjs);
|
import { hash, compare, genSaltSync} from "bcrypt";
const saltRounds = 10;
/**
* Generate crypt and decrypt
* @param plainString
*/
exports.getHash = (plainString) => {
return hash(plainString, saltRounds)
.then((hash) => hash)
.catch((e) => console.log(e.message));
}
exports.getSalt = (length) => {
return genSaltSync(length)
}
exports.compareHash = (salted, hash) => {
return compare(salted, hash)
.then((res) => res)
.catch((e) => console.log(e.message));
} |
var tape = require("tape"),
getCurrentStyle = require("..");
tape("getCurrentStyle([element : Element]) should return elements current styles", function(assert) {
var element = document.createElement("div");
element.style.marginLeft = "10px";
document.body.appendChild(element);
assert.equal(getCurrentStyle(element, "marginLeft"), "10px");
assert.end();
});
|
var freeice = require('freeice');
var _ = require('eakwell');
var Socket = require('./socket.js');
var Storage = require('./storage.js');
var Broadcast = function(broadcastName, roomName, keepVideos) {
var self = this;
var stream = _.deferred();
var video;
var senderPeer;
var senderId = _.deferred();
var receiverPeers = {};
var senderIceCandidateCache = [];
var shutdown = false;
var stopRecord = null;
var socket = new Socket();
socket.onerror = function(error) {
console.log('WebSocket Error', error);
};
socket.onreconnect = function() {
if(senderPeer) reconnect();
};
socket.onmessage = function(data) {
switch(data.type) {
case 'offer':
console.log("Got offer from receiver " + data.fromReceiver);
var peer = getPeerConnection('publisher');
receiverPeers[data.fromReceiver] = peer;
peer.onicecandidate = function(e) {
if(e.candidate) {
socket.send({
type: 'iceCandidate',
roomName: roomName,
broadcastName: broadcastName,
candidate: e.candidate,
to: data.fromReceiver
});
}
};
stream.then(function(stream) {
// stream.getTracks().forEach(function(track) {
// peer.addTrack(track, stream);
// });
peer.addStream(stream);
// stream.getTracks().forEach(track => peer.addTrack(track, stream));
peer.setRemoteDescription(data.offer).then(function() {
peer.createAnswer().then(function(desc) {
peer.setLocalDescription(desc).then(function() {
socket.send({
type: 'answer',
answer: peer.localDescription,
roomName: roomName,
broadcastName: broadcastName,
toReceiver: data.fromReceiver
});
});
});
});
});
break;
case 'answer':
senderId.resolve(data.fromSender);
console.log("Got answer from sender " + data.fromSender);
senderPeer.setRemoteDescription(data.answer);
break;
case 'iceCandidate':
console.log("Got iceCandidate from " + data.from);
var peer = receiverPeers[data.from] || senderPeer;
peer.addIceCandidate(data.candidate);
break;
case 'stop':
stop();
break;
case 'dropReceiver':
var peer = receiverPeers[data.receiverId];
if(peer) {
peer.close();
delete receiverPeers[data.receiverId];
}
break;
case 'reconnect':
reconnect();
break;
}
};
var createVideoElement = function() {
var video = document.createElement('video');
video.autoplay = true;
return video;
};
var getMedia = function(constraints) {
return navigator.mediaDevices.getUserMedia(_.merge({
audio: true,
video: {
width: 320,
height: 240,
frameRate: 24
}}, constraints || {})
).then(function(_stream) {
// if(stream.getVideoTracks().length > 0)
video = video || createVideoElement();
video.muted = true;
video.srcObject = _stream;
stream.resolve(_stream);
return new Promise(function(ok, fail) {
video.onplaying = ok;
video.play();
});
});
};
var getPeerConnection = function(type) {
var peer = new RTCPeerConnection({iceServers: freeice()});
return peer;
return getPeerStats(peer, function(type, score) {
console.log(type, score);
});
};
var terminate = function() {
// Close peer connections
_.each(receiverPeers, function(peer) {
peer.close();
});
if(senderPeer) senderPeer.close();
// Close device stream if we are publishing
if(!senderPeer) {
stream.then(function(stream) {
_.each(stream.getTracks(), function(track) {
track.stop();
});
});
}
receiverPeers = {};
senderPeer = null;
senderId = _.deferred();
stream = _.deferred();
};
var reconnect = function() {
terminate();
self.receive();
};
var stop = function() {
terminate();
if(video && video.parentElement && !keepVideos) video.parentElement.removeChild(video);
video = null;
shutdown = true;
socket && socket.close();
socket = null;
self.onStop && self.onStop();
self.onStop = null;
stopRecord && stopRecord();
};
var record = function(cb, chunksize) {
chunksize = chunksize || Infinity;
var buffersize = 0;
var recordedBlobs = [];
var mediaRecorder = stream.then(function(stream) {
var mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = function(e) {
if(e.data && e.data.size > 0) {
if(buffersize + e.data.size > chunksize && recordedBlobs.length) {
cb && cb(new Blob(recordedBlobs, {type: 'video/webm'}));
recordedBlobs = [];
buffersize = 0;
}
recordedBlobs.push(e.data);
buffersize += e.data.size;
}
};
mediaRecorder.start(100);
return mediaRecorder;
});
return function() {
mediaRecorder.then(function(mediaRecorder) {
mediaRecorder.stop();
cb && recordedBlobs.length && cb(new Blob(recordedBlobs, {type: 'video/webm'}));
});
};
};
self.publish = function(constraints, cb) {
console.log(constraints);
getMedia(constraints).then(function() {
socket.send({
type: 'publishStream',
roomName: roomName,
broadcastName: broadcastName
});
cb && cb(null, video);
}).catch(function() {
cb && cb('Could not initialize video stream');
});
};
self.receive = function(cb) {
senderPeer = getPeerConnection('receiver');
senderPeer.onaddstream = function(e) {
stream.resolve(e.stream);
video = video || createVideoElement();
video.srcObject = e.stream;
video.play().catch(function(){});
cb && cb(null, video);
};
// senderPeer.ontrack = function(e) {
// // remoteVideo = createVideoElement();
// // remoteVideo.srcObject = e.streams[0];
// // remoteStream = e.streams[0];
// console.log('ontrack called');
// console.log('ontrack', e.streams)
// if(!cb) return;
// stream.resolve(e.streams[0]);
// video = video || createVideoElement();
// video.srcObject = e.streams[0];
// cb(null, video);
// cb = undefined;
// };
senderPeer.onicecandidate = function(e) {
if(e.candidate) {
senderId.then(function(senderId) {
socket.send({
type: 'iceCandidate',
roomName: roomName,
broadcastName: broadcastName,
candidate: e.candidate,
to: senderId
});
});
}
};
senderPeer.createOffer({
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
}).then(function(desc) {
senderPeer.setLocalDescription(desc).then(function() {
socket.send({
type: 'receiveStream',
roomName: roomName,
broadcastName: broadcastName,
offer: senderPeer.localDescription
});
});
}).catch(function() {
cb('Unable to create offer');
});
};
self.stop = function() {
// Close the entire broadcast if we are the publisher
if(!senderPeer) {
socket && socket.send({
type: 'closeBroadcast'
});
}
stop();
};
self.record = function(cb) {
// Record stream to disk
var recordId = _.uuid();
var storage = new Storage();
var stopRec = record(function(chunk) {
storage.store(chunk, recordId);
}, 500000);
// Start uploading chunks to the server
var uploading = true;
var uploadingFinished = false;
var uploadChunks = function() {
if(uploadingFinished) return cb(null);
storage.retrieve(recordId).then(function(chunk) {
return cb(chunk);
}).then(uploadChunks).catch(function() {
if(!uploading) uploadingFinished = true;
return _.delay(1000).then(uploadChunks);
});
};
uploadChunks();
// Recording shall end automatically when the broadcast stops
stopRecord = function() {
uploading = false;
stopRec && stopRec();
stopRec = null;
};
return stopRecord;
};
self.snapshot = function() {
if(!video) return;
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL('image/png');
};
};
var getPeerStats = function(peer, cb) {
var value = function(str) {
if(!str) return 0;
if(!isNaN(str)) return Number(str);
if(str == 'true') return true;
if(str == 'false') return false;
return str;
};
peer.onsignalingstatechange = function() {
if(peer.signalingState === 'closed') {
clearInterval(iv);
}
};
var iv = setInterval(function() {
getStats(peer, null).then(function(stats) {
var score = 0;
_.each(stats, function(stat) {
if(type == 'receiver') {
// Receiver
if(stat.type == 'ssrc' || stat.type == 'inboundrtp') {
var received = value(stat.packetsReceived);
if(stat.mediaType == 'video') {
score -= value(stat.googTargetDelayMs) +
// value(stat.packetsLost) / received +
value(stat.googCurrentDelayMs) +
value(stat.googDecodeMs) +
value(stat.googJitterBufferMs) +
value(stat.googRenderDelayMs) +
value(stat.framerateStdDev) +
value(stat.bitrateStdDev) +
value(stat.jitter) -
value(stat.packetsReceivedPerSecond) -
value(stat.bitsReceivedPerSecond) -
value(stat.googFrameRateReceived) -
value(stat.googFrameWidthReceived);
} else if(stat.mediaType == 'audio') {
score -= value(stat.googCurrentDelayMs) +
// value(stat.packetsLost) / received +
value(stat.googJitterReceived) +
value(stat.googJitterBufferMs) +
value(stat.jitter) -
value(stat.packetsReceivedPerSecond) -
value(stat.bitsReceivedPerSecond);
}
}
} else {
// Publisher
if((stat.type == 'ssrc' || stat.type == 'outboundrtp') && stat.mediaType == 'video') {
var sent = value(stat.packetsSent);
score -= value(stat.googAvgEncodeMs) +
value(stat.packetsLost) +
value(stat.googRtt) +
value(stat.googEncodeUsagePercent) +
value(stat.droppedFrames) +
value(stat.framerateStdDev) -
value(stat.packetsSentPerSecond) -
value(stat.bitsSentPerSecond) -
value(stat.googFrameRateSent) -
value(stat.googFrameWidthSent);
var limitedResolution = value(stat.googBandwidthLimitedResolution) || value(stat.googCpuLimitedResolution);
} else if(stat.type == 'VideoBwe') {
score += value(stat.googTransmitBitrate) +
value(stat.googReTransmitBitrate) +
value(stat.googAvailableSendBandwidth) +
value(stat.googActualEncBitrate);
}
}
});
cb(type, score);
});
}, 1000);
return peer;
};
function getStats(pc, selector) {
if(navigator.mozGetUserMedia) {
return pc.getStats(selector);
}
return new Promise(function(resolve, reject) {
pc.getStats(function(response) {
var standardReport = {};
response.result().forEach(function(report) {
var standardStats = {
id: report.id,
type: report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
resolve(standardReport);
}, selector, reject);
});
}
module.exports = Broadcast;
|
import ElementSerializer from 'ember-fhir/serializers/element';
export default ElementSerializer.extend({
attrs: {profile: { embedded: 'always' }
}
}); |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Jumapili",
"Jumatatu",
"Jumanne",
"Jumatano",
"Alhamisi",
"Ijumaa",
"Jumamosi"
],
"MONTH": [
"Januari",
"Februari",
"Machi",
"Aprili",
"Mei",
"Juni",
"Julai",
"Agosti",
"Septemba",
"Oktoba",
"Novemba",
"Desemba"
],
"SHORTDAY": [
"Jumapili",
"Jumatatu",
"Jumanne",
"Jumatano",
"Alhamisi",
"Ijumaa",
"Jumamosi"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mac",
"Apr",
"Mei",
"Jun",
"Jul",
"Ago",
"Sep",
"Okt",
"Nov",
"Des"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "UGX",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "sw-ug",
"pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
// @flow
import * as React from 'react';
import { connect } from 'react-redux';
import styles from './NavigationBar.scss';
import likedColorsSelector from '../../redux/selectors/likedColorsSelector';
import ExportButton from '../export/ExportButton';
type Props = {
likedColors: Array<Object>,
};
class NavigationBar extends React.Component<Props> {
handleClickTweet = () => {
const text =
'Check out this great color palette I made with Palettable, made by @whynotdostuff.';
const url = window.location.href;
window.open(
`http://twitter.com/intent/tweet?text=${text}&url=${url}`,
'thsare',
'height=400,width=550,resizable=1, toolbar=0,menubar=0,status=0, location=0'
);
};
render() {
return (
<div className={styles.navigationBar}>
<div className={styles.navigationText}>
<a href="/">
<h1>PALETTABLE</h1>
</a>
<p>
Generate beautiful color palettes using the knowledge of millions of
designers.
</p>
</div>
<div className={styles.exportOptions}>
<div className={styles.helpers}>
<p>
<span className={styles.key}>L</span>
Like
</p>
<p>
<span className={styles.key}>D</span>
Dislike
</p>
</div>
<div className={styles.divider} />
<a onClick={this.handleClickTweet}>
<svg
style={{ cursor: 'pointer' }}
fill="#619fcc"
preserveAspectRatio="xMidYMid meet"
height="20"
width="20"
viewBox="0 0 40 40"
>
<g>
<path d="m37.7 9.1q-1.5 2.2-3.7 3.7 0.1 0.3 0.1 1 0 2.9-0.9 5.8t-2.6 5.5-4.1 4.7-5.7 3.3-7.2 1.2q-6.1 0-11.1-3.3 0.8 0.1 1.7 0.1 5 0 9-3-2.4-0.1-4.2-1.5t-2.6-3.5q0.8 0.1 1.4 0.1 1 0 1.9-0.3-2.5-0.5-4.1-2.5t-1.7-4.6v0q1.5 0.8 3.3 0.9-1.5-1-2.4-2.6t-0.8-3.4q0-2 0.9-3.7 2.7 3.4 6.6 5.4t8.3 2.2q-0.2-0.9-0.2-1.7 0-3 2.1-5.1t5.1-2.1q3.2 0 5.3 2.3 2.4-0.5 4.6-1.7-0.8 2.5-3.2 3.9 2.1-0.2 4.2-1.1z" />
</g>
</svg>
</a>
<div className={styles.divider} />
<ExportButton />
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
likedColors: likedColorsSelector(state),
};
};
export default connect(
mapStateToProps,
null
)(NavigationBar);
|
var fs = require('fs')
module.exports = {
NODE_ENV: '"production"',
APP_VERSION: JSON.stringify(JSON.parse(fs.readFileSync('./package.json')).version)
}
|
if (typeof T === 'undefined') require('../setup');
T('clone', function () {
function t(expression) {
T.assert(expression);
}
Decimal.config({
precision: 10,
rounding: 4,
toExpNeg: -7,
toExpPos: 21,
minE: -9e15,
maxE: 9e15
});
var D1 = Decimal.clone({ precision: 1 });
var D2 = Decimal.clone({ precision: 2 });
var D3 = Decimal.clone({ precision: 3 });
var D4 = Decimal.clone({ precision: 4 });
var D5 = Decimal.clone({ precision: 5 });
var D6 = Decimal.clone({ precision: 6 });
var D7 = Decimal.clone({ precision: 7 });
var D8 = Decimal.clone();
D8.config({ precision: 8 });
var D9 = Decimal.clone({ precision: 9 });
t(Decimal.prototype === D9.prototype);
t(Decimal !== D9);
var x = new Decimal(5);
var x1 = new D1(5);
var x2 = new D2(5);
var x3 = new D3(5);
var x4 = new D4(5);
var x5 = new D5(5);
var x6 = new D6(5);
var x7 = new D7(5);
var x8 = new D8(5);
var x9 = new D9(5);
t(x1.div(3).eq(2));
t(x2.div(3).eq(1.7));
t(x3.div(3).eq(1.67));
t(x4.div(3).eq(1.667));
t(x5.div(3).eq(1.6667));
t(x6.div(3).eq(1.66667));
t(x7.div(3).eq(1.666667));
t(x8.div(3).eq(1.6666667));
t(x9.div(3).eq(1.66666667));
t(x .div(3).eq(1.666666667));
var y = new Decimal(3);
var y1 = new D1(3);
var y2 = new D2(3);
var y3 = new D3(3);
var y4 = new D4(3);
var y5 = new D5(3);
var y6 = new D6(3);
var y7 = new D7(3);
var y8 = new D8(3);
var y9 = new D9(3);
t(x1.div(y1).eq(2));
t(x2.div(y2).eq(1.7));
t(x3.div(y3).eq(1.67));
t(x4.div(y4).eq(1.667));
t(x5.div(y5).eq(1.6667));
t(x6.div(y6).eq(1.66667));
t(x7.div(y7).eq(1.666667));
t(x8.div(y8).eq(1.6666667));
t(x9.div(y9).eq(1.66666667));
t(x .div(y ).eq(1.666666667));
t(x1.div(y9).eq(2));
t(x2.div(y8).eq(1.7));
t(x3.div(y7).eq(1.67));
t(x4.div(y6).eq(1.667));
t(x5.div(y5).eq(1.6667));
t(x6.div(y4).eq(1.66667));
t(x7.div(y3).eq(1.666667));
t(x8.div(y2).eq(1.6666667));
t(x9.div(y1).eq(1.66666667));
t(Decimal.precision == 10);
t(D9.precision === 9);
t(D8.precision === 8);
t(D7.precision === 7);
t(D6.precision === 6);
t(D5.precision === 5);
t(D4.precision === 4);
t(D3.precision === 3);
t(D2.precision === 2);
t(D1.precision === 1);
t(new Decimal(9.99).eq(new D5('9.99')));
t(!new Decimal(9.99).eq(new D3('-9.99')));
t(!new Decimal(123.456789).toSD().eq(new D3('123.456789').toSD()));
t(new Decimal(123.456789).round().eq(new D3('123.456789').round()));
t(new Decimal(1).constructor === new Decimal(1).constructor);
t(new D9(1).constructor === new D9(1).constructor);
t(new Decimal(1).constructor !== new D1(1).constructor);
t(new D8(1).constructor !== new D9(1).constructor);
T.assertException(function () { Decimal.clone(null) }, "Decimal.clone(null)");
// defaults: true
Decimal.config({
precision: 100,
rounding: 2,
toExpNeg: -100,
toExpPos: 200,
defaults: true
});
t(Decimal.precision === 100);
t(Decimal.rounding === 2);
t(Decimal.toExpNeg === -100);
t(Decimal.toExpPos === 200);
t(Decimal.defaults === undefined);
D1 = Decimal.clone({ defaults: true });
t(D1.precision === 20);
t(D1.rounding === 4);
t(D1.toExpNeg === -7);
t(D1.toExpPos === 21);
t(D1.defaults === undefined);
D2 = Decimal.clone({ defaults: true, rounding: 5 });
t(D2.precision === 20);
t(D2.rounding === 5);
t(D2.toExpNeg === -7);
t(D2.toExpPos === 21);
D3 = Decimal.clone({ defaults: false });
t(D3.rounding === 2);
});
|
'use babel';
'use strict';
var fs = require('fs-extra');
var temp = require('temp');
var specHelpers = require('./spec-helpers');
describe('Visible', function() {
var directory = null;
var workspaceElement = null;
temp.track();
beforeEach(function() {
atom.config.set('build.buildOnSave', false);
atom.config.set('build.panelVisibility', 'Toggle');
atom.config.set('build.saveOnBuild', false);
atom.config.set('build.stealFocus', true);
atom.notifications.clear();
workspaceElement = atom.views.getView(atom.workspace);
jasmine.attachToDOM(workspaceElement);
jasmine.unspy(window, 'setTimeout');
jasmine.unspy(window, 'clearTimeout');
runs(function() {
workspaceElement = atom.views.getView(atom.workspace);
jasmine.attachToDOM(workspaceElement);
});
waitsForPromise(function() {
return specHelpers.vouch(temp.mkdir, { prefix: 'atom-build-spec-' }).then(function (dir) {
return specHelpers.vouch(fs.realpath, dir);
}).then(function (dir) {
directory = dir + '/';
atom.project.setPaths([ directory ]);
});
});
});
afterEach(function () {
fs.removeSync(directory);
});
describe('when package is activated with panel visibility set to Keep Visible', function() {
beforeEach(function () {
atom.config.set('build.panelVisibility', 'Keep Visible');
waitsForPromise(function () {
return atom.packages.activatePackage('build');
});
});
it('should not show build window', function() {
expect(workspaceElement.querySelector('.build')).not.toExist();
});
});
describe('when package is activated with panel visibility set to Toggle', function () {
beforeEach(function () {
atom.config.set('build.panelVisibility', 'Toggle');
waitsForPromise(function () {
return atom.packages.activatePackage('build');
});
});
describe('when build panel is toggled and it is visible', function() {
beforeEach(function () {
atom.commands.dispatch(workspaceElement, 'build:toggle-panel');
});
it('should hide the build panel', function() {
expect(workspaceElement.querySelector('.build')).toExist();
atom.commands.dispatch(workspaceElement, 'build:toggle-panel');
expect(workspaceElement.querySelector('.build')).not.toExist();
});
});
describe('when panel visibility is set to Show on Error', function() {
it('should only show an the build panel if a build fails', function () {
atom.config.set('build.panelVisibility', 'Show on Error');
fs.writeFileSync(directory + 'Makefile', fs.readFileSync(__dirname + '/fixture/Makefile.good'));
atom.commands.dispatch(workspaceElement, 'build:trigger');
/* Give it some reasonable time to show itself if there is a bug */
waits(200);
runs(function() {
expect(workspaceElement.querySelector('.build')).not.toExist();
});
runs(function () {
fs.writeFileSync(directory + 'Makefile', fs.readFileSync(__dirname + '/fixture/Makefile.bad'));
atom.commands.dispatch(workspaceElement, 'build:trigger');
});
waitsFor(function() {
return workspaceElement.querySelector('.build');
});
runs(function() {
expect(workspaceElement.querySelector('.build .output').textContent).toMatch(/Very bad\.\.\./);
});
});
});
describe('when panel visibility is set to Hidden', function() {
it('should not show the build panel if build succeeeds', function () {
atom.config.set('build.panelVisibility', 'Hidden');
fs.writeFileSync(directory + 'Makefile', fs.readFileSync(__dirname + '/fixture/Makefile.good'));
atom.commands.dispatch(workspaceElement, 'build:trigger');
/* Give it some reasonable time to show itself if there is a bug */
waits(200);
runs(function() {
expect(workspaceElement.querySelector('.build')).not.toExist();
});
});
it('should not show the build panel if build fails', function () {
atom.config.set('build.panelVisibility', 'Hidden');
fs.writeFileSync(directory + 'Makefile', fs.readFileSync(__dirname + '/fixture/Makefile.bad'));
atom.commands.dispatch(workspaceElement, 'build:trigger');
/* Give it some reasonable time to show itself if there is a bug */
waits(200);
runs(function() {
expect(workspaceElement.querySelector('.build')).not.toExist();
});
});
it('should show the build panel if it is toggled', function () {
atom.config.set('build.panelVisibility', 'Hidden');
fs.writeFileSync(directory + 'Makefile', fs.readFileSync(__dirname + '/fixture/Makefile.good'));
atom.commands.dispatch(workspaceElement, 'build:trigger');
waits(200); // Let build finish. Since UI component is not visible yet, there's nothing to poll.
runs(function () {
atom.commands.dispatch(workspaceElement, 'build:toggle-panel');
});
waitsFor(function() {
return workspaceElement.querySelector('.build .title') &&
workspaceElement.querySelector('.build .title').classList.contains('success');
});
runs(function() {
expect(workspaceElement.querySelector('.build .output').textContent).toMatch(/Surprising is the passing of time\nbut not so, as the time of passing/);
});
});
});
});
});
|
'use strict';
angular.module('discover').filter('relativeDate', function(){
return function(dateStr){
var date = new Date(dateStr),
//var date = new Date((dateStr || "").replace(/-/g, "/").replace(/[TZ]/g, " ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
var year = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate();
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31)
return (
year.toString()+'-'+
((month<10) ? '0'+month.toString() : month.toString())+'-'+
((day<10) ? '0'+day.toString() : day.toString())
);
var r =
(
(
day_diff === 0 &&
(
(diff < 60 && "just now") ||
(diff < 120 && "1 minute ago") ||
(diff < 3600 && Math.floor(diff / 60) + " minutes ago") ||
(diff < 7200 && "1 hour ago") ||
(diff < 86400 && Math.floor(diff / 3600) + " hours ago")
)
) ||
(day_diff === 1 && "Yesterday") ||
(day_diff < 7 && day_diff + " days ago") ||
(day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago")
);
return r;
};
});
|
// Regular expression that matches all symbols in the `Glagolitic` script as per Unicode v6.2.0:
/[\u2C00-\u2C2E\u2C30-\u2C5E]/; |
var async = require('async'),
PropValidator = require('./propvalidator');
/**
* Run validation functions.
* @param {Object} doc
* @param {Object} functions
* @param {boolean} parallel
* @param {function} done
*/
function validate(doc, functions, parallel, done) {
var tasks = [];
for (var key in functions) {
if (functions.hasOwnProperty(key)) {
(function (key) {
var func = functions[key];
tasks.push(function (next) {
var validator = new PropValidator(doc, key, func);
validator.process_(next);
});
})(key);
}
}
if (tasks.length > 0) {
var run = (parallel ? async.parallel : async.series);
run(tasks, function (err, results) {
if (err)
done(err);
else {
var errors = {},
hasError = false,
index = 0;
for (var key in functions) {
if (functions.hasOwnProperty(key)) {
var result = results[index];
if (result.length) {
errors[key] = result;
hasError = true;
}
++index;
}
}
done(null, hasError ? errors : null)
}
});
} else {
done();
}
}
function avalidator(schema, options) {
options = options || {};
if (options.parallel === undefined)
options.parallel = true;
var functions = options.validate || {},
hasFunction = false;
schema.eachPath(function (key, option) {
if ('avalidator' in option.options) {
hasFunction = true;
functions[key] = option.options['avalidator'];
}
});
if (hasFunction) {
schema.pre('validate', function (next) {
var self = this;
validate(this, functions, options.parallel, function (err, validationErrors) {
if (err)
next(err);
else {
if (validationErrors) {
for (var key in validationErrors) {
if (validationErrors.hasOwnProperty(key)) {
self.invalidate(key, validationErrors[key]);
}
}
}
next();
}
});
});
}
}
module.exports = avalidator; |
/* global define */
define([
'backbone',
'marionette',
'buses/event-bus',
// Behaviors
'behaviors/search-behavior',
// Templates
'templates/forms/navigation-search-template'
/* jshint unused: false */
], function (Backbone, Marionette, EventBus) {
'use strict';
var SearchView = Backbone.Marionette.ItemView.extend({
template: 'forms/navigation-search-template.dust',
ui: {
searchForm: '#search-site',
searchField: '#s'
},
behaviors: {
Search: { min: 3 }
},
initialize: function (options) {
options = options || {};
this.searchId = options.searchId || 'search-nav-bar';
},
onRender: function () {
this.$el.attr('id', this.searchId);
}
});
return SearchView;
});
|
'use strict';
// lesson-groups-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const lessonGroupsSchema = new Schema({
name: { type: String, required: true },
dates: [Date],
lessonId: { type: Schema.ObjectId, ref: 'lessons', required: true },
createdAt: { type: Date, 'default': Date.now },
updatedAt: { type: Date, 'default': Date.now }
});
lessonGroupsSchema.index({ name: 1, lessonId: 1 }, { unique: true });
const lessonGroupsModel = mongoose.model('lesson-groups', lessonGroupsSchema);
module.exports = lessonGroupsModel;
|
'use strict';
exports.up = function(knex, Promise) {
return Promise.all([
/*******************************************************
AUCTIONS TABLE
*******************************************************/
knex.schema.createTableIfNotExists('auctions', function(t) {
t.bigIncrements().primary();
t.charset('utf8');
t.string('auction_id');
t.string('actor');
t.string('action');
t.integer('plat_bid');
t.integer('plat_buyout');
t.integer('gold_bid');
t.integer('gold_buyout');
t.string('item');
t.timestamp('created_at').defaultTo(knex.fn.now());
}),
knex.schema.raw('create index auctions_createdat_idx on auctions("created_at");'),
knex.schema.raw('create index auctions_auctionid_idx on auctions("auction_id");'),
knex.schema.raw('create index auctions_action_idx on auctions("action");')
]);
};
exports.down = function(knex, Promise) {
return Promise.all([
/*******************************************************
AUCTIONS TABLE
*******************************************************/
knex.schema.dropTableIfExists('auctions'),
]);
};
|
/*jshint browserify: true */
var _ = require('underscore');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var $ = Backbone.$;
var Events = require('./events');
var Searchbox = require('./searchbox');
var Content = {};
var NavbarHeaderLayout = Marionette.LayoutView.extend({
template: _.template('<div class="container-fluid"><div id="nav-top-actions"></div><div id="nav-top-subactions" class="pull-right"></div></div>'),
className: 'navbar',
attributes: {
'role' : 'navigation'
},
ui: {
'toggle' : '#nav-left-toggle'
},
events: {
'click @ui.toggle' : 'toggle'
},
toggle: function(e) {
e.preventDefault();
Events.trigger('menu:toggleCollapse');
},
regions: {
actions: '#nav-top-actions',
subactions: '#nav-top-subactions'
}
});
var NavbarAction = Content.NavbarAction = Backbone.Model.extend({
defaults: {
className: ''
}
});
var NavbarActionCollection = Backbone.Collection.extend({
item: NavbarAction
});
var navbarActions = new NavbarActionCollection([
{ className: 'toggle', template: _.template('<a id="nav-left-toggle" href="#toggle"><i class="fa fa-bars"></i></a>') },
{ className: 'search', template: _.template('<div id="searchbox"></div>') }
]);
var NavbarActionView = Marionette.ItemView.extend({
tagName: 'li',
className: function() {
return this.model.get('className');
}
});
var NavbarActionCollectionView = Marionette.CollectionView.extend({
childView: NavbarActionView,
childViewOptions: function(model,index) {
return { template: model.get('template') }
},
template: _.template(''),
tagName: 'ul',
className: 'nav navbar-nav'
});
var ContentLayout = Marionette.LayoutView.extend({
template: _.template('<div id="nav-content"></div><div id="main-content" class="container-fluid"></div>'),
className: 'main-content',
regions: {
nav: '#nav-content',
content: '#main-content'
}
});
Content.show = function(actions) {
actions = actions || navbarActions;
var contentLayout = new ContentLayout();
var navLayout = new NavbarHeaderLayout();
var actions = new NavbarActionCollectionView({collection:navbarActions});
Plank.App.contentRegion.show(contentLayout);
contentLayout.nav.show(navLayout);
navLayout.actions.show(actions);
// yuck x_x
var $searchbox = $('#searchbox');
var searchbox = new Searchbox.SearchboxView({namespace: 'cases', el: $searchbox});
searchbox.render();
searchbox.on('searchbox:search:cases', function(source, value) {
console.log('search: ' + value);
var pid = setTimeout(function() {
source.trigger('search:complete');
}, 1500);
});
return contentLayout;
};
module.exports = Content; |
let models = require('../models');
const isNullOrUndefinedOrNaN = (value) => {
if (typeof value === 'null' ||
typeof value === 'undefined' ||
Number.isNaN(value)) {
return true;
}
return false;
}
const getJSONDiff = (prev = {}, next = {}) => {
const diffPrev = {};
const diffNext = {};
if (Object.keys(next).length < 1) {
return [prev, {}];
}
for(let i in next) {
if(!prev.hasOwnProperty(i) || next[i] !== prev[i]) {
if(
!Array.isArray(next[i]) ||
!(JSON.stringify(next[i]) == JSON.stringify(prev[i]))
){
if (!isNullOrUndefinedOrNaN(prev[i]) || !isNullOrUndefinedOrNaN(next[i])
) {
diffPrev[i] = !isNullOrUndefinedOrNaN(prev[i]) ? prev[i] : null;
diffNext[i] = !isNullOrUndefinedOrNaN(next[i]) ? next[i] : null;
}
}
}
}
for(let i in prev) {
if(!next.hasOwnProperty(i) || prev[i] !== next[i]) {
if(
!Array.isArray(prev[i]) ||
!(JSON.stringify(prev[i]) == JSON.stringify(next[i]))
){
if (!isNullOrUndefinedOrNaN(prev[i]) || !isNullOrUndefinedOrNaN(next[i])
) {
diffPrev[i] = !isNullOrUndefinedOrNaN(prev[i]) ? prev[i] : null;
diffNext[i] = !isNullOrUndefinedOrNaN(next[i]) ? next[i] : null;
}
}
}
}
const exactlySame = JSON.stringify(diffPrev) === JSON.stringify(diffNext);
return [diffPrev, diffNext, exactlySame];
}
exports.operation = {
CREATE: 'create',
UPDATE: 'update',
DELETE: 'delete',
}
exports.getJSONDiff = getJSONDiff;
exports.logData = (prevValue, nextValue, operation, resource, resourceID, desc, reference, referenceID) => {
const [diffPrev, diffNext, exactlySame] = getJSONDiff(prevValue, nextValue);
const now = new Date();
if (exactlySame) return;
models.Log.create({
diffPrev,
diffNext,
op: operation,
resource,
resourceID,
desc,
ref: reference,
refID: referenceID,
createdAt: now,
updatedAt: now,
})
}
|
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health = 100;
}
damage() {
this.health -= 10;
}
getHealth() {
return this.health
}
toString() {
return "x: " + this.x + " y: " + this.y + " health: " + this.health;
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString(){
return "name: " + this.name + " " + super.toString();
}
}
let x = process.argv[2];
let y = process.argv[3];
let name = process.argv[4];
let character = new Character(+x, +y);
character.damage();
console.log(character.toString());
let player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
|
import deepFreeze from 'deep-freeze';
import { ActionPrefixes, ReduxNames } from '../../constants';
import ucastniciTestData, {
AKTUALNI_DATUM_KONANI,
} from '../../entities/ucastnici/ucastniciTestData';
import { SortDirTypes } from '../../sort';
import {
createKategorieFilterChange,
createTextFilterChange,
} from '../Filterable/FilterableActions';
import { createSortDirChange } from '../UcastniciTable/UcastniciTableActions';
import {
createDohlaseniFilterChange,
createHideAkceMenu,
createPrihlaseniFilterChange,
createShowAkceMenu,
} from './PrihlaseniDohlaseniActions';
import {
createPrihlaseniDohlaseniReducer,
getPrihlaseniDohlaseniSorted,
} from './prihlaseniDohlaseniReducer';
const actionPrefix = ActionPrefixes.PRIHLASENI;
const reduxName = ReduxNames.prihlaseni;
const dohlaseniFilterChange = createDohlaseniFilterChange(actionPrefix);
const hideAkceMenu = createHideAkceMenu(actionPrefix);
const kategorieFilterChange = createKategorieFilterChange(actionPrefix);
const prihlaseniFilterChange = createPrihlaseniFilterChange(actionPrefix);
const prihlaseniDohlaseniReducer = createPrihlaseniDohlaseniReducer(actionPrefix);
const showAkceMenu = createShowAkceMenu(actionPrefix);
const sortDirChange = createSortDirChange(actionPrefix);
const textFilterChange = createTextFilterChange(actionPrefix);
it('na začátku', () => {
const stateBefore = undefined;
const stateAfter = prihlaseniDohlaseniReducer(stateBefore, {});
expect(stateAfter.dohlaseniFilter).toBe(false);
expect(stateAfter.prihlaseniFilter).toBe(true);
expect(stateAfter.kategorieFilter).toEqual('');
expect(stateAfter.showingAkceMenuFor).toBe(undefined);
expect(stateAfter.textFilter).toEqual('');
expect(stateAfter.sortColumn).toBe(undefined);
expect(stateAfter.sortDir).toEqual(SortDirTypes.NONE);
});
it('přepínání dohlaseniFilter - tam', () => {
const stateBefore = { dohlaseniFilter: false };
const stateAfter = { dohlaseniFilter: true };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, dohlaseniFilterChange())).toEqual(stateAfter);
});
it('přepínání dohlaseniFilter - a zase zpět', () => {
const stateBefore = { dohlaseniFilter: true };
const stateAfter = { dohlaseniFilter: false };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, dohlaseniFilterChange())).toEqual(stateAfter);
});
it('přepínání prihlaseniFilter - tam', () => {
const stateBefore = { prihlaseniFilter: true };
const stateAfter = { prihlaseniFilter: false };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, prihlaseniFilterChange())).toEqual(stateAfter);
});
it('přepínání prihlaseniFilter - a zase zpět', () => {
const stateBefore = { prihlaseniFilter: false };
const stateAfter = { prihlaseniFilter: true };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, prihlaseniFilterChange())).toEqual(stateAfter);
});
it('hideAkceMenu()', () => {
const stateBefore = { showingAkceMenuFor: '===id1===' };
const stateAfter = { showingAkceMenuFor: undefined };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, hideAkceMenu())).toEqual(stateAfter);
});
it('přepínání showAkceMenu', () => {
const stateBefore = { showingAkceMenuFor: undefined };
const stateAfter = { showingAkceMenuFor: '===id2===' };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, showAkceMenu('===id2==='))).toEqual(stateAfter);
});
it('řadit dle příjmení vzestupně', () => {
const stateBefore = {
sortColumn: undefined,
sortDir: SortDirTypes.NONE,
kategorieFilter: '',
textFilter: '',
};
const stateAfter = { ...stateBefore, sortColumn: 'prijmeni', sortDir: SortDirTypes.ASC };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, sortDirChange('prijmeni'))).toEqual(stateAfter);
});
it('řadit dle příjmení sestupně', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.ASC,
kategorieFilter: '',
textFilter: '',
};
const stateAfter = { ...stateBefore, sortColumn: 'prijmeni', sortDir: SortDirTypes.DESC };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, sortDirChange('prijmeni'))).toEqual(stateAfter);
});
it('řadit dle příjmení zase vzestupně', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.DESC,
kategorieFilter: '',
textFilter: '',
};
const stateAfter = { ...stateBefore, sortColumn: 'prijmeni', sortDir: SortDirTypes.ASC };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, sortDirChange('prijmeni'))).toEqual(stateAfter);
});
it('řadit dle jména vzestupně', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.ASC,
kategorieFilter: '',
textFilter: '',
};
const stateAfter = { ...stateBefore, sortColumn: 'jmeno', sortDir: SortDirTypes.ASC };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, sortDirChange('jmeno'))).toEqual(stateAfter);
});
it('zapnout filtrování podle kategorie výkonu', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.ASC,
kategorieFilter: '',
textFilter: '',
};
const stateAfter = { ...stateBefore, kategorieFilter: 'půlmaraton' };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, kategorieFilterChange('půlmaraton'))).toEqual(
stateAfter
);
});
it('vypnout filtrování podle kategorie výkonu', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.ASC,
kategorieFilter: 'půlmaraton',
textFilter: '',
};
const stateAfter = { ...stateBefore, kategorieFilter: '' };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, kategorieFilterChange('půlmaraton'))).toEqual(
stateAfter
);
});
it('přepnout filtrování podle kategorie výkonu', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.ASC,
kategorieFilter: 'půlmaraton',
textFilter: '',
};
const stateAfter = { ...stateBefore, kategorieFilter: 'pěší' };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, kategorieFilterChange('pěší'))).toEqual(
stateAfter
);
});
it('filtrovat na dvě písmena', () => {
const stateBefore = {
sortColumn: 'prijmeni',
sortDir: SortDirTypes.ASC,
kategorieFilter: '',
textFilter: '',
};
const stateAfter = { ...stateBefore, textFilter: 'kl' };
deepFreeze(stateBefore);
expect(prihlaseniDohlaseniReducer(stateBefore, textFilterChange('Kl'))).toEqual(stateAfter);
});
it('getPrihlaseniSorted() by default - prihlášeni i dohlášeni', () => {
const state = {
...ucastniciTestData,
registrator: {
[reduxName]: {
dohlaseniFilter: false,
prihlaseniFilter: false,
sortColumn: undefined,
sortDir: undefined,
kategorieFilter: '',
textFilter: '',
},
},
};
const selected = [
{
id: '5a09b1fd371dec1e99b7e1c9',
prijmeni: 'Balabák',
jmeno: 'Roman',
narozeni: { rok: 1956 },
pohlavi: 'muž',
obec: 'Ostrava 2',
email: '',
datum: new Date(AKTUALNI_DATUM_KONANI),
kategorie: {
id: '5a587e1b051c181132cf83d7',
pohlavi: 'muž',
typ: 'půlmaraton',
vek: { min: 60, max: 150 },
},
startCislo: 17,
kod: '10728864',
zaplaceno: 350,
predepsano: 350,
nejakaPoznamka: false,
},
{
id: '8344bc71dec1e99b7e1d01e',
prijmeni: 'Kyselová',
jmeno: 'Slavěna',
narozeni: { den: 13, mesic: 8, rok: 2001 },
pohlavi: 'žena',
obec: 'Aš',
email: 'sks@por.cz',
datum: new Date(AKTUALNI_DATUM_KONANI),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 15,
kod: '0234jsdj0jdaklsd',
zaplaceno: 0,
predepsano: 0,
nejakaPoznamka: true,
},
{
id: '9ccbc71dedc1e99b7e1d671',
prijmeni: 'Půlmaratonka',
jmeno: 'Božena',
narozeni: { den: 25, mesic: 7, rok: 2001 },
pohlavi: 'žena',
obec: 'Velhartice',
email: 'pul.ka@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 8,
kod: 'abc023skd204mvs345',
zaplaceno: 0,
predepsano: 350,
nejakaPoznamka: false,
},
{
id: 'f5c88400190a4bed88c76736',
prijmeni: 'Smalt',
jmeno: 'Josef',
narozeni: { den: 25, mesic: 7, rok: 2001 },
pohlavi: 'muž',
obec: 'Králův Dvůr',
email: '',
datum: new Date('2020-05-17T00:00:00.000Z'),
kategorie: {
id: '5a587e1a051c181132cf83b8',
typ: 'maraton',
pohlavi: 'muž',
vek: { min: 18, max: 39 },
},
startCislo: 15,
kod: 'rcc023skd204mvs345',
zaplaceno: 250,
predepsano: 250,
nejakaPoznamka: false,
},
{
id: '7a09b1fd371dec1e99b7e142',
prijmeni: 'Zralá',
jmeno: 'Hana',
narozeni: { den: 25, mesic: 7, rok: 1999 },
pohlavi: 'žena',
obec: 'Bučovice',
email: 'zrala.kl@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 10,
kod: 'abc023skd204mvs345',
zaplaceno: 180,
predepsano: 350,
nejakaPoznamka: true,
},
];
deepFreeze(state);
const {
entities,
registrator: { [reduxName]: props },
} = state;
expect(getPrihlaseniDohlaseniSorted({ ...entities, ...props })).toEqual(selected);
});
it('getPrihlaseniSorted() filtrováno na z', () => {
const state = {
...ucastniciTestData,
registrator: {
[reduxName]: {
dohlaseniFilter: false,
prihlaseniFilter: false,
sortColumn: undefined,
sortDir: undefined,
kategorieFilter: '',
textFilter: 'z',
},
},
};
const selected = [
{
id: '7a09b1fd371dec1e99b7e142',
prijmeni: 'Zralá',
jmeno: 'Hana',
narozeni: { den: 25, mesic: 7, rok: 1999 },
pohlavi: 'žena',
obec: 'Bučovice',
email: 'zrala.kl@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 10,
kod: 'abc023skd204mvs345',
zaplaceno: 180,
predepsano: 350,
nejakaPoznamka: true,
},
];
deepFreeze(state);
const {
entities,
registrator: { [reduxName]: props },
} = state;
expect(getPrihlaseniDohlaseniSorted({ ...entities, ...props })).toEqual(selected);
});
it('getPrihlaseniSorted() filtrováno na kategorii výkonu půlmaraton', () => {
const state = {
...ucastniciTestData,
registrator: {
[reduxName]: {
dohlaseniFilter: false,
prihlaseniFilter: false,
sortColumn: undefined,
sortDir: undefined,
kategorieFilter: 'půlmaraton',
textFilter: '',
},
},
};
const selected = [
{
id: '5a09b1fd371dec1e99b7e1c9',
prijmeni: 'Balabák',
jmeno: 'Roman',
narozeni: { rok: 1956 },
pohlavi: 'muž',
obec: 'Ostrava 2',
email: '',
datum: new Date(AKTUALNI_DATUM_KONANI),
kategorie: {
id: '5a587e1b051c181132cf83d7',
pohlavi: 'muž',
typ: 'půlmaraton',
vek: { min: 60, max: 150 },
},
startCislo: 17,
kod: '10728864',
zaplaceno: 350,
predepsano: 350,
nejakaPoznamka: false,
},
{
id: '8344bc71dec1e99b7e1d01e',
prijmeni: 'Kyselová',
jmeno: 'Slavěna',
narozeni: { den: 13, mesic: 8, rok: 2001 },
pohlavi: 'žena',
obec: 'Aš',
email: 'sks@por.cz',
datum: new Date(AKTUALNI_DATUM_KONANI),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 15,
kod: '0234jsdj0jdaklsd',
zaplaceno: 0,
predepsano: 0,
nejakaPoznamka: true,
},
{
id: '9ccbc71dedc1e99b7e1d671',
prijmeni: 'Půlmaratonka',
jmeno: 'Božena',
narozeni: { den: 25, mesic: 7, rok: 2001 },
pohlavi: 'žena',
obec: 'Velhartice',
email: 'pul.ka@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 8,
kod: 'abc023skd204mvs345',
zaplaceno: 0,
predepsano: 350,
nejakaPoznamka: false,
},
{
id: '7a09b1fd371dec1e99b7e142',
prijmeni: 'Zralá',
jmeno: 'Hana',
narozeni: { den: 25, mesic: 7, rok: 1999 },
pohlavi: 'žena',
obec: 'Bučovice',
email: 'zrala.kl@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 10,
kod: 'abc023skd204mvs345',
zaplaceno: 180,
predepsano: 350,
nejakaPoznamka: true,
},
];
deepFreeze(state);
const {
entities,
registrator: { [reduxName]: props },
} = state;
expect(getPrihlaseniDohlaseniSorted({ ...entities, ...props })).toEqual(selected);
});
it('getPrihlaseniSorted() by default - jen prihlášeni', () => {
const state = {
...ucastniciTestData,
registrator: {
[reduxName]: {
dohlaseniFilter: false,
prihlaseniFilter: true,
sortColumn: undefined,
sortDir: undefined,
kategorieFilter: '',
textFilter: '',
},
},
};
const selected = [
{
id: '9ccbc71dedc1e99b7e1d671',
prijmeni: 'Půlmaratonka',
jmeno: 'Božena',
narozeni: { den: 25, mesic: 7, rok: 2001 },
pohlavi: 'žena',
obec: 'Velhartice',
email: 'pul.ka@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 8,
kod: 'abc023skd204mvs345',
zaplaceno: 0,
predepsano: 350,
nejakaPoznamka: false,
},
{
id: 'f5c88400190a4bed88c76736',
prijmeni: 'Smalt',
jmeno: 'Josef',
narozeni: { den: 25, mesic: 7, rok: 2001 },
pohlavi: 'muž',
obec: 'Králův Dvůr',
email: '',
datum: new Date('2020-05-17T00:00:00.000Z'),
kategorie: {
id: '5a587e1a051c181132cf83b8',
typ: 'maraton',
pohlavi: 'muž',
vek: { min: 18, max: 39 },
},
startCislo: 15,
kod: 'rcc023skd204mvs345',
zaplaceno: 250,
predepsano: 250,
nejakaPoznamka: false,
},
{
id: '7a09b1fd371dec1e99b7e142',
prijmeni: 'Zralá',
jmeno: 'Hana',
narozeni: { den: 25, mesic: 7, rok: 1999 },
pohlavi: 'žena',
obec: 'Bučovice',
email: 'zrala.kl@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 10,
kod: 'abc023skd204mvs345',
zaplaceno: 180,
predepsano: 350,
nejakaPoznamka: true,
},
];
deepFreeze(state);
const {
entities,
registrator: { [reduxName]: props },
} = state;
expect(getPrihlaseniDohlaseniSorted({ ...entities, ...props })).toEqual(selected);
});
it('getPrihlaseniSorted() by default - jen dohlášeni', () => {
const state = {
...ucastniciTestData,
registrator: {
[reduxName]: {
dohlaseniFilter: true,
prihlaseniFilter: false,
sortColumn: undefined,
sortDir: undefined,
kategorieFilter: '',
textFilter: '',
},
},
};
const selected = [
{
id: '5a09b1fd371dec1e99b7e1c9',
prijmeni: 'Balabák',
jmeno: 'Roman',
narozeni: { rok: 1956 },
pohlavi: 'muž',
obec: 'Ostrava 2',
email: '',
datum: new Date(AKTUALNI_DATUM_KONANI),
kategorie: {
id: '5a587e1b051c181132cf83d7',
pohlavi: 'muž',
typ: 'půlmaraton',
vek: { min: 60, max: 150 },
},
startCislo: 17,
kod: '10728864',
zaplaceno: 350,
predepsano: 350,
nejakaPoznamka: false,
},
{
id: '8344bc71dec1e99b7e1d01e',
prijmeni: 'Kyselová',
jmeno: 'Slavěna',
narozeni: { den: 13, mesic: 8, rok: 2001 },
pohlavi: 'žena',
obec: 'Aš',
email: 'sks@por.cz',
datum: new Date(AKTUALNI_DATUM_KONANI),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 15,
kod: '0234jsdj0jdaklsd',
zaplaceno: 0,
predepsano: 0,
nejakaPoznamka: true,
},
{
id: '7a09b1fd371dec1e99b7e142',
prijmeni: 'Zralá',
jmeno: 'Hana',
narozeni: { den: 25, mesic: 7, rok: 1999 },
pohlavi: 'žena',
obec: 'Bučovice',
email: 'zrala.kl@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 10,
kod: 'abc023skd204mvs345',
zaplaceno: 180,
predepsano: 350,
nejakaPoznamka: true,
},
];
deepFreeze(state);
const {
entities,
registrator: { [reduxName]: props },
} = state;
expect(getPrihlaseniDohlaseniSorted({ ...entities, ...props })).toEqual(selected);
});
it('getPrihlaseniSorted() by default - jen přihlášeni i dohlášeni', () => {
const state = {
...ucastniciTestData,
registrator: {
[reduxName]: {
dohlaseniFilter: true,
prihlaseniFilter: true,
sortColumn: undefined,
sortDir: undefined,
kategorieFilter: '',
textFilter: '',
},
},
};
const selected = [
{
id: '7a09b1fd371dec1e99b7e142',
prijmeni: 'Zralá',
jmeno: 'Hana',
narozeni: { den: 25, mesic: 7, rok: 1999 },
pohlavi: 'žena',
obec: 'Bučovice',
email: 'zrala.kl@s.cz',
datum: new Date('2020-05-12T00:00:00.000Z'),
kategorie: {
id: '5a587e1b051c181132cf83d9',
typ: 'půlmaraton',
pohlavi: 'žena',
vek: { min: 18, max: 39 },
},
startCislo: 10,
kod: 'abc023skd204mvs345',
zaplaceno: 180,
predepsano: 350,
nejakaPoznamka: true,
},
];
deepFreeze(state);
const {
entities,
registrator: { [reduxName]: props },
} = state;
expect(getPrihlaseniDohlaseniSorted({ ...entities, ...props })).toEqual(selected);
});
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Zimlets
* Copyright (C) 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
function com_zimbra_socialPreferences(zimlet) {
this.zimlet = zimlet;
this.shell = this.zimlet.getShell();
this._fbNeedPermCount = 0;
this.social_pref_tweetmemePopularIsOn = this.zimlet.getUserProperty("social_pref_tweetmemePopularIsOn") == "true";
this.social_pref_trendsPopularIsOn = this.zimlet.getUserProperty("social_pref_trendsPopularIsOn") == "true";
this.social_pref_diggPopularIsOn = this.zimlet.getUserProperty("social_pref_diggPopularIsOn") == "true";
this.social_pref_SocialMailUpdateOn = this.zimlet.getUserProperty("social_pref_SocialMailUpdateOn") == "true";
this.social_pref_dontShowWelcomeScreenOn = this.zimlet.getUserProperty("social_pref_dontShowWelcomeScreenOn") == "true";
this.social_pref_showTweetAlertsOn = this.zimlet.getUserProperty("social_pref_showTweetAlertsOn") == "true";
this.social_pref_cardWidthList = this.zimlet.getUserProperty("social_pref_cardWidthList");
this.social_pref_numberofTweetsToReturn = parseInt(this.zimlet.getUserProperty("social_pref_numberofTweetsToReturn"));
this.social_pref_numberofTweetsSearchesToReturn = parseInt(this.zimlet.getUserProperty("social_pref_numberofTweetsSearchesToReturn"));
this.social_pref_autoShortenURLOn = this.zimlet.getUserProperty("social_pref_autoShortenURLOn") == "true";
this.social_pref_socializeBtnOn = this.zimlet.getUserProperty("social_pref_socializeBtnOn") == "true";
var socialcastAccounts = this.zimlet.getUserProperty("socialcastAccounts");
if(!socialcastAccounts) {
this.zimlet.socialcastAccounts = this.socialcastAccounts = [];
} else {
this.zimlet.socialcastAccounts = this.socialcastAccounts = JSON.parse(socialcastAccounts);
}
}
com_zimbra_socialPreferences.prototype._showManageAccntsDlg = function() {
//if zimlet dialog already exists...
if (this._manageAccntsDlg) {
this._updateAccountsTable();
this._updateAllFBPermissions();
this._manageAccntsDlg.popup();
return;
}
this._manageAccntsView = new DwtComposite(this.shell);
this._manageAccntsView.setSize(550, 300);
this._manageAccntsView.getHtmlElement().style.overflow = "auto";
this._manageAccntsView.getHtmlElement().innerHTML = this._createManageeAccntsView();
this._manageAccntsDlg = this.zimlet._createDialog({title:this.zimlet.getMessage("addRemoveAccounts"), view:this._manageAccntsView, standardButtons:[DwtDialog.OK_BUTTON, DwtDialog.CANCEL_BUTTON]});
this._manageAccntsDlg.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._manageAccntsOKBtnListener));
this.socialcastAddAccountDlg = new SocialcastAddAccountDlg(this, this.zimlet);
this._addPrefButtons();
this._updateAccountsTable();
this._updateAllFBPermissions();
this._manageAccntsDlg.popup();
};
com_zimbra_socialPreferences.prototype._addPrefButtons =
function() {
/*var addTwitterBtn = new DwtButton({parent:this.zimlet.getShell()});
addTwitterBtn.setText(this.zimlet.getMessage("addTwitterAcc"));
addTwitterBtn.setImage("social_twitterIcon");
addTwitterBtn.addSelectionListener(new AjxListener(this, this._addTwitterBtnListener));
document.getElementById("social_pref_addTwitterButtonCell").appendChild(addTwitterBtn.getHtmlElement());
var addFacebookBtn = new DwtButton({parent:this.zimlet.getShell()});
addFacebookBtn.setText(this.zimlet.getMessage("addFacebookAcc"));
addFacebookBtn.setImage("social_facebookIcon");
addFacebookBtn.addSelectionListener(new AjxListener(this, this._addFacebookBtnListener));
document.getElementById("social_pref_addFaceBookButtonCell").appendChild(addFacebookBtn.getHtmlElement());
*/
var btn = new DwtButton({parent:this.zimlet.getShell()});
btn.setText(this.zimlet.getMessage("addAccounts"));
btn.setImage("social-panelIcon");
var menu = new ZmPopupMenu(btn);
btn.setMenu(menu);
document.getElementById("social_pref_addAccountsCell").appendChild(btn.getHtmlElement());
var id = "social_pref_add_twitter_account";
var mi = menu.createMenuItem(id, {image:"social_twitterIcon", text:this.zimlet.getMessage("addTwitterAcc")});
mi.addSelectionListener(new AjxListener(this, this._addTwitterBtnListener));
var id = "social_pref_add_fb_account";
var mi = menu.createMenuItem(id, {image:"social_facebookIcon", text:this.zimlet.getMessage("addFacebookAcc")});
mi.addSelectionListener(new AjxListener(this, this._addFacebookBtnListener));
var id = "social_pref_add_sc_account";
var mi = menu.createMenuItem(id, {image:"social_socialcastIcon", text:this.zimlet.getMessage("addSocialcastAcc")});
mi.addSelectionListener(new AjxListener(this.socialcastAddAccountDlg, this.socialcastAddAccountDlg.popup));
var deleteAccountBtn = new DwtButton({parent:this.zimlet.getShell()});
deleteAccountBtn.setText(this.zimlet.getMessage("deleteAcc"));
deleteAccountBtn.setImage("Trash");
deleteAccountBtn.addSelectionListener(new AjxListener(this, this._deleteAccountBtnListener));
document.getElementById("social_pref_deleteAccountCell").appendChild(deleteAccountBtn.getHtmlElement());
var refreshTableBtn = new DwtButton({parent:this.zimlet.getShell()});
refreshTableBtn.setText( this.zimlet.getMessage("refreshAcc"));
refreshTableBtn.setImage("Refresh");
refreshTableBtn.addSelectionListener(new AjxListener(this, this._refreshTableBtnListener));
document.getElementById("social_pref_refreshTableCell").appendChild(refreshTableBtn.getHtmlElement());
};
com_zimbra_socialPreferences.prototype._refreshTableBtnListener =
function() {
this._updateAllFBPermissions();
};
com_zimbra_socialPreferences.prototype._addTwitterBtnListener =
function() {
this.zimlet.twitter.performOAuth();
};
com_zimbra_socialPreferences.prototype.addSocialCastAccount =
function(email, pwd, server) {
this.zimlet.socialcast.addAccount(email, pwd, server);
};
com_zimbra_socialPreferences.prototype._addFacebookBtnListener =
function() {
this.reloginToFB = true;
//this.showAddFBInfoDlg();
this.zimlet.facebook.showFBWindow();
};
com_zimbra_socialPreferences.prototype._deleteAccountBtnListener =
function() {
var needToUpdateAllAccounts = false;
var needToUpdateSocialcastAccounts = false;
var hasAllAccounts = false;
var hasSCAccounts = false;
var newAllAccounts = new Array();
for (var id in this.zimlet.allAccounts) {
hasAllAccounts = true;
if (!document.getElementById("social_pref_accnts_checkbox" + id).checked) {
newAllAccounts[id] = this.zimlet.allAccounts[id];
} else {
needToUpdateAllAccounts = true;
}
}
var newSAAccount = [];
for(var i=0; i< this.zimlet.socialcastAccounts.length; i++) {
hasSCAccounts = true;
var account = this.zimlet.socialcastAccounts[i];
if (document.getElementById("social_pref_accnts_checkbox" + account.un).checked) {
needToUpdateSocialcastAccounts = true;
} else {
newSAAccount.push(account);
}
}
if (needToUpdateAllAccounts && hasAllAccounts) {
this.zimlet.allAccounts = newAllAccounts;
this.zimlet.setUserProperty("social_AllTwitterAccounts", this.zimlet.getAllAccountsAsString());
}
if (needToUpdateSocialcastAccounts && hasSCAccounts) {
this.zimlet.socialcastAccounts = this.socialcastAccounts = newSAAccount;
this.zimlet.setUserProperty("socialcastAccounts", JSON.stringify(this.zimlet.socialcastAccounts));
}
if(needToUpdateSocialcastAccounts || needToUpdateAllAccounts) {
this.zimlet.saveUserProperties();
this._updateAccountsTable();
this.zimlet._updateAllWidgetItems({updateSearchTree:false, updateSystemTree:true, updateAccntCheckboxes:true, searchCards:false});
}
};
com_zimbra_socialPreferences.prototype._createManageeAccntsView =
function() {
var html = new Array();
var i = 0;
html[i++] = "<BR/>";
html[i++] = "<DIV class='social_topWgtClass' >";
html[i++] = "<table width=400px cellpadding=2 cellspacing=2>";
html[i++] = "<TR>";
html[i++] = "<TD>";
html[i++] = "<label style=\"font-size:12px;color:black;font-weight:bold\">"+ this.zimlet.getMessage("manageAccounts");
html[i++] = "</label>";
html[i++] = "</TD>";
html[i++] = "</TR>";
html[i++] = "</table>";
html[i++] = "</DIV>";
html[i++] = "<DIV class='social_white' id='social_pref_accntsTable'>";
html[i++] = this._getPrefAccountsTableHTML();
html[i++] = "</DIV>";
html[i++] = "<BR>";
html[i++] = "<BR>";
html[i++] = "<DIV>";
html[i++] = "<table align='center'>";
html[i++] = "<TR>";
html[i++] = "<TD id='social_pref_addAccountsCell'>";
html[i++] = "</TD>";
html[i++] = "<TD id='social_pref_refreshTableCell'>";
html[i++] = "</TD>";
html[i++] = "<TD id='social_pref_deleteAccountCell'>";
html[i++] = "</TD>";
html[i++] = "</TR>";
html[i++] = "</table>";
html[i++] = "</DIV>";
html[i++] = "<BR/>";
html[i++] = "<DIV id='social_prefDlg_currentStateMessage' class='social_yellowBold' style='display:none'>";
html[i++] = "</DIV >";
html[i++] = "<BR/>";
html[i++] = "<BR/>";
html[i++] = "<BR/>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._updateAccountsTable =
function(additionalMsgParams) {
document.getElementById("social_pref_accntsTable").innerHTML = this._getPrefAccountsTableHTML();
for (var i = 0; i < this._authorizeDivIdAndAccountMap.length; i++) {
var map = this._authorizeDivIdAndAccountMap[i];
var authBtn = new DwtButton({parent:this.zimlet.getShell()});
authBtn.setText("Authorize");
authBtn.addSelectionListener(new AjxListener(this, this._authorizeBtnListener, map));
document.getElementById(map.divId).appendChild(authBtn.getHtmlElement());
}
if (this._fbNeedPermCount != 0) {
this._setAccountPrefDlgAuthMessage(this.zimlet.getMessage("authorizeZimbraToAccessFacebook"), "blue");
} else {
this._setAccountPrefDlgAuthMessage(this.zimlet.getMessage("accountsUpdated"), "green");
}
if (additionalMsgParams != undefined
&& additionalMsgParams.askForPermissions != undefined
&& additionalMsgParams.askForPermissions == true
&& this._fbNeedPermCount != 0) {
this.showAddFBInfoDlg({permName:"", permCount: this._fbNeedPermCount});
this.zimlet.facebook.askForPermissions();
}
};
com_zimbra_socialPreferences.prototype._setAccountPrefDlgAuthMessage =
function (message, color) {
document.getElementById("social_prefDlg_currentStateMessage").innerHTML = "<lable style='color:" + color + "'>" + message + "</label>";
document.getElementById("social_prefDlg_currentStateMessage").style.display = "block";
};
com_zimbra_socialPreferences.prototype._updateAllFBPermissions =
function(additionalMsgParams) {
for (var id in this.zimlet.allAccounts) {
var account = this.zimlet.allAccounts[id];
if (account.type == "facebook") {
var callback0 = new AjxCallback(this, this._updateAccountsTable, additionalMsgParams);
var callback1 = new AjxCallback(this.zimlet.facebook, this.zimlet.facebook._getExtendedPermissionInfo, {account:account, permission:"read_stream", callback:callback0});
var callback2 = new AjxCallback(this.zimlet.facebook, this.zimlet.facebook._getExtendedPermissionInfo, {account:account, permission:"publish_stream", callback:callback1});
this.zimlet.facebook._getExtendedPermissionInfo({account:account, permission:"offline_access", callback:callback2});
}
}
};
/*
com_zimbra_socialPreferences.prototype._authorizeBtnListener =
function(params) {
var permName = "";
if (params.permission == "read_stream")
permName = "read";
else if (params.permission == "publish_stream")
permName = "write/publish";
else if (params.permission == "offline_access")
permName = "offline/rememberMe";
this._addFacebookBtnListener();
};
*/
com_zimbra_socialPreferences.prototype._getPrefAccountsTableHTML =
function() {
this._authorizeDivIdAndAccountMap = new Array();
var html = new Array();
var i = 0;
var noAccountsFound = true;
this._fbNeedPermCount = 0;
this._fbNeedPermissions = "";
html[i++] = "<table width=100% border=1 cellspacing=0 cellpadding=3>";
html[i++] = "<TR><TH>"+this.zimlet.getMessage("select")+"</TH><TH>"
+this.zimlet.getMessage("accountType")+
"</TH><TH>"+this.zimlet.getMessage("accountName")+
"</TH><TH>"+this.zimlet.getMessage("accountActivated")+
"</TH>";
/*"<TH>"+this.zimlet.getMessage("writePermission")+
"</TH><TH>"+this.zimlet.getMessage("rememberMePermission")+"</TH>";
*/
for (var id in this.zimlet.allAccounts) {
var account = this.zimlet.allAccounts[id];
var accIcon;
var statIcon;
if (account.type == "twitter") {
accIcon = "social_twitterIcon";
statIcon = "social_checkIcon";
} else if(account.type == "facebook") {
accIcon = "social_facebookIcon";
statIcon = "social_checkIcon";
}
var params = {id:id, type: account.type, accIcon: accIcon, statIcon:statIcon, name:account.name};
html[i++] = this._getAccountPrefRowHtml(params);
noAccountsFound = false;
}
for(var j=0; j< this.socialcastAccounts.length; j++) {
var sa = this.socialcastAccounts[j];
var params = {id:sa.un, type: "socialcast", accIcon: "social_socialcastIcon", statIcon:"social_checkIcon", name:sa.e};
html[i++] = this._getAccountPrefRowHtml(params);
noAccountsFound = false;
}
if (noAccountsFound) {
html[i++] = "<TR>";
html[i++] = "<TD colspan=6 align='center' style='font-weight:bold;font-size:12px;color:blue'>";
html[i++] = this.zimlet.getMessage("noAccountsFound");
html[i++] = "</TD>";
html[i++] = "</TR>";
}
html[i++] = "</table>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._getAccountPrefRowHtml = function(params) {
var html = [];
var i = 0;
html[i++] = "<TR>";
html[i++] = "<TD width=16px>";
html[i++] = "<input type='checkbox' id='social_pref_accnts_checkbox" + params.id + "' />";
html[i++] = "</TD>";
html[i++] = "<TD align='center'>";
html[i++] = AjxImg.getImageHtml(params.accIcon);
html[i++] = "</TD>";
html[i++] = "<TD align='center'>";
html[i++] = "<label style=\"font-size:12px;color:black;font-weight:bold\">";
html[i++] = params.name;
html[i++] = "</label>";
html[i++] = "</TD>";
html[i++] = "<TD align='center'>";
html[i++] = AjxImg.getImageHtml(params.statIcon);
html[i++] = "</TD>";
html[i++] = "</TR>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._setNeedPermission =
function(permission) {
if (this._fbNeedPermissions == "")
this._fbNeedPermissions = permission;
else
this._fbNeedPermissions = this._fbNeedPermissions + "," + permission;
};
com_zimbra_socialPreferences.prototype._manageAccntsOKBtnListener =
function() {
this.zimlet.setUserProperty("social_AllTwitterAccounts", this.zimlet.getAllAccountsAsString(), true);
this.zimlet._updateAllWidgetItems({updateSearchTree:false, updateSystemTree:true, updateAccntCheckboxes:true, searchCards:false});
this._manageAccntsDlg.popdown();
};
com_zimbra_socialPreferences.prototype.showAddFBInfoDlg = function(obj) {
//if zimlet dialog already exists...
var permStr = "";
if (obj) {
permStr = this.zimlet.getMessage("pressAllowAccessThenOKToGrandFacebookPerm");
}
if (this._getFbInfoDialog) {
this._getFbInfoDialog.popup();
return;
}
this._getFbInfoView = new DwtComposite(this.zimlet.getShell());
this._getFbInfoView.getHtmlElement().style.overflow = "auto";
this._getFbInfoView.setSize(590);
this._getFbInfoView.getHtmlElement().innerHTML = this._createFbInfoView();
var className = this._getFbInfoView.getHtmlElement().className;
this._getFbInfoView.getHtmlElement().className = className + " social_fbLoginContainer";
var addFBAccntButtonId = Dwt.getNextId();
var addFBAccntButton = new DwtDialog_ButtonDescriptor(addFBAccntButtonId, ("Authorized"), DwtDialog.ALIGN_RIGHT);
this._getFbInfoDialog = this.zimlet._createDialog({title:this.zimlet.getMessage("addFacebookAcc"), view:this._getFbInfoView, standardButtons:[DwtDialog.OK_BUTTON, DwtDialog.CANCEL_BUTTON]});
this._getFbInfoDialog.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._getFbInfoOKBtnListener));
this.goButton = new DwtButton({parent:this.zimlet.getShell()});
this.goButton.setText(this.zimlet.getMessage("goToFacebook"));
this.goButton.setImage("social_facebookIcon");
this.goButton.addSelectionListener(new AjxListener(this.zimlet.facebook, this.zimlet.facebook.loginToFB, null));
document.getElementById("social_goToFacebookPage").appendChild(this.goButton.getHtmlElement());
this.loadFbPermBtn = new DwtButton({parent:this.zimlet.getShell()});
this.loadFbPermBtn.setText(this.zimlet.getMessage("loadPermissions"));
this.loadFbPermBtn.setImage("social_facebookIcon");
this.loadFbPermBtn.addSelectionListener(new AjxListener(this, this._getFbInfoOKBtnListener, null));
document.getElementById("social_loadFBAccountPermissions").appendChild(this.loadFbPermBtn.getHtmlElement());
this._getFbInfoDialog.popup();
};
com_zimbra_socialPreferences.prototype._getFbInfoOKBtnListener = function() {
if (this.reloginToFB) {
this.reloginToFB = false;
this.needSessionId = true;
this.zimlet.facebook.fbCreateToken();
} else if (this.needSessionId) {
this.reloginToFB = false;
this.needSessionId = false;
this.zimlet.facebook._getSessionId();
} else {
this._refreshTableBtnListener();
this._getFbInfoDialog.popdown();
}
};
com_zimbra_socialPreferences.prototype._createFbInfoView =
function() {
var html = new Array();
var i = 0;
html[i++] = "<DIV>";
html[i++] = AjxMessageFormat.format(this.zimlet.getMessage("logoutfirst"), "Facebook")+"<br/><br/>";
html[i++] = "<b><u><i><label style='color:white;font-size:14px'>"+this.zimlet.getMessage("pleaseCompleteBothParts")+"</label></i></u></b><br/>";
html[i++] = "<B>"+this.zimlet.getMessage("fbSignInPart1")+"</B><br/>";
html[i++] = this.zimlet.getMessage("fbSignInLine1") + " <div id='social_goToFacebookPage'> </div>";
html[i++] = this.zimlet.getMessage("fbSignInLine2") + " <br/><br/>";
html[i++] = "<br/> <B>"+this.zimlet.getMessage("fbSignInPart2")+"</B><br/>";
html[i++] = this.zimlet.getMessage("fbSignInLine3") + "<div id='social_loadFBAccountPermissions'></div>";
html[i++] = this.zimlet.getMessage("fbSignInLine4")+ " <br/>";
html[i++] = this.zimlet.getMessage("fbSignInLine5")+ " <br/>";
html[i++] = "</DIV>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._showPreferencesDlg = function() {
//if zimlet dialog already exists...
if (this._getPrefDialog) {
this._setPrefCheckboxes();
this._getPrefDialog.popup();
return;
}
this._getPrefView = new DwtComposite(this.zimlet.getShell());
this._getPrefView.getHtmlElement().style.overflow = "auto";
this._getPrefView.getHtmlElement().innerHTML = this._createPrefView();
this._getPrefDialog = this.zimlet._createDialog({title:this.zimlet.getMessage("socialZimletPreferences"), view:this._getPrefView, standardButtons:[DwtDialog.OK_BUTTON, DwtDialog.CANCEL_BUTTON]});
this._getPrefDialog.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._okPrefBtnListener));
this._getPrefDialog.popup();
this._setPrefCheckboxes();
};
com_zimbra_socialPreferences.prototype._okPrefBtnListener =
function() {
var save = false;
var currentVal;
currentVal = document.getElementById("social_pref_tweetmemePopularIsOn").checked;
if (this.social_pref_tweetmemePopularIsOn != currentVal) {
this.zimlet.setUserProperty("social_pref_tweetmemePopularIsOn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_trendsPopularIsOn").checked;
if (this.social_pref_trendsPopularIsOn != currentVal) {
this.zimlet.setUserProperty("social_pref_trendsPopularIsOn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_diggPopularIsOn").checked;
if (this.social_pref_diggPopularIsOn != currentVal) {
this.zimlet.setUserProperty("social_pref_diggPopularIsOn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_socializeBtnOn").checked;
if (this.social_pref_socializeBtnOn != currentVal) {
this.zimlet.setUserProperty("social_pref_socializeBtnOn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_SocialMailUpdateOn").checked;
if (this.social_pref_SocialMailUpdateOn != currentVal) {
this.zimlet.setUserProperty("social_pref_SocialMailUpdateOn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_showTweetAlertsOn").checked;
if (this.social_pref_showTweetAlertsOn != currentVal) {
this.zimlet.setUserProperty("social_pref_showTweetAlertsOn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_cardWidthList").value;
if (this.social_pref_cardWidthList != currentVal) {
this.zimlet.setUserProperty("social_pref_cardWidthList", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_numberofTweetsToReturn").value;
if (this.social_pref_numberofTweetsToReturn != parseInt(currentVal)) {
this.zimlet.setUserProperty("social_pref_numberofTweetsToReturn", currentVal);
save = true;
}
currentVal = document.getElementById("social_pref_numberofTweetsSearchesToReturn").value;
if (this.social_pref_numberofTweetsSearchesToReturn != parseInt(currentVal)) {
this.zimlet.setUserProperty("social_pref_numberofTweetsSearchesToReturn", currentVal);
save = true;
}
if (save) {
this.zimlet.saveUserProperties(new AjxCallback(this, this.showYesNoDialog));
appCtxt.getAppController().setStatusMsg(this.zimlet.getMessage("preferencesSaved"), ZmStatusView.LEVEL_INFO);
}
this._getPrefDialog.popdown();
};
com_zimbra_socialPreferences.prototype.showYesNoDialog =
function() {
var dlg = appCtxt.getYesNoMsgDialog();
dlg.registerCallback(DwtDialog.YES_BUTTON, this._yesButtonClicked, this, dlg);
dlg.registerCallback(DwtDialog.NO_BUTTON, this._NoButtonClicked, this, dlg);
dlg.setMessage(this.zimlet.getMessage("browserMustBeRefreshed"), DwtMessageDialog.WARNING_STYLE);
dlg.popup();
};
com_zimbra_socialPreferences.prototype._yesButtonClicked =
function(dlg) {
dlg.popdown();
this._refreshBrowser();
};
com_zimbra_socialPreferences.prototype._NoButtonClicked =
function(dlg) {
dlg.popdown();
}
com_zimbra_socialPreferences.prototype._refreshBrowser =
function() {
window.onbeforeunload = null;
var url = AjxUtil.formatUrl({});
ZmZimbraMail.sendRedirect(url);
};
com_zimbra_socialPreferences.prototype._setPrefCheckboxes = function() {
if (this.social_pref_tweetmemePopularIsOn) {
document.getElementById("social_pref_tweetmemePopularIsOn").checked = true;
}
if (this.social_pref_trendsPopularIsOn) {
document.getElementById("social_pref_trendsPopularIsOn").checked = true;
}
if (this.social_pref_diggPopularIsOn) {
document.getElementById("social_pref_diggPopularIsOn").checked = true;
}
if (this.social_pref_socializeBtnOn) {
document.getElementById("social_pref_socializeBtnOn").checked = true;
}
if (this.social_pref_SocialMailUpdateOn) {
document.getElementById("social_pref_SocialMailUpdateOn").checked = true;
}
if (this.social_pref_showTweetAlertsOn) {
document.getElementById("social_pref_showTweetAlertsOn").checked = true;
}
var list = document.getElementById("social_pref_cardWidthList");
for (var i = 0; i < list.options.length; i++) {
if (list.options[i].value == this.social_pref_cardWidthList) {
list.options[i].selected = true;
break;
}
}
var list = document.getElementById("social_pref_numberofTweetsToReturn");
for (var i = 0; i < list.options.length; i++) {
if (list.options[i].value == this.social_pref_numberofTweetsToReturn) {
list.options[i].selected = true;
break;
}
}
var list = document.getElementById("social_pref_numberofTweetsSearchesToReturn");
for (var i = 0; i < list.options.length; i++) {
if (list.options[i].value == this.social_pref_numberofTweetsSearchesToReturn) {
list.options[i].selected = true;
break;
}
}
};
com_zimbra_socialPreferences.prototype._createPrefView =
function() {
var html = new Array();
var i = 0;
html[i++] = "<label style='font-weight:bold'>"+this.zimlet.getMessage("socialAppPreferences")+"</label>";
html[i++] = "<BR/>";
html[i++] = "<table>";
html[i++] = "<tr><td><input type='checkbox' id='social_pref_tweetmemePopularIsOn' /></td><td width=100%>"+this.zimlet.getMessage("showTweetmemeByDefault")+"</td></tr>";
html[i++] = "<tr><td><input type='checkbox' id='social_pref_trendsPopularIsOn' /></td><td width=100%>"+this.zimlet.getMessage("showTopTwitterTrendsByDefault")+"</td></tr>";
html[i++] = "<tr><td><input type='checkbox' id='social_pref_diggPopularIsOn' /></td><td width=100%> "+this.zimlet.getMessage("showDiggsPopularByDefault")+"</td></tr>";
html[i++] = "</table>";
html[i++] = "<table>";
html[i++] = "<tr><td>"+this.zimlet.getMessage("feedCardWidth") +"</td><td>" + this._createCardWidthList() + "</td></tr>";
html[i++] = "<tr><td >"+this.zimlet.getMessage("numberOfTweetsToReturn")+"</td><td>" + this._createNumberOfTweetsToReturnList() + "</td></tr>";
html[i++] = "<tr><td>"+this.zimlet.getMessage("numberOfTwitterSearchesToReturn")+"</td><td>" + this._createNumberOfTweetSearchesToReturnList() + "</td></tr>";
html[i++] = "</table>";
html[i++] = "<BR/>";
html[i++] = "<BR/>";
html[i++] = "<label style='font-weight:bold'>"+this.zimlet.getMessage("socialZimlbraIntegrationPref")+"</label>";
html[i++] = "<BR/>";
html[i++] = "<table>";
html[i++] = "<tr><td><input type='checkbox' id='social_pref_SocialMailUpdateOn' /></td><td width=100%>"+this.zimlet.getMessage("sendSocialMail")+"</td></tr>";
html[i++] = "<tr><td><input type='checkbox' id='social_pref_showTweetAlertsOn' /></td><td width=100%>"+this.zimlet.getMessage("showTweetAlert")+"</td></tr>";
html[i++] = "<tr><td><input type='checkbox' id='social_pref_socializeBtnOn' /></td><td width=100%>"+this.zimlet.getMessage("showSocializeBtn")+"</td></tr>";
html[i++] = "</table>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._createCardWidthList =
function() {
var html = new Array();
var i = 0;
html[i++] = "<select id='social_pref_cardWidthList'>";
var sizes = [
{
name:this.zimlet.getMessage("verySmall"),
val:"300px"
},
{
name:this.zimlet.getMessage("small"),
val:"350px"
},
{
name:this.zimlet.getMessage("medium"),
val:"400px"
},
{
name:this.zimlet.getMessage("large"),
val:"450px"
},
{
name:this.zimlet.getMessage("xl"),
val:"500px"
},
{
name:this.zimlet.getMessage("2xl"),
val:"550px"
},
{
name:this.zimlet.getMessage("3xl"),
val:"600px"
}
];
for (var j = 0; j < sizes.length; j++) {
html[i++] = "<option value='" + sizes[j].val + "'>" + sizes[j].name + " (" + sizes[j].val + ")</option>";
}
html[i++] = "</select>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._createNumberOfTweetsToReturnList =
function() {
var html = new Array();
var i = 0;
html[i++] = "<select id='social_pref_numberofTweetsToReturn'>";
var sizes = [
{
name:"50",
val:"50"
},
{
name:"100",
val:"100"
},
{
name:"150",
val:"150"
},
{
name:"200",
val:"200"
}
];
for (var j = 0; j < sizes.length; j++) {
html[i++] = "<option value='" + sizes[j].val + "'>" + sizes[j].name + "</option>";
}
html[i++] = "</select>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._createNumberOfTweetSearchesToReturnList =
function() {
var html = new Array();
var i = 0;
html[i++] = "<select id='social_pref_numberofTweetsSearchesToReturn'>";
var sizes = [
{
name:"50",
val:"50"
},
{
name:"100",
val:"100"
}
];
for (var j = 0; j < sizes.length; j++) {
html[i++] = "<option value='" + sizes[j].val + "'>" + sizes[j].name + "</option>";
}
html[i++] = "</select>";
return html.join("");
};
com_zimbra_socialPreferences.prototype._setWelCheckboxes = function() {
if (this.social_pref_dontShowWelcomeScreenOn)
document.getElementById("social_pref_dontShowWelcomeScreenOn").checked = true;
};
com_zimbra_socialPreferences.prototype._okWelBtnListener =
function() {
var save = false;
var currentVal = document.getElementById("social_pref_dontShowWelcomeScreenOn").checked;
if (this.social_pref_dontShowWelcomeScreenOn != currentVal) {
this.zimlet.setUserProperty("social_pref_dontShowWelcomeScreenOn", currentVal);
save = true;
}
if (save) {
this.zimlet.saveUserProperties();
appCtxt.getAppController().setStatusMsg(this.zimlet.getMessage("preferencesSaved"), ZmStatusView.LEVEL_INFO);
}
this._getwelDialog.popdown();
};
com_zimbra_socialPreferences.prototype._showWelcomeDlg = function() {
if (this._getwelDialog) {
this._setWelCheckboxes();
this._getwelDialog.popup();
return;
}
this._getWelView = new DwtComposite(this.zimlet.getShell());
this._getWelView.getHtmlElement().style.overflow = "auto";
this._getWelView.getHtmlElement().innerHTML = this._createWelView();
this._getwelDialog = this.zimlet._createDialog({title:this.zimlet.getMessage("zimbraSocial"), view:this._getWelView, standardButtons:[DwtDialog.OK_BUTTON], id: "SocialZimlet_WelcomeDlg"});
this._getwelDialog.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._okWelBtnListener));
this._getwelDialog.popup();
this._setWelCheckboxes();
};
com_zimbra_socialPreferences.prototype._createWelView =
function() {
var html = new Array();
var i = 0;
html[i++] = "<DIV id='SocialZimlet_WelcomeDlgTxt' class='social_yellow'>";
html[i++] = " <h3 align=center>"+this.zimlet.getMessage("welcome")+"</h3>";
html[i++] = "<b>"+this.zimlet.getMessage("gettingStarted")+"</b><br/>";
html[i++] = "<ul>";
html[i++] = "<li>"+this.zimlet.getMessage("welDlgLine1")+"</li>";
html[i++] = "</ul><b>"+this.zimlet.getMessage("thingsToDo")+"</b>";
html[i++] = "<ul>";
html[i++] = "<li>"+this.zimlet.getMessage("thingsToDo1")+"</li>";
html[i++] = "<li>"+this.zimlet.getMessage("thingsToDo2")+"</li>";
html[i++] = "<li>"+this.zimlet.getMessage("thingsToDo3")+"</li>";
html[i++] = "<li>"+this.zimlet.getMessage("thingsToDo4")+"</li>";
html[i++] = "<li>"+this.zimlet.getMessage("thingsToDo5")+"</li>";
html[i++] = "</ul>";
html[i++] = this.zimlet.getMessage("takeA")+" <label id='SocialZimlet_takeATourLnk' style=\"color:blue;text-decoration: underline;font-weight:bold\"><a href='http://wiki.zimbra.com/index.php?title=Social' target=\"_blank\">"+
this.zimlet.getMessage("quickTour")+"</a></label> "+this.zimlet.getMessage("forExtraHelp");
html[i++] = "<br/><br/><input type='checkbox' id='social_pref_dontShowWelcomeScreenOn' /><b/>"+ this.zimlet.getMessage("dontShowMeThisAgain");
html[i++] = "</DIV>";
return html.join("");
}; |
(function () {
var toggles = document.querySelectorAll('[data-action="toggle-menu"]');
var nav = document.querySelector('nav');
var main = document.querySelector('main');
var victor = document.getElementById('victor');
Array.from(toggles).forEach(function (node) {
node.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector('nav').classList.toggle('open');
document.querySelector('main').classList.toggle('menu-open');
});
});
main.addEventListener('click', function (e) {
nav.classList.remove('open');
main.classList.remove('menu-open');
});
if (victor) {
Elm.Victor.embed(document.getElementById('victor'));
}
}());
|
var searchData=
[
['make_5ffuture_5fwith_5fexception',['make_future_with_exception',['../namespacetranswarp_1_1detail.html#a34c09a6639f52048a1e4642d32520783',1,'transwarp::detail']]],
['make_5ffuture_5fwith_5fvalue',['make_future_with_value',['../namespacetranswarp_1_1detail.html#ac5851824847b3e272e5c4b0864706fae',1,'transwarp::detail']]],
['make_5fready_5ffuture',['make_ready_future',['../namespacetranswarp_1_1detail.html#a4af1f9b80e5a2d5180d42c1c8e6d0cc7',1,'transwarp::detail']]],
['make_5ftask',['make_task',['../namespacetranswarp.html#a0abf735a374ea96dfdc11af57c89cda9',1,'transwarp::make_task(TaskType, Functor &&functor, std::shared_ptr< Parents >...parents) -> std::shared_ptr< transwarp::task_impl< TaskType, typename std::decay< Functor >::type, typename Parents::result_type...>>'],['../namespacetranswarp.html#ab16aca2b1ca1f3f3afc76f935589264a',1,'transwarp::make_task(TaskType, Functor &&functor, std::vector< ParentType > parents) -> std::shared_ptr< transwarp::task_impl< TaskType, typename std::decay< Functor >::type, std::vector< ParentType >>>']]],
['make_5fvalue_5ftask',['make_value_task',['../namespacetranswarp.html#a3e8aab80faff265698b144510ee3f12b',1,'transwarp']]],
['maximum_5fsize',['maximum_size',['../classtranswarp_1_1task__pool.html#a62d667ae01cc72bbb2a47c98ff567b4a',1,'transwarp::task_pool']]],
['minimum_5fsize',['minimum_size',['../classtranswarp_1_1task__pool.html#ae92893a69a1898756bf3724060e1cfd2',1,'transwarp::task_pool']]]
];
|
import AbstractList from '../abstract/AbstractList.js';
export default class extends AbstractList {
constructor($injector, $scope, $filter, $WPHCPosts) {
'ngInject';
super($injector, $scope);
this.setType('posts');
this.setTitle();
this.setService($WPHCPosts);
}
}
|
/**
* umd
* ===
*
* Wraps the library into an universal module definition (AMD + CommonJS + Global).
*
* Link: https://github.com/bebraw/grunt-umd
*/
'use strict';
module.exports = function (grunt) {
return {
dist: {
src: '<%= pkg.config.src %>/scripts/chartist-plugin-threshold.js',
dest: '<%= pkg.config.dist %>/chartist-plugin-threshold.js',
objectToExport: 'Chartist.plugins.ctThreshold',
indent: ' '
}
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.