<commit_before>/**
* Donatello - A pure CSS vector drawing library.
*
* Provided under the MIT license.
* See LICENSE file for full text of the license.
* Copyright 2011 Dan Newcome.
*//**
* Donatello objects are used to represent shapes drawn
* in the scene. The scene consists of a tree of these.
*
* id - id string of an existing DOM element or a reference
* to the DOM element itself.
* x/y, w/h - position and size
*/function Donatello(a,b,c,d,e){this.properties={};if(typeof a=="string"){var f=document.getElementById(a);Donatello.createElement(b,c,d,e,f),this.dom=f}else a!=null&&(this.dom=a)}Donatello.getTransform=function(){var a,b=document.createElement("div");return Donatello.transform==undefined?(typeof b.style.transform!="undefined"?a="transform":typeof b.style.webkitTransform!="undefined"?a="webkitTransform":typeof b.style.MozTransform!="undefined"?a="MozTransform":typeof b.style.msTransform!="undefined"?a="msTransform":typeof b.style.OTransform!="undefined"?a="OTransform":a=null,console.log("css transform: "+a),Donatello.transform=a):a=Donatello.transform,a},Donatello.merge=function(a,b){for(var c in a)b[c]=a[c];return b},Donatello.prototype.attrMap={fill:"backgroundColor",stroke:"borderColor","stroke-style":"borderStyle",r:"borderRadius",type:null,children:null,transform:Donatello.getTransform()},Donatello.prototype.draw=function(){},Donatello.paper=function(a,b,c,d,e,f){return new Donatello(a,b,c,d,e,f)},Donatello.createLinearGradient=function(a,b,c){a=Math.floor(a/45);var d="center top, center bottom";switch(a){case 0:d="left center, right center";break;case 1:d="left bottom, right top";break;case 2:d="center bottom, center top";break;case 3:d="right bottom, left top";break;case 4:d="right center, left center";break;case 5:d="right top, left bottom";break;case 6:d="center top, center bottom";break;case 7:d="left top, right bottom";break;case 8:d="left center, right center"}var e;switch(Donatello.getTransform()){case"MozTransform":e="-moz-linear-gradient("+a*45+"deg,"+b+", "+c+")";break;case"webkitTransform":e="-webkit-gradient(linear, "+d+", from("+b+"), to("+c+"))";break;case"msTransform":var f=Math.floor(a%4/2);e="progid:DXImageTransform.Microsoft.gradient(GradientType="+f+', startColorstr="'+b+'", endColorstr="'+c+'")';break;case"OTransform":e="-o-linear-gradient("+a*45+"deg,"+b+","+c+")"}return e},Donatello.prototype.rotate=function(a){this.dom.style[Donatello.getTransform()]+="rotate("+a+"deg)"},Donatello.prototype.clear=function(){while(this.dom.hasChildNodes())this.dom.removeChild(this.dom.lastChild)},Donatello.prototype["delete"]=function(){this.dom.parentNode.removeChild(this.dom)},Donatello.prototype.node=function(){return this.dom},Donatello.prototype.attr=function(a){if(a=="undefined")return this.properties;Donatello.merge(a,this.properties);var b=this.attrMap;for(attr in a)if(b[attr]!=null)if(attr=="r"||attr=="stroke-width")this.dom.style[b[attr]]=a[attr]+"px";else if(attr=="fill")if(a.fill&&a.fill.length>7){var c=a.fill;this.dom.style.backgroundImage=Donatello.createLinearGradient(c.substr(0,2),c.substr(3,7),c.substr(11,7))}else this.dom.style[b[attr]]=a[attr];else attr!="scale"&&(this.dom.style[b[attr]]=a[attr]);else if(attr!="stroke-width"&&attr!="x"&&attr!="y"&&attr!="w"&&attr!="h"&&attr!="type"&&attr!="children")if(typeof this.styleableElements!="undefined")for(var d=0;d<this.styleableElements.length;d++)console.log("setting "+attr+" to "+a[attr]),this.styleableElements[d].style[attr]=a[attr];else this.dom.style[attr]=a[attr];return this.draw(),this},Donatello.createElement=function(a,b,c,d,e){var f;return typeof e=="string"?f=document.createElement(e):f=e,f.style.position="absolute",f.style.top=b+"px",f.style.left=a+"px",f.style.width=c+"px",f.style.height=d+"px",f},Donatello.attrDefaults=function(a){return a=a||{},a["stroke-width"]||(a["stroke-width"]=1),a.stroke||(a.stroke="black"),a.fill||(a.fill="transparent"),a["stroke-style"]||(a["stroke-style"]="solid"),a},Donatello.prototype.rect=function(a,b,c,d,e){return this.pgram(a,b,c,d,null,e)},Donatello.Pgram=function(a,b,c,d,e,f,g){g=Donatello.attrDefaults(g);var h=Donatello.createElement(b,c,d,e,"div"),i=g["stroke-width"],j=g.stroke,k=g.fill,l=g["stroke-style"];this.properties={x:b,y:c,dx:e,skew:f,"stroke-width":i,"stroke-style":l,stroke:j,fill:k},a.dom.appendChild(h),this.dom=h,this.attr(g)},Donatello.Pgram.prototype=new Donatello(null),Donatello.Pgram.prototype.draw=function(){var a=this.dom,b=this.properties.skew;a.style.borderWidth=this.properties["stroke-width"]+"px",b!=null&&(a.style[Donatello.getTransform()]+="skew("+b+"deg)")},Donatello.prototype.pgram=function(a,b,c,d,e,f){return new Donatello.Pgram(this,a,b,c,d,e,f)},Donatello.Circle=function(a,b,c,d,e){e=Donatello.attrDefaults(e);var f=e["stroke-width"],g=e.stroke,h=e.fill,i=e["stroke-style"];this.properties={x:b,y:c,r:d,"stroke-width":f,"stroke-style":i,stroke:g,fill:h};var j=Donatello.createElement(b-d-f,c-d-f,2*d,2*d,"div");a.dom.appendChild(j),this.dom=j,this.attr(e)},Donatello.Circle.prototype=new Donatello(null),Donatello.prototype.circle=function(a,b,c,d){return new Donatello.Circle(this,a,b,c,d)},Donatello.Circle.prototype.draw=function(){var a=this.properties.x,b=this.properties.y,c=this.properties.r,d=this.properties["stroke-width"],e=this.properties.stroke,f=this.properties.fill,g=this.properties["stroke-style"],h=this.dom;h.style.borderRadius=c+d+"px",h.style.borderWidth=d+"px",h.style.borderStyle=g,h.style.bordercolor=e,h.style.backgroundColor=f,h.style.left=a-c-d+"px",h.style.top=b-c-d+"px"},Donatello.Ellipse=function(a,b,c,d,e,f){f=Donatello.attrDefaults(f);var g=f["stroke-width"],h=f.stroke,i=f.fill,j=f["stroke-style"];this.properties={x:b,y:c,rx:d,ry:e,"stroke-width":g,"stroke-style":j,stroke:h,fill:i};var k=Donatello.createElement(b-d-g,c-e-g,2*d,2*e,"div");a.dom.appendChild(k),this.dom=k,this.attr(f)},Donatello.Ellipse.prototype=new Donatello(null),Donatello.prototype.ellipse=function(a,b,c,d,e){return new Donatello.Ellipse(this,a,b,c,d,e)},Donatello.Ellipse.prototype.draw=function(){var a=this.properties.x,b=this.properties.y,c=this.properties.r,d=this.properties.rx,e=this.properties.ry,f=this.properties["stroke-width"],g=this.properties.stroke,h=this.properties.fill,i=this.properties["stroke-style"],j=this.dom;j.style.borderRadius=d+f+"px / "+(e+f)+"px",j.style.borderWidth=f+"px",j.style.borderStyle=i,j.style.borderColor=g,j.style.backgroundColor=h,j.style.left=a-d-f+"px",j.style.top=b-e-f+"px"},Donatello.Arc=function(a,b,c,d,e,f,g){g=Donatello.attrDefaults(g);var h=g["stroke-width"],i=g.stroke,j=g.fill,k=g["stroke-style"];this.properties={x:b,y:c,r:d,t1:e,t2:f,"stroke-width":h,"stroke-style":k,stroke:i,fill:j};var l=f,m=Donatello.createElement(b-2*d,c-2*d,2*d,2*d,"div"),n=Donatello.createElement(d-h,d-h,2*d,2*d,"div"),o=Donatello.createElement(d-h,d-h,2*d,2*d,"div"),p=Donatello.createElement(d-h,d-h,2*d,2*d,"div"),q=Donatello.createElement(d-h,d-h,2*d,2*d,"div");m.appendChild(n),m.appendChild(o),m.appendChild(p),m.appendChild(q),this.styleableElements=[n,o,p,q],m.style[Donatello.transform+"Origin"]="100% 100%",a.dom.appendChild(m),this.dom=m,this.draw(f)},Donatello.Arc.prototype=new Donatello(null),Donatello.prototype.arc=function(a,b,c,d,e,f){return new Donatello.Arc(this,a,b,c,d,e,f)},Donatello.Arc.prototype.draw=function(a){function i(a,c){a.style.borderRadius=d+e+"px",a.style.borderWidth=e+"px",a.style.borderStyle=h,a.style.borderColor=f,a.style.borderBottomColor="transparent",a.style.borderLeftColor="transparent",a.style.borderRightColor="transparent",a.style.backgroundColor=g,b<90?a.style[Donatello.transform]="skew("+ -(90-b)+"deg)rotate("+(c-45)+"deg)":a.style[Donatello.transform]="rotate("+(c-45)+"deg)"}var b=a,c=this.properties.t1;b<90?(this.dom.style.overflow="hidden",this.dom.style[Donatello.transform]="rotate("+(180+c)+"deg)"+"skew("+(90-b)+"deg)"):(this.dom.style.overflow="visible",this.dom.style[Donatello.transform]="rotate("+(180+c)+"deg)"+"skew(0deg)");var d=this.properties.r,e=this.properties["stroke-width"],f=this.properties.stroke,g=this.properties.fill,h=this.properties["stroke-style"];for(var j=0;j<4;j++)i(this.dom.children[j],(b-90)*j/3)},Donatello.Line=function(a,b,c,d,e,f){f=Donatello.attrDefaults(f);var g=f["stroke-width"];this.properties={x:b,y:c,dx:d,dy:e,"stroke-width":g};var h=f.stroke,i=f.fill,j=f["stroke-style"],k=Donatello.createElement(b,c,0,0,"div");this.attrMap["stroke-width"]="borderTopWidth",this.attrMap["stroke-style"]="borderTopStyle",this.attrMap.stroke="borderTopColor",this.dom=k,this.draw(f),k.style[Donatello.getTransform()+"Origin"]="0px 0px",a.dom.appendChild(k),this.attr(f)},Donatello.Line.prototype=new Donatello(null),Donatello.Line.prototype.draw=function(a){var b=this.properties.x,c=this.properties.y,d=this.properties.dx,e=this.properties.dy,f=this.properties["stroke-width"],g=Math.sqrt(d*d+e*e);this.dom.style.width=g+"px",this.dom.style.height="0px";var h=Math.asin(Math.abs(e)/g);h*=180/Math.PI,d<0&&e>=0?h=180-h:d<0&&e<0?h=180+h:d>=0&&e<0&&(h=360-h),this.dom.style[Donatello.getTransform()]="rotate("+h+"deg) translate(0px, -"+f/2+"px)",this.dom.style.borderTopWidth=f+"px",this.dom.style.left=b+"px",this.dom.style.top=c+"px"},Donatello.prototype.line=function(a,b,c,d,e){return new Donatello.Line(this,a,b,c,d,e)}<commit_msg>built new minified donatello version<commit_after>/**
* Donatello - A pure CSS vector drawing library.
*
* Provided under the MIT license.
* See LICENSE file for full text of the license.
* Copyright 2011 Dan Newcome.
*//**
* Donatello objects are used to represent shapes drawn
* in the scene. The scene consists of a tree of these.
*
* id - id string of an existing DOM element or a reference
* to the DOM element itself.
* x/y, w/h - position and size
*/function Donatello(a,b,c,d,e){this.properties={},this.attrMap={fill:"backgroundColor",stroke:"borderColor","stroke-style":"borderStyle",r:"borderRadius",type:null,children:null,transform:Donatello.getTransform()};if(typeof a=="string"){var f=document.getElementById(a);Donatello.createElement(b,c,d,e,f),this.dom=f}else a!=null&&(this.dom=a)}Donatello.getTransform=function(){var a,b=document.createElement("div");return Donatello.transform==undefined?(typeof b.style.transform!="undefined"?a="transform":typeof b.style.webkitTransform!="undefined"?a="webkitTransform":typeof b.style.MozTransform!="undefined"?a="MozTransform":typeof b.style.msTransform!="undefined"?a="msTransform":typeof b.style.OTransform!="undefined"?a="OTransform":a=null,console.log("css transform: "+a),Donatello.transform=a):a=Donatello.transform,a},Donatello.merge=function(a,b){for(var c in a)b[c]=a[c];return b},Donatello.prototype.draw=function(){},Donatello.paper=function(a,b,c,d,e,f){return new Donatello(a,b,c,d,e,f)},Donatello.createLinearGradient=function(a,b,c){a=Math.floor(a/45);var d="center top, center bottom";switch(a){case 0:d="left center, right center";break;case 1:d="left bottom, right top";break;case 2:d="center bottom, center top";break;case 3:d="right bottom, left top";break;case 4:d="right center, left center";break;case 5:d="right top, left bottom";break;case 6:d="center top, center bottom";break;case 7:d="left top, right bottom";break;case 8:d="left center, right center"}var e;switch(Donatello.getTransform()){case"MozTransform":e="-moz-linear-gradient("+a*45+"deg,"+b+", "+c+")";break;case"webkitTransform":e="-webkit-gradient(linear, "+d+", from("+b+"), to("+c+"))";break;case"msTransform":var f=Math.floor(a%4/2);e="progid:DXImageTransform.Microsoft.gradient(GradientType="+f+', startColorstr="'+b+'", endColorstr="'+c+'")';break;case"OTransform":e="-o-linear-gradient("+a*45+"deg,"+b+","+c+")"}return e},Donatello.prototype.rotate=function(a){this.dom.style[Donatello.getTransform()]+="rotate("+a+"deg)"},Donatello.prototype.clear=function(){while(this.dom.hasChildNodes())this.dom.removeChild(this.dom.lastChild)},Donatello.prototype["delete"]=function(){this.dom.parentNode.removeChild(this.dom)},Donatello.prototype.node=function(){return this.dom},Donatello.prototype.attr=function(a){if(a==undefined)return this.properties;Donatello.merge(a,this.properties);var b=this.attrMap;for(attr in a)if(b[attr]!=null)if(attr=="r"||attr=="stroke-width")this.dom.style[b[attr]]=a[attr]+"px";else if(attr=="fill")if(a.fill&&a.fill.length>7){var c=a.fill;this.dom.style.backgroundImage=Donatello.createLinearGradient(c.substr(0,2),c.substr(3,7),c.substr(11,7))}else this.dom.style[b[attr]]=a[attr];else attr!="scale"&&(this.dom.style[b[attr]]=a[attr]);else if(attr!="stroke-width"&&attr!="x"&&attr!="y"&&attr!="w"&&attr!="h"&&attr!="type"&&attr!="children")if(typeof this.styleableElements!="undefined")for(var d=0;d<this.styleableElements.length;d++)console.log("setting "+attr+" to "+a[attr]),this.styleableElements[d].style[attr]=a[attr];else this.dom.style[attr]=a[attr];return this.draw(),this},Donatello.createElement=function(a,b,c,d,e){var f;return typeof e=="string"?f=document.createElement(e):f=e,f.style.position="absolute",f.style.top=b+"px",f.style.left=a+"px",f.style.width=c+"px",f.style.height=d+"px",f},Donatello.attrDefaults=function(a){return a=a||{},a["stroke-width"]===undefined&&(a["stroke-width"]=1),a.stroke||(a.stroke="black"),a.fill||(a.fill="transparent"),a["stroke-style"]||(a["stroke-style"]="solid"),a},Donatello.prototype.rect=function(a,b,c,d,e){return this.pgram(a,b,c,d,null,e)},Donatello.Pgram=function(a,b,c,d,e,f,g){g=Donatello.attrDefaults(g);var h=Donatello.createElement(b,c,d,e,"div"),i=g["stroke-width"],j=g.stroke,k=g.fill,l=g["stroke-style"];this.properties={x:b,y:c,w:d,h:e,skew:f,"stroke-width":i,"stroke-style":l,stroke:j,fill:k},a.dom.appendChild(h),this.dom=h,this.attr(g)},Donatello.Pgram.prototype=new Donatello(null),Donatello.Pgram.prototype.draw=function(){var a=this.dom,b=this.properties.skew;a.style.borderWidth=this.properties["stroke-width"]+"px",b!=null&&(console.log("setting skew "+b),a.style[Donatello.getTransform()]+="skew("+b+"deg)"),a.style.top=this.properties.y+"px",a.style.left=this.properties.x+"px",a.style.width=this.properties.w+"px",a.style.height=this.properties.h+"px"},Donatello.prototype.pgram=function(a,b,c,d,e,f){return new Donatello.Pgram(this,a,b,c,d,e,f)},Donatello.Circle=function(a,b,c,d,e){e=Donatello.attrDefaults(e);var f=e["stroke-width"],g=e.stroke,h=e.fill,i=e["stroke-style"];this.properties={x:b,y:c,r:d,"stroke-width":f,"stroke-style":i,stroke:g,fill:h};var j=Donatello.createElement(b-d-f,c-d-f,2*d,2*d,"div");a.dom.appendChild(j),this.dom=j,this.attr(e)},Donatello.Circle.prototype=new Donatello(null),Donatello.prototype.circle=function(a,b,c,d){return new Donatello.Circle(this,a,b,c,d)},Donatello.Circle.prototype.draw=function(){var a=this.properties.x,b=this.properties.y,c=this.properties.r,d=this.properties["stroke-width"],e=this.properties.stroke,f=this.properties.fill,g=this.properties["stroke-style"],h=this.dom;h.style.borderRadius=c+d+"px",h.style.borderWidth=d+"px",h.style.borderStyle=g,h.style.bordercolor=e,h.style.backgroundColor=f,h.style.left=a-c-d+"px",h.style.top=b-c-d+"px"},Donatello.Ellipse=function(a,b,c,d,e,f){f=Donatello.attrDefaults(f);var g=f["stroke-width"],h=f.stroke,i=f.fill,j=f["stroke-style"];this.properties={x:b,y:c,rx:d,ry:e,"stroke-width":g,"stroke-style":j,stroke:h,fill:i};var k=Donatello.createElement(b-d-g,c-e-g,2*d,2*e,"div");a.dom.appendChild(k),this.dom=k,this.attr(f)},Donatello.Ellipse.prototype=new Donatello(null),Donatello.prototype.ellipse=function(a,b,c,d,e){return new Donatello.Ellipse(this,a,b,c,d,e)},Donatello.Ellipse.prototype.draw=function(){var a=this.properties.x,b=this.properties.y,c=this.properties.r,d=this.properties.rx,e=this.properties.ry,f=this.properties["stroke-width"],g=this.properties.stroke,h=this.properties.fill,i=this.properties["stroke-style"],j=this.dom;j.style.borderRadius=d+f+"px / "+(e+f)+"px",j.style.borderWidth=f+"px",j.style.borderStyle=i,j.style.borderColor=g,j.style.backgroundColor=h,j.style.left=a-d-f+"px",j.style.top=b-e-f+"px"},Donatello.Arc=function(a,b,c,d,e,f,g){g=Donatello.attrDefaults(g);var h=g["stroke-width"],i=g.stroke,j=g.fill,k=g["stroke-style"];this.properties={x:b,y:c,r:d,t1:e,t2:f,"stroke-width":h,"stroke-style":k,stroke:i,fill:j};var l=f,m=Donatello.createElement(b-2*d,c-2*d,2*d,2*d,"div"),n=Donatello.createElement(d-h,d-h,2*d,2*d,"div"),o=Donatello.createElement(d-h,d-h,2*d,2*d,"div"),p=Donatello.createElement(d-h,d-h,2*d,2*d,"div"),q=Donatello.createElement(d-h,d-h,2*d,2*d,"div");m.appendChild(n),m.appendChild(o),m.appendChild(p),m.appendChild(q),this.styleableElements=[n,o,p,q],m.style[Donatello.transform+"Origin"]="100% 100%",a.dom.appendChild(m),this.dom=m,this.draw(f)},Donatello.Arc.prototype=new Donatello(null),Donatello.prototype.arc=function(a,b,c,d,e,f){return new Donatello.Arc(this,a,b,c,d,e,f)},Donatello.Arc.prototype.draw=function(a){function i(a,c){a.style.borderRadius=d+e+"px",a.style.borderWidth=e+"px",a.style.borderStyle=h,a.style.borderColor=f,a.style.borderBottomColor="transparent",a.style.borderLeftColor="transparent",a.style.borderRightColor="transparent",a.style.backgroundColor=g,b<90?a.style[Donatello.transform]="skew("+ -(90-b)+"deg)rotate("+(c-45)+"deg)":a.style[Donatello.transform]="rotate("+(c-45)+"deg)"}var b=a,c=this.properties.t1;b<90?(this.dom.style.overflow="hidden",this.dom.style[Donatello.transform]="rotate("+(180+c)+"deg)"+"skew("+(90-b)+"deg)"):(this.dom.style.overflow="visible",this.dom.style[Donatello.transform]="rotate("+(180+c)+"deg)"+"skew(0deg)");var d=this.properties.r,e=this.properties["stroke-width"],f=this.properties.stroke,g=this.properties.fill,h=this.properties["stroke-style"];for(var j=0;j<4;j++)i(this.dom.children[j],(b-90)*j/3)},Donatello.Line=function(a,b,c,d,e,f){f=Donatello.attrDefaults(f);var g=f["stroke-width"];this.properties={x:b,y:c,dx:d,dy:e,"stroke-width":g};var h=f.stroke,i=f.fill,j=f["stroke-style"],k=Donatello.createElement(b,c,0,0,"div");this.attrMap["stroke-width"]="borderTopWidth",this.attrMap["stroke-style"]="borderTopStyle",this.attrMap.stroke="borderTopColor",this.dom=k,this.draw(f),k.style[Donatello.getTransform()+"Origin"]="0px 0px",a.dom.appendChild(k),this.attr(f)},Donatello.Line.prototype=new Donatello(null),Donatello.Line.prototype.draw=function(a){var b=this.properties.x,c=this.properties.y,d=this.properties.dx,e=this.properties.dy,f=this.properties["stroke-width"],g=Math.sqrt(d*d+e*e);this.dom.style.width=g+"px",this.dom.style.height="0px";var h=Math.asin(Math.abs(e)/g);h*=180/Math.PI,d<0&&e>=0?h=180-h:d<0&&e<0?h=180+h:d>=0&&e<0&&(h=360-h),this.dom.style[Donatello.getTransform()]="rotate("+h+"deg) translate(0px, -"+f/2+"px)",this.dom.style.borderTopWidth=f+"px",this.dom.style.left=b+"px",this.dom.style.top=c+"px"},Donatello.prototype.line=function(a,b,c,d,e){return new Donatello.Line(this,a,b,c,d,e)},Donatello.prototype.text=function(a,b,c,d){var e=Donatello.createElement(a,b,null,null,"div");e.innerHTML=c,this.dom.appendChild(e);var f=new Donatello(e);return f.attr(d),f},Donatello.Text=function(a,b,c,d,e){e=Donatello.attrDefaults(e),this.properties={x:b,y:c,str:d};var f=Donatello.createElement(b,c,null,null,"div");this.dom=f,this.draw(),a.dom.appendChild(f),this.attr(e)},Donatello.Text.prototype=new Donatello(null),Donatello.Text.prototype.draw=function(){this.dom.innerHTML=this.properties.str},Donatello.prototype.text=function(a,b,c,d){return new Donatello.Text(this,a,b,c,d)}
<|endoftext|>


<commit_before>var fs = require('fs');
var serialize = require('node-serialize');
var trainerCards = {};

function loadTrainerCards() {
    try {
        trainerCards = serialize.unserialize(fs.readFileSync('config/trainercards.json', 'utf8'));
        Object.assign(CommandParserc
}

setTimeout(function load() {
    loadTrainerCards();
}, 1000);

function saveTrainerCards() {
    fs.writeFileSync('config/trainercards.json', serialize.serialize(trainerCards));
    Object.assign(CommandParser.commands, trainerCards);
}

exports.commands = {
    eztc: 'trainercard',
    trainercards: 'trainercard',
    tc: 'trainercard',
    trainercard: function(target, room, user) {
        if (!target) target = 'help';
        var parts = target.split(',');
        for (var u in parts) parts[u] = parts[u].trim();

        switch (parts[0]) {
            case 'add':
                if (!this.can('trainercard')) return false;
                if (!parts[2]) return this.sendReply("Usage: /trainercard add, [command name], [html]");
                var commandName = toId(parts[1]);
                if (CommandParser.commands[commandName]) return this.sendReply("/trainercards - The command \"" + commandName + "\" already exists.");
                var html = parts.splice(2, parts.length).join(',');
                trainerCards[commandName] = new Function('target', 'room', 'user', "if (!room.disableTrainerCards) if (!this.runBroadcast()) return; this.sendReplyBox('" + html.replace(/'/g, "\\'") + "');");
                saveTrainerCards();
                this.sendReply("The trainer card \"" + commandName + "\" has been added.");
                this.logModCommand(user.name + " added the trainer card " + commandName);
                break;

            case 'rem':
            case 'del':
            case 'delete':
            case 'remove':
                if (!this.can('trainercard')) return false;
                if (!parts[1]) return this.sendReply("Usage: /trainercard remove, [command name]");
                var commandName = toId(parts[1]);
                if (!trainerCards[commandName]) return this.sendReply("/trainercards - The command \"" + commandName + "\" does not exist, or was added manually.");
                delete CommandParser.commands[commandName];
                delete trainerCards[commandName];
                saveTrainerCards();
                this.sendReply("The trainer card \"" + commandName + "\" has been removed.");
                this.logModCommand(user.name + " removed the trainer card " + commandName);
                break;

            case 'list':
                if (!this.can('trainercard')) return false;
                var output = "There's a total of " + Object.size(trainerCards) + " trainer cards added with this command:
";
                for (var tc in trainerCards) {
                    output += tc + "
";
                }
                this.sendReplyBox(output);
                break;

            case 'off':
                if (!this.can('roommod', null, room)) return false;
                if (room.disableTrainerCards) return this.sendReply("Broadcasting trainer cards is already disabled in this room.");
                room.disableTrainerCards = true;
                room.chatRoomData.disableTrainerCards = true;
                Rooms.global.writeChatRoomData();
                this.privateModCommand("(" + user.name + " has disabled broadcasting trainer cards in this room.)");
                break;

            case 'on':
                if (!this.can('roommod', null, room)) return false;
                if (!room.disableTrainerCards) return this.sendReply("Broadcasing trainer cards is already enabled in this room.");
                delete room.disableTrainerCards;
                delete room.chatRoomData.disableTrainerCards;
                Rooms.global.writeChatRoomData();
                this.privateModCommand("(" + user.name + " has enabled broadcasting trainer cards in this room.)");
                break;

            default:
            case 'info':
            case 'help':
                if (!this.runBroadcast()) return;
                this.sendReplyBox(
                    "EZ-TC Commands:
" +
                    "/trainercard add, [command name], [html] - Adds a trainer card.
" +
                    "/trainercard remove, [command name] - Removes a trainer card.
" +
                    "/trainercard list - Shows a list of all trainer cards added with this command.
" +
                    "/trainercard off - Disables broadcasting trainer cards in the current room.
" +
                    "/trainercard on - Enables broadcasting trainer cards in the current room.
" +
                    "/trainercard help - Shows this help command.
" +
                    "EZ-TC Plugin by jd"
                );
        }
    }
};
<commit_msg>Update ez-tc.js<commit_after>var fs = require('fs');
var serialize = require('node-serialize');
var trainerCards = {};

function loadTrainerCards() {
    try {
        trainerCards = serialize.unserialize(fs.readFileSync('config/trainercards.json', 'utf8'));
              Object.assign(CommandParser.commands, trainerCards);
    } catch (e) {}
}

setTimeout(function load() {
    loadTrainerCards();
}, 1000);

function saveTrainerCards() {
    fs.writeFileSync('config/trainercards.json', serialize.serialize(trainerCards));
    Object.assign(CommandParser.commands, trainerCards);
}

exports.commands = {
    eztc: 'trainercard',
    trainercards: 'trainercard',
    tc: 'trainercard',
    trainercard: function(target, room, user) {
        if (!target) target = 'help';
        var parts = target.split(',');
        for (var u in parts) parts[u] = parts[u].trim();

        switch (parts[0]) {
            case 'add':
                if (!this.can('trainercard')) return false;
                if (!parts[2]) return this.sendReply("Usage: /trainercard add, [command name], [html]");
                var commandName = toId(parts[1]);
                if (CommandParser.commands[commandName]) return this.sendReply("/trainercards - The command \"" + commandName + "\" already exists.");
                var html = parts.splice(2, parts.length).join(',');
                trainerCards[commandName] = new Function('target', 'room', 'user', "if (!room.disableTrainerCards) if (!this.runBroadcast()) return; this.sendReplyBox('" + html.replace(/'/g, "\\'") + "');");
                saveTrainerCards();
                this.sendReply("The trainer card \"" + commandName + "\" has been added.");
                this.logModCommand(user.name + " added the trainer card " + commandName);
                break;

            case 'rem':
            case 'del':
            case 'delete':
            case 'remove':
                if (!this.can('trainercard')) return false;
                if (!parts[1]) return this.sendReply("Usage: /trainercard remove, [command name]");
                var commandName = toId(parts[1]);
                if (!trainerCards[commandName]) return this.sendReply("/trainercards - The command \"" + commandName + "\" does not exist, or was added manually.");
                delete CommandParser.commands[commandName];
                delete trainerCards[commandName];
                saveTrainerCards();
                this.sendReply("The trainer card \"" + commandName + "\" has been removed.");
                this.logModCommand(user.name + " removed the trainer card " + commandName);
                break;

            case 'list':
                if (!this.can('trainercard')) return false;
                var output = "There's a total of " + Object.size(trainerCards) + " trainer cards added with this command:
";
                for (var tc in trainerCards) {
                    output += tc + "
";
                }
                this.sendReplyBox(output);
                break;

            case 'off':
                if (!this.can('roommod', null, room)) return false;
                if (room.disableTrainerCards) return this.sendReply("Broadcasting trainer cards is already disabled in this room.");
                room.disableTrainerCards = true;
                room.chatRoomData.disableTrainerCards = true;
                Rooms.global.writeChatRoomData();
                this.privateModCommand("(" + user.name + " has disabled broadcasting trainer cards in this room.)");
                break;

            case 'on':
                if (!this.can('roommod', null, room)) return false;
                if (!room.disableTrainerCards) return this.sendReply("Broadcasing trainer cards is already enabled in this room.");
                delete room.disableTrainerCards;
                delete room.chatRoomData.disableTrainerCards;
                Rooms.global.writeChatRoomData();
                this.privateModCommand("(" + user.name + " has enabled broadcasting trainer cards in this room.)");
                break;

            default:
            case 'info':
            case 'help':
                if (!this.runBroadcast()) return;
                this.sendReplyBox(
                    "EZ-TC Commands:
" +
                    "/trainercard add, [command name], [html] - Adds a trainer card.
" +
                    "/trainercard remove, [command name] - Removes a trainer card.
" +
                    "/trainercard list - Shows a list of all trainer cards added with this command.
" +
                    "/trainercard off - Disables broadcasting trainer cards in the current room.
" +
                    "/trainercard on - Enables broadcasting trainer cards in the current room.
" +
                    "/trainercard help - Shows this help command.
" +
                    "EZ-TC Plugin by jd"
                );
        }
    }
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
require(["jquery", "sakai/sakai.api.core"], function($, sakai){

    /**
     * @name sakai_global.carousel
     *
     * @class carousel
     *
     * @description
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.carousel = function(tuid, showSettings){

        /////////////////////////////
        // Configuration variables //
        /////////////////////////////

        // Containers
        var carouselContainer = "#carousel_container";

        // Templates
        var carouselSingleColumnTemplate = "carousel_single_column_template";

        /////////////////////
        // RENDER PREVIEWS //
        /////////////////////

        var renderImagePreview = function(contentURL, lastModified){
            var url = "/p/" + contentURL + "?_=" + lastModified;
            return "";
        };

        var isJwPlayerSupportedVideo = function(mimeType){
            supported = false;
            if (mimeType.substring(0, 6) === "video/") {
                var mimeSuffix = mimeType.substring(6);
                if (mimeSuffix === "x-flv" || mimeSuffix === "mp4" || mimeSuffix === "3gpp" || mimeSuffix === "quicktime") {
                    supported = true;
                }
            }
            return supported;
        };

        var createSWFObject = function(url, params, flashvars){
            if (!url) {
                url = "/devwidgets/video/jwplayer/player-licensed.swf";
            }
            var so = new SWFObject(url, 'ply', '350', '197', '9', '#ffffff');
            so.addParam('allowfullscreen', 'true');
            if (params.allowscriptaccess) {
                so.addParam('allowscriptaccess', params.allowscriptaccess);
            }
            else {
                so.addParam('allowscriptaccess', 'always');
            }
            so.addParam('wmode', 'opaque');
            return so;
        };

        var renderVideoPlayer = function(url){
            var so = createSWFObject(false, {}, {});
            so.addVariable('file', "/p/" + url);
            so.addVariable('stretching', 'uniform');
            so.write("carousel_video");
            return $("#carousel_video_holder").html();
        };

        /////////////////////
        // RENDER CAROUSEL //
        /////////////////////

        var updateViewAfterAnimation = function(carousel, li, index, state){
            if (index > carousel.options.size || index < 1) {
                index = index % carousel.options.size;
                if (!index) {
                    index = carousel.options.size;
                }
                if (index < 1) {
                    index = carousel.options.size + index;
                }
            }
            $("#carousel_container .carousel_view_toggle li").removeClass("carousel_view_toggle_selected");
            $("#carousel_view_toggle_" + carousel.last).removeClass("carousel_view_toggle_selected");
            $("#carousel_view_toggle_" + index).addClass("carousel_view_toggle_selected");
        };

        var stopAutoScrolling = function(carousel){
            carousel.startAuto(0);
        };

        var carouselBinding = function(carousel){
            // Pause autoscrolling if the user moves with the cursor over the clip.
            carousel.clip.hover(function(){
                carousel.stopAuto();
            }, function(){
                carousel.startAuto();
            });

            // Disable autoscrolling if the user clicks the prev or next button.
            carousel.buttonNext.bind('click', function(){
                stopAutoScrolling(carousel);
            });

            carousel.buttonPrev.bind('click', function(){
                stopAutoScrolling(carousel);
            });

            $('.carousel_view_toggle li').bind('click', function(){
                stopAutoScrolling(carousel);
                carousel.scroll($.jcarousel.intval($(this)[0].id.split("carousel_view_toggle_")[1]));
                $("#carousel_container .carousel_view_toggle li").removeClass("carousel_view_toggle_selected");
                $(this).addClass("carousel_view_toggle_selected");
                return false;
            });
        };

        var renderCarousel = function(dataArr){
            sakai.api.Util.TemplateRenderer(carouselSingleColumnTemplate, {
                "data": dataArr
            }, $(carouselContainer), false);
            $(carouselContainer).jcarousel({
                auto: 5,
                animation: "slow",
                scroll: 1,
                easing: "swing",
                size: dataArr.length,
                initCallback: carouselBinding,
                buttonNextHTML: "

",
                buttonPrevHTML: "

",
                wrap: "circular",
                itemFirstInCallback: {
                    onAfterAnimation: updateViewAfterAnimation
                }
            });
        };

        var parseMessages = function(data, dataArr){
            var messageArr = [];

            for(var item in data.messages){
                if(data.messages[item].hasOwnProperty("sakai:body")){
                    var obj = {};

                    obj.subject = sakai.api.Util.applyThreeDots(data.messages[item]["sakai:subject"], 200,{},"s3d-bold");
                    obj.from = data.messages[item]["sakai:from"];
                    obj.date = sakai.api.l10n.transformDate(sakai.api.Util.parseSakaiDate(data.messages[item]["sakai:created"]));

                    obj.contentType = "message";
                    messageArr.push(obj);
                    if (messageArr.length >= 4) {
                        break;
                    }
                }
            }

            if (messageArr.length) {
                dataArr.push(messageArr);
            }
        };

        var parseContent = function(data, dataArr){
            var noPreviewArr = [];

            $.each(data.content.results, function(index, item) {
                var obj = {};
                var thumbnail = sakai.api.Content.getThumbnail(item);
                var mimeType = sakai.api.Content.getMimeType(item);
                if (mimeType.substring(0, 6) === "image/") {
                    obj.preview = renderImagePreview(item["jcr:name"], item["_lastModified"]);
                }else if (isJwPlayerSupportedVideo(mimeType || "")) {
                    obj.preview = renderVideoPlayer(item["jcr:name"]);
                } else if (thumbnail) {
                    obj.preview = renderImagePreview(item["jcr:name"] + ".page1-small.jpg", item["_lastModified"]);
                } else {
                    obj.preview = false;
                }
                if (item["sakai:description"]) {
                    obj.description = sakai.api.Util.applyThreeDots(item["sakai:description"], 700);
                }
                if (item["sakai:tags"]) {
                    obj.tags = sakai.api.Util.formatTagsExcludeLocation(item["sakai:tags"]);
                }
                if (item[item["jcr:name"] + "/comments"]) {
                    obj.comments = [];
                    for (var prop in item[item["jcr:name"] + "/comments"]) {
                        if (item[item["jcr:name"] + "/comments"][prop].hasOwnProperty("_id")) {
                            obj.comments.push(item[item["jcr:name"] + "/comments"][prop]);
                        }
                    }
                }
                if(sakai.config.MimeTypes[mimeType]) {
                    obj.icon = sakai.config.MimeTypes[mimeType].URL;
                }else{
                    obj.icon = sakai.config.MimeTypes.other.URL;
                }

                obj.title = item["sakai:pooled-content-file-name"];
                obj.mimeType = mimeType || "";
                obj.created = sakai.api.l10n.transformDate(sakai.api.l10n.fromEpoch(item["_created"]), sakai.data.me);
                obj.createdBy = item["sakai:pool-content-created-for"];
                obj.lastModified = sakai.api.l10n.transformDate(sakai.api.l10n.fromEpoch(item["_lastModified"]), sakai.data.me);
                obj.lastModifiedBy = item["_lastModifiedBy"];
                obj.url = "/content#content_path=/p/" + item["jcr:name"];
                obj.contentType = "content";

                if (obj.preview) {
                    dataArr.push(obj);
                } else {
                    noPreviewArr.push(obj);
                }
            });

            // Add items with no preview to final array.
            // Objective is to fill one rendered list item with two items (without preview), drop item that's left over if necessary.
            if (noPreviewArr.length) {
                if (noPreviewArr.length % 2) {
                    noPreviewArr.splice(noPreviewArr.length - 1, 1);
                }

                var tempArr = [];
                for (var item in noPreviewArr) {
                    if (tempArr.length != 2) {
                        tempArr.push(noPreviewArr[item]);
                        if (tempArr.length == 2) {
                            dataArr.push(tempArr);
                            tempArr = [];
                        }
                    }
                }
            }
        };

        var parseGroups = function(data, dataArr){
            $.each(data.groups.results, function (index, group){
                if (group.members) {
                    var obj = {};

                    if (group.members && group.members.length) {
                        obj.members = group.members;
                    }
                    if (group["sakai:group-description"] && group["sakai:group-description"].length) {
                        obj.description = group["sakai:group-description"];
                    }
                    if (group["sakai:tags"] && group["sakai:tags"].length) {
                        obj.tags = sakai.api.Util.formatTagsExcludeLocation(group["sakai:tags"]);
                    }

                    obj.contentType = "group";
                    obj.groupid = group["sakai:group-id"];
                    obj.title = group["sakai:group-title"];

                    dataArr.push(obj);
                }
            });
        };

        var parseUsers = function(data, dataArr){
            $.each(data.users.results, function (index, user){
                var obj = {};

                if (user["sakai:tags"] && user["sakai:tags"].length){
                    obj.tags = sakai.api.Util.formatTagsExcludeLocation(user["sakai:tags"]);
                }
                if (user.aboutme){
                    obj.aboutme = user.aboutme.elements.aboutme.value;
                }
                if (user.picture && user.picture.length){
                    obj.picture = $.parseJSON(user.picture);
                }

                obj.contentType = "user";
                obj.userid = user.userid;
                obj.displayName = sakai.api.User.getDisplayName(user);

                dataArr.push(obj);
            });
        };

        var parseInvitations = function(data, dataArr){
            $.each(data.invitations.results, function (index, invitation){
                var obj = {};

                if (invitation["sakai:tags"] && invitation["sakai:tags"].length){
                    obj.tags = sakai.api.Util.formatTagsExcludeLocation(invitation["sakai:tags"]);
                }
                if (invitation.aboutme){
                    obj.aboutme = invitation.aboutme.elements.aboutme.value;
                }
                if (invitation.profile.basic.elements.picture && invitation.profile.basic.elements.picture.value.length){
                    obj.picture = $.parseJSON(invitation.profile.basic.elements.picture.value);
                }

                obj.contentType = "invitation";
                obj.userid = invitation.profile.userid;
                obj.displayName = sakai.api.User.getDisplayName(invitation.profile);

                dataArr.push(obj);
            });
        };

        var parseData = function(data){
            var dataArr = [];

            parseContent(data, dataArr);
            parseGroups(data, dataArr);
            parseMessages(data, dataArr);
            //parseUsers(data, dataArr);
            //parseInvitations(data, dataArr);
            if (dataArr.length) {
                renderCarousel(dataArr);
            }
        };

        var checkDataParsable = function(data){
            if (data.content && data.groups && data.messages){ // && data.users && data.invitations) {
                parseData(data);
            }
        };

        var loadFeatured = function(){
            var dataArr = {
                "content": false,
                "groups": false,
                "messages": false,
                "users": false,
                "invitations": false
            };
            $.ajax({
                url: "/var/search/pool/me/manager-all.1.json?sortOn=_created&sortOrder=desc&page=0&items=50",
                cache: false,
                success: function(data){
                    dataArr.content = data;
                    checkDataParsable(dataArr);
                }
            });

            /*$.ajax({
                url: "/var/contacts/findstate.json?state=INVITED&page=0&items=1000",
                cache: false,
                success: function(data){
                    dataArr.invitations = data;
                    checkDataParsable(dataArr);
                }
            });

            $.ajax({
                url: "/var/search/users-all.json?page=0&items=50&q=*&sortOn=lastName&sortOrder=asc",
                cache: false,
                success: function(data){
                    dataArr.users = data;
                    checkDataParsable(dataArr);
                }
            }); */

            $.ajax({
                url: "/var/search/groups-all.json?page=0&items=50&q=*",
                cache: false,
                success: function(data){
                    $.each(data.results, function(index, group) {
                        data.results[group] = data.results[group] || false;
                        if (data.results[group].groupid) {
                            $.ajax({
                                url: "/system/userManager/group/" + data.results[group].groupid + ".members.json?items=50",
                                cache: false,
                                async: false,
                                success: function(memberData){
                                    data.results[group].members = memberData;
                                }
                            });
                        }
                    });
                    dataArr.groups = data;
                    checkDataParsable(dataArr);
                }
            });

            sakai.api.Communication.getAllMessages("inbox", "*", 4, 1, "sakai:created", "desc", function(success, data){
                dataArr.messages = data;
                checkDataParsable(dataArr);
            });
        };

        var doInit = function(){
            loadFeatured();
        };

        doInit();
    };

    sakai.api.Widgets.widgetLoader.informOnLoad("carousel");
});<commit_msg>NOJIRA - Change content feed carousel is pointing to<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
require(["jquery", "sakai/sakai.api.core"], function($, sakai){

    /**
     * @name sakai_global.carousel
     *
     * @class carousel
     *
     * @description
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.carousel = function(tuid, showSettings){

        /////////////////////////////
        // Configuration variables //
        /////////////////////////////

        // Containers
        var carouselContainer = "#carousel_container";

        // Templates
        var carouselSingleColumnTemplate = "carousel_single_column_template";

        /////////////////////
        // RENDER PREVIEWS //
        /////////////////////

        var renderImagePreview = function(contentURL, lastModified){
            var url = "/p/" + contentURL + "?_=" + lastModified;
            return "";
        };

        var isJwPlayerSupportedVideo = function(mimeType){
            supported = false;
            if (mimeType.substring(0, 6) === "video/") {
                var mimeSuffix = mimeType.substring(6);
                if (mimeSuffix === "x-flv" || mimeSuffix === "mp4" || mimeSuffix === "3gpp" || mimeSuffix === "quicktime") {
                    supported = true;
                }
            }
            return supported;
        };

        var createSWFObject = function(url, params, flashvars){
            if (!url) {
                url = "/devwidgets/video/jwplayer/player-licensed.swf";
            }
            var so = new SWFObject(url, 'ply', '350', '197', '9', '#ffffff');
            so.addParam('allowfullscreen', 'true');
            if (params.allowscriptaccess) {
                so.addParam('allowscriptaccess', params.allowscriptaccess);
            }
            else {
                so.addParam('allowscriptaccess', 'always');
            }
            so.addParam('wmode', 'opaque');
            return so;
        };

        var renderVideoPlayer = function(url){
            var so = createSWFObject(false, {}, {});
            so.addVariable('file', "/p/" + url);
            so.addVariable('stretching', 'uniform');
            so.write("carousel_video");
            return $("#carousel_video_holder").html();
        };

        /////////////////////
        // RENDER CAROUSEL //
        /////////////////////

        var updateViewAfterAnimation = function(carousel, li, index, state){
            if (index > carousel.options.size || index < 1) {
                index = index % carousel.options.size;
                if (!index) {
                    index = carousel.options.size;
                }
                if (index < 1) {
                    index = carousel.options.size + index;
                }
            }
            $("#carousel_container .carousel_view_toggle li").removeClass("carousel_view_toggle_selected");
            $("#carousel_view_toggle_" + carousel.last).removeClass("carousel_view_toggle_selected");
            $("#carousel_view_toggle_" + index).addClass("carousel_view_toggle_selected");
        };

        var stopAutoScrolling = function(carousel){
            carousel.startAuto(0);
        };

        var carouselBinding = function(carousel){
            // Pause autoscrolling if the user moves with the cursor over the clip.
            carousel.clip.hover(function(){
                carousel.stopAuto();
            }, function(){
                carousel.startAuto();
            });

            // Disable autoscrolling if the user clicks the prev or next button.
            carousel.buttonNext.bind('click', function(){
                stopAutoScrolling(carousel);
            });

            carousel.buttonPrev.bind('click', function(){
                stopAutoScrolling(carousel);
            });

            $('.carousel_view_toggle li').bind('click', function(){
                stopAutoScrolling(carousel);
                carousel.scroll($.jcarousel.intval($(this)[0].id.split("carousel_view_toggle_")[1]));
                $("#carousel_container .carousel_view_toggle li").removeClass("carousel_view_toggle_selected");
                $(this).addClass("carousel_view_toggle_selected");
                return false;
            });
        };

        var renderCarousel = function(dataArr){
            sakai.api.Util.TemplateRenderer(carouselSingleColumnTemplate, {
                "data": dataArr
            }, $(carouselContainer), false);
            $(carouselContainer).jcarousel({
                auto: 5,
                animation: "slow",
                scroll: 1,
                easing: "swing",
                size: dataArr.length,
                initCallback: carouselBinding,
                buttonNextHTML: "

",
                buttonPrevHTML: "

",
                wrap: "circular",
                itemFirstInCallback: {
                    onAfterAnimation: updateViewAfterAnimation
                }
            });
        };

        var parseMessages = function(data, dataArr){
            var messageArr = [];

            for(var item in data.messages){
                if(data.messages[item].hasOwnProperty("sakai:body")){
                    var obj = {};

                    obj.subject = sakai.api.Util.applyThreeDots(data.messages[item]["sakai:subject"], 200,{},"s3d-bold");
                    obj.from = data.messages[item]["sakai:from"];
                    obj.date = sakai.api.l10n.transformDate(sakai.api.Util.parseSakaiDate(data.messages[item]["sakai:created"]));

                    obj.contentType = "message";
                    messageArr.push(obj);
                    if (messageArr.length >= 4) {
                        break;
                    }
                }
            }

            if (messageArr.length) {
                dataArr.push(messageArr);
            }
        };

        var parseContent = function(data, dataArr){
            var noPreviewArr = [];

            $.each(data.content.results, function(index, item) {
                var obj = {};
                var thumbnail = sakai.api.Content.getThumbnail(item);
                var mimeType = sakai.api.Content.getMimeType(item);
                if (mimeType.substring(0, 6) === "image/") {
                    obj.preview = renderImagePreview(item["jcr:name"], item["_lastModified"]);
                }else if (isJwPlayerSupportedVideo(mimeType || "")) {
                    obj.preview = renderVideoPlayer(item["jcr:name"]);
                } else if (thumbnail) {
                    obj.preview = renderImagePreview(item["jcr:name"] + ".page1-small.jpg", item["_lastModified"]);
                } else {
                    obj.preview = false;
                }
                if (item["sakai:description"]) {
                    obj.description = sakai.api.Util.applyThreeDots(item["sakai:description"], 700);
                }
                if (item["sakai:tags"]) {
                    obj.tags = sakai.api.Util.formatTagsExcludeLocation(item["sakai:tags"]);
                }
                if (item[item["jcr:name"] + "/comments"]) {
                    obj.comments = [];
                    for (var prop in item[item["jcr:name"] + "/comments"]) {
                        if (item[item["jcr:name"] + "/comments"][prop].hasOwnProperty("_id")) {
                            obj.comments.push(item[item["jcr:name"] + "/comments"][prop]);
                        }
                    }
                }
                if(sakai.config.MimeTypes[mimeType]) {
                    obj.icon = sakai.config.MimeTypes[mimeType].URL;
                }else{
                    obj.icon = sakai.config.MimeTypes.other.URL;
                }

                obj.title = item["sakai:pooled-content-file-name"];
                obj.mimeType = mimeType || "";
                obj.created = sakai.api.l10n.transformDate(sakai.api.l10n.fromEpoch(item["_created"]), sakai.data.me);
                obj.createdBy = item["sakai:pool-content-created-for"];
                obj.lastModified = sakai.api.l10n.transformDate(sakai.api.l10n.fromEpoch(item["_lastModified"]), sakai.data.me);
                obj.lastModifiedBy = item["_lastModifiedBy"];
                obj.url = "/content#content_path=/p/" + item["jcr:name"];
                obj.contentType = "content";

                if (obj.preview) {
                    dataArr.push(obj);
                } else {
                    noPreviewArr.push(obj);
                }
            });

            // Add items with no preview to final array.
            // Objective is to fill one rendered list item with two items (without preview), drop item that's left over if necessary.
            if (noPreviewArr.length) {
                if (noPreviewArr.length % 2) {
                    noPreviewArr.splice(noPreviewArr.length - 1, 1);
                }

                var tempArr = [];
                for (var item in noPreviewArr) {
                    if (tempArr.length != 2) {
                        tempArr.push(noPreviewArr[item]);
                        if (tempArr.length == 2) {
                            dataArr.push(tempArr);
                            tempArr = [];
                        }
                    }
                }
            }
        };

        var parseGroups = function(data, dataArr){
            $.each(data.groups.results, function (index, group){
                if (group.members) {
                    var obj = {};

                    if (group.members && group.members.length) {
                        obj.members = group.members;
                    }
                    if (group["sakai:group-description"] && group["sakai:group-description"].length) {
                        obj.description = group["sakai:group-description"];
                    }
                    if (group["sakai:tags"] && group["sakai:tags"].length) {
                        obj.tags = sakai.api.Util.formatTagsExcludeLocation(group["sakai:tags"]);
                    }

                    obj.contentType = "group";
                    obj.groupid = group["sakai:group-id"];
                    obj.title = group["sakai:group-title"];

                    dataArr.push(obj);
                }
            });
        };

        var parseUsers = function(data, dataArr){
            $.each(data.users.results, function (index, user){
                var obj = {};

                if (user["sakai:tags"] && user["sakai:tags"].length){
                    obj.tags = sakai.api.Util.formatTagsExcludeLocation(user["sakai:tags"]);
                }
                if (user.aboutme){
                    obj.aboutme = user.aboutme.elements.aboutme.value;
                }
                if (user.picture && user.picture.length){
                    obj.picture = $.parseJSON(user.picture);
                }

                obj.contentType = "user";
                obj.userid = user.userid;
                obj.displayName = sakai.api.User.getDisplayName(user);

                dataArr.push(obj);
            });
        };

        var parseInvitations = function(data, dataArr){
            $.each(data.invitations.results, function (index, invitation){
                var obj = {};

                if (invitation["sakai:tags"] && invitation["sakai:tags"].length){
                    obj.tags = sakai.api.Util.formatTagsExcludeLocation(invitation["sakai:tags"]);
                }
                if (invitation.aboutme){
                    obj.aboutme = invitation.aboutme.elements.aboutme.value;
                }
                if (invitation.profile.basic.elements.picture && invitation.profile.basic.elements.picture.value.length){
                    obj.picture = $.parseJSON(invitation.profile.basic.elements.picture.value);
                }

                obj.contentType = "invitation";
                obj.userid = invitation.profile.userid;
                obj.displayName = sakai.api.User.getDisplayName(invitation.profile);

                dataArr.push(obj);
            });
        };

        var parseData = function(data){
            var dataArr = [];

            parseContent(data, dataArr);
            parseGroups(data, dataArr);
            parseMessages(data, dataArr);
            //parseUsers(data, dataArr);
            //parseInvitations(data, dataArr);
            if (dataArr.length) {
                renderCarousel(dataArr);
            }
        };

        var checkDataParsable = function(data){
            if (data.content && data.groups && data.messages){ // && data.users && data.invitations) {
                parseData(data);
            }
        };

        var loadFeatured = function(){
            var dataArr = {
                "content": false,
                "groups": false,
                "messages": false,
                "users": false,
                "invitations": false
            };
            $.ajax({
                url: "/var/search/pool/all-all.json?page=0&items=15&q=*&_charset_=utf-8",
                cache: false,
                success: function(data){
                    dataArr.content = data;
                    checkDataParsable(dataArr);
                }
            });

            /*$.ajax({
                url: "/var/contacts/findstate.json?state=INVITED&page=0&items=1000",
                cache: false,
                success: function(data){
                    dataArr.invitations = data;
                    checkDataParsable(dataArr);
                }
            });

            $.ajax({
                url: "/var/search/users-all.json?page=0&items=50&q=*&sortOn=lastName&sortOrder=asc",
                cache: false,
                success: function(data){
                    dataArr.users = data;
                    checkDataParsable(dataArr);
                }
            }); */

            $.ajax({
                url: "/var/search/groups-all.json?page=0&items=50&q=*",
                cache: false,
                success: function(data){
                    $.each(data.results, function(index, group) {
                        data.results[group] = data.results[group] || false;
                        if (data.results[group].groupid) {
                            $.ajax({
                                url: "/system/userManager/group/" + data.results[group].groupid + ".members.json?items=50",
                                cache: false,
                                async: false,
                                success: function(memberData){
                                    data.results[group].members = memberData;
                                }
                            });
                        }
                    });
                    dataArr.groups = data;
                    checkDataParsable(dataArr);
                }
            });

            sakai.api.Communication.getAllMessages("inbox", "*", 4, 1, "sakai:created", "desc", function(success, data){
                dataArr.messages = data;
                checkDataParsable(dataArr);
            });
        };

        var doInit = function(){
            loadFeatured();
        };

        doInit();
    };

    sakai.api.Widgets.widgetLoader.informOnLoad("carousel");
});<|endoftext|>


<commit_before>
////////////////////////////////
		//Setup//
////////////////////////////////

// Plugins
var gulp = require('gulp'),
      pjson = require('./package.json'),
      gutil = require('gulp-util'),
      sass = require('gulp-sass'),
      autoprefixer = require('gulp-autoprefixer'),
      cssnano = require('gulp-cssnano'),
      rename = require('gulp-rename'),
      del = require('del'),
      plumber = require('gulp-plumber'),
      pixrem = require('gulp-pixrem'),
      uglify = require('gulp-uglify'),
      imagemin = require('gulp-imagemin'),
      exec = require('child_process').exec,
      runSequence = require('run-sequence'),
      browserSync = require('browser-sync').create(),
      reload = browserSync.reload;

// Relative paths function
var pathsConfig = function (appName) {
  this.app = "./" + (appName || pjson.name);

  return {
    app: this.app,
    templates: this.app + '/templates',
    css: this.app + '/static/css',
    sass: this.app + '/static/sass',
    fonts: this.app + '/static/fonts',
    images: this.app + '/static/images',
    js: this.app + '/static/js',
  }
};

var paths = pathsConfig();

////////////////////////////////
		//Tasks//
////////////////////////////////

// Styles autoprefixing and minification
gulp.task('styles', function() {
  return gulp.src(paths.sass + '/project.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber()) // Checks for errors
    .pipe(autoprefixer({browsers: ['last 2 version']})) // Adds vendor prefixes
    .pipe(pixrem())  // add fallbacks for rem units
    .pipe(gulp.dest(paths.css))
    .pipe(rename({ suffix: '.min' }))
    .pipe(cssnano()) // Minifies the result
    .pipe(gulp.dest(paths.css));
});

// Javascript minification
gulp.task('scripts', function() {
  return gulp.src(paths.js + '/project.js')
    .pipe(plumber()) // Checks for errors
    .pipe(uglify()) // Minifies the js
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(paths.js));
});

// Image compression
gulp.task('imgCompression', function(){
  return gulp.src(paths.images + '/*')
    .pipe(imagemin()) // Compresses PNG, JPEG, GIF and SVG images
    .pipe(gulp.dest(paths.images))
});

// Run django server
gulp.task('runServer', function() {
  exec('python manage.py runserver', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});

// Browser sync server for live reload
gulp.task('browserSync', function() {
    browserSync.init(
      [paths.css + "/*.css", paths.js + "*.js", paths.templates + '*.html'], {
        proxy:  "localhost:8000"
    });
});

// Default task
gulp.task('default', function() {
    runSequence(['styles', 'scripts', 'imgCompression'], 'runServer', 'browserSync');
});

////////////////////////////////
		//Watch//
////////////////////////////////

// Watch
gulp.task('watch', ['default'], function() {

  gulp.watch(paths.sass + '/*.scss', ['styles']);
  gulp.watch(paths.js + '/*.js', ['scripts']).on("change", reload);
  gulp.watch(paths.images + '/*', ['imgCompression']);
  gulp.watch(paths.templates + '/**/*.html').on("change", reload);

});
<commit_msg>Removed dependency of `watch` task and put it in runSequence; there was no runSequence for it, which makes `watch` task won’t be run. (#1019)<commit_after>
////////////////////////////////
		//Setup//
////////////////////////////////

// Plugins
var gulp = require('gulp'),
      pjson = require('./package.json'),
      gutil = require('gulp-util'),
      sass = require('gulp-sass'),
      autoprefixer = require('gulp-autoprefixer'),
      cssnano = require('gulp-cssnano'),
      rename = require('gulp-rename'),
      del = require('del'),
      plumber = require('gulp-plumber'),
      pixrem = require('gulp-pixrem'),
      uglify = require('gulp-uglify'),
      imagemin = require('gulp-imagemin'),
      exec = require('child_process').exec,
      runSequence = require('run-sequence'),
      browserSync = require('browser-sync').create(),
      reload = browserSync.reload;

// Relative paths function
var pathsConfig = function (appName) {
  this.app = "./" + (appName || pjson.name);

  return {
    app: this.app,
    templates: this.app + '/templates',
    css: this.app + '/static/css',
    sass: this.app + '/static/sass',
    fonts: this.app + '/static/fonts',
    images: this.app + '/static/images',
    js: this.app + '/static/js',
  }
};

var paths = pathsConfig();

////////////////////////////////
		//Tasks//
////////////////////////////////

// Styles autoprefixing and minification
gulp.task('styles', function() {
  return gulp.src(paths.sass + '/project.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber()) // Checks for errors
    .pipe(autoprefixer({browsers: ['last 2 version']})) // Adds vendor prefixes
    .pipe(pixrem())  // add fallbacks for rem units
    .pipe(gulp.dest(paths.css))
    .pipe(rename({ suffix: '.min' }))
    .pipe(cssnano()) // Minifies the result
    .pipe(gulp.dest(paths.css));
});

// Javascript minification
gulp.task('scripts', function() {
  return gulp.src(paths.js + '/project.js')
    .pipe(plumber()) // Checks for errors
    .pipe(uglify()) // Minifies the js
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(paths.js));
});

// Image compression
gulp.task('imgCompression', function(){
  return gulp.src(paths.images + '/*')
    .pipe(imagemin()) // Compresses PNG, JPEG, GIF and SVG images
    .pipe(gulp.dest(paths.images))
});

// Run django server
gulp.task('runServer', function() {
  exec('python manage.py runserver', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});

// Browser sync server for live reload
gulp.task('browserSync', function() {
    browserSync.init(
      [paths.css + "/*.css", paths.js + "*.js", paths.templates + '*.html'], {
        proxy:  "localhost:8000"
    });
});

// Watch
gulp.task('watch', function() {

  gulp.watch(paths.sass + '/*.scss', ['styles']);
  gulp.watch(paths.js + '/*.js', ['scripts']).on("change", reload);
  gulp.watch(paths.images + '/*', ['imgCompression']);
  gulp.watch(paths.templates + '/**/*.html').on("change", reload);

});

// Default task
gulp.task('default', function() {
    runSequence(['styles', 'scripts', 'imgCompression'], 'runServer', 'browserSync', 'watch');
});
<|endoftext|>


<commit_before>module.exports = function(cluster) {
    var Promise = require('bluebird');
    function incoming_message(worker, msg) {
        switch(msg.method) {
            case "set":
                cache.set(msg.key, msg.val, msg.ttl, function(err, success) {
                worker.send({
                    sig: msg.method + msg.key,
                    body: {
                        err: err,
                        success: success
                    }
                });
            });
            break;
            case "get":
                cache.get(msg.key, function(err, value) {
                    worker.send({
                        sig: msg.method + msg.key,
                        body: {
                            err: err,
                            value: value
                        }
                    });
            });
            break;
            case "del":
                cache.del(msg.key, function(err, count) {
                    worker.send({
                        sig: msg.method + msg.key,
                        body: {
                            err: err,
                            count: count
                        }
                    });
            });
            break;
            case "ttl":
                cache.ttl(msg.key, msg.ttl, function(err, changed) {
                    worker.send({
                        sig: msg.method + msg.key,
                        body: {
                            err: err,
                            changed: changed
                        }
                    });
            });
            break;
            case "keys":
                cache.keys(function(err, keys) {
                    worker.send({
                        sig: msg.method,
                        body: {
                            err: err,
                            keys: keys
                        }
                    });
            });
            break;
            case "getStats":
                worker.send({
                    sig: msg.method,
                    body: cache.getStats()
                });
            break;
            case "flushAll":
                cache.flushAll();
                worker.send({
                    sig: msg.method,
                    body: cache.getStats()
                });
            break;
        }
    }
    if(cluster.isMaster) {
        var NodeCache = require("node-cache");
        var cache = new NodeCache();

        cluster.on('online', function(worker) {
            console.log("Cluster cache has been told about " + worker.id);
            worker.on('message', incoming_message.bind(null, worker));
        });
    } else {
        var ClusterCache = {};
        var resolve_dict = {};

        process.on("message", function(msg) {
            if(resolve_dict[msg.sig]) {
                resolve_dict[msg.sig](msg.body);
                delete resolve_dict[msg.sig];
            }
        });

        ClusterCache.set = function(key, val, ttl) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "set",
                    key: key,
                    val: val,
                    ttl: ttl
                });
                resolve_dict["set" + key] = resolve;
            });
        };

        ClusterCache.get = function(key) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "get",
                    key: key,
                });
                resolve_dict["get" + key] = resolve;
            });
        };

        ClusterCache.del = function(key) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "del",
                    key: key,
                });
                resolve_dict["del" + key] = resolve;
            });
        };

        ClusterCache.ttl = function(key, ttl) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "ttl",
                    key: key,
                    ttl: ttl
                });
                resolve_dict["ttl" + key] = resolve;
            });
        };

        ClusterCache.keys = function() {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "keys",
                });
                resolve_dict.keys = resolve;
            });
        };

        ClusterCache.getStats = function() {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "getStats"
                });
                resolve_dict.getStats = resolve;
            });
        };

        ClusterCache.flushAll = function() {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "flushAll"
                });
                resolve_dict.flushAll = resolve;
            });
        };

        return ClusterCache;
    }
};
<commit_msg>Removed console log<commit_after>module.exports = function(cluster) {
    var Promise = require('bluebird');
    function incoming_message(worker, msg) {
        switch(msg.method) {
            case "set":
                cache.set(msg.key, msg.val, msg.ttl, function(err, success) {
                worker.send({
                    sig: msg.method + msg.key,
                    body: {
                        err: err,
                        success: success
                    }
                });
            });
            break;
            case "get":
                cache.get(msg.key, function(err, value) {
                    worker.send({
                        sig: msg.method + msg.key,
                        body: {
                            err: err,
                            value: value
                        }
                    });
            });
            break;
            case "del":
                cache.del(msg.key, function(err, count) {
                    worker.send({
                        sig: msg.method + msg.key,
                        body: {
                            err: err,
                            count: count
                        }
                    });
            });
            break;
            case "ttl":
                cache.ttl(msg.key, msg.ttl, function(err, changed) {
                    worker.send({
                        sig: msg.method + msg.key,
                        body: {
                            err: err,
                            changed: changed
                        }
                    });
            });
            break;
            case "keys":
                cache.keys(function(err, keys) {
                    worker.send({
                        sig: msg.method,
                        body: {
                            err: err,
                            keys: keys
                        }
                    });
            });
            break;
            case "getStats":
                worker.send({
                    sig: msg.method,
                    body: cache.getStats()
                });
            break;
            case "flushAll":
                cache.flushAll();
                worker.send({
                    sig: msg.method,
                    body: cache.getStats()
                });
            break;
        }
    }
    if(cluster.isMaster) {
        var NodeCache = require("node-cache");
        var cache = new NodeCache();

        cluster.on('online', function(worker) {
            worker.on('message', incoming_message.bind(null, worker));
        });
    } else {
        var ClusterCache = {};
        var resolve_dict = {};

        process.on("message", function(msg) {
            if(resolve_dict[msg.sig]) {
                resolve_dict[msg.sig](msg.body);
                delete resolve_dict[msg.sig];
            }
        });

        ClusterCache.set = function(key, val, ttl) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "set",
                    key: key,
                    val: val,
                    ttl: ttl
                });
                resolve_dict["set" + key] = resolve;
            });
        };

        ClusterCache.get = function(key) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "get",
                    key: key,
                });
                resolve_dict["get" + key] = resolve;
            });
        };

        ClusterCache.del = function(key) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "del",
                    key: key,
                });
                resolve_dict["del" + key] = resolve;
            });
        };

        ClusterCache.ttl = function(key, ttl) {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "ttl",
                    key: key,
                    ttl: ttl
                });
                resolve_dict["ttl" + key] = resolve;
            });
        };

        ClusterCache.keys = function() {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "keys",
                });
                resolve_dict.keys = resolve;
            });
        };

        ClusterCache.getStats = function() {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "getStats"
                });
                resolve_dict.getStats = resolve;
            });
        };

        ClusterCache.flushAll = function() {
            return new Promise(function(resolve, reject) {
                process.send({
                    method: "flushAll"
                });
                resolve_dict.flushAll = resolve;
            });
        };

        return ClusterCache;
    }
};
<|endoftext|>


<commit_before>
/**
 * dropdown when user clicks on a column name
 */
cdb.admin.HeaderDropdown = cdb.admin.DropdownMenu.extend({

  className: "dropdown border",
  isPublic: false,

  events: {
    'click .asc': 'orderColumnsAsc',
    'click .desc': 'orderColumnsDesc',
    'click .rename_column': 'renameColumn',
    'click .change_data_type': 'changeType',
    'click .georeference': 'georeference',
    'click .filter_by_this_column': 'filterColumn',
    'click .delete_column': 'deleteColumn',
    'click .add_new_column': 'addColumn'
  },

  initialize: function() {
    this.options.reserved_column = false;
    this.options.isPublic = this.isPublic;
    this.elder('initialize');
  },

  setTable: function(table, column) {
    this.table = table;
    this.column = column;

    // depending on column type (reserved, normal) some fields should not be shown
    // so render the dropdown again
    this.options.reserved_column = this.table.data().isReadOnly() || this.table.isReservedColumn(column);
    this.render();

    this.$('.asc').removeClass('selected');
    this.$('.desc').removeClass('selected');
    //set options for ordering
    if(table.data().options.get('order_by') === column) {
      if(table.data().options.get('mode') === 'asc') {
        this.$('.asc').addClass('selected');
      } else {
        this.$('.desc').addClass('selected');
      }
    }
  },

  orderColumnsAsc: function(e) {
    e.preventDefault();
    this.table.data().setOptions({
      mode: 'asc',
      order_by: this.column
    });
    this.hide();
    return false;
  },

  orderColumnsDesc: function(e) {
    e.preventDefault();
    this.table.data().setOptions({
      mode: 'des',
      order_by: this.column
    });
    this.hide();
    return false;
  },

  renameColumn: function(e) {
    e.preventDefault();
    this.hide();
    this.trigger('renameColumn');
    return false;
  },

  changeType: function(e) {
    e.preventDefault();
    this.hide();
    this.trigger('changeType', this.column);
    return false;
  },

  georeference: function(e) {
    e.preventDefault();
    this.trigger('georeference', this.column);
    this.hide();
    return false;
  },

  filterColumn: function(e) {
    var self = this;
    var dlg = new cdb.admin.FilterColumnDialog({
      table: this.table,
      column: this.column,
      ok: function(filter) {
        self.trigger('applyFilter', self.column, filter);
      }
    });

    $('body').append(dlg.render().el);
    this.hide();
    dlg.open();
    e.preventDefault();
  },

  deleteColumn: function(e) {
    e.preventDefault();
    var self = this;
    cdb.log.debug("removing column: " + this.column);
    this.hide();
    var confirmation = new cdb.admin.DeleteColumnConfirmationDialog ({
      model: self.table,
      globalError: self.globalError,
      column: this.column
    });
    confirmation.appendToBody().open();
    var promise = confirmation.confirm();
    $.when(promise).done(function() {
      self.table.deleteColumn(self.column)
    });

    return false;
  },

  addColumn: function(e) {
    e.preventDefault();
    var dlg = new cdb.admin.NewColumnDialog({
      table: this.table
    });
    $('body').append(dlg.render().el);
    this.hide();
    dlg.show();
    return false;
  }
});

<commit_msg>filter view now prevents to open again table header options<commit_after>
/**
 * dropdown when user clicks on a column name
 */
cdb.admin.HeaderDropdown = cdb.admin.DropdownMenu.extend({

  className: "dropdown border",
  isPublic: false,

  events: {
    'click .asc': 'orderColumnsAsc',
    'click .desc': 'orderColumnsDesc',
    'click .rename_column': 'renameColumn',
    'click .change_data_type': 'changeType',
    'click .georeference': 'georeference',
    'click .filter_by_this_column': 'filterColumn',
    'click .delete_column': 'deleteColumn',
    'click .add_new_column': 'addColumn'
  },

  initialize: function() {
    this.options.reserved_column = false;
    this.options.isPublic = this.isPublic;
    this.elder('initialize');
  },

  setTable: function(table, column) {
    this.table = table;
    this.column = column;

    // depending on column type (reserved, normal) some fields should not be shown
    // so render the dropdown again
    this.options.reserved_column = this.table.data().isReadOnly() || this.table.isReservedColumn(column);
    this.render();

    this.$('.asc').removeClass('selected');
    this.$('.desc').removeClass('selected');
    //set options for ordering
    if(table.data().options.get('order_by') === column) {
      if(table.data().options.get('mode') === 'asc') {
        this.$('.asc').addClass('selected');
      } else {
        this.$('.desc').addClass('selected');
      }
    }
  },

  orderColumnsAsc: function(e) {
    e.preventDefault();
    this.table.data().setOptions({
      mode: 'asc',
      order_by: this.column
    });
    this.hide();
    return false;
  },

  orderColumnsDesc: function(e) {
    e.preventDefault();
    this.table.data().setOptions({
      mode: 'des',
      order_by: this.column
    });
    this.hide();
    return false;
  },

  renameColumn: function(e) {
    e.preventDefault();
    this.hide();
    this.trigger('renameColumn');
    return false;
  },

  changeType: function(e) {
    e.preventDefault();
    this.hide();
    this.trigger('changeType', this.column);
    return false;
  },

  georeference: function(e) {
    e.preventDefault();
    this.trigger('georeference', this.column);
    this.hide();
    return false;
  },

  filterColumn: function(e) {
    this.killEvent(e);

    var self = this;
    var dlg = new cdb.admin.FilterColumnDialog({
      table: this.table,
      column: this.column,
      ok: function(filter) {
        self.trigger('applyFilter', self.column, filter);
      }
    });

    $('body').append(dlg.render().el);
    this.hide();
    dlg.open();
  },

  deleteColumn: function(e) {
    e.preventDefault();
    var self = this;
    cdb.log.debug("removing column: " + this.column);
    this.hide();
    var confirmation = new cdb.admin.DeleteColumnConfirmationDialog ({
      model: self.table,
      globalError: self.globalError,
      column: this.column
    });
    confirmation.appendToBody().open();
    var promise = confirmation.confirm();
    $.when(promise).done(function() {
      self.table.deleteColumn(self.column)
    });

    return false;
  },

  addColumn: function(e) {
    e.preventDefault();
    var dlg = new cdb.admin.NewColumnDialog({
      table: this.table
    });
    $('body').append(dlg.render().el);
    this.hide();
    dlg.show();
    return false;
  }
});

<|endoftext|>


<commit_before>/*
   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.

   This file is licensed under the Apache License, Version 2.0 (the "License").
   You may not use this file except in compliance with the License. A copy of
   the License is located at

    http://aws.amazon.com/apache2.0/

   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied. See the License for the
   specific language governing permissions and limitations under the License.

   ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
   https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-alises.html
*/

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create the IAM service object
var iam = new AWS.IAM({apiVersion: '2010-05-08'});

iam.listAccountAliases({MaxItems: 10}, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
<commit_msg>Update iam_listaccountalises.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-alises.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

// Create the IAM service object
var iam = new AWS.IAM({apiVersion: '2010-05-08'});

iam.listAccountAliases({MaxItems: 10}, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
<|endoftext|>


<commit_before>import { CallBuilder } from "./call_builder";
import { NotFoundError, NetworkError, BadRequestError } from "./errors";

const allowedResolutions = [300000, 900000, 3600000, 86400000, 604800000];

/**
 * Trade Aggregations facilitate efficient gathering of historical trade data
 * Do not create this object directly, use {@link Server#tradeAggregation}.
 * @param {string} serverUrl serverUrl Horizon server URL.
 * @param {Asset} base base asset
 * @param {Asset} counter counter asset
 * @param {long} start_time lower time boundary represented as millis since epoch
 * @param {long} end_time upper time boundary represented as millis since epoch
 * @param {long} resolution segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000).
 * @returns {OrderbookCallBuilder}
 */
export class TradeAggregationCallBuilder extends CallBuilder {
  constructor (serverUrl, base, counter, start_time, end_time, resolution){
    super(serverUrl);

    this.url.segment('trade_aggregations');
    if (!base.isNative()) {
        this.url.addQuery("base_asset_type", base.getAssetType());
        this.url.addQuery("base_asset_code", base.getCode());
        this.url.addQuery("base_asset_issuer", base.getIssuer());
    } else {
        this.url.addQuery("base_asset_type", 'native');
    }
    if (!counter.isNative()) {
        this.url.addQuery("counter_asset_type", counter.getAssetType());
        this.url.addQuery("counter_asset_code", counter.getCode());
        this.url.addQuery("counter_asset_issuer", counter.getIssuer());
    } else {
        this.url.addQuery("counter_asset_type", 'native');
    }
    if ((typeof start_time === 'undefined') || (typeof end_time === 'undefined')) {
        throw new BadRequestError("Invalid time bounds", [start_time, end_time]);
    }else{
        this.url.addQuery("start_time", start_time);
        this.url.addQuery("end_time", end_time);
    }
    if (!this.isValidResolution(resolution)) {
        throw new BadRequestError("Invalid resolution", resolution);
    }else{
        this.url.addQuery("resolution", resolution);
    }

  }

  /**
   * @private
   * @param {long} resolution
   */
  isValidResolution(resolution){
    let found = false;

    for (let i = 0; i < allowedResolutions.length; i++) {
        if (allowedResolutions[i] == resolution) {
            found = true;
            break;
        }
    }
    return found;
  }

}<commit_msg>add one minute trade aggregation resolution (#164)<commit_after>import { CallBuilder } from "./call_builder";
import { NotFoundError, NetworkError, BadRequestError } from "./errors";

const allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000];

/**
 * Trade Aggregations facilitate efficient gathering of historical trade data
 * Do not create this object directly, use {@link Server#tradeAggregation}.
 * @param {string} serverUrl serverUrl Horizon server URL.
 * @param {Asset} base base asset
 * @param {Asset} counter counter asset
 * @param {long} start_time lower time boundary represented as millis since epoch
 * @param {long} end_time upper time boundary represented as millis since epoch
 * @param {long} resolution segment duration as millis since epoch. *Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000).
 * @returns {OrderbookCallBuilder}
 */
export class TradeAggregationCallBuilder extends CallBuilder {
  constructor (serverUrl, base, counter, start_time, end_time, resolution){
    super(serverUrl);

    this.url.segment('trade_aggregations');
    if (!base.isNative()) {
        this.url.addQuery("base_asset_type", base.getAssetType());
        this.url.addQuery("base_asset_code", base.getCode());
        this.url.addQuery("base_asset_issuer", base.getIssuer());
    } else {
        this.url.addQuery("base_asset_type", 'native');
    }
    if (!counter.isNative()) {
        this.url.addQuery("counter_asset_type", counter.getAssetType());
        this.url.addQuery("counter_asset_code", counter.getCode());
        this.url.addQuery("counter_asset_issuer", counter.getIssuer());
    } else {
        this.url.addQuery("counter_asset_type", 'native');
    }
    if ((typeof start_time === 'undefined') || (typeof end_time === 'undefined')) {
        throw new BadRequestError("Invalid time bounds", [start_time, end_time]);
    }else{
        this.url.addQuery("start_time", start_time);
        this.url.addQuery("end_time", end_time);
    }
    if (!this.isValidResolution(resolution)) {
        throw new BadRequestError("Invalid resolution", resolution);
    }else{
        this.url.addQuery("resolution", resolution);
    }

  }

  /**
   * @private
   * @param {long} resolution
   */
  isValidResolution(resolution){
    let found = false;

    for (let i = 0; i < allowedResolutions.length; i++) {
        if (allowedResolutions[i] == resolution) {
            found = true;
            break;
        }
    }
    return found;
  }

}<|endoftext|>


<commit_before>safari.application.addEventListener('contextmenu', function (event) {
  if(event.userInfo && event.userInfo.magnet) {
    event.contextMenu.appendContextMenuItem('sendMagnet', "Send Magnet to Transmission");

    sendRequest({
      url: event.userInfo.magnet,
      server: safari.extension.settings.server,
      id: '',
      retry: 3
    });
  }
}, false);

function sendRequest(config) {
  var error = false;
  var rpc = {
    "method": "torrent-add",
    "arguments": {
      "filename": config.url
    },
  };
  var req = new XMLHttpRequest();
  //TODO cache this value
  req.open('POST', config.server, true);
  req.setRequestHeader('X-Transmission-Session-Id', config.id);
  req.addEventListener('load', function () {
    if(req.status === 409) {
      console.log('Magnetic: received new session id');
      config.id = req.getResponseHeader('X-Transmission-Session-Id');
      if(--config.retry) {
        console.log('Magnetic: resending request');
        sendRequest(config);
      } else {
        console.log('Magnetic: giving up after 3 attempts');
      }
    }
    if(req.status === 200) {
      var res = JSON.parse(req.response);
      console.log('Magnetic: Server response \'' + res.result + '\'');
    }
  });
  req.addEventListener('error', function () {
    console.log('Magnetic: error');
  });

  req.send(JSON.stringify(rpc));
}
<commit_msg>Oops. Was adding the torrent when the context menu was brought up, rather than when the actual menu item was clicked. Fixed.<commit_after>// use the contextmenu event to add a context menu item if a magnet link
// has been clicked
safari.application.addEventListener('contextmenu', function (event) {
  if(event.userInfo && event.userInfo.magnet) {
    event.contextMenu.appendContextMenuItem('sendMagnet', "Send Magnet to Transmission");
  }
}, false);

// when the sendMagnet command is received, send the request to the
// user's specified transmission server.
safari.application.addEventListener('command', function (event) {
  if(event.command === 'sendMagnet') {
    sendRequest({
      url: event.userInfo.magnet,
      server: safari.extension.settings.server,
      id: '',
      retry: 3
    });
  }
});

function sendRequest(config) {
  var error = false;
  var rpc = {
    "method": "torrent-add",
    "arguments": {
      "filename": config.url
    },
  };
  var req = new XMLHttpRequest();
  //TODO cache this value
  req.open('POST', config.server, true);
  req.setRequestHeader('X-Transmission-Session-Id', config.id);
  req.addEventListener('load', function () {
    if(req.status === 409) {
      console.log('Magnetic: received new session id');
      config.id = req.getResponseHeader('X-Transmission-Session-Id');
      if(--config.retry) {
        console.log('Magnetic: resending request');
        sendRequest(config);
      } else {
        console.log('Magnetic: giving up after 3 attempts');
      }
    }
    if(req.status === 200) {
      var res = JSON.parse(req.response);
      console.log('Magnetic: Server response \'' + res.result + '\'');
    }
  });
  req.addEventListener('error', function () {
    console.log('Magnetic: error');
  });

  req.send(JSON.stringify(rpc));
}
<|endoftext|>